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