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