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