LLVM API Documentation

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