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