LLVM API Documentation

BitcodeReader.cpp
Go to the documentation of this file.
00001 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/Bitcode/ReaderWriter.h"
00011 #include "BitcodeReader.h"
00012 #include "llvm/ADT/SmallString.h"
00013 #include "llvm/ADT/SmallVector.h"
00014 #include "llvm/Bitcode/LLVMBitCodes.h"
00015 #include "llvm/IR/AutoUpgrade.h"
00016 #include "llvm/IR/Constants.h"
00017 #include "llvm/IR/DerivedTypes.h"
00018 #include "llvm/IR/InlineAsm.h"
00019 #include "llvm/IR/IntrinsicInst.h"
00020 #include "llvm/IR/LLVMContext.h"
00021 #include "llvm/IR/Module.h"
00022 #include "llvm/IR/OperandTraits.h"
00023 #include "llvm/IR/Operator.h"
00024 #include "llvm/Support/DataStream.h"
00025 #include "llvm/Support/MathExtras.h"
00026 #include "llvm/Support/MemoryBuffer.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include "llvm/Support/ManagedStatic.h"
00029 
00030 using namespace llvm;
00031 
00032 enum {
00033   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
00034 };
00035 
00036 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
00037   if (WillMaterializeAllForwardRefs)
00038     return std::error_code();
00039 
00040   // Prevent recursion.
00041   WillMaterializeAllForwardRefs = true;
00042 
00043   while (!BasicBlockFwdRefQueue.empty()) {
00044     Function *F = BasicBlockFwdRefQueue.front();
00045     BasicBlockFwdRefQueue.pop_front();
00046     assert(F && "Expected valid function");
00047     if (!BasicBlockFwdRefs.count(F))
00048       // Already materialized.
00049       continue;
00050 
00051     // Check for a function that isn't materializable to prevent an infinite
00052     // loop.  When parsing a blockaddress stored in a global variable, there
00053     // isn't a trivial way to check if a function will have a body without a
00054     // linear search through FunctionsWithBodies, so just check it here.
00055     if (!F->isMaterializable())
00056       return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
00057 
00058     // Try to materialize F.
00059     if (std::error_code EC = Materialize(F))
00060       return EC;
00061   }
00062   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
00063 
00064   // Reset state.
00065   WillMaterializeAllForwardRefs = false;
00066   return std::error_code();
00067 }
00068 
00069 void BitcodeReader::FreeState() {
00070   Buffer = nullptr;
00071   std::vector<Type*>().swap(TypeList);
00072   ValueList.clear();
00073   MDValueList.clear();
00074   std::vector<Comdat *>().swap(ComdatList);
00075 
00076   std::vector<AttributeSet>().swap(MAttributes);
00077   std::vector<BasicBlock*>().swap(FunctionBBs);
00078   std::vector<Function*>().swap(FunctionsWithBodies);
00079   DeferredFunctionInfo.clear();
00080   MDKindMap.clear();
00081 
00082   assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
00083   BasicBlockFwdRefQueue.clear();
00084 }
00085 
00086 //===----------------------------------------------------------------------===//
00087 //  Helper functions to implement forward reference resolution, etc.
00088 //===----------------------------------------------------------------------===//
00089 
00090 /// ConvertToString - Convert a string from a record into an std::string, return
00091 /// true on failure.
00092 template<typename StrTy>
00093 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
00094                             StrTy &Result) {
00095   if (Idx > Record.size())
00096     return true;
00097 
00098   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
00099     Result += (char)Record[i];
00100   return false;
00101 }
00102 
00103 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
00104   switch (Val) {
00105   default: // Map unknown/new linkages to external
00106   case 0:  return GlobalValue::ExternalLinkage;
00107   case 1:  return GlobalValue::WeakAnyLinkage;
00108   case 2:  return GlobalValue::AppendingLinkage;
00109   case 3:  return GlobalValue::InternalLinkage;
00110   case 4:  return GlobalValue::LinkOnceAnyLinkage;
00111   case 5:  return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
00112   case 6:  return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
00113   case 7:  return GlobalValue::ExternalWeakLinkage;
00114   case 8:  return GlobalValue::CommonLinkage;
00115   case 9:  return GlobalValue::PrivateLinkage;
00116   case 10: return GlobalValue::WeakODRLinkage;
00117   case 11: return GlobalValue::LinkOnceODRLinkage;
00118   case 12: return GlobalValue::AvailableExternallyLinkage;
00119   case 13:
00120     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
00121   case 14:
00122     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
00123   }
00124 }
00125 
00126 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
00127   switch (Val) {
00128   default: // Map unknown visibilities to default.
00129   case 0: return GlobalValue::DefaultVisibility;
00130   case 1: return GlobalValue::HiddenVisibility;
00131   case 2: return GlobalValue::ProtectedVisibility;
00132   }
00133 }
00134 
00135 static GlobalValue::DLLStorageClassTypes
00136 GetDecodedDLLStorageClass(unsigned Val) {
00137   switch (Val) {
00138   default: // Map unknown values to default.
00139   case 0: return GlobalValue::DefaultStorageClass;
00140   case 1: return GlobalValue::DLLImportStorageClass;
00141   case 2: return GlobalValue::DLLExportStorageClass;
00142   }
00143 }
00144 
00145 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
00146   switch (Val) {
00147     case 0: return GlobalVariable::NotThreadLocal;
00148     default: // Map unknown non-zero value to general dynamic.
00149     case 1: return GlobalVariable::GeneralDynamicTLSModel;
00150     case 2: return GlobalVariable::LocalDynamicTLSModel;
00151     case 3: return GlobalVariable::InitialExecTLSModel;
00152     case 4: return GlobalVariable::LocalExecTLSModel;
00153   }
00154 }
00155 
00156 static int GetDecodedCastOpcode(unsigned Val) {
00157   switch (Val) {
00158   default: return -1;
00159   case bitc::CAST_TRUNC   : return Instruction::Trunc;
00160   case bitc::CAST_ZEXT    : return Instruction::ZExt;
00161   case bitc::CAST_SEXT    : return Instruction::SExt;
00162   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
00163   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
00164   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
00165   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
00166   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
00167   case bitc::CAST_FPEXT   : return Instruction::FPExt;
00168   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
00169   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
00170   case bitc::CAST_BITCAST : return Instruction::BitCast;
00171   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
00172   }
00173 }
00174 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
00175   switch (Val) {
00176   default: return -1;
00177   case bitc::BINOP_ADD:
00178     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
00179   case bitc::BINOP_SUB:
00180     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
00181   case bitc::BINOP_MUL:
00182     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
00183   case bitc::BINOP_UDIV: return Instruction::UDiv;
00184   case bitc::BINOP_SDIV:
00185     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
00186   case bitc::BINOP_UREM: return Instruction::URem;
00187   case bitc::BINOP_SREM:
00188     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
00189   case bitc::BINOP_SHL:  return Instruction::Shl;
00190   case bitc::BINOP_LSHR: return Instruction::LShr;
00191   case bitc::BINOP_ASHR: return Instruction::AShr;
00192   case bitc::BINOP_AND:  return Instruction::And;
00193   case bitc::BINOP_OR:   return Instruction::Or;
00194   case bitc::BINOP_XOR:  return Instruction::Xor;
00195   }
00196 }
00197 
00198 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
00199   switch (Val) {
00200   default: return AtomicRMWInst::BAD_BINOP;
00201   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
00202   case bitc::RMW_ADD: return AtomicRMWInst::Add;
00203   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
00204   case bitc::RMW_AND: return AtomicRMWInst::And;
00205   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
00206   case bitc::RMW_OR: return AtomicRMWInst::Or;
00207   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
00208   case bitc::RMW_MAX: return AtomicRMWInst::Max;
00209   case bitc::RMW_MIN: return AtomicRMWInst::Min;
00210   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
00211   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
00212   }
00213 }
00214 
00215 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
00216   switch (Val) {
00217   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
00218   case bitc::ORDERING_UNORDERED: return Unordered;
00219   case bitc::ORDERING_MONOTONIC: return Monotonic;
00220   case bitc::ORDERING_ACQUIRE: return Acquire;
00221   case bitc::ORDERING_RELEASE: return Release;
00222   case bitc::ORDERING_ACQREL: return AcquireRelease;
00223   default: // Map unknown orderings to sequentially-consistent.
00224   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
00225   }
00226 }
00227 
00228 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
00229   switch (Val) {
00230   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
00231   default: // Map unknown scopes to cross-thread.
00232   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
00233   }
00234 }
00235 
00236 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
00237   switch (Val) {
00238   default: // Map unknown selection kinds to any.
00239   case bitc::COMDAT_SELECTION_KIND_ANY:
00240     return Comdat::Any;
00241   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
00242     return Comdat::ExactMatch;
00243   case bitc::COMDAT_SELECTION_KIND_LARGEST:
00244     return Comdat::Largest;
00245   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
00246     return Comdat::NoDuplicates;
00247   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
00248     return Comdat::SameSize;
00249   }
00250 }
00251 
00252 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
00253   switch (Val) {
00254   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
00255   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
00256   }
00257 }
00258 
00259 namespace llvm {
00260 namespace {
00261   /// @brief A class for maintaining the slot number definition
00262   /// as a placeholder for the actual definition for forward constants defs.
00263   class ConstantPlaceHolder : public ConstantExpr {
00264     void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
00265   public:
00266     // allocate space for exactly one operand
00267     void *operator new(size_t s) {
00268       return User::operator new(s, 1);
00269     }
00270     explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
00271       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
00272       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
00273     }
00274 
00275     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
00276     static bool classof(const Value *V) {
00277       return isa<ConstantExpr>(V) &&
00278              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
00279     }
00280 
00281 
00282     /// Provide fast operand accessors
00283     //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00284   };
00285 }
00286 
00287 // FIXME: can we inherit this from ConstantExpr?
00288 template <>
00289 struct OperandTraits<ConstantPlaceHolder> :
00290   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
00291 };
00292 }
00293 
00294 
00295 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
00296   if (Idx == size()) {
00297     push_back(V);
00298     return;
00299   }
00300 
00301   if (Idx >= size())
00302     resize(Idx+1);
00303 
00304   WeakVH &OldV = ValuePtrs[Idx];
00305   if (!OldV) {
00306     OldV = V;
00307     return;
00308   }
00309 
00310   // Handle constants and non-constants (e.g. instrs) differently for
00311   // efficiency.
00312   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
00313     ResolveConstants.push_back(std::make_pair(PHC, Idx));
00314     OldV = V;
00315   } else {
00316     // If there was a forward reference to this value, replace it.
00317     Value *PrevVal = OldV;
00318     OldV->replaceAllUsesWith(V);
00319     delete PrevVal;
00320   }
00321 }
00322 
00323 
00324 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
00325                                                     Type *Ty) {
00326   if (Idx >= size())
00327     resize(Idx + 1);
00328 
00329   if (Value *V = ValuePtrs[Idx]) {
00330     assert(Ty == V->getType() && "Type mismatch in constant table!");
00331     return cast<Constant>(V);
00332   }
00333 
00334   // Create and return a placeholder, which will later be RAUW'd.
00335   Constant *C = new ConstantPlaceHolder(Ty, Context);
00336   ValuePtrs[Idx] = C;
00337   return C;
00338 }
00339 
00340 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
00341   if (Idx >= size())
00342     resize(Idx + 1);
00343 
00344   if (Value *V = ValuePtrs[Idx]) {
00345     assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
00346     return V;
00347   }
00348 
00349   // No type specified, must be invalid reference.
00350   if (!Ty) return nullptr;
00351 
00352   // Create and return a placeholder, which will later be RAUW'd.
00353   Value *V = new Argument(Ty);
00354   ValuePtrs[Idx] = V;
00355   return V;
00356 }
00357 
00358 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
00359 /// resolves any forward references.  The idea behind this is that we sometimes
00360 /// get constants (such as large arrays) which reference *many* forward ref
00361 /// constants.  Replacing each of these causes a lot of thrashing when
00362 /// building/reuniquing the constant.  Instead of doing this, we look at all the
00363 /// uses and rewrite all the place holders at once for any constant that uses
00364 /// a placeholder.
00365 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
00366   // Sort the values by-pointer so that they are efficient to look up with a
00367   // binary search.
00368   std::sort(ResolveConstants.begin(), ResolveConstants.end());
00369 
00370   SmallVector<Constant*, 64> NewOps;
00371 
00372   while (!ResolveConstants.empty()) {
00373     Value *RealVal = operator[](ResolveConstants.back().second);
00374     Constant *Placeholder = ResolveConstants.back().first;
00375     ResolveConstants.pop_back();
00376 
00377     // Loop over all users of the placeholder, updating them to reference the
00378     // new value.  If they reference more than one placeholder, update them all
00379     // at once.
00380     while (!Placeholder->use_empty()) {
00381       auto UI = Placeholder->user_begin();
00382       User *U = *UI;
00383 
00384       // If the using object isn't uniqued, just update the operands.  This
00385       // handles instructions and initializers for global variables.
00386       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
00387         UI.getUse().set(RealVal);
00388         continue;
00389       }
00390 
00391       // Otherwise, we have a constant that uses the placeholder.  Replace that
00392       // constant with a new constant that has *all* placeholder uses updated.
00393       Constant *UserC = cast<Constant>(U);
00394       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
00395            I != E; ++I) {
00396         Value *NewOp;
00397         if (!isa<ConstantPlaceHolder>(*I)) {
00398           // Not a placeholder reference.
00399           NewOp = *I;
00400         } else if (*I == Placeholder) {
00401           // Common case is that it just references this one placeholder.
00402           NewOp = RealVal;
00403         } else {
00404           // Otherwise, look up the placeholder in ResolveConstants.
00405           ResolveConstantsTy::iterator It =
00406             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
00407                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
00408                                                             0));
00409           assert(It != ResolveConstants.end() && It->first == *I);
00410           NewOp = operator[](It->second);
00411         }
00412 
00413         NewOps.push_back(cast<Constant>(NewOp));
00414       }
00415 
00416       // Make the new constant.
00417       Constant *NewC;
00418       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
00419         NewC = ConstantArray::get(UserCA->getType(), NewOps);
00420       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
00421         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
00422       } else if (isa<ConstantVector>(UserC)) {
00423         NewC = ConstantVector::get(NewOps);
00424       } else {
00425         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
00426         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
00427       }
00428 
00429       UserC->replaceAllUsesWith(NewC);
00430       UserC->destroyConstant();
00431       NewOps.clear();
00432     }
00433 
00434     // Update all ValueHandles, they should be the only users at this point.
00435     Placeholder->replaceAllUsesWith(RealVal);
00436     delete Placeholder;
00437   }
00438 }
00439 
00440 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
00441   if (Idx == size()) {
00442     push_back(V);
00443     return;
00444   }
00445 
00446   if (Idx >= size())
00447     resize(Idx+1);
00448 
00449   WeakVH &OldV = MDValuePtrs[Idx];
00450   if (!OldV) {
00451     OldV = V;
00452     return;
00453   }
00454 
00455   // If there was a forward reference to this value, replace it.
00456   MDNode *PrevVal = cast<MDNode>(OldV);
00457   OldV->replaceAllUsesWith(V);
00458   MDNode::deleteTemporary(PrevVal);
00459   // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
00460   // value for Idx.
00461   MDValuePtrs[Idx] = V;
00462 }
00463 
00464 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
00465   if (Idx >= size())
00466     resize(Idx + 1);
00467 
00468   if (Value *V = MDValuePtrs[Idx]) {
00469     assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
00470     return V;
00471   }
00472 
00473   // Create and return a placeholder, which will later be RAUW'd.
00474   Value *V = MDNode::getTemporary(Context, None);
00475   MDValuePtrs[Idx] = V;
00476   return V;
00477 }
00478 
00479 Type *BitcodeReader::getTypeByID(unsigned ID) {
00480   // The type table size is always specified correctly.
00481   if (ID >= TypeList.size())
00482     return nullptr;
00483 
00484   if (Type *Ty = TypeList[ID])
00485     return Ty;
00486 
00487   // If we have a forward reference, the only possible case is when it is to a
00488   // named struct.  Just create a placeholder for now.
00489   return TypeList[ID] = StructType::create(Context);
00490 }
00491 
00492 
00493 //===----------------------------------------------------------------------===//
00494 //  Functions for parsing blocks from the bitcode file
00495 //===----------------------------------------------------------------------===//
00496 
00497 
00498 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
00499 /// been decoded from the given integer. This function must stay in sync with
00500 /// 'encodeLLVMAttributesForBitcode'.
00501 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
00502                                            uint64_t EncodedAttrs) {
00503   // FIXME: Remove in 4.0.
00504 
00505   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
00506   // the bits above 31 down by 11 bits.
00507   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
00508   assert((!Alignment || isPowerOf2_32(Alignment)) &&
00509          "Alignment must be a power of two.");
00510 
00511   if (Alignment)
00512     B.addAlignmentAttr(Alignment);
00513   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
00514                 (EncodedAttrs & 0xffff));
00515 }
00516 
00517 std::error_code BitcodeReader::ParseAttributeBlock() {
00518   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
00519     return Error(BitcodeError::InvalidRecord);
00520 
00521   if (!MAttributes.empty())
00522     return Error(BitcodeError::InvalidMultipleBlocks);
00523 
00524   SmallVector<uint64_t, 64> Record;
00525 
00526   SmallVector<AttributeSet, 8> Attrs;
00527 
00528   // Read all the records.
00529   while (1) {
00530     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
00531 
00532     switch (Entry.Kind) {
00533     case BitstreamEntry::SubBlock: // Handled for us already.
00534     case BitstreamEntry::Error:
00535       return Error(BitcodeError::MalformedBlock);
00536     case BitstreamEntry::EndBlock:
00537       return std::error_code();
00538     case BitstreamEntry::Record:
00539       // The interesting case.
00540       break;
00541     }
00542 
00543     // Read a record.
00544     Record.clear();
00545     switch (Stream.readRecord(Entry.ID, Record)) {
00546     default:  // Default behavior: ignore.
00547       break;
00548     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
00549       // FIXME: Remove in 4.0.
00550       if (Record.size() & 1)
00551         return Error(BitcodeError::InvalidRecord);
00552 
00553       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
00554         AttrBuilder B;
00555         decodeLLVMAttributesForBitcode(B, Record[i+1]);
00556         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
00557       }
00558 
00559       MAttributes.push_back(AttributeSet::get(Context, Attrs));
00560       Attrs.clear();
00561       break;
00562     }
00563     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
00564       for (unsigned i = 0, e = Record.size(); i != e; ++i)
00565         Attrs.push_back(MAttributeGroups[Record[i]]);
00566 
00567       MAttributes.push_back(AttributeSet::get(Context, Attrs));
00568       Attrs.clear();
00569       break;
00570     }
00571     }
00572   }
00573 }
00574 
00575 // Returns Attribute::None on unrecognized codes.
00576 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
00577   switch (Code) {
00578   default:
00579     return Attribute::None;
00580   case bitc::ATTR_KIND_ALIGNMENT:
00581     return Attribute::Alignment;
00582   case bitc::ATTR_KIND_ALWAYS_INLINE:
00583     return Attribute::AlwaysInline;
00584   case bitc::ATTR_KIND_BUILTIN:
00585     return Attribute::Builtin;
00586   case bitc::ATTR_KIND_BY_VAL:
00587     return Attribute::ByVal;
00588   case bitc::ATTR_KIND_IN_ALLOCA:
00589     return Attribute::InAlloca;
00590   case bitc::ATTR_KIND_COLD:
00591     return Attribute::Cold;
00592   case bitc::ATTR_KIND_INLINE_HINT:
00593     return Attribute::InlineHint;
00594   case bitc::ATTR_KIND_IN_REG:
00595     return Attribute::InReg;
00596   case bitc::ATTR_KIND_JUMP_TABLE:
00597     return Attribute::JumpTable;
00598   case bitc::ATTR_KIND_MIN_SIZE:
00599     return Attribute::MinSize;
00600   case bitc::ATTR_KIND_NAKED:
00601     return Attribute::Naked;
00602   case bitc::ATTR_KIND_NEST:
00603     return Attribute::Nest;
00604   case bitc::ATTR_KIND_NO_ALIAS:
00605     return Attribute::NoAlias;
00606   case bitc::ATTR_KIND_NO_BUILTIN:
00607     return Attribute::NoBuiltin;
00608   case bitc::ATTR_KIND_NO_CAPTURE:
00609     return Attribute::NoCapture;
00610   case bitc::ATTR_KIND_NO_DUPLICATE:
00611     return Attribute::NoDuplicate;
00612   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
00613     return Attribute::NoImplicitFloat;
00614   case bitc::ATTR_KIND_NO_INLINE:
00615     return Attribute::NoInline;
00616   case bitc::ATTR_KIND_NON_LAZY_BIND:
00617     return Attribute::NonLazyBind;
00618   case bitc::ATTR_KIND_NON_NULL:
00619     return Attribute::NonNull;
00620   case bitc::ATTR_KIND_DEREFERENCEABLE:
00621     return Attribute::Dereferenceable;
00622   case bitc::ATTR_KIND_NO_RED_ZONE:
00623     return Attribute::NoRedZone;
00624   case bitc::ATTR_KIND_NO_RETURN:
00625     return Attribute::NoReturn;
00626   case bitc::ATTR_KIND_NO_UNWIND:
00627     return Attribute::NoUnwind;
00628   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
00629     return Attribute::OptimizeForSize;
00630   case bitc::ATTR_KIND_OPTIMIZE_NONE:
00631     return Attribute::OptimizeNone;
00632   case bitc::ATTR_KIND_READ_NONE:
00633     return Attribute::ReadNone;
00634   case bitc::ATTR_KIND_READ_ONLY:
00635     return Attribute::ReadOnly;
00636   case bitc::ATTR_KIND_RETURNED:
00637     return Attribute::Returned;
00638   case bitc::ATTR_KIND_RETURNS_TWICE:
00639     return Attribute::ReturnsTwice;
00640   case bitc::ATTR_KIND_S_EXT:
00641     return Attribute::SExt;
00642   case bitc::ATTR_KIND_STACK_ALIGNMENT:
00643     return Attribute::StackAlignment;
00644   case bitc::ATTR_KIND_STACK_PROTECT:
00645     return Attribute::StackProtect;
00646   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
00647     return Attribute::StackProtectReq;
00648   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
00649     return Attribute::StackProtectStrong;
00650   case bitc::ATTR_KIND_STRUCT_RET:
00651     return Attribute::StructRet;
00652   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
00653     return Attribute::SanitizeAddress;
00654   case bitc::ATTR_KIND_SANITIZE_THREAD:
00655     return Attribute::SanitizeThread;
00656   case bitc::ATTR_KIND_SANITIZE_MEMORY:
00657     return Attribute::SanitizeMemory;
00658   case bitc::ATTR_KIND_UW_TABLE:
00659     return Attribute::UWTable;
00660   case bitc::ATTR_KIND_Z_EXT:
00661     return Attribute::ZExt;
00662   }
00663 }
00664 
00665 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
00666                                              Attribute::AttrKind *Kind) {
00667   *Kind = GetAttrFromCode(Code);
00668   if (*Kind == Attribute::None)
00669     return Error(BitcodeError::InvalidValue);
00670   return std::error_code();
00671 }
00672 
00673 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
00674   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
00675     return Error(BitcodeError::InvalidRecord);
00676 
00677   if (!MAttributeGroups.empty())
00678     return Error(BitcodeError::InvalidMultipleBlocks);
00679 
00680   SmallVector<uint64_t, 64> Record;
00681 
00682   // Read all the records.
00683   while (1) {
00684     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
00685 
00686     switch (Entry.Kind) {
00687     case BitstreamEntry::SubBlock: // Handled for us already.
00688     case BitstreamEntry::Error:
00689       return Error(BitcodeError::MalformedBlock);
00690     case BitstreamEntry::EndBlock:
00691       return std::error_code();
00692     case BitstreamEntry::Record:
00693       // The interesting case.
00694       break;
00695     }
00696 
00697     // Read a record.
00698     Record.clear();
00699     switch (Stream.readRecord(Entry.ID, Record)) {
00700     default:  // Default behavior: ignore.
00701       break;
00702     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
00703       if (Record.size() < 3)
00704         return Error(BitcodeError::InvalidRecord);
00705 
00706       uint64_t GrpID = Record[0];
00707       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
00708 
00709       AttrBuilder B;
00710       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
00711         if (Record[i] == 0) {        // Enum attribute
00712           Attribute::AttrKind Kind;
00713           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
00714             return EC;
00715 
00716           B.addAttribute(Kind);
00717         } else if (Record[i] == 1) { // Integer attribute
00718           Attribute::AttrKind Kind;
00719           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
00720             return EC;
00721           if (Kind == Attribute::Alignment)
00722             B.addAlignmentAttr(Record[++i]);
00723           else if (Kind == Attribute::StackAlignment)
00724             B.addStackAlignmentAttr(Record[++i]);
00725           else if (Kind == Attribute::Dereferenceable)
00726             B.addDereferenceableAttr(Record[++i]);
00727         } else {                     // String attribute
00728           assert((Record[i] == 3 || Record[i] == 4) &&
00729                  "Invalid attribute group entry");
00730           bool HasValue = (Record[i++] == 4);
00731           SmallString<64> KindStr;
00732           SmallString<64> ValStr;
00733 
00734           while (Record[i] != 0 && i != e)
00735             KindStr += Record[i++];
00736           assert(Record[i] == 0 && "Kind string not null terminated");
00737 
00738           if (HasValue) {
00739             // Has a value associated with it.
00740             ++i; // Skip the '0' that terminates the "kind" string.
00741             while (Record[i] != 0 && i != e)
00742               ValStr += Record[i++];
00743             assert(Record[i] == 0 && "Value string not null terminated");
00744           }
00745 
00746           B.addAttribute(KindStr.str(), ValStr.str());
00747         }
00748       }
00749 
00750       MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
00751       break;
00752     }
00753     }
00754   }
00755 }
00756 
00757 std::error_code BitcodeReader::ParseTypeTable() {
00758   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
00759     return Error(BitcodeError::InvalidRecord);
00760 
00761   return ParseTypeTableBody();
00762 }
00763 
00764 std::error_code BitcodeReader::ParseTypeTableBody() {
00765   if (!TypeList.empty())
00766     return Error(BitcodeError::InvalidMultipleBlocks);
00767 
00768   SmallVector<uint64_t, 64> Record;
00769   unsigned NumRecords = 0;
00770 
00771   SmallString<64> TypeName;
00772 
00773   // Read all the records for this type table.
00774   while (1) {
00775     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
00776 
00777     switch (Entry.Kind) {
00778     case BitstreamEntry::SubBlock: // Handled for us already.
00779     case BitstreamEntry::Error:
00780       return Error(BitcodeError::MalformedBlock);
00781     case BitstreamEntry::EndBlock:
00782       if (NumRecords != TypeList.size())
00783         return Error(BitcodeError::MalformedBlock);
00784       return std::error_code();
00785     case BitstreamEntry::Record:
00786       // The interesting case.
00787       break;
00788     }
00789 
00790     // Read a record.
00791     Record.clear();
00792     Type *ResultTy = nullptr;
00793     switch (Stream.readRecord(Entry.ID, Record)) {
00794     default:
00795       return Error(BitcodeError::InvalidValue);
00796     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
00797       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
00798       // type list.  This allows us to reserve space.
00799       if (Record.size() < 1)
00800         return Error(BitcodeError::InvalidRecord);
00801       TypeList.resize(Record[0]);
00802       continue;
00803     case bitc::TYPE_CODE_VOID:      // VOID
00804       ResultTy = Type::getVoidTy(Context);
00805       break;
00806     case bitc::TYPE_CODE_HALF:     // HALF
00807       ResultTy = Type::getHalfTy(Context);
00808       break;
00809     case bitc::TYPE_CODE_FLOAT:     // FLOAT
00810       ResultTy = Type::getFloatTy(Context);
00811       break;
00812     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
00813       ResultTy = Type::getDoubleTy(Context);
00814       break;
00815     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
00816       ResultTy = Type::getX86_FP80Ty(Context);
00817       break;
00818     case bitc::TYPE_CODE_FP128:     // FP128
00819       ResultTy = Type::getFP128Ty(Context);
00820       break;
00821     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
00822       ResultTy = Type::getPPC_FP128Ty(Context);
00823       break;
00824     case bitc::TYPE_CODE_LABEL:     // LABEL
00825       ResultTy = Type::getLabelTy(Context);
00826       break;
00827     case bitc::TYPE_CODE_METADATA:  // METADATA
00828       ResultTy = Type::getMetadataTy(Context);
00829       break;
00830     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
00831       ResultTy = Type::getX86_MMXTy(Context);
00832       break;
00833     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
00834       if (Record.size() < 1)
00835         return Error(BitcodeError::InvalidRecord);
00836 
00837       ResultTy = IntegerType::get(Context, Record[0]);
00838       break;
00839     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
00840                                     //          [pointee type, address space]
00841       if (Record.size() < 1)
00842         return Error(BitcodeError::InvalidRecord);
00843       unsigned AddressSpace = 0;
00844       if (Record.size() == 2)
00845         AddressSpace = Record[1];
00846       ResultTy = getTypeByID(Record[0]);
00847       if (!ResultTy)
00848         return Error(BitcodeError::InvalidType);
00849       ResultTy = PointerType::get(ResultTy, AddressSpace);
00850       break;
00851     }
00852     case bitc::TYPE_CODE_FUNCTION_OLD: {
00853       // FIXME: attrid is dead, remove it in LLVM 4.0
00854       // FUNCTION: [vararg, attrid, retty, paramty x N]
00855       if (Record.size() < 3)
00856         return Error(BitcodeError::InvalidRecord);
00857       SmallVector<Type*, 8> ArgTys;
00858       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
00859         if (Type *T = getTypeByID(Record[i]))
00860           ArgTys.push_back(T);
00861         else
00862           break;
00863       }
00864 
00865       ResultTy = getTypeByID(Record[2]);
00866       if (!ResultTy || ArgTys.size() < Record.size()-3)
00867         return Error(BitcodeError::InvalidType);
00868 
00869       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
00870       break;
00871     }
00872     case bitc::TYPE_CODE_FUNCTION: {
00873       // FUNCTION: [vararg, retty, paramty x N]
00874       if (Record.size() < 2)
00875         return Error(BitcodeError::InvalidRecord);
00876       SmallVector<Type*, 8> ArgTys;
00877       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
00878         if (Type *T = getTypeByID(Record[i]))
00879           ArgTys.push_back(T);
00880         else
00881           break;
00882       }
00883 
00884       ResultTy = getTypeByID(Record[1]);
00885       if (!ResultTy || ArgTys.size() < Record.size()-2)
00886         return Error(BitcodeError::InvalidType);
00887 
00888       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
00889       break;
00890     }
00891     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
00892       if (Record.size() < 1)
00893         return Error(BitcodeError::InvalidRecord);
00894       SmallVector<Type*, 8> EltTys;
00895       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
00896         if (Type *T = getTypeByID(Record[i]))
00897           EltTys.push_back(T);
00898         else
00899           break;
00900       }
00901       if (EltTys.size() != Record.size()-1)
00902         return Error(BitcodeError::InvalidType);
00903       ResultTy = StructType::get(Context, EltTys, Record[0]);
00904       break;
00905     }
00906     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
00907       if (ConvertToString(Record, 0, TypeName))
00908         return Error(BitcodeError::InvalidRecord);
00909       continue;
00910 
00911     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
00912       if (Record.size() < 1)
00913         return Error(BitcodeError::InvalidRecord);
00914 
00915       if (NumRecords >= TypeList.size())
00916         return Error(BitcodeError::InvalidTYPETable);
00917 
00918       // Check to see if this was forward referenced, if so fill in the temp.
00919       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
00920       if (Res) {
00921         Res->setName(TypeName);
00922         TypeList[NumRecords] = nullptr;
00923       } else  // Otherwise, create a new struct.
00924         Res = StructType::create(Context, TypeName);
00925       TypeName.clear();
00926 
00927       SmallVector<Type*, 8> EltTys;
00928       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
00929         if (Type *T = getTypeByID(Record[i]))
00930           EltTys.push_back(T);
00931         else
00932           break;
00933       }
00934       if (EltTys.size() != Record.size()-1)
00935         return Error(BitcodeError::InvalidRecord);
00936       Res->setBody(EltTys, Record[0]);
00937       ResultTy = Res;
00938       break;
00939     }
00940     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
00941       if (Record.size() != 1)
00942         return Error(BitcodeError::InvalidRecord);
00943 
00944       if (NumRecords >= TypeList.size())
00945         return Error(BitcodeError::InvalidTYPETable);
00946 
00947       // Check to see if this was forward referenced, if so fill in the temp.
00948       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
00949       if (Res) {
00950         Res->setName(TypeName);
00951         TypeList[NumRecords] = nullptr;
00952       } else  // Otherwise, create a new struct with no body.
00953         Res = StructType::create(Context, TypeName);
00954       TypeName.clear();
00955       ResultTy = Res;
00956       break;
00957     }
00958     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
00959       if (Record.size() < 2)
00960         return Error(BitcodeError::InvalidRecord);
00961       if ((ResultTy = getTypeByID(Record[1])))
00962         ResultTy = ArrayType::get(ResultTy, Record[0]);
00963       else
00964         return Error(BitcodeError::InvalidType);
00965       break;
00966     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
00967       if (Record.size() < 2)
00968         return Error(BitcodeError::InvalidRecord);
00969       if ((ResultTy = getTypeByID(Record[1])))
00970         ResultTy = VectorType::get(ResultTy, Record[0]);
00971       else
00972         return Error(BitcodeError::InvalidType);
00973       break;
00974     }
00975 
00976     if (NumRecords >= TypeList.size())
00977       return Error(BitcodeError::InvalidTYPETable);
00978     assert(ResultTy && "Didn't read a type?");
00979     assert(!TypeList[NumRecords] && "Already read type?");
00980     TypeList[NumRecords++] = ResultTy;
00981   }
00982 }
00983 
00984 std::error_code BitcodeReader::ParseValueSymbolTable() {
00985   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
00986     return Error(BitcodeError::InvalidRecord);
00987 
00988   SmallVector<uint64_t, 64> Record;
00989 
00990   // Read all the records for this value table.
00991   SmallString<128> ValueName;
00992   while (1) {
00993     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
00994 
00995     switch (Entry.Kind) {
00996     case BitstreamEntry::SubBlock: // Handled for us already.
00997     case BitstreamEntry::Error:
00998       return Error(BitcodeError::MalformedBlock);
00999     case BitstreamEntry::EndBlock:
01000       return std::error_code();
01001     case BitstreamEntry::Record:
01002       // The interesting case.
01003       break;
01004     }
01005 
01006     // Read a record.
01007     Record.clear();
01008     switch (Stream.readRecord(Entry.ID, Record)) {
01009     default:  // Default behavior: unknown type.
01010       break;
01011     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
01012       if (ConvertToString(Record, 1, ValueName))
01013         return Error(BitcodeError::InvalidRecord);
01014       unsigned ValueID = Record[0];
01015       if (ValueID >= ValueList.size() || !ValueList[ValueID])
01016         return Error(BitcodeError::InvalidRecord);
01017       Value *V = ValueList[ValueID];
01018 
01019       V->setName(StringRef(ValueName.data(), ValueName.size()));
01020       ValueName.clear();
01021       break;
01022     }
01023     case bitc::VST_CODE_BBENTRY: {
01024       if (ConvertToString(Record, 1, ValueName))
01025         return Error(BitcodeError::InvalidRecord);
01026       BasicBlock *BB = getBasicBlock(Record[0]);
01027       if (!BB)
01028         return Error(BitcodeError::InvalidRecord);
01029 
01030       BB->setName(StringRef(ValueName.data(), ValueName.size()));
01031       ValueName.clear();
01032       break;
01033     }
01034     }
01035   }
01036 }
01037 
01038 std::error_code BitcodeReader::ParseMetadata() {
01039   unsigned NextMDValueNo = MDValueList.size();
01040 
01041   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
01042     return Error(BitcodeError::InvalidRecord);
01043 
01044   SmallVector<uint64_t, 64> Record;
01045 
01046   // Read all the records.
01047   while (1) {
01048     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01049 
01050     switch (Entry.Kind) {
01051     case BitstreamEntry::SubBlock: // Handled for us already.
01052     case BitstreamEntry::Error:
01053       return Error(BitcodeError::MalformedBlock);
01054     case BitstreamEntry::EndBlock:
01055       return std::error_code();
01056     case BitstreamEntry::Record:
01057       // The interesting case.
01058       break;
01059     }
01060 
01061     bool IsFunctionLocal = false;
01062     // Read a record.
01063     Record.clear();
01064     unsigned Code = Stream.readRecord(Entry.ID, Record);
01065     switch (Code) {
01066     default:  // Default behavior: ignore.
01067       break;
01068     case bitc::METADATA_NAME: {
01069       // Read name of the named metadata.
01070       SmallString<8> Name(Record.begin(), Record.end());
01071       Record.clear();
01072       Code = Stream.ReadCode();
01073 
01074       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
01075       unsigned NextBitCode = Stream.readRecord(Code, Record);
01076       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
01077 
01078       // Read named metadata elements.
01079       unsigned Size = Record.size();
01080       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
01081       for (unsigned i = 0; i != Size; ++i) {
01082         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
01083         if (!MD)
01084           return Error(BitcodeError::InvalidRecord);
01085         NMD->addOperand(MD);
01086       }
01087       break;
01088     }
01089     case bitc::METADATA_FN_NODE:
01090       IsFunctionLocal = true;
01091       // fall-through
01092     case bitc::METADATA_NODE: {
01093       if (Record.size() % 2 == 1)
01094         return Error(BitcodeError::InvalidRecord);
01095 
01096       unsigned Size = Record.size();
01097       SmallVector<Value*, 8> Elts;
01098       for (unsigned i = 0; i != Size; i += 2) {
01099         Type *Ty = getTypeByID(Record[i]);
01100         if (!Ty)
01101           return Error(BitcodeError::InvalidRecord);
01102         if (Ty->isMetadataTy())
01103           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
01104         else if (!Ty->isVoidTy())
01105           Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
01106         else
01107           Elts.push_back(nullptr);
01108       }
01109       Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
01110       IsFunctionLocal = false;
01111       MDValueList.AssignValue(V, NextMDValueNo++);
01112       break;
01113     }
01114     case bitc::METADATA_STRING: {
01115       std::string String(Record.begin(), Record.end());
01116       llvm::UpgradeMDStringConstant(String);
01117       Value *V = MDString::get(Context, String);
01118       MDValueList.AssignValue(V, NextMDValueNo++);
01119       break;
01120     }
01121     case bitc::METADATA_KIND: {
01122       if (Record.size() < 2)
01123         return Error(BitcodeError::InvalidRecord);
01124 
01125       unsigned Kind = Record[0];
01126       SmallString<8> Name(Record.begin()+1, Record.end());
01127 
01128       unsigned NewKind = TheModule->getMDKindID(Name.str());
01129       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
01130         return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
01131       break;
01132     }
01133     }
01134   }
01135 }
01136 
01137 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
01138 /// the LSB for dense VBR encoding.
01139 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
01140   if ((V & 1) == 0)
01141     return V >> 1;
01142   if (V != 1)
01143     return -(V >> 1);
01144   // There is no such thing as -0 with integers.  "-0" really means MININT.
01145   return 1ULL << 63;
01146 }
01147 
01148 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
01149 /// values and aliases that we can.
01150 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
01151   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
01152   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
01153   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
01154 
01155   GlobalInitWorklist.swap(GlobalInits);
01156   AliasInitWorklist.swap(AliasInits);
01157   FunctionPrefixWorklist.swap(FunctionPrefixes);
01158 
01159   while (!GlobalInitWorklist.empty()) {
01160     unsigned ValID = GlobalInitWorklist.back().second;
01161     if (ValID >= ValueList.size()) {
01162       // Not ready to resolve this yet, it requires something later in the file.
01163       GlobalInits.push_back(GlobalInitWorklist.back());
01164     } else {
01165       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
01166         GlobalInitWorklist.back().first->setInitializer(C);
01167       else
01168         return Error(BitcodeError::ExpectedConstant);
01169     }
01170     GlobalInitWorklist.pop_back();
01171   }
01172 
01173   while (!AliasInitWorklist.empty()) {
01174     unsigned ValID = AliasInitWorklist.back().second;
01175     if (ValID >= ValueList.size()) {
01176       AliasInits.push_back(AliasInitWorklist.back());
01177     } else {
01178       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
01179         AliasInitWorklist.back().first->setAliasee(C);
01180       else
01181         return Error(BitcodeError::ExpectedConstant);
01182     }
01183     AliasInitWorklist.pop_back();
01184   }
01185 
01186   while (!FunctionPrefixWorklist.empty()) {
01187     unsigned ValID = FunctionPrefixWorklist.back().second;
01188     if (ValID >= ValueList.size()) {
01189       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
01190     } else {
01191       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
01192         FunctionPrefixWorklist.back().first->setPrefixData(C);
01193       else
01194         return Error(BitcodeError::ExpectedConstant);
01195     }
01196     FunctionPrefixWorklist.pop_back();
01197   }
01198 
01199   return std::error_code();
01200 }
01201 
01202 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
01203   SmallVector<uint64_t, 8> Words(Vals.size());
01204   std::transform(Vals.begin(), Vals.end(), Words.begin(),
01205                  BitcodeReader::decodeSignRotatedValue);
01206 
01207   return APInt(TypeBits, Words);
01208 }
01209 
01210 std::error_code BitcodeReader::ParseConstants() {
01211   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
01212     return Error(BitcodeError::InvalidRecord);
01213 
01214   SmallVector<uint64_t, 64> Record;
01215 
01216   // Read all the records for this value table.
01217   Type *CurTy = Type::getInt32Ty(Context);
01218   unsigned NextCstNo = ValueList.size();
01219   while (1) {
01220     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01221 
01222     switch (Entry.Kind) {
01223     case BitstreamEntry::SubBlock: // Handled for us already.
01224     case BitstreamEntry::Error:
01225       return Error(BitcodeError::MalformedBlock);
01226     case BitstreamEntry::EndBlock:
01227       if (NextCstNo != ValueList.size())
01228         return Error(BitcodeError::InvalidConstantReference);
01229 
01230       // Once all the constants have been read, go through and resolve forward
01231       // references.
01232       ValueList.ResolveConstantForwardRefs();
01233       return std::error_code();
01234     case BitstreamEntry::Record:
01235       // The interesting case.
01236       break;
01237     }
01238 
01239     // Read a record.
01240     Record.clear();
01241     Value *V = nullptr;
01242     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
01243     switch (BitCode) {
01244     default:  // Default behavior: unknown constant
01245     case bitc::CST_CODE_UNDEF:     // UNDEF
01246       V = UndefValue::get(CurTy);
01247       break;
01248     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
01249       if (Record.empty())
01250         return Error(BitcodeError::InvalidRecord);
01251       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
01252         return Error(BitcodeError::InvalidRecord);
01253       CurTy = TypeList[Record[0]];
01254       continue;  // Skip the ValueList manipulation.
01255     case bitc::CST_CODE_NULL:      // NULL
01256       V = Constant::getNullValue(CurTy);
01257       break;
01258     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
01259       if (!CurTy->isIntegerTy() || Record.empty())
01260         return Error(BitcodeError::InvalidRecord);
01261       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
01262       break;
01263     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
01264       if (!CurTy->isIntegerTy() || Record.empty())
01265         return Error(BitcodeError::InvalidRecord);
01266 
01267       APInt VInt = ReadWideAPInt(Record,
01268                                  cast<IntegerType>(CurTy)->getBitWidth());
01269       V = ConstantInt::get(Context, VInt);
01270 
01271       break;
01272     }
01273     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
01274       if (Record.empty())
01275         return Error(BitcodeError::InvalidRecord);
01276       if (CurTy->isHalfTy())
01277         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
01278                                              APInt(16, (uint16_t)Record[0])));
01279       else if (CurTy->isFloatTy())
01280         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
01281                                              APInt(32, (uint32_t)Record[0])));
01282       else if (CurTy->isDoubleTy())
01283         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
01284                                              APInt(64, Record[0])));
01285       else if (CurTy->isX86_FP80Ty()) {
01286         // Bits are not stored the same way as a normal i80 APInt, compensate.
01287         uint64_t Rearrange[2];
01288         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
01289         Rearrange[1] = Record[0] >> 48;
01290         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
01291                                              APInt(80, Rearrange)));
01292       } else if (CurTy->isFP128Ty())
01293         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
01294                                              APInt(128, Record)));
01295       else if (CurTy->isPPC_FP128Ty())
01296         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
01297                                              APInt(128, Record)));
01298       else
01299         V = UndefValue::get(CurTy);
01300       break;
01301     }
01302 
01303     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
01304       if (Record.empty())
01305         return Error(BitcodeError::InvalidRecord);
01306 
01307       unsigned Size = Record.size();
01308       SmallVector<Constant*, 16> Elts;
01309 
01310       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
01311         for (unsigned i = 0; i != Size; ++i)
01312           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
01313                                                      STy->getElementType(i)));
01314         V = ConstantStruct::get(STy, Elts);
01315       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
01316         Type *EltTy = ATy->getElementType();
01317         for (unsigned i = 0; i != Size; ++i)
01318           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
01319         V = ConstantArray::get(ATy, Elts);
01320       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
01321         Type *EltTy = VTy->getElementType();
01322         for (unsigned i = 0; i != Size; ++i)
01323           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
01324         V = ConstantVector::get(Elts);
01325       } else {
01326         V = UndefValue::get(CurTy);
01327       }
01328       break;
01329     }
01330     case bitc::CST_CODE_STRING:    // STRING: [values]
01331     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
01332       if (Record.empty())
01333         return Error(BitcodeError::InvalidRecord);
01334 
01335       SmallString<16> Elts(Record.begin(), Record.end());
01336       V = ConstantDataArray::getString(Context, Elts,
01337                                        BitCode == bitc::CST_CODE_CSTRING);
01338       break;
01339     }
01340     case bitc::CST_CODE_DATA: {// DATA: [n x value]
01341       if (Record.empty())
01342         return Error(BitcodeError::InvalidRecord);
01343 
01344       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
01345       unsigned Size = Record.size();
01346 
01347       if (EltTy->isIntegerTy(8)) {
01348         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
01349         if (isa<VectorType>(CurTy))
01350           V = ConstantDataVector::get(Context, Elts);
01351         else
01352           V = ConstantDataArray::get(Context, Elts);
01353       } else if (EltTy->isIntegerTy(16)) {
01354         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
01355         if (isa<VectorType>(CurTy))
01356           V = ConstantDataVector::get(Context, Elts);
01357         else
01358           V = ConstantDataArray::get(Context, Elts);
01359       } else if (EltTy->isIntegerTy(32)) {
01360         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
01361         if (isa<VectorType>(CurTy))
01362           V = ConstantDataVector::get(Context, Elts);
01363         else
01364           V = ConstantDataArray::get(Context, Elts);
01365       } else if (EltTy->isIntegerTy(64)) {
01366         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
01367         if (isa<VectorType>(CurTy))
01368           V = ConstantDataVector::get(Context, Elts);
01369         else
01370           V = ConstantDataArray::get(Context, Elts);
01371       } else if (EltTy->isFloatTy()) {
01372         SmallVector<float, 16> Elts(Size);
01373         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
01374         if (isa<VectorType>(CurTy))
01375           V = ConstantDataVector::get(Context, Elts);
01376         else
01377           V = ConstantDataArray::get(Context, Elts);
01378       } else if (EltTy->isDoubleTy()) {
01379         SmallVector<double, 16> Elts(Size);
01380         std::transform(Record.begin(), Record.end(), Elts.begin(),
01381                        BitsToDouble);
01382         if (isa<VectorType>(CurTy))
01383           V = ConstantDataVector::get(Context, Elts);
01384         else
01385           V = ConstantDataArray::get(Context, Elts);
01386       } else {
01387         return Error(BitcodeError::InvalidTypeForValue);
01388       }
01389       break;
01390     }
01391 
01392     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
01393       if (Record.size() < 3)
01394         return Error(BitcodeError::InvalidRecord);
01395       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
01396       if (Opc < 0) {
01397         V = UndefValue::get(CurTy);  // Unknown binop.
01398       } else {
01399         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
01400         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
01401         unsigned Flags = 0;
01402         if (Record.size() >= 4) {
01403           if (Opc == Instruction::Add ||
01404               Opc == Instruction::Sub ||
01405               Opc == Instruction::Mul ||
01406               Opc == Instruction::Shl) {
01407             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
01408               Flags |= OverflowingBinaryOperator::NoSignedWrap;
01409             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
01410               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
01411           } else if (Opc == Instruction::SDiv ||
01412                      Opc == Instruction::UDiv ||
01413                      Opc == Instruction::LShr ||
01414                      Opc == Instruction::AShr) {
01415             if (Record[3] & (1 << bitc::PEO_EXACT))
01416               Flags |= SDivOperator::IsExact;
01417           }
01418         }
01419         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
01420       }
01421       break;
01422     }
01423     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
01424       if (Record.size() < 3)
01425         return Error(BitcodeError::InvalidRecord);
01426       int Opc = GetDecodedCastOpcode(Record[0]);
01427       if (Opc < 0) {
01428         V = UndefValue::get(CurTy);  // Unknown cast.
01429       } else {
01430         Type *OpTy = getTypeByID(Record[1]);
01431         if (!OpTy)
01432           return Error(BitcodeError::InvalidRecord);
01433         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
01434         V = UpgradeBitCastExpr(Opc, Op, CurTy);
01435         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
01436       }
01437       break;
01438     }
01439     case bitc::CST_CODE_CE_INBOUNDS_GEP:
01440     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
01441       if (Record.size() & 1)
01442         return Error(BitcodeError::InvalidRecord);
01443       SmallVector<Constant*, 16> Elts;
01444       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
01445         Type *ElTy = getTypeByID(Record[i]);
01446         if (!ElTy)
01447           return Error(BitcodeError::InvalidRecord);
01448         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
01449       }
01450       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
01451       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
01452                                          BitCode ==
01453                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
01454       break;
01455     }
01456     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
01457       if (Record.size() < 3)
01458         return Error(BitcodeError::InvalidRecord);
01459 
01460       Type *SelectorTy = Type::getInt1Ty(Context);
01461 
01462       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
01463       // vector. Otherwise, it must be a single bit.
01464       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
01465         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
01466                                      VTy->getNumElements());
01467 
01468       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
01469                                                               SelectorTy),
01470                                   ValueList.getConstantFwdRef(Record[1],CurTy),
01471                                   ValueList.getConstantFwdRef(Record[2],CurTy));
01472       break;
01473     }
01474     case bitc::CST_CODE_CE_EXTRACTELT
01475         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
01476       if (Record.size() < 3)
01477         return Error(BitcodeError::InvalidRecord);
01478       VectorType *OpTy =
01479         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
01480       if (!OpTy)
01481         return Error(BitcodeError::InvalidRecord);
01482       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
01483       Constant *Op1 = nullptr;
01484       if (Record.size() == 4) {
01485         Type *IdxTy = getTypeByID(Record[2]);
01486         if (!IdxTy)
01487           return Error(BitcodeError::InvalidRecord);
01488         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
01489       } else // TODO: Remove with llvm 4.0
01490         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
01491       if (!Op1)
01492         return Error(BitcodeError::InvalidRecord);
01493       V = ConstantExpr::getExtractElement(Op0, Op1);
01494       break;
01495     }
01496     case bitc::CST_CODE_CE_INSERTELT
01497         : { // CE_INSERTELT: [opval, opval, opty, opval]
01498       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
01499       if (Record.size() < 3 || !OpTy)
01500         return Error(BitcodeError::InvalidRecord);
01501       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
01502       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
01503                                                   OpTy->getElementType());
01504       Constant *Op2 = nullptr;
01505       if (Record.size() == 4) {
01506         Type *IdxTy = getTypeByID(Record[2]);
01507         if (!IdxTy)
01508           return Error(BitcodeError::InvalidRecord);
01509         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
01510       } else // TODO: Remove with llvm 4.0
01511         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
01512       if (!Op2)
01513         return Error(BitcodeError::InvalidRecord);
01514       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
01515       break;
01516     }
01517     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
01518       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
01519       if (Record.size() < 3 || !OpTy)
01520         return Error(BitcodeError::InvalidRecord);
01521       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
01522       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
01523       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
01524                                                  OpTy->getNumElements());
01525       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
01526       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
01527       break;
01528     }
01529     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
01530       VectorType *RTy = dyn_cast<VectorType>(CurTy);
01531       VectorType *OpTy =
01532         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
01533       if (Record.size() < 4 || !RTy || !OpTy)
01534         return Error(BitcodeError::InvalidRecord);
01535       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
01536       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
01537       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
01538                                                  RTy->getNumElements());
01539       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
01540       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
01541       break;
01542     }
01543     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
01544       if (Record.size() < 4)
01545         return Error(BitcodeError::InvalidRecord);
01546       Type *OpTy = getTypeByID(Record[0]);
01547       if (!OpTy)
01548         return Error(BitcodeError::InvalidRecord);
01549       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
01550       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
01551 
01552       if (OpTy->isFPOrFPVectorTy())
01553         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
01554       else
01555         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
01556       break;
01557     }
01558     // This maintains backward compatibility, pre-asm dialect keywords.
01559     // FIXME: Remove with the 4.0 release.
01560     case bitc::CST_CODE_INLINEASM_OLD: {
01561       if (Record.size() < 2)
01562         return Error(BitcodeError::InvalidRecord);
01563       std::string AsmStr, ConstrStr;
01564       bool HasSideEffects = Record[0] & 1;
01565       bool IsAlignStack = Record[0] >> 1;
01566       unsigned AsmStrSize = Record[1];
01567       if (2+AsmStrSize >= Record.size())
01568         return Error(BitcodeError::InvalidRecord);
01569       unsigned ConstStrSize = Record[2+AsmStrSize];
01570       if (3+AsmStrSize+ConstStrSize > Record.size())
01571         return Error(BitcodeError::InvalidRecord);
01572 
01573       for (unsigned i = 0; i != AsmStrSize; ++i)
01574         AsmStr += (char)Record[2+i];
01575       for (unsigned i = 0; i != ConstStrSize; ++i)
01576         ConstrStr += (char)Record[3+AsmStrSize+i];
01577       PointerType *PTy = cast<PointerType>(CurTy);
01578       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
01579                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
01580       break;
01581     }
01582     // This version adds support for the asm dialect keywords (e.g.,
01583     // inteldialect).
01584     case bitc::CST_CODE_INLINEASM: {
01585       if (Record.size() < 2)
01586         return Error(BitcodeError::InvalidRecord);
01587       std::string AsmStr, ConstrStr;
01588       bool HasSideEffects = Record[0] & 1;
01589       bool IsAlignStack = (Record[0] >> 1) & 1;
01590       unsigned AsmDialect = Record[0] >> 2;
01591       unsigned AsmStrSize = Record[1];
01592       if (2+AsmStrSize >= Record.size())
01593         return Error(BitcodeError::InvalidRecord);
01594       unsigned ConstStrSize = Record[2+AsmStrSize];
01595       if (3+AsmStrSize+ConstStrSize > Record.size())
01596         return Error(BitcodeError::InvalidRecord);
01597 
01598       for (unsigned i = 0; i != AsmStrSize; ++i)
01599         AsmStr += (char)Record[2+i];
01600       for (unsigned i = 0; i != ConstStrSize; ++i)
01601         ConstrStr += (char)Record[3+AsmStrSize+i];
01602       PointerType *PTy = cast<PointerType>(CurTy);
01603       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
01604                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
01605                          InlineAsm::AsmDialect(AsmDialect));
01606       break;
01607     }
01608     case bitc::CST_CODE_BLOCKADDRESS:{
01609       if (Record.size() < 3)
01610         return Error(BitcodeError::InvalidRecord);
01611       Type *FnTy = getTypeByID(Record[0]);
01612       if (!FnTy)
01613         return Error(BitcodeError::InvalidRecord);
01614       Function *Fn =
01615         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
01616       if (!Fn)
01617         return Error(BitcodeError::InvalidRecord);
01618 
01619       // Don't let Fn get dematerialized.
01620       BlockAddressesTaken.insert(Fn);
01621 
01622       // If the function is already parsed we can insert the block address right
01623       // away.
01624       BasicBlock *BB;
01625       unsigned BBID = Record[2];
01626       if (!BBID)
01627         // Invalid reference to entry block.
01628         return Error(BitcodeError::InvalidID);
01629       if (!Fn->empty()) {
01630         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
01631         for (size_t I = 0, E = BBID; I != E; ++I) {
01632           if (BBI == BBE)
01633             return Error(BitcodeError::InvalidID);
01634           ++BBI;
01635         }
01636         BB = BBI;
01637       } else {
01638         // Otherwise insert a placeholder and remember it so it can be inserted
01639         // when the function is parsed.
01640         auto &FwdBBs = BasicBlockFwdRefs[Fn];
01641         if (FwdBBs.empty())
01642           BasicBlockFwdRefQueue.push_back(Fn);
01643         if (FwdBBs.size() < BBID + 1)
01644           FwdBBs.resize(BBID + 1);
01645         if (!FwdBBs[BBID])
01646           FwdBBs[BBID] = BasicBlock::Create(Context);
01647         BB = FwdBBs[BBID];
01648       }
01649       V = BlockAddress::get(Fn, BB);
01650       break;
01651     }
01652     }
01653 
01654     ValueList.AssignValue(V, NextCstNo);
01655     ++NextCstNo;
01656   }
01657 }
01658 
01659 std::error_code BitcodeReader::ParseUseLists() {
01660   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
01661     return Error(BitcodeError::InvalidRecord);
01662 
01663   // Read all the records.
01664   SmallVector<uint64_t, 64> Record;
01665   while (1) {
01666     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01667 
01668     switch (Entry.Kind) {
01669     case BitstreamEntry::SubBlock: // Handled for us already.
01670     case BitstreamEntry::Error:
01671       return Error(BitcodeError::MalformedBlock);
01672     case BitstreamEntry::EndBlock:
01673       return std::error_code();
01674     case BitstreamEntry::Record:
01675       // The interesting case.
01676       break;
01677     }
01678 
01679     // Read a use list record.
01680     Record.clear();
01681     bool IsBB = false;
01682     switch (Stream.readRecord(Entry.ID, Record)) {
01683     default:  // Default behavior: unknown type.
01684       break;
01685     case bitc::USELIST_CODE_BB:
01686       IsBB = true;
01687       // fallthrough
01688     case bitc::USELIST_CODE_DEFAULT: {
01689       unsigned RecordLength = Record.size();
01690       if (RecordLength < 3)
01691         // Records should have at least an ID and two indexes.
01692         return Error(BitcodeError::InvalidRecord);
01693       unsigned ID = Record.back();
01694       Record.pop_back();
01695 
01696       Value *V;
01697       if (IsBB) {
01698         assert(ID < FunctionBBs.size() && "Basic block not found");
01699         V = FunctionBBs[ID];
01700       } else
01701         V = ValueList[ID];
01702       unsigned NumUses = 0;
01703       SmallDenseMap<const Use *, unsigned, 16> Order;
01704       for (const Use &U : V->uses()) {
01705         if (++NumUses > Record.size())
01706           break;
01707         Order[&U] = Record[NumUses - 1];
01708       }
01709       if (Order.size() != Record.size() || NumUses > Record.size())
01710         // Mismatches can happen if the functions are being materialized lazily
01711         // (out-of-order), or a value has been upgraded.
01712         break;
01713 
01714       V->sortUseList([&](const Use &L, const Use &R) {
01715         return Order.lookup(&L) < Order.lookup(&R);
01716       });
01717       break;
01718     }
01719     }
01720   }
01721 }
01722 
01723 /// RememberAndSkipFunctionBody - When we see the block for a function body,
01724 /// remember where it is and then skip it.  This lets us lazily deserialize the
01725 /// functions.
01726 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
01727   // Get the function we are talking about.
01728   if (FunctionsWithBodies.empty())
01729     return Error(BitcodeError::InsufficientFunctionProtos);
01730 
01731   Function *Fn = FunctionsWithBodies.back();
01732   FunctionsWithBodies.pop_back();
01733 
01734   // Save the current stream state.
01735   uint64_t CurBit = Stream.GetCurrentBitNo();
01736   DeferredFunctionInfo[Fn] = CurBit;
01737 
01738   // Skip over the function block for now.
01739   if (Stream.SkipBlock())
01740     return Error(BitcodeError::InvalidRecord);
01741   return std::error_code();
01742 }
01743 
01744 std::error_code BitcodeReader::GlobalCleanup() {
01745   // Patch the initializers for globals and aliases up.
01746   ResolveGlobalAndAliasInits();
01747   if (!GlobalInits.empty() || !AliasInits.empty())
01748     return Error(BitcodeError::MalformedGlobalInitializerSet);
01749 
01750   // Look for intrinsic functions which need to be upgraded at some point
01751   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
01752        FI != FE; ++FI) {
01753     Function *NewFn;
01754     if (UpgradeIntrinsicFunction(FI, NewFn))
01755       UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
01756   }
01757 
01758   // Look for global variables which need to be renamed.
01759   for (Module::global_iterator
01760          GI = TheModule->global_begin(), GE = TheModule->global_end();
01761        GI != GE;) {
01762     GlobalVariable *GV = GI++;
01763     UpgradeGlobalVariable(GV);
01764   }
01765 
01766   // Force deallocation of memory for these vectors to favor the client that
01767   // want lazy deserialization.
01768   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
01769   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
01770   return std::error_code();
01771 }
01772 
01773 std::error_code BitcodeReader::ParseModule(bool Resume) {
01774   if (Resume)
01775     Stream.JumpToBit(NextUnreadBit);
01776   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
01777     return Error(BitcodeError::InvalidRecord);
01778 
01779   SmallVector<uint64_t, 64> Record;
01780   std::vector<std::string> SectionTable;
01781   std::vector<std::string> GCTable;
01782 
01783   // Read all the records for this module.
01784   while (1) {
01785     BitstreamEntry Entry = Stream.advance();
01786 
01787     switch (Entry.Kind) {
01788     case BitstreamEntry::Error:
01789       return Error(BitcodeError::MalformedBlock);
01790     case BitstreamEntry::EndBlock:
01791       return GlobalCleanup();
01792 
01793     case BitstreamEntry::SubBlock:
01794       switch (Entry.ID) {
01795       default:  // Skip unknown content.
01796         if (Stream.SkipBlock())
01797           return Error(BitcodeError::InvalidRecord);
01798         break;
01799       case bitc::BLOCKINFO_BLOCK_ID:
01800         if (Stream.ReadBlockInfoBlock())
01801           return Error(BitcodeError::MalformedBlock);
01802         break;
01803       case bitc::PARAMATTR_BLOCK_ID:
01804         if (std::error_code EC = ParseAttributeBlock())
01805           return EC;
01806         break;
01807       case bitc::PARAMATTR_GROUP_BLOCK_ID:
01808         if (std::error_code EC = ParseAttributeGroupBlock())
01809           return EC;
01810         break;
01811       case bitc::TYPE_BLOCK_ID_NEW:
01812         if (std::error_code EC = ParseTypeTable())
01813           return EC;
01814         break;
01815       case bitc::VALUE_SYMTAB_BLOCK_ID:
01816         if (std::error_code EC = ParseValueSymbolTable())
01817           return EC;
01818         SeenValueSymbolTable = true;
01819         break;
01820       case bitc::CONSTANTS_BLOCK_ID:
01821         if (std::error_code EC = ParseConstants())
01822           return EC;
01823         if (std::error_code EC = ResolveGlobalAndAliasInits())
01824           return EC;
01825         break;
01826       case bitc::METADATA_BLOCK_ID:
01827         if (std::error_code EC = ParseMetadata())
01828           return EC;
01829         break;
01830       case bitc::FUNCTION_BLOCK_ID:
01831         // If this is the first function body we've seen, reverse the
01832         // FunctionsWithBodies list.
01833         if (!SeenFirstFunctionBody) {
01834           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
01835           if (std::error_code EC = GlobalCleanup())
01836             return EC;
01837           SeenFirstFunctionBody = true;
01838         }
01839 
01840         if (std::error_code EC = RememberAndSkipFunctionBody())
01841           return EC;
01842         // For streaming bitcode, suspend parsing when we reach the function
01843         // bodies. Subsequent materialization calls will resume it when
01844         // necessary. For streaming, the function bodies must be at the end of
01845         // the bitcode. If the bitcode file is old, the symbol table will be
01846         // at the end instead and will not have been seen yet. In this case,
01847         // just finish the parse now.
01848         if (LazyStreamer && SeenValueSymbolTable) {
01849           NextUnreadBit = Stream.GetCurrentBitNo();
01850           return std::error_code();
01851         }
01852         break;
01853       case bitc::USELIST_BLOCK_ID:
01854         if (std::error_code EC = ParseUseLists())
01855           return EC;
01856         break;
01857       }
01858       continue;
01859 
01860     case BitstreamEntry::Record:
01861       // The interesting case.
01862       break;
01863     }
01864 
01865 
01866     // Read a record.
01867     switch (Stream.readRecord(Entry.ID, Record)) {
01868     default: break;  // Default behavior, ignore unknown content.
01869     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
01870       if (Record.size() < 1)
01871         return Error(BitcodeError::InvalidRecord);
01872       // Only version #0 and #1 are supported so far.
01873       unsigned module_version = Record[0];
01874       switch (module_version) {
01875         default:
01876           return Error(BitcodeError::InvalidValue);
01877         case 0:
01878           UseRelativeIDs = false;
01879           break;
01880         case 1:
01881           UseRelativeIDs = true;
01882           break;
01883       }
01884       break;
01885     }
01886     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
01887       std::string S;
01888       if (ConvertToString(Record, 0, S))
01889         return Error(BitcodeError::InvalidRecord);
01890       TheModule->setTargetTriple(S);
01891       break;
01892     }
01893     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
01894       std::string S;
01895       if (ConvertToString(Record, 0, S))
01896         return Error(BitcodeError::InvalidRecord);
01897       TheModule->setDataLayout(S);
01898       break;
01899     }
01900     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
01901       std::string S;
01902       if (ConvertToString(Record, 0, S))
01903         return Error(BitcodeError::InvalidRecord);
01904       TheModule->setModuleInlineAsm(S);
01905       break;
01906     }
01907     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
01908       // FIXME: Remove in 4.0.
01909       std::string S;
01910       if (ConvertToString(Record, 0, S))
01911         return Error(BitcodeError::InvalidRecord);
01912       // Ignore value.
01913       break;
01914     }
01915     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
01916       std::string S;
01917       if (ConvertToString(Record, 0, S))
01918         return Error(BitcodeError::InvalidRecord);
01919       SectionTable.push_back(S);
01920       break;
01921     }
01922     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
01923       std::string S;
01924       if (ConvertToString(Record, 0, S))
01925         return Error(BitcodeError::InvalidRecord);
01926       GCTable.push_back(S);
01927       break;
01928     }
01929     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
01930       if (Record.size() < 2)
01931         return Error(BitcodeError::InvalidRecord);
01932       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
01933       unsigned ComdatNameSize = Record[1];
01934       std::string ComdatName;
01935       ComdatName.reserve(ComdatNameSize);
01936       for (unsigned i = 0; i != ComdatNameSize; ++i)
01937         ComdatName += (char)Record[2 + i];
01938       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
01939       C->setSelectionKind(SK);
01940       ComdatList.push_back(C);
01941       break;
01942     }
01943     // GLOBALVAR: [pointer type, isconst, initid,
01944     //             linkage, alignment, section, visibility, threadlocal,
01945     //             unnamed_addr, dllstorageclass]
01946     case bitc::MODULE_CODE_GLOBALVAR: {
01947       if (Record.size() < 6)
01948         return Error(BitcodeError::InvalidRecord);
01949       Type *Ty = getTypeByID(Record[0]);
01950       if (!Ty)
01951         return Error(BitcodeError::InvalidRecord);
01952       if (!Ty->isPointerTy())
01953         return Error(BitcodeError::InvalidTypeForValue);
01954       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
01955       Ty = cast<PointerType>(Ty)->getElementType();
01956 
01957       bool isConstant = Record[1];
01958       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
01959       unsigned Alignment = (1 << Record[4]) >> 1;
01960       std::string Section;
01961       if (Record[5]) {
01962         if (Record[5]-1 >= SectionTable.size())
01963           return Error(BitcodeError::InvalidID);
01964         Section = SectionTable[Record[5]-1];
01965       }
01966       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
01967       // Local linkage must have default visibility.
01968       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
01969         // FIXME: Change to an error if non-default in 4.0.
01970         Visibility = GetDecodedVisibility(Record[6]);
01971 
01972       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
01973       if (Record.size() > 7)
01974         TLM = GetDecodedThreadLocalMode(Record[7]);
01975 
01976       bool UnnamedAddr = false;
01977       if (Record.size() > 8)
01978         UnnamedAddr = Record[8];
01979 
01980       bool ExternallyInitialized = false;
01981       if (Record.size() > 9)
01982         ExternallyInitialized = Record[9];
01983 
01984       GlobalVariable *NewGV =
01985         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
01986                            TLM, AddressSpace, ExternallyInitialized);
01987       NewGV->setAlignment(Alignment);
01988       if (!Section.empty())
01989         NewGV->setSection(Section);
01990       NewGV->setVisibility(Visibility);
01991       NewGV->setUnnamedAddr(UnnamedAddr);
01992 
01993       if (Record.size() > 10)
01994         NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
01995       else
01996         UpgradeDLLImportExportLinkage(NewGV, Record[3]);
01997 
01998       ValueList.push_back(NewGV);
01999 
02000       // Remember which value to use for the global initializer.
02001       if (unsigned InitID = Record[2])
02002         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
02003 
02004       if (Record.size() > 11)
02005         if (unsigned ComdatID = Record[11]) {
02006           assert(ComdatID <= ComdatList.size());
02007           NewGV->setComdat(ComdatList[ComdatID - 1]);
02008         }
02009       break;
02010     }
02011     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
02012     //             alignment, section, visibility, gc, unnamed_addr,
02013     //             dllstorageclass]
02014     case bitc::MODULE_CODE_FUNCTION: {
02015       if (Record.size() < 8)
02016         return Error(BitcodeError::InvalidRecord);
02017       Type *Ty = getTypeByID(Record[0]);
02018       if (!Ty)
02019         return Error(BitcodeError::InvalidRecord);
02020       if (!Ty->isPointerTy())
02021         return Error(BitcodeError::InvalidTypeForValue);
02022       FunctionType *FTy =
02023         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
02024       if (!FTy)
02025         return Error(BitcodeError::InvalidTypeForValue);
02026 
02027       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
02028                                         "", TheModule);
02029 
02030       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
02031       bool isProto = Record[2];
02032       Func->setLinkage(GetDecodedLinkage(Record[3]));
02033       Func->setAttributes(getAttributes(Record[4]));
02034 
02035       Func->setAlignment((1 << Record[5]) >> 1);
02036       if (Record[6]) {
02037         if (Record[6]-1 >= SectionTable.size())
02038           return Error(BitcodeError::InvalidID);
02039         Func->setSection(SectionTable[Record[6]-1]);
02040       }
02041       // Local linkage must have default visibility.
02042       if (!Func->hasLocalLinkage())
02043         // FIXME: Change to an error if non-default in 4.0.
02044         Func->setVisibility(GetDecodedVisibility(Record[7]));
02045       if (Record.size() > 8 && Record[8]) {
02046         if (Record[8]-1 > GCTable.size())
02047           return Error(BitcodeError::InvalidID);
02048         Func->setGC(GCTable[Record[8]-1].c_str());
02049       }
02050       bool UnnamedAddr = false;
02051       if (Record.size() > 9)
02052         UnnamedAddr = Record[9];
02053       Func->setUnnamedAddr(UnnamedAddr);
02054       if (Record.size() > 10 && Record[10] != 0)
02055         FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
02056 
02057       if (Record.size() > 11)
02058         Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
02059       else
02060         UpgradeDLLImportExportLinkage(Func, Record[3]);
02061 
02062       if (Record.size() > 12)
02063         if (unsigned ComdatID = Record[12]) {
02064           assert(ComdatID <= ComdatList.size());
02065           Func->setComdat(ComdatList[ComdatID - 1]);
02066         }
02067 
02068       ValueList.push_back(Func);
02069 
02070       // If this is a function with a body, remember the prototype we are
02071       // creating now, so that we can match up the body with them later.
02072       if (!isProto) {
02073         FunctionsWithBodies.push_back(Func);
02074         if (LazyStreamer)
02075           DeferredFunctionInfo[Func] = 0;
02076       }
02077       break;
02078     }
02079     // ALIAS: [alias type, aliasee val#, linkage]
02080     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
02081     case bitc::MODULE_CODE_ALIAS: {
02082       if (Record.size() < 3)
02083         return Error(BitcodeError::InvalidRecord);
02084       Type *Ty = getTypeByID(Record[0]);
02085       if (!Ty)
02086         return Error(BitcodeError::InvalidRecord);
02087       auto *PTy = dyn_cast<PointerType>(Ty);
02088       if (!PTy)
02089         return Error(BitcodeError::InvalidTypeForValue);
02090 
02091       auto *NewGA =
02092           GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
02093                               GetDecodedLinkage(Record[2]), "", TheModule);
02094       // Old bitcode files didn't have visibility field.
02095       // Local linkage must have default visibility.
02096       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
02097         // FIXME: Change to an error if non-default in 4.0.
02098         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
02099       if (Record.size() > 4)
02100         NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
02101       else
02102         UpgradeDLLImportExportLinkage(NewGA, Record[2]);
02103       if (Record.size() > 5)
02104   NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
02105       if (Record.size() > 6)
02106   NewGA->setUnnamedAddr(Record[6]);
02107       ValueList.push_back(NewGA);
02108       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
02109       break;
02110     }
02111     /// MODULE_CODE_PURGEVALS: [numvals]
02112     case bitc::MODULE_CODE_PURGEVALS:
02113       // Trim down the value list to the specified size.
02114       if (Record.size() < 1 || Record[0] > ValueList.size())
02115         return Error(BitcodeError::InvalidRecord);
02116       ValueList.shrinkTo(Record[0]);
02117       break;
02118     }
02119     Record.clear();
02120   }
02121 }
02122 
02123 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
02124   TheModule = nullptr;
02125 
02126   if (std::error_code EC = InitStream())
02127     return EC;
02128 
02129   // Sniff for the signature.
02130   if (Stream.Read(8) != 'B' ||
02131       Stream.Read(8) != 'C' ||
02132       Stream.Read(4) != 0x0 ||
02133       Stream.Read(4) != 0xC ||
02134       Stream.Read(4) != 0xE ||
02135       Stream.Read(4) != 0xD)
02136     return Error(BitcodeError::InvalidBitcodeSignature);
02137 
02138   // We expect a number of well-defined blocks, though we don't necessarily
02139   // need to understand them all.
02140   while (1) {
02141     if (Stream.AtEndOfStream())
02142       return std::error_code();
02143 
02144     BitstreamEntry Entry =
02145       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
02146 
02147     switch (Entry.Kind) {
02148     case BitstreamEntry::Error:
02149       return Error(BitcodeError::MalformedBlock);
02150     case BitstreamEntry::EndBlock:
02151       return std::error_code();
02152 
02153     case BitstreamEntry::SubBlock:
02154       switch (Entry.ID) {
02155       case bitc::BLOCKINFO_BLOCK_ID:
02156         if (Stream.ReadBlockInfoBlock())
02157           return Error(BitcodeError::MalformedBlock);
02158         break;
02159       case bitc::MODULE_BLOCK_ID:
02160         // Reject multiple MODULE_BLOCK's in a single bitstream.
02161         if (TheModule)
02162           return Error(BitcodeError::InvalidMultipleBlocks);
02163         TheModule = M;
02164         if (std::error_code EC = ParseModule(false))
02165           return EC;
02166         if (LazyStreamer)
02167           return std::error_code();
02168         break;
02169       default:
02170         if (Stream.SkipBlock())
02171           return Error(BitcodeError::InvalidRecord);
02172         break;
02173       }
02174       continue;
02175     case BitstreamEntry::Record:
02176       // There should be no records in the top-level of blocks.
02177 
02178       // The ranlib in Xcode 4 will align archive members by appending newlines
02179       // to the end of them. If this file size is a multiple of 4 but not 8, we
02180       // have to read and ignore these final 4 bytes :-(
02181       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
02182           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
02183           Stream.AtEndOfStream())
02184         return std::error_code();
02185 
02186       return Error(BitcodeError::InvalidRecord);
02187     }
02188   }
02189 }
02190 
02191 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
02192   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
02193     return Error(BitcodeError::InvalidRecord);
02194 
02195   SmallVector<uint64_t, 64> Record;
02196 
02197   std::string Triple;
02198   // Read all the records for this module.
02199   while (1) {
02200     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
02201 
02202     switch (Entry.Kind) {
02203     case BitstreamEntry::SubBlock: // Handled for us already.
02204     case BitstreamEntry::Error:
02205       return Error(BitcodeError::MalformedBlock);
02206     case BitstreamEntry::EndBlock:
02207       return Triple;
02208     case BitstreamEntry::Record:
02209       // The interesting case.
02210       break;
02211     }
02212 
02213     // Read a record.
02214     switch (Stream.readRecord(Entry.ID, Record)) {
02215     default: break;  // Default behavior, ignore unknown content.
02216     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
02217       std::string S;
02218       if (ConvertToString(Record, 0, S))
02219         return Error(BitcodeError::InvalidRecord);
02220       Triple = S;
02221       break;
02222     }
02223     }
02224     Record.clear();
02225   }
02226   llvm_unreachable("Exit infinite loop");
02227 }
02228 
02229 ErrorOr<std::string> BitcodeReader::parseTriple() {
02230   if (std::error_code EC = InitStream())
02231     return EC;
02232 
02233   // Sniff for the signature.
02234   if (Stream.Read(8) != 'B' ||
02235       Stream.Read(8) != 'C' ||
02236       Stream.Read(4) != 0x0 ||
02237       Stream.Read(4) != 0xC ||
02238       Stream.Read(4) != 0xE ||
02239       Stream.Read(4) != 0xD)
02240     return Error(BitcodeError::InvalidBitcodeSignature);
02241 
02242   // We expect a number of well-defined blocks, though we don't necessarily
02243   // need to understand them all.
02244   while (1) {
02245     BitstreamEntry Entry = Stream.advance();
02246 
02247     switch (Entry.Kind) {
02248     case BitstreamEntry::Error:
02249       return Error(BitcodeError::MalformedBlock);
02250     case BitstreamEntry::EndBlock:
02251       return std::error_code();
02252 
02253     case BitstreamEntry::SubBlock:
02254       if (Entry.ID == bitc::MODULE_BLOCK_ID)
02255         return parseModuleTriple();
02256 
02257       // Ignore other sub-blocks.
02258       if (Stream.SkipBlock())
02259         return Error(BitcodeError::MalformedBlock);
02260       continue;
02261 
02262     case BitstreamEntry::Record:
02263       Stream.skipRecord(Entry.ID);
02264       continue;
02265     }
02266   }
02267 }
02268 
02269 /// ParseMetadataAttachment - Parse metadata attachments.
02270 std::error_code BitcodeReader::ParseMetadataAttachment() {
02271   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
02272     return Error(BitcodeError::InvalidRecord);
02273 
02274   SmallVector<uint64_t, 64> Record;
02275   while (1) {
02276     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
02277 
02278     switch (Entry.Kind) {
02279     case BitstreamEntry::SubBlock: // Handled for us already.
02280     case BitstreamEntry::Error:
02281       return Error(BitcodeError::MalformedBlock);
02282     case BitstreamEntry::EndBlock:
02283       return std::error_code();
02284     case BitstreamEntry::Record:
02285       // The interesting case.
02286       break;
02287     }
02288 
02289     // Read a metadata attachment record.
02290     Record.clear();
02291     switch (Stream.readRecord(Entry.ID, Record)) {
02292     default:  // Default behavior: ignore.
02293       break;
02294     case bitc::METADATA_ATTACHMENT: {
02295       unsigned RecordLength = Record.size();
02296       if (Record.empty() || (RecordLength - 1) % 2 == 1)
02297         return Error(BitcodeError::InvalidRecord);
02298       Instruction *Inst = InstructionList[Record[0]];
02299       for (unsigned i = 1; i != RecordLength; i = i+2) {
02300         unsigned Kind = Record[i];
02301         DenseMap<unsigned, unsigned>::iterator I =
02302           MDKindMap.find(Kind);
02303         if (I == MDKindMap.end())
02304           return Error(BitcodeError::InvalidID);
02305         Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
02306         Inst->setMetadata(I->second, cast<MDNode>(Node));
02307         if (I->second == LLVMContext::MD_tbaa)
02308           InstsWithTBAATag.push_back(Inst);
02309       }
02310       break;
02311     }
02312     }
02313   }
02314 }
02315 
02316 /// ParseFunctionBody - Lazily parse the specified function body block.
02317 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
02318   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
02319     return Error(BitcodeError::InvalidRecord);
02320 
02321   InstructionList.clear();
02322   unsigned ModuleValueListSize = ValueList.size();
02323   unsigned ModuleMDValueListSize = MDValueList.size();
02324 
02325   // Add all the function arguments to the value table.
02326   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
02327     ValueList.push_back(I);
02328 
02329   unsigned NextValueNo = ValueList.size();
02330   BasicBlock *CurBB = nullptr;
02331   unsigned CurBBNo = 0;
02332 
02333   DebugLoc LastLoc;
02334 
02335   // Read all the records.
02336   SmallVector<uint64_t, 64> Record;
02337   while (1) {
02338     BitstreamEntry Entry = Stream.advance();
02339 
02340     switch (Entry.Kind) {
02341     case BitstreamEntry::Error:
02342       return Error(BitcodeError::MalformedBlock);
02343     case BitstreamEntry::EndBlock:
02344       goto OutOfRecordLoop;
02345 
02346     case BitstreamEntry::SubBlock:
02347       switch (Entry.ID) {
02348       default:  // Skip unknown content.
02349         if (Stream.SkipBlock())
02350           return Error(BitcodeError::InvalidRecord);
02351         break;
02352       case bitc::CONSTANTS_BLOCK_ID:
02353         if (std::error_code EC = ParseConstants())
02354           return EC;
02355         NextValueNo = ValueList.size();
02356         break;
02357       case bitc::VALUE_SYMTAB_BLOCK_ID:
02358         if (std::error_code EC = ParseValueSymbolTable())
02359           return EC;
02360         break;
02361       case bitc::METADATA_ATTACHMENT_ID:
02362         if (std::error_code EC = ParseMetadataAttachment())
02363           return EC;
02364         break;
02365       case bitc::METADATA_BLOCK_ID:
02366         if (std::error_code EC = ParseMetadata())
02367           return EC;
02368         break;
02369       case bitc::USELIST_BLOCK_ID:
02370         if (std::error_code EC = ParseUseLists())
02371           return EC;
02372         break;
02373       }
02374       continue;
02375 
02376     case BitstreamEntry::Record:
02377       // The interesting case.
02378       break;
02379     }
02380 
02381     // Read a record.
02382     Record.clear();
02383     Instruction *I = nullptr;
02384     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
02385     switch (BitCode) {
02386     default: // Default behavior: reject
02387       return Error(BitcodeError::InvalidValue);
02388     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
02389       if (Record.size() < 1 || Record[0] == 0)
02390         return Error(BitcodeError::InvalidRecord);
02391       // Create all the basic blocks for the function.
02392       FunctionBBs.resize(Record[0]);
02393 
02394       // See if anything took the address of blocks in this function.
02395       auto BBFRI = BasicBlockFwdRefs.find(F);
02396       if (BBFRI == BasicBlockFwdRefs.end()) {
02397         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
02398           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
02399       } else {
02400         auto &BBRefs = BBFRI->second;
02401         // Check for invalid basic block references.
02402         if (BBRefs.size() > FunctionBBs.size())
02403           return Error(BitcodeError::InvalidID);
02404         assert(!BBRefs.empty() && "Unexpected empty array");
02405         assert(!BBRefs.front() && "Invalid reference to entry block");
02406         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
02407              ++I)
02408           if (I < RE && BBRefs[I]) {
02409             BBRefs[I]->insertInto(F);
02410             FunctionBBs[I] = BBRefs[I];
02411           } else {
02412             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
02413           }
02414 
02415         // Erase from the table.
02416         BasicBlockFwdRefs.erase(BBFRI);
02417       }
02418 
02419       CurBB = FunctionBBs[0];
02420       continue;
02421     }
02422 
02423     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
02424       // This record indicates that the last instruction is at the same
02425       // location as the previous instruction with a location.
02426       I = nullptr;
02427 
02428       // Get the last instruction emitted.
02429       if (CurBB && !CurBB->empty())
02430         I = &CurBB->back();
02431       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
02432                !FunctionBBs[CurBBNo-1]->empty())
02433         I = &FunctionBBs[CurBBNo-1]->back();
02434 
02435       if (!I)
02436         return Error(BitcodeError::InvalidRecord);
02437       I->setDebugLoc(LastLoc);
02438       I = nullptr;
02439       continue;
02440 
02441     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
02442       I = nullptr;     // Get the last instruction emitted.
02443       if (CurBB && !CurBB->empty())
02444         I = &CurBB->back();
02445       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
02446                !FunctionBBs[CurBBNo-1]->empty())
02447         I = &FunctionBBs[CurBBNo-1]->back();
02448       if (!I || Record.size() < 4)
02449         return Error(BitcodeError::InvalidRecord);
02450 
02451       unsigned Line = Record[0], Col = Record[1];
02452       unsigned ScopeID = Record[2], IAID = Record[3];
02453 
02454       MDNode *Scope = nullptr, *IA = nullptr;
02455       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
02456       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
02457       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
02458       I->setDebugLoc(LastLoc);
02459       I = nullptr;
02460       continue;
02461     }
02462 
02463     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
02464       unsigned OpNum = 0;
02465       Value *LHS, *RHS;
02466       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
02467           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
02468           OpNum+1 > Record.size())
02469         return Error(BitcodeError::InvalidRecord);
02470 
02471       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
02472       if (Opc == -1)
02473         return Error(BitcodeError::InvalidRecord);
02474       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
02475       InstructionList.push_back(I);
02476       if (OpNum < Record.size()) {
02477         if (Opc == Instruction::Add ||
02478             Opc == Instruction::Sub ||
02479             Opc == Instruction::Mul ||
02480             Opc == Instruction::Shl) {
02481           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
02482             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
02483           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
02484             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
02485         } else if (Opc == Instruction::SDiv ||
02486                    Opc == Instruction::UDiv ||
02487                    Opc == Instruction::LShr ||
02488                    Opc == Instruction::AShr) {
02489           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
02490             cast<BinaryOperator>(I)->setIsExact(true);
02491         } else if (isa<FPMathOperator>(I)) {
02492           FastMathFlags FMF;
02493           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
02494             FMF.setUnsafeAlgebra();
02495           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
02496             FMF.setNoNaNs();
02497           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
02498             FMF.setNoInfs();
02499           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
02500             FMF.setNoSignedZeros();
02501           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
02502             FMF.setAllowReciprocal();
02503           if (FMF.any())
02504             I->setFastMathFlags(FMF);
02505         }
02506 
02507       }
02508       break;
02509     }
02510     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
02511       unsigned OpNum = 0;
02512       Value *Op;
02513       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
02514           OpNum+2 != Record.size())
02515         return Error(BitcodeError::InvalidRecord);
02516 
02517       Type *ResTy = getTypeByID(Record[OpNum]);
02518       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
02519       if (Opc == -1 || !ResTy)
02520         return Error(BitcodeError::InvalidRecord);
02521       Instruction *Temp = nullptr;
02522       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
02523         if (Temp) {
02524           InstructionList.push_back(Temp);
02525           CurBB->getInstList().push_back(Temp);
02526         }
02527       } else {
02528         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
02529       }
02530       InstructionList.push_back(I);
02531       break;
02532     }
02533     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
02534     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
02535       unsigned OpNum = 0;
02536       Value *BasePtr;
02537       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
02538         return Error(BitcodeError::InvalidRecord);
02539 
02540       SmallVector<Value*, 16> GEPIdx;
02541       while (OpNum != Record.size()) {
02542         Value *Op;
02543         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
02544           return Error(BitcodeError::InvalidRecord);
02545         GEPIdx.push_back(Op);
02546       }
02547 
02548       I = GetElementPtrInst::Create(BasePtr, GEPIdx);
02549       InstructionList.push_back(I);
02550       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
02551         cast<GetElementPtrInst>(I)->setIsInBounds(true);
02552       break;
02553     }
02554 
02555     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
02556                                        // EXTRACTVAL: [opty, opval, n x indices]
02557       unsigned OpNum = 0;
02558       Value *Agg;
02559       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
02560         return Error(BitcodeError::InvalidRecord);
02561 
02562       SmallVector<unsigned, 4> EXTRACTVALIdx;
02563       for (unsigned RecSize = Record.size();
02564            OpNum != RecSize; ++OpNum) {
02565         uint64_t Index = Record[OpNum];
02566         if ((unsigned)Index != Index)
02567           return Error(BitcodeError::InvalidValue);
02568         EXTRACTVALIdx.push_back((unsigned)Index);
02569       }
02570 
02571       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
02572       InstructionList.push_back(I);
02573       break;
02574     }
02575 
02576     case bitc::FUNC_CODE_INST_INSERTVAL: {
02577                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
02578       unsigned OpNum = 0;
02579       Value *Agg;
02580       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
02581         return Error(BitcodeError::InvalidRecord);
02582       Value *Val;
02583       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
02584         return Error(BitcodeError::InvalidRecord);
02585 
02586       SmallVector<unsigned, 4> INSERTVALIdx;
02587       for (unsigned RecSize = Record.size();
02588            OpNum != RecSize; ++OpNum) {
02589         uint64_t Index = Record[OpNum];
02590         if ((unsigned)Index != Index)
02591           return Error(BitcodeError::InvalidValue);
02592         INSERTVALIdx.push_back((unsigned)Index);
02593       }
02594 
02595       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
02596       InstructionList.push_back(I);
02597       break;
02598     }
02599 
02600     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
02601       // obsolete form of select
02602       // handles select i1 ... in old bitcode
02603       unsigned OpNum = 0;
02604       Value *TrueVal, *FalseVal, *Cond;
02605       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
02606           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
02607           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
02608         return Error(BitcodeError::InvalidRecord);
02609 
02610       I = SelectInst::Create(Cond, TrueVal, FalseVal);
02611       InstructionList.push_back(I);
02612       break;
02613     }
02614 
02615     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
02616       // new form of select
02617       // handles select i1 or select [N x i1]
02618       unsigned OpNum = 0;
02619       Value *TrueVal, *FalseVal, *Cond;
02620       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
02621           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
02622           getValueTypePair(Record, OpNum, NextValueNo, Cond))
02623         return Error(BitcodeError::InvalidRecord);
02624 
02625       // select condition can be either i1 or [N x i1]
02626       if (VectorType* vector_type =
02627           dyn_cast<VectorType>(Cond->getType())) {
02628         // expect <n x i1>
02629         if (vector_type->getElementType() != Type::getInt1Ty(Context))
02630           return Error(BitcodeError::InvalidTypeForValue);
02631       } else {
02632         // expect i1
02633         if (Cond->getType() != Type::getInt1Ty(Context))
02634           return Error(BitcodeError::InvalidTypeForValue);
02635       }
02636 
02637       I = SelectInst::Create(Cond, TrueVal, FalseVal);
02638       InstructionList.push_back(I);
02639       break;
02640     }
02641 
02642     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
02643       unsigned OpNum = 0;
02644       Value *Vec, *Idx;
02645       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
02646           getValueTypePair(Record, OpNum, NextValueNo, Idx))
02647         return Error(BitcodeError::InvalidRecord);
02648       I = ExtractElementInst::Create(Vec, Idx);
02649       InstructionList.push_back(I);
02650       break;
02651     }
02652 
02653     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
02654       unsigned OpNum = 0;
02655       Value *Vec, *Elt, *Idx;
02656       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
02657           popValue(Record, OpNum, NextValueNo,
02658                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
02659           getValueTypePair(Record, OpNum, NextValueNo, Idx))
02660         return Error(BitcodeError::InvalidRecord);
02661       I = InsertElementInst::Create(Vec, Elt, Idx);
02662       InstructionList.push_back(I);
02663       break;
02664     }
02665 
02666     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
02667       unsigned OpNum = 0;
02668       Value *Vec1, *Vec2, *Mask;
02669       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
02670           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
02671         return Error(BitcodeError::InvalidRecord);
02672 
02673       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
02674         return Error(BitcodeError::InvalidRecord);
02675       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
02676       InstructionList.push_back(I);
02677       break;
02678     }
02679 
02680     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
02681       // Old form of ICmp/FCmp returning bool
02682       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
02683       // both legal on vectors but had different behaviour.
02684     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
02685       // FCmp/ICmp returning bool or vector of bool
02686 
02687       unsigned OpNum = 0;
02688       Value *LHS, *RHS;
02689       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
02690           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
02691           OpNum+1 != Record.size())
02692         return Error(BitcodeError::InvalidRecord);
02693 
02694       if (LHS->getType()->isFPOrFPVectorTy())
02695         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
02696       else
02697         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
02698       InstructionList.push_back(I);
02699       break;
02700     }
02701 
02702     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
02703       {
02704         unsigned Size = Record.size();
02705         if (Size == 0) {
02706           I = ReturnInst::Create(Context);
02707           InstructionList.push_back(I);
02708           break;
02709         }
02710 
02711         unsigned OpNum = 0;
02712         Value *Op = nullptr;
02713         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
02714           return Error(BitcodeError::InvalidRecord);
02715         if (OpNum != Record.size())
02716           return Error(BitcodeError::InvalidRecord);
02717 
02718         I = ReturnInst::Create(Context, Op);
02719         InstructionList.push_back(I);
02720         break;
02721       }
02722     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
02723       if (Record.size() != 1 && Record.size() != 3)
02724         return Error(BitcodeError::InvalidRecord);
02725       BasicBlock *TrueDest = getBasicBlock(Record[0]);
02726       if (!TrueDest)
02727         return Error(BitcodeError::InvalidRecord);
02728 
02729       if (Record.size() == 1) {
02730         I = BranchInst::Create(TrueDest);
02731         InstructionList.push_back(I);
02732       }
02733       else {
02734         BasicBlock *FalseDest = getBasicBlock(Record[1]);
02735         Value *Cond = getValue(Record, 2, NextValueNo,
02736                                Type::getInt1Ty(Context));
02737         if (!FalseDest || !Cond)
02738           return Error(BitcodeError::InvalidRecord);
02739         I = BranchInst::Create(TrueDest, FalseDest, Cond);
02740         InstructionList.push_back(I);
02741       }
02742       break;
02743     }
02744     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
02745       // Check magic
02746       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
02747         // "New" SwitchInst format with case ranges. The changes to write this
02748         // format were reverted but we still recognize bitcode that uses it.
02749         // Hopefully someday we will have support for case ranges and can use
02750         // this format again.
02751 
02752         Type *OpTy = getTypeByID(Record[1]);
02753         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
02754 
02755         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
02756         BasicBlock *Default = getBasicBlock(Record[3]);
02757         if (!OpTy || !Cond || !Default)
02758           return Error(BitcodeError::InvalidRecord);
02759 
02760         unsigned NumCases = Record[4];
02761 
02762         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
02763         InstructionList.push_back(SI);
02764 
02765         unsigned CurIdx = 5;
02766         for (unsigned i = 0; i != NumCases; ++i) {
02767           SmallVector<ConstantInt*, 1> CaseVals;
02768           unsigned NumItems = Record[CurIdx++];
02769           for (unsigned ci = 0; ci != NumItems; ++ci) {
02770             bool isSingleNumber = Record[CurIdx++];
02771 
02772             APInt Low;
02773             unsigned ActiveWords = 1;
02774             if (ValueBitWidth > 64)
02775               ActiveWords = Record[CurIdx++];
02776             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
02777                                 ValueBitWidth);
02778             CurIdx += ActiveWords;
02779 
02780             if (!isSingleNumber) {
02781               ActiveWords = 1;
02782               if (ValueBitWidth > 64)
02783                 ActiveWords = Record[CurIdx++];
02784               APInt High =
02785                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
02786                                 ValueBitWidth);
02787               CurIdx += ActiveWords;
02788 
02789               // FIXME: It is not clear whether values in the range should be
02790               // compared as signed or unsigned values. The partially
02791               // implemented changes that used this format in the past used
02792               // unsigned comparisons.
02793               for ( ; Low.ule(High); ++Low)
02794                 CaseVals.push_back(ConstantInt::get(Context, Low));
02795             } else
02796               CaseVals.push_back(ConstantInt::get(Context, Low));
02797           }
02798           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
02799           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
02800                  cve = CaseVals.end(); cvi != cve; ++cvi)
02801             SI->addCase(*cvi, DestBB);
02802         }
02803         I = SI;
02804         break;
02805       }
02806 
02807       // Old SwitchInst format without case ranges.
02808 
02809       if (Record.size() < 3 || (Record.size() & 1) == 0)
02810         return Error(BitcodeError::InvalidRecord);
02811       Type *OpTy = getTypeByID(Record[0]);
02812       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
02813       BasicBlock *Default = getBasicBlock(Record[2]);
02814       if (!OpTy || !Cond || !Default)
02815         return Error(BitcodeError::InvalidRecord);
02816       unsigned NumCases = (Record.size()-3)/2;
02817       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
02818       InstructionList.push_back(SI);
02819       for (unsigned i = 0, e = NumCases; i != e; ++i) {
02820         ConstantInt *CaseVal =
02821           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
02822         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
02823         if (!CaseVal || !DestBB) {
02824           delete SI;
02825           return Error(BitcodeError::InvalidRecord);
02826         }
02827         SI->addCase(CaseVal, DestBB);
02828       }
02829       I = SI;
02830       break;
02831     }
02832     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
02833       if (Record.size() < 2)
02834         return Error(BitcodeError::InvalidRecord);
02835       Type *OpTy = getTypeByID(Record[0]);
02836       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
02837       if (!OpTy || !Address)
02838         return Error(BitcodeError::InvalidRecord);
02839       unsigned NumDests = Record.size()-2;
02840       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
02841       InstructionList.push_back(IBI);
02842       for (unsigned i = 0, e = NumDests; i != e; ++i) {
02843         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
02844           IBI->addDestination(DestBB);
02845         } else {
02846           delete IBI;
02847           return Error(BitcodeError::InvalidRecord);
02848         }
02849       }
02850       I = IBI;
02851       break;
02852     }
02853 
02854     case bitc::FUNC_CODE_INST_INVOKE: {
02855       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
02856       if (Record.size() < 4)
02857         return Error(BitcodeError::InvalidRecord);
02858       AttributeSet PAL = getAttributes(Record[0]);
02859       unsigned CCInfo = Record[1];
02860       BasicBlock *NormalBB = getBasicBlock(Record[2]);
02861       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
02862 
02863       unsigned OpNum = 4;
02864       Value *Callee;
02865       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
02866         return Error(BitcodeError::InvalidRecord);
02867 
02868       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
02869       FunctionType *FTy = !CalleeTy ? nullptr :
02870         dyn_cast<FunctionType>(CalleeTy->getElementType());
02871 
02872       // Check that the right number of fixed parameters are here.
02873       if (!FTy || !NormalBB || !UnwindBB ||
02874           Record.size() < OpNum+FTy->getNumParams())
02875         return Error(BitcodeError::InvalidRecord);
02876 
02877       SmallVector<Value*, 16> Ops;
02878       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
02879         Ops.push_back(getValue(Record, OpNum, NextValueNo,
02880                                FTy->getParamType(i)));
02881         if (!Ops.back())
02882           return Error(BitcodeError::InvalidRecord);
02883       }
02884 
02885       if (!FTy->isVarArg()) {
02886         if (Record.size() != OpNum)
02887           return Error(BitcodeError::InvalidRecord);
02888       } else {
02889         // Read type/value pairs for varargs params.
02890         while (OpNum != Record.size()) {
02891           Value *Op;
02892           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
02893             return Error(BitcodeError::InvalidRecord);
02894           Ops.push_back(Op);
02895         }
02896       }
02897 
02898       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
02899       InstructionList.push_back(I);
02900       cast<InvokeInst>(I)->setCallingConv(
02901         static_cast<CallingConv::ID>(CCInfo));
02902       cast<InvokeInst>(I)->setAttributes(PAL);
02903       break;
02904     }
02905     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
02906       unsigned Idx = 0;
02907       Value *Val = nullptr;
02908       if (getValueTypePair(Record, Idx, NextValueNo, Val))
02909         return Error(BitcodeError::InvalidRecord);
02910       I = ResumeInst::Create(Val);
02911       InstructionList.push_back(I);
02912       break;
02913     }
02914     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
02915       I = new UnreachableInst(Context);
02916       InstructionList.push_back(I);
02917       break;
02918     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
02919       if (Record.size() < 1 || ((Record.size()-1)&1))
02920         return Error(BitcodeError::InvalidRecord);
02921       Type *Ty = getTypeByID(Record[0]);
02922       if (!Ty)
02923         return Error(BitcodeError::InvalidRecord);
02924 
02925       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
02926       InstructionList.push_back(PN);
02927 
02928       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
02929         Value *V;
02930         // With the new function encoding, it is possible that operands have
02931         // negative IDs (for forward references).  Use a signed VBR
02932         // representation to keep the encoding small.
02933         if (UseRelativeIDs)
02934           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
02935         else
02936           V = getValue(Record, 1+i, NextValueNo, Ty);
02937         BasicBlock *BB = getBasicBlock(Record[2+i]);
02938         if (!V || !BB)
02939           return Error(BitcodeError::InvalidRecord);
02940         PN->addIncoming(V, BB);
02941       }
02942       I = PN;
02943       break;
02944     }
02945 
02946     case bitc::FUNC_CODE_INST_LANDINGPAD: {
02947       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
02948       unsigned Idx = 0;
02949       if (Record.size() < 4)
02950         return Error(BitcodeError::InvalidRecord);
02951       Type *Ty = getTypeByID(Record[Idx++]);
02952       if (!Ty)
02953         return Error(BitcodeError::InvalidRecord);
02954       Value *PersFn = nullptr;
02955       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
02956         return Error(BitcodeError::InvalidRecord);
02957 
02958       bool IsCleanup = !!Record[Idx++];
02959       unsigned NumClauses = Record[Idx++];
02960       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
02961       LP->setCleanup(IsCleanup);
02962       for (unsigned J = 0; J != NumClauses; ++J) {
02963         LandingPadInst::ClauseType CT =
02964           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
02965         Value *Val;
02966 
02967         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
02968           delete LP;
02969           return Error(BitcodeError::InvalidRecord);
02970         }
02971 
02972         assert((CT != LandingPadInst::Catch ||
02973                 !isa<ArrayType>(Val->getType())) &&
02974                "Catch clause has a invalid type!");
02975         assert((CT != LandingPadInst::Filter ||
02976                 isa<ArrayType>(Val->getType())) &&
02977                "Filter clause has invalid type!");
02978         LP->addClause(cast<Constant>(Val));
02979       }
02980 
02981       I = LP;
02982       InstructionList.push_back(I);
02983       break;
02984     }
02985 
02986     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
02987       if (Record.size() != 4)
02988         return Error(BitcodeError::InvalidRecord);
02989       PointerType *Ty =
02990         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
02991       Type *OpTy = getTypeByID(Record[1]);
02992       Value *Size = getFnValueByID(Record[2], OpTy);
02993       unsigned AlignRecord = Record[3];
02994       bool InAlloca = AlignRecord & (1 << 5);
02995       unsigned Align = AlignRecord & ((1 << 5) - 1);
02996       if (!Ty || !Size)
02997         return Error(BitcodeError::InvalidRecord);
02998       AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
02999       AI->setUsedWithInAlloca(InAlloca);
03000       I = AI;
03001       InstructionList.push_back(I);
03002       break;
03003     }
03004     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
03005       unsigned OpNum = 0;
03006       Value *Op;
03007       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
03008           OpNum+2 != Record.size())
03009         return Error(BitcodeError::InvalidRecord);
03010 
03011       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
03012       InstructionList.push_back(I);
03013       break;
03014     }
03015     case bitc::FUNC_CODE_INST_LOADATOMIC: {
03016        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
03017       unsigned OpNum = 0;
03018       Value *Op;
03019       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
03020           OpNum+4 != Record.size())
03021         return Error(BitcodeError::InvalidRecord);
03022 
03023       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
03024       if (Ordering == NotAtomic || Ordering == Release ||
03025           Ordering == AcquireRelease)
03026         return Error(BitcodeError::InvalidRecord);
03027       if (Ordering != NotAtomic && Record[OpNum] == 0)
03028         return Error(BitcodeError::InvalidRecord);
03029       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
03030 
03031       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
03032                        Ordering, SynchScope);
03033       InstructionList.push_back(I);
03034       break;
03035     }
03036     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
03037       unsigned OpNum = 0;
03038       Value *Val, *Ptr;
03039       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03040           popValue(Record, OpNum, NextValueNo,
03041                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
03042           OpNum+2 != Record.size())
03043         return Error(BitcodeError::InvalidRecord);
03044 
03045       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
03046       InstructionList.push_back(I);
03047       break;
03048     }
03049     case bitc::FUNC_CODE_INST_STOREATOMIC: {
03050       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
03051       unsigned OpNum = 0;
03052       Value *Val, *Ptr;
03053       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03054           popValue(Record, OpNum, NextValueNo,
03055                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
03056           OpNum+4 != Record.size())
03057         return Error(BitcodeError::InvalidRecord);
03058 
03059       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
03060       if (Ordering == NotAtomic || Ordering == Acquire ||
03061           Ordering == AcquireRelease)
03062         return Error(BitcodeError::InvalidRecord);
03063       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
03064       if (Ordering != NotAtomic && Record[OpNum] == 0)
03065         return Error(BitcodeError::InvalidRecord);
03066 
03067       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
03068                         Ordering, SynchScope);
03069       InstructionList.push_back(I);
03070       break;
03071     }
03072     case bitc::FUNC_CODE_INST_CMPXCHG: {
03073       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
03074       //          failureordering?, isweak?]
03075       unsigned OpNum = 0;
03076       Value *Ptr, *Cmp, *New;
03077       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03078           popValue(Record, OpNum, NextValueNo,
03079                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
03080           popValue(Record, OpNum, NextValueNo,
03081                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
03082           (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
03083         return Error(BitcodeError::InvalidRecord);
03084       AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
03085       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
03086         return Error(BitcodeError::InvalidRecord);
03087       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
03088 
03089       AtomicOrdering FailureOrdering;
03090       if (Record.size() < 7)
03091         FailureOrdering =
03092             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
03093       else
03094         FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
03095 
03096       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
03097                                 SynchScope);
03098       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
03099 
03100       if (Record.size() < 8) {
03101         // Before weak cmpxchgs existed, the instruction simply returned the
03102         // value loaded from memory, so bitcode files from that era will be
03103         // expecting the first component of a modern cmpxchg.
03104         CurBB->getInstList().push_back(I);
03105         I = ExtractValueInst::Create(I, 0);
03106       } else {
03107         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
03108       }
03109 
03110       InstructionList.push_back(I);
03111       break;
03112     }
03113     case bitc::FUNC_CODE_INST_ATOMICRMW: {
03114       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
03115       unsigned OpNum = 0;
03116       Value *Ptr, *Val;
03117       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03118           popValue(Record, OpNum, NextValueNo,
03119                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
03120           OpNum+4 != Record.size())
03121         return Error(BitcodeError::InvalidRecord);
03122       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
03123       if (Operation < AtomicRMWInst::FIRST_BINOP ||
03124           Operation > AtomicRMWInst::LAST_BINOP)
03125         return Error(BitcodeError::InvalidRecord);
03126       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
03127       if (Ordering == NotAtomic || Ordering == Unordered)
03128         return Error(BitcodeError::InvalidRecord);
03129       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
03130       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
03131       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
03132       InstructionList.push_back(I);
03133       break;
03134     }
03135     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
03136       if (2 != Record.size())
03137         return Error(BitcodeError::InvalidRecord);
03138       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
03139       if (Ordering == NotAtomic || Ordering == Unordered ||
03140           Ordering == Monotonic)
03141         return Error(BitcodeError::InvalidRecord);
03142       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
03143       I = new FenceInst(Context, Ordering, SynchScope);
03144       InstructionList.push_back(I);
03145       break;
03146     }
03147     case bitc::FUNC_CODE_INST_CALL: {
03148       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
03149       if (Record.size() < 3)
03150         return Error(BitcodeError::InvalidRecord);
03151 
03152       AttributeSet PAL = getAttributes(Record[0]);
03153       unsigned CCInfo = Record[1];
03154 
03155       unsigned OpNum = 2;
03156       Value *Callee;
03157       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
03158         return Error(BitcodeError::InvalidRecord);
03159 
03160       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
03161       FunctionType *FTy = nullptr;
03162       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
03163       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
03164         return Error(BitcodeError::InvalidRecord);
03165 
03166       SmallVector<Value*, 16> Args;
03167       // Read the fixed params.
03168       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
03169         if (FTy->getParamType(i)->isLabelTy())
03170           Args.push_back(getBasicBlock(Record[OpNum]));
03171         else
03172           Args.push_back(getValue(Record, OpNum, NextValueNo,
03173                                   FTy->getParamType(i)));
03174         if (!Args.back())
03175           return Error(BitcodeError::InvalidRecord);
03176       }
03177 
03178       // Read type/value pairs for varargs params.
03179       if (!FTy->isVarArg()) {
03180         if (OpNum != Record.size())
03181           return Error(BitcodeError::InvalidRecord);
03182       } else {
03183         while (OpNum != Record.size()) {
03184           Value *Op;
03185           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
03186             return Error(BitcodeError::InvalidRecord);
03187           Args.push_back(Op);
03188         }
03189       }
03190 
03191       I = CallInst::Create(Callee, Args);
03192       InstructionList.push_back(I);
03193       cast<CallInst>(I)->setCallingConv(
03194           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
03195       CallInst::TailCallKind TCK = CallInst::TCK_None;
03196       if (CCInfo & 1)
03197         TCK = CallInst::TCK_Tail;
03198       if (CCInfo & (1 << 14))
03199         TCK = CallInst::TCK_MustTail;
03200       cast<CallInst>(I)->setTailCallKind(TCK);
03201       cast<CallInst>(I)->setAttributes(PAL);
03202       break;
03203     }
03204     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
03205       if (Record.size() < 3)
03206         return Error(BitcodeError::InvalidRecord);
03207       Type *OpTy = getTypeByID(Record[0]);
03208       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
03209       Type *ResTy = getTypeByID(Record[2]);
03210       if (!OpTy || !Op || !ResTy)
03211         return Error(BitcodeError::InvalidRecord);
03212       I = new VAArgInst(Op, ResTy);
03213       InstructionList.push_back(I);
03214       break;
03215     }
03216     }
03217 
03218     // Add instruction to end of current BB.  If there is no current BB, reject
03219     // this file.
03220     if (!CurBB) {
03221       delete I;
03222       return Error(BitcodeError::InvalidInstructionWithNoBB);
03223     }
03224     CurBB->getInstList().push_back(I);
03225 
03226     // If this was a terminator instruction, move to the next block.
03227     if (isa<TerminatorInst>(I)) {
03228       ++CurBBNo;
03229       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
03230     }
03231 
03232     // Non-void values get registered in the value table for future use.
03233     if (I && !I->getType()->isVoidTy())
03234       ValueList.AssignValue(I, NextValueNo++);
03235   }
03236 
03237 OutOfRecordLoop:
03238 
03239   // Check the function list for unresolved values.
03240   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
03241     if (!A->getParent()) {
03242       // We found at least one unresolved value.  Nuke them all to avoid leaks.
03243       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
03244         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
03245           A->replaceAllUsesWith(UndefValue::get(A->getType()));
03246           delete A;
03247         }
03248       }
03249       return Error(BitcodeError::NeverResolvedValueFoundInFunction);
03250     }
03251   }
03252 
03253   // FIXME: Check for unresolved forward-declared metadata references
03254   // and clean up leaks.
03255 
03256   // Trim the value list down to the size it was before we parsed this function.
03257   ValueList.shrinkTo(ModuleValueListSize);
03258   MDValueList.shrinkTo(ModuleMDValueListSize);
03259   std::vector<BasicBlock*>().swap(FunctionBBs);
03260   return std::error_code();
03261 }
03262 
03263 /// Find the function body in the bitcode stream
03264 std::error_code BitcodeReader::FindFunctionInStream(
03265     Function *F,
03266     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
03267   while (DeferredFunctionInfoIterator->second == 0) {
03268     if (Stream.AtEndOfStream())
03269       return Error(BitcodeError::CouldNotFindFunctionInStream);
03270     // ParseModule will parse the next body in the stream and set its
03271     // position in the DeferredFunctionInfo map.
03272     if (std::error_code EC = ParseModule(true))
03273       return EC;
03274   }
03275   return std::error_code();
03276 }
03277 
03278 //===----------------------------------------------------------------------===//
03279 // GVMaterializer implementation
03280 //===----------------------------------------------------------------------===//
03281 
03282 void BitcodeReader::releaseBuffer() { Buffer.release(); }
03283 
03284 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
03285   if (const Function *F = dyn_cast<Function>(GV)) {
03286     return F->isDeclaration() &&
03287       DeferredFunctionInfo.count(const_cast<Function*>(F));
03288   }
03289   return false;
03290 }
03291 
03292 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
03293   Function *F = dyn_cast<Function>(GV);
03294   // If it's not a function or is already material, ignore the request.
03295   if (!F || !F->isMaterializable())
03296     return std::error_code();
03297 
03298   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
03299   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
03300   // If its position is recorded as 0, its body is somewhere in the stream
03301   // but we haven't seen it yet.
03302   if (DFII->second == 0 && LazyStreamer)
03303     if (std::error_code EC = FindFunctionInStream(F, DFII))
03304       return EC;
03305 
03306   // Move the bit stream to the saved position of the deferred function body.
03307   Stream.JumpToBit(DFII->second);
03308 
03309   if (std::error_code EC = ParseFunctionBody(F))
03310     return EC;
03311 
03312   // Upgrade any old intrinsic calls in the function.
03313   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
03314        E = UpgradedIntrinsics.end(); I != E; ++I) {
03315     if (I->first != I->second) {
03316       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
03317            UI != UE;) {
03318         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
03319           UpgradeIntrinsicCall(CI, I->second);
03320       }
03321     }
03322   }
03323 
03324   // Bring in any functions that this function forward-referenced via
03325   // blockaddresses.
03326   return materializeForwardReferencedFunctions();
03327 }
03328 
03329 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
03330   const Function *F = dyn_cast<Function>(GV);
03331   if (!F || F->isDeclaration())
03332     return false;
03333 
03334   // Dematerializing F would leave dangling references that wouldn't be
03335   // reconnected on re-materialization.
03336   if (BlockAddressesTaken.count(F))
03337     return false;
03338 
03339   return DeferredFunctionInfo.count(const_cast<Function*>(F));
03340 }
03341 
03342 void BitcodeReader::Dematerialize(GlobalValue *GV) {
03343   Function *F = dyn_cast<Function>(GV);
03344   // If this function isn't dematerializable, this is a noop.
03345   if (!F || !isDematerializable(F))
03346     return;
03347 
03348   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
03349 
03350   // Just forget the function body, we can remat it later.
03351   F->dropAllReferences();
03352 }
03353 
03354 std::error_code BitcodeReader::MaterializeModule(Module *M) {
03355   assert(M == TheModule &&
03356          "Can only Materialize the Module this BitcodeReader is attached to.");
03357 
03358   // Promise to materialize all forward references.
03359   WillMaterializeAllForwardRefs = true;
03360 
03361   // Iterate over the module, deserializing any functions that are still on
03362   // disk.
03363   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
03364        F != E; ++F) {
03365     if (F->isMaterializable()) {
03366       if (std::error_code EC = Materialize(F))
03367         return EC;
03368     }
03369   }
03370   // At this point, if there are any function bodies, the current bit is
03371   // pointing to the END_BLOCK record after them. Now make sure the rest
03372   // of the bits in the module have been read.
03373   if (NextUnreadBit)
03374     ParseModule(true);
03375 
03376   // Check that all block address forward references got resolved (as we
03377   // promised above).
03378   if (!BasicBlockFwdRefs.empty())
03379     return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
03380 
03381   // Upgrade any intrinsic calls that slipped through (should not happen!) and
03382   // delete the old functions to clean up. We can't do this unless the entire
03383   // module is materialized because there could always be another function body
03384   // with calls to the old function.
03385   for (std::vector<std::pair<Function*, Function*> >::iterator I =
03386        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
03387     if (I->first != I->second) {
03388       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
03389            UI != UE;) {
03390         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
03391           UpgradeIntrinsicCall(CI, I->second);
03392       }
03393       if (!I->first->use_empty())
03394         I->first->replaceAllUsesWith(I->second);
03395       I->first->eraseFromParent();
03396     }
03397   }
03398   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
03399 
03400   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
03401     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
03402 
03403   UpgradeDebugInfo(*M);
03404   return std::error_code();
03405 }
03406 
03407 std::error_code BitcodeReader::InitStream() {
03408   if (LazyStreamer)
03409     return InitLazyStream();
03410   return InitStreamFromBuffer();
03411 }
03412 
03413 std::error_code BitcodeReader::InitStreamFromBuffer() {
03414   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
03415   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
03416 
03417   if (Buffer->getBufferSize() & 3)
03418     return Error(BitcodeError::InvalidBitcodeSignature);
03419 
03420   // If we have a wrapper header, parse it and ignore the non-bc file contents.
03421   // The magic number is 0x0B17C0DE stored in little endian.
03422   if (isBitcodeWrapper(BufPtr, BufEnd))
03423     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
03424       return Error(BitcodeError::InvalidBitcodeWrapperHeader);
03425 
03426   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
03427   Stream.init(*StreamFile);
03428 
03429   return std::error_code();
03430 }
03431 
03432 std::error_code BitcodeReader::InitLazyStream() {
03433   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
03434   // see it.
03435   StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
03436   StreamFile.reset(new BitstreamReader(Bytes));
03437   Stream.init(*StreamFile);
03438 
03439   unsigned char buf[16];
03440   if (Bytes->readBytes(0, 16, buf) == -1)
03441     return Error(BitcodeError::InvalidBitcodeSignature);
03442 
03443   if (!isBitcode(buf, buf + 16))
03444     return Error(BitcodeError::InvalidBitcodeSignature);
03445 
03446   if (isBitcodeWrapper(buf, buf + 4)) {
03447     const unsigned char *bitcodeStart = buf;
03448     const unsigned char *bitcodeEnd = buf + 16;
03449     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
03450     Bytes->dropLeadingBytes(bitcodeStart - buf);
03451     Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
03452   }
03453   return std::error_code();
03454 }
03455 
03456 namespace {
03457 class BitcodeErrorCategoryType : public std::error_category {
03458   const char *name() const LLVM_NOEXCEPT override {
03459     return "llvm.bitcode";
03460   }
03461   std::string message(int IE) const override {
03462     BitcodeError E = static_cast<BitcodeError>(IE);
03463     switch (E) {
03464     case BitcodeError::ConflictingMETADATA_KINDRecords:
03465       return "Conflicting METADATA_KIND records";
03466     case BitcodeError::CouldNotFindFunctionInStream:
03467       return "Could not find function in stream";
03468     case BitcodeError::ExpectedConstant:
03469       return "Expected a constant";
03470     case BitcodeError::InsufficientFunctionProtos:
03471       return "Insufficient function protos";
03472     case BitcodeError::InvalidBitcodeSignature:
03473       return "Invalid bitcode signature";
03474     case BitcodeError::InvalidBitcodeWrapperHeader:
03475       return "Invalid bitcode wrapper header";
03476     case BitcodeError::InvalidConstantReference:
03477       return "Invalid ronstant reference";
03478     case BitcodeError::InvalidID:
03479       return "Invalid ID";
03480     case BitcodeError::InvalidInstructionWithNoBB:
03481       return "Invalid instruction with no BB";
03482     case BitcodeError::InvalidRecord:
03483       return "Invalid record";
03484     case BitcodeError::InvalidTypeForValue:
03485       return "Invalid type for value";
03486     case BitcodeError::InvalidTYPETable:
03487       return "Invalid TYPE table";
03488     case BitcodeError::InvalidType:
03489       return "Invalid type";
03490     case BitcodeError::MalformedBlock:
03491       return "Malformed block";
03492     case BitcodeError::MalformedGlobalInitializerSet:
03493       return "Malformed global initializer set";
03494     case BitcodeError::InvalidMultipleBlocks:
03495       return "Invalid multiple blocks";
03496     case BitcodeError::NeverResolvedValueFoundInFunction:
03497       return "Never resolved value found in function";
03498     case BitcodeError::NeverResolvedFunctionFromBlockAddress:
03499       return "Never resolved function from blockaddress";
03500     case BitcodeError::InvalidValue:
03501       return "Invalid value";
03502     }
03503     llvm_unreachable("Unknown error type!");
03504   }
03505 };
03506 }
03507 
03508 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
03509 
03510 const std::error_category &llvm::BitcodeErrorCategory() {
03511   return *ErrorCategory;
03512 }
03513 
03514 //===----------------------------------------------------------------------===//
03515 // External interface
03516 //===----------------------------------------------------------------------===//
03517 
03518 /// \brief Get a lazy one-at-time loading module from bitcode.
03519 ///
03520 /// This isn't always used in a lazy context.  In particular, it's also used by
03521 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
03522 /// in forward-referenced functions from block address references.
03523 ///
03524 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
03525 /// materialize everything -- in particular, if this isn't truly lazy.
03526 static ErrorOr<Module *>
03527 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
03528                          LLVMContext &Context, bool WillMaterializeAll) {
03529   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
03530   BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
03531   M->setMaterializer(R);
03532 
03533   auto cleanupOnError = [&](std::error_code EC) {
03534     R->releaseBuffer(); // Never take ownership on error.
03535     delete M;  // Also deletes R.
03536     return EC;
03537   };
03538 
03539   if (std::error_code EC = R->ParseBitcodeInto(M))
03540     return cleanupOnError(EC);
03541 
03542   if (!WillMaterializeAll)
03543     // Resolve forward references from blockaddresses.
03544     if (std::error_code EC = R->materializeForwardReferencedFunctions())
03545       return cleanupOnError(EC);
03546 
03547   Buffer.release(); // The BitcodeReader owns it now.
03548   return M;
03549 }
03550 
03551 ErrorOr<Module *>
03552 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
03553                            LLVMContext &Context) {
03554   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
03555 }
03556 
03557 Module *llvm::getStreamedBitcodeModule(const std::string &name,
03558                                        DataStreamer *streamer,
03559                                        LLVMContext &Context,
03560                                        std::string *ErrMsg) {
03561   Module *M = new Module(name, Context);
03562   BitcodeReader *R = new BitcodeReader(streamer, Context);
03563   M->setMaterializer(R);
03564   if (std::error_code EC = R->ParseBitcodeInto(M)) {
03565     if (ErrMsg)
03566       *ErrMsg = EC.message();
03567     delete M;  // Also deletes R.
03568     return nullptr;
03569   }
03570   return M;
03571 }
03572 
03573 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
03574                                          LLVMContext &Context) {
03575   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
03576   ErrorOr<Module *> ModuleOrErr =
03577       getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
03578   if (!ModuleOrErr)
03579     return ModuleOrErr;
03580   Module *M = ModuleOrErr.get();
03581   // Read in the entire module, and destroy the BitcodeReader.
03582   if (std::error_code EC = M->materializeAllPermanently()) {
03583     delete M;
03584     return EC;
03585   }
03586 
03587   // TODO: Restore the use-lists to the in-memory state when the bitcode was
03588   // written.  We must defer until the Module has been fully materialized.
03589 
03590   return M;
03591 }
03592 
03593 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
03594                                          LLVMContext &Context) {
03595   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
03596   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
03597   ErrorOr<std::string> Triple = R->parseTriple();
03598   if (Triple.getError())
03599     return "";
03600   return Triple.get();
03601 }