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