Home | History | Annotate | Download | only in BitReader_3_0
      1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This header defines the BitcodeReader class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "llvm/Bitcode/ReaderWriter.h"
     15 #include "BitReader_3_0.h"
     16 #include "llvm/ADT/STLExtras.h"
     17 #include "llvm/ADT/SmallString.h"
     18 #include "llvm/ADT/SmallVector.h"
     19 #include "llvm/IR/AutoUpgrade.h"
     20 #include "llvm/IR/Constants.h"
     21 #include "llvm/IR/CFG.h"
     22 #include "llvm/IR/DerivedTypes.h"
     23 #include "llvm/IR/DiagnosticPrinter.h"
     24 #include "llvm/IR/GVMaterializer.h"
     25 #include "llvm/IR/InlineAsm.h"
     26 #include "llvm/IR/IntrinsicInst.h"
     27 #include "llvm/IR/IRBuilder.h"
     28 #include "llvm/IR/LLVMContext.h"
     29 #include "llvm/IR/Module.h"
     30 #include "llvm/IR/OperandTraits.h"
     31 #include "llvm/IR/Operator.h"
     32 #include "llvm/ADT/SmallPtrSet.h"
     33 #include "llvm/Support/ManagedStatic.h"
     34 #include "llvm/Support/MathExtras.h"
     35 #include "llvm/Support/MemoryBuffer.h"
     36 
     37 using namespace llvm;
     38 using namespace llvm_3_0;
     39 
     40 #define FUNC_CODE_INST_UNWIND_2_7     14
     41 #define eh_exception_2_7             145
     42 #define eh_selector_2_7              149
     43 
     44 #define TYPE_BLOCK_ID_OLD_3_0         10
     45 #define TYPE_SYMTAB_BLOCK_ID_OLD_3_0  13
     46 #define TYPE_CODE_STRUCT_OLD_3_0      10
     47 
     48 namespace {
     49   void FindExnAndSelIntrinsics(BasicBlock *BB, CallInst *&Exn,
     50                                       CallInst *&Sel,
     51                                       SmallPtrSet<BasicBlock*, 8> &Visited) {
     52     if (!Visited.insert(BB).second) return;
     53 
     54     for (BasicBlock::iterator
     55            I = BB->begin(), E = BB->end(); I != E; ++I) {
     56       if (CallInst *CI = dyn_cast<CallInst>(I)) {
     57         switch (CI->getCalledFunction()->getIntrinsicID()) {
     58         default: break;
     59         case eh_exception_2_7:
     60           assert(!Exn && "Found more than one eh.exception call!");
     61           Exn = CI;
     62           break;
     63         case eh_selector_2_7:
     64           assert(!Sel && "Found more than one eh.selector call!");
     65           Sel = CI;
     66           break;
     67         }
     68 
     69         if (Exn && Sel) return;
     70       }
     71     }
     72 
     73     if (Exn && Sel) return;
     74 
     75     for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
     76       FindExnAndSelIntrinsics(*I, Exn, Sel, Visited);
     77       if (Exn && Sel) return;
     78     }
     79   }
     80 
     81 
     82 
     83   /// TransferClausesToLandingPadInst - Transfer the exception handling clauses
     84   /// from the eh_selector call to the new landingpad instruction.
     85   void TransferClausesToLandingPadInst(LandingPadInst *LPI,
     86                                               CallInst *EHSel) {
     87     LLVMContext &Context = LPI->getContext();
     88     unsigned N = EHSel->getNumArgOperands();
     89 
     90     for (unsigned i = N - 1; i > 1; --i) {
     91       if (const ConstantInt *CI = dyn_cast<ConstantInt>(EHSel->getArgOperand(i))){
     92         unsigned FilterLength = CI->getZExtValue();
     93         unsigned FirstCatch = i + FilterLength + !FilterLength;
     94         assert(FirstCatch <= N && "Invalid filter length");
     95 
     96         if (FirstCatch < N)
     97           for (unsigned j = FirstCatch; j < N; ++j) {
     98             Value *Val = EHSel->getArgOperand(j);
     99             if (!Val->hasName() || Val->getName() != "llvm.eh.catch.all.value") {
    100               LPI->addClause(cast<Constant>(EHSel->getArgOperand(j)));
    101             } else {
    102               GlobalVariable *GV = cast<GlobalVariable>(Val);
    103               LPI->addClause(GV->getInitializer());
    104             }
    105           }
    106 
    107         if (!FilterLength) {
    108           // Cleanup.
    109           LPI->setCleanup(true);
    110         } else {
    111           // Filter.
    112           SmallVector<Constant *, 4> TyInfo;
    113           TyInfo.reserve(FilterLength - 1);
    114           for (unsigned j = i + 1; j < FirstCatch; ++j)
    115             TyInfo.push_back(cast<Constant>(EHSel->getArgOperand(j)));
    116           ArrayType *AType =
    117             ArrayType::get(!TyInfo.empty() ? TyInfo[0]->getType() :
    118                            PointerType::getUnqual(Type::getInt8Ty(Context)),
    119                            TyInfo.size());
    120           LPI->addClause(ConstantArray::get(AType, TyInfo));
    121         }
    122 
    123         N = i;
    124       }
    125     }
    126 
    127     if (N > 2)
    128       for (unsigned j = 2; j < N; ++j) {
    129         Value *Val = EHSel->getArgOperand(j);
    130         if (!Val->hasName() || Val->getName() != "llvm.eh.catch.all.value") {
    131           LPI->addClause(cast<Constant>(EHSel->getArgOperand(j)));
    132         } else {
    133           GlobalVariable *GV = cast<GlobalVariable>(Val);
    134           LPI->addClause(GV->getInitializer());
    135         }
    136       }
    137   }
    138 
    139 
    140   /// This function upgrades the old pre-3.0 exception handling system to the new
    141   /// one. N.B. This will be removed in 3.1.
    142   void UpgradeExceptionHandling(Module *M) {
    143     Function *EHException = M->getFunction("llvm.eh.exception");
    144     Function *EHSelector = M->getFunction("llvm.eh.selector");
    145     if (!EHException || !EHSelector)
    146       return;
    147 
    148     LLVMContext &Context = M->getContext();
    149     Type *ExnTy = PointerType::getUnqual(Type::getInt8Ty(Context));
    150     Type *SelTy = Type::getInt32Ty(Context);
    151     Type *LPadSlotTy = StructType::get(ExnTy, SelTy, nullptr);
    152 
    153     // This map links the invoke instruction with the eh.exception and eh.selector
    154     // calls associated with it.
    155     DenseMap<InvokeInst*, std::pair<Value*, Value*> > InvokeToIntrinsicsMap;
    156     for (Module::iterator
    157            I = M->begin(), E = M->end(); I != E; ++I) {
    158       Function &F = *I;
    159 
    160       for (Function::iterator
    161              II = F.begin(), IE = F.end(); II != IE; ++II) {
    162         BasicBlock *BB = &*II;
    163         InvokeInst *Inst = dyn_cast<InvokeInst>(BB->getTerminator());
    164         if (!Inst) continue;
    165         BasicBlock *UnwindDest = Inst->getUnwindDest();
    166         if (UnwindDest->isLandingPad()) continue; // Already converted.
    167 
    168         SmallPtrSet<BasicBlock*, 8> Visited;
    169         CallInst *Exn = 0;
    170         CallInst *Sel = 0;
    171         FindExnAndSelIntrinsics(UnwindDest, Exn, Sel, Visited);
    172         assert(Exn && Sel && "Cannot find eh.exception and eh.selector calls!");
    173         InvokeToIntrinsicsMap[Inst] = std::make_pair(Exn, Sel);
    174       }
    175     }
    176 
    177     // This map stores the slots where the exception object and selector value are
    178     // stored within a function.
    179     DenseMap<Function*, std::pair<Value*, Value*> > FnToLPadSlotMap;
    180     SmallPtrSet<Instruction*, 32> DeadInsts;
    181     for (DenseMap<InvokeInst*, std::pair<Value*, Value*> >::iterator
    182            I = InvokeToIntrinsicsMap.begin(), E = InvokeToIntrinsicsMap.end();
    183          I != E; ++I) {
    184       InvokeInst *Invoke = I->first;
    185       BasicBlock *UnwindDest = Invoke->getUnwindDest();
    186       Function *F = UnwindDest->getParent();
    187       std::pair<Value*, Value*> EHIntrinsics = I->second;
    188       CallInst *Exn = cast<CallInst>(EHIntrinsics.first);
    189       CallInst *Sel = cast<CallInst>(EHIntrinsics.second);
    190 
    191       // Store the exception object and selector value in the entry block.
    192       Value *ExnSlot = 0;
    193       Value *SelSlot = 0;
    194       if (!FnToLPadSlotMap[F].first) {
    195         BasicBlock *Entry = &F->front();
    196         ExnSlot = new AllocaInst(ExnTy, "exn", Entry->getTerminator());
    197         SelSlot = new AllocaInst(SelTy, "sel", Entry->getTerminator());
    198         FnToLPadSlotMap[F] = std::make_pair(ExnSlot, SelSlot);
    199       } else {
    200         ExnSlot = FnToLPadSlotMap[F].first;
    201         SelSlot = FnToLPadSlotMap[F].second;
    202       }
    203 
    204       if (!UnwindDest->getSinglePredecessor()) {
    205         // The unwind destination doesn't have a single predecessor. Create an
    206         // unwind destination which has only one predecessor.
    207         BasicBlock *NewBB = BasicBlock::Create(Context, "new.lpad",
    208                                                UnwindDest->getParent());
    209         BranchInst::Create(UnwindDest, NewBB);
    210         Invoke->setUnwindDest(NewBB);
    211 
    212         // Fix up any PHIs in the original unwind destination block.
    213         for (BasicBlock::iterator
    214                II = UnwindDest->begin(); isa<PHINode>(II); ++II) {
    215           PHINode *PN = cast<PHINode>(II);
    216           int Idx = PN->getBasicBlockIndex(Invoke->getParent());
    217           if (Idx == -1) continue;
    218           PN->setIncomingBlock(Idx, NewBB);
    219         }
    220 
    221         UnwindDest = NewBB;
    222       }
    223 
    224       IRBuilder<> Builder(Context);
    225       Builder.SetInsertPoint(UnwindDest, UnwindDest->getFirstInsertionPt());
    226 
    227       LandingPadInst *LPI = Builder.CreateLandingPad(LPadSlotTy, 0);
    228       Value *LPExn = Builder.CreateExtractValue(LPI, 0);
    229       Value *LPSel = Builder.CreateExtractValue(LPI, 1);
    230       Builder.CreateStore(LPExn, ExnSlot);
    231       Builder.CreateStore(LPSel, SelSlot);
    232 
    233       TransferClausesToLandingPadInst(LPI, Sel);
    234 
    235       DeadInsts.insert(Exn);
    236       DeadInsts.insert(Sel);
    237     }
    238 
    239     // Replace the old intrinsic calls with the values from the landingpad
    240     // instruction(s). These values were stored in allocas for us to use here.
    241     for (DenseMap<InvokeInst*, std::pair<Value*, Value*> >::iterator
    242            I = InvokeToIntrinsicsMap.begin(), E = InvokeToIntrinsicsMap.end();
    243          I != E; ++I) {
    244       std::pair<Value*, Value*> EHIntrinsics = I->second;
    245       CallInst *Exn = cast<CallInst>(EHIntrinsics.first);
    246       CallInst *Sel = cast<CallInst>(EHIntrinsics.second);
    247       BasicBlock *Parent = Exn->getParent();
    248 
    249       std::pair<Value*,Value*> ExnSelSlots = FnToLPadSlotMap[Parent->getParent()];
    250 
    251       IRBuilder<> Builder(Context);
    252       Builder.SetInsertPoint(Parent, Exn->getIterator());
    253       LoadInst *LPExn = Builder.CreateLoad(ExnSelSlots.first, "exn.load");
    254       LoadInst *LPSel = Builder.CreateLoad(ExnSelSlots.second, "sel.load");
    255 
    256       Exn->replaceAllUsesWith(LPExn);
    257       Sel->replaceAllUsesWith(LPSel);
    258     }
    259 
    260     // Remove the dead instructions.
    261     for (SmallPtrSet<Instruction*, 32>::iterator
    262            I = DeadInsts.begin(), E = DeadInsts.end(); I != E; ++I) {
    263       Instruction *Inst = *I;
    264       Inst->eraseFromParent();
    265     }
    266 
    267     // Replace calls to "llvm.eh.resume" with the 'resume' instruction. Load the
    268     // exception and selector values from the stored place.
    269     Function *EHResume = M->getFunction("llvm.eh.resume");
    270     if (!EHResume) return;
    271 
    272     while (!EHResume->use_empty()) {
    273       CallInst *Resume = cast<CallInst>(*EHResume->use_begin());
    274       BasicBlock *BB = Resume->getParent();
    275 
    276       IRBuilder<> Builder(Context);
    277       Builder.SetInsertPoint(BB, Resume->getIterator());
    278 
    279       Value *LPadVal =
    280         Builder.CreateInsertValue(UndefValue::get(LPadSlotTy),
    281                                   Resume->getArgOperand(0), 0, "lpad.val");
    282       LPadVal = Builder.CreateInsertValue(LPadVal, Resume->getArgOperand(1),
    283                                           1, "lpad.val");
    284       Builder.CreateResume(LPadVal);
    285 
    286       // Remove all instructions after the 'resume.'
    287       BasicBlock::iterator I = Resume->getIterator();
    288       while (I != BB->end()) {
    289         Instruction *Inst = &*I++;
    290         Inst->eraseFromParent();
    291       }
    292     }
    293   }
    294 
    295 
    296   void StripDebugInfoOfFunction(Module* M, const char* name) {
    297     if (Function* FuncStart = M->getFunction(name)) {
    298       while (!FuncStart->use_empty()) {
    299         cast<CallInst>(*FuncStart->use_begin())->eraseFromParent();
    300       }
    301       FuncStart->eraseFromParent();
    302     }
    303   }
    304 
    305   /// This function strips all debug info intrinsics, except for llvm.dbg.declare.
    306   /// If an llvm.dbg.declare intrinsic is invalid, then this function simply
    307   /// strips that use.
    308   void CheckDebugInfoIntrinsics(Module *M) {
    309     StripDebugInfoOfFunction(M, "llvm.dbg.func.start");
    310     StripDebugInfoOfFunction(M, "llvm.dbg.stoppoint");
    311     StripDebugInfoOfFunction(M, "llvm.dbg.region.start");
    312     StripDebugInfoOfFunction(M, "llvm.dbg.region.end");
    313 
    314     if (Function *Declare = M->getFunction("llvm.dbg.declare")) {
    315       if (!Declare->use_empty()) {
    316         DbgDeclareInst *DDI = cast<DbgDeclareInst>(*Declare->use_begin());
    317         if (!isa<MDNode>(ValueAsMetadata::get(DDI->getArgOperand(0))) ||
    318             !isa<MDNode>(ValueAsMetadata::get(DDI->getArgOperand(1)))) {
    319           while (!Declare->use_empty()) {
    320             CallInst *CI = cast<CallInst>(*Declare->use_begin());
    321             CI->eraseFromParent();
    322           }
    323           Declare->eraseFromParent();
    324         }
    325       }
    326     }
    327   }
    328 
    329 
    330 //===----------------------------------------------------------------------===//
    331 //                          BitcodeReaderValueList Class
    332 //===----------------------------------------------------------------------===//
    333 
    334 class BitcodeReaderValueList {
    335   std::vector<WeakVH> ValuePtrs;
    336 
    337   /// ResolveConstants - As we resolve forward-referenced constants, we add
    338   /// information about them to this vector.  This allows us to resolve them in
    339   /// bulk instead of resolving each reference at a time.  See the code in
    340   /// ResolveConstantForwardRefs for more information about this.
    341   ///
    342   /// The key of this vector is the placeholder constant, the value is the slot
    343   /// number that holds the resolved value.
    344   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
    345   ResolveConstantsTy ResolveConstants;
    346   LLVMContext &Context;
    347 public:
    348   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
    349   ~BitcodeReaderValueList() {
    350     assert(ResolveConstants.empty() && "Constants not resolved?");
    351   }
    352 
    353   // vector compatibility methods
    354   unsigned size() const { return ValuePtrs.size(); }
    355   void resize(unsigned N) { ValuePtrs.resize(N); }
    356   void push_back(Value *V) {
    357     ValuePtrs.push_back(V);
    358   }
    359 
    360   void clear() {
    361     assert(ResolveConstants.empty() && "Constants not resolved?");
    362     ValuePtrs.clear();
    363   }
    364 
    365   Value *operator[](unsigned i) const {
    366     assert(i < ValuePtrs.size());
    367     return ValuePtrs[i];
    368   }
    369 
    370   Value *back() const { return ValuePtrs.back(); }
    371     void pop_back() { ValuePtrs.pop_back(); }
    372   bool empty() const { return ValuePtrs.empty(); }
    373   void shrinkTo(unsigned N) {
    374     assert(N <= size() && "Invalid shrinkTo request!");
    375     ValuePtrs.resize(N);
    376   }
    377 
    378   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
    379   Value *getValueFwdRef(unsigned Idx, Type *Ty);
    380 
    381   void AssignValue(Value *V, unsigned Idx);
    382 
    383   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
    384   /// resolves any forward references.
    385   void ResolveConstantForwardRefs();
    386 };
    387 
    388 
    389 //===----------------------------------------------------------------------===//
    390 //                          BitcodeReaderMDValueList Class
    391 //===----------------------------------------------------------------------===//
    392 
    393 class BitcodeReaderMDValueList {
    394   unsigned NumFwdRefs;
    395   bool AnyFwdRefs;
    396   std::vector<TrackingMDRef> MDValuePtrs;
    397 
    398   LLVMContext &Context;
    399 public:
    400   BitcodeReaderMDValueList(LLVMContext &C)
    401       : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
    402 
    403   // vector compatibility methods
    404   unsigned size() const       { return MDValuePtrs.size(); }
    405   void resize(unsigned N)     { MDValuePtrs.resize(N); }
    406   void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
    407   void clear()                { MDValuePtrs.clear();  }
    408   Metadata *back() const      { return MDValuePtrs.back(); }
    409   void pop_back()             { MDValuePtrs.pop_back(); }
    410   bool empty() const          { return MDValuePtrs.empty(); }
    411 
    412   Metadata *operator[](unsigned i) const {
    413     assert(i < MDValuePtrs.size());
    414     return MDValuePtrs[i];
    415   }
    416 
    417   void shrinkTo(unsigned N) {
    418     assert(N <= size() && "Invalid shrinkTo request!");
    419     MDValuePtrs.resize(N);
    420   }
    421 
    422   Metadata *getValueFwdRef(unsigned Idx);
    423   void AssignValue(Metadata *MD, unsigned Idx);
    424   void tryToResolveCycles();
    425 };
    426 
    427 class BitcodeReader : public GVMaterializer {
    428   LLVMContext &Context;
    429   DiagnosticHandlerFunction DiagnosticHandler;
    430   Module *TheModule;
    431   std::unique_ptr<MemoryBuffer> Buffer;
    432   std::unique_ptr<BitstreamReader> StreamFile;
    433   BitstreamCursor Stream;
    434   std::unique_ptr<DataStreamer> LazyStreamer;
    435   uint64_t NextUnreadBit;
    436   bool SeenValueSymbolTable;
    437 
    438   std::vector<Type*> TypeList;
    439   BitcodeReaderValueList ValueList;
    440   BitcodeReaderMDValueList MDValueList;
    441   SmallVector<Instruction *, 64> InstructionList;
    442 
    443   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
    444   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
    445 
    446   /// MAttributes - The set of attributes by index.  Index zero in the
    447   /// file is for null, and is thus not represented here.  As such all indices
    448   /// are off by one.
    449   std::vector<AttributeSet> MAttributes;
    450 
    451   /// \brief The set of attribute groups.
    452   std::map<unsigned, AttributeSet> MAttributeGroups;
    453 
    454   /// FunctionBBs - While parsing a function body, this is a list of the basic
    455   /// blocks for the function.
    456   std::vector<BasicBlock*> FunctionBBs;
    457 
    458   // When reading the module header, this list is populated with functions that
    459   // have bodies later in the file.
    460   std::vector<Function*> FunctionsWithBodies;
    461 
    462   // When intrinsic functions are encountered which require upgrading they are
    463   // stored here with their replacement function.
    464   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
    465   UpgradedIntrinsicMap UpgradedIntrinsics;
    466 
    467   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
    468   DenseMap<unsigned, unsigned> MDKindMap;
    469 
    470   // Several operations happen after the module header has been read, but
    471   // before function bodies are processed. This keeps track of whether
    472   // we've done this yet.
    473   bool SeenFirstFunctionBody;
    474 
    475   /// DeferredFunctionInfo - When function bodies are initially scanned, this
    476   /// map contains info about where to find deferred function body in the
    477   /// stream.
    478   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
    479 
    480   /// BlockAddrFwdRefs - These are blockaddr references to basic blocks.  These
    481   /// are resolved lazily when functions are loaded.
    482   typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
    483   DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
    484 
    485   static const std::error_category &BitcodeErrorCategory();
    486 
    487 public:
    488   std::error_code Error(BitcodeError E, const Twine &Message);
    489   std::error_code Error(BitcodeError E);
    490   std::error_code Error(const Twine &Message);
    491 
    492   explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
    493                          DiagnosticHandlerFunction DiagnosticHandler);
    494   ~BitcodeReader() { FreeState(); }
    495 
    496   void FreeState();
    497 
    498   void releaseBuffer();
    499 
    500   bool isDematerializable(const GlobalValue *GV) const;
    501   std::error_code materialize(GlobalValue *GV) override;
    502   std::error_code materializeModule() override;
    503   std::vector<StructType *> getIdentifiedStructTypes() const override;
    504   void dematerialize(GlobalValue *GV);
    505 
    506   /// @brief Main interface to parsing a bitcode buffer.
    507   /// @returns true if an error occurred.
    508   std::error_code ParseBitcodeInto(Module *M);
    509 
    510   /// @brief Cheap mechanism to just extract module triple
    511   /// @returns true if an error occurred.
    512   llvm::ErrorOr<std::string> parseTriple();
    513 
    514   static uint64_t decodeSignRotatedValue(uint64_t V);
    515 
    516   /// Materialize any deferred Metadata block.
    517   std::error_code materializeMetadata() override;
    518 
    519   void setStripDebugInfo() override;
    520 
    521 private:
    522   std::vector<StructType *> IdentifiedStructTypes;
    523   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
    524   StructType *createIdentifiedStructType(LLVMContext &Context);
    525 
    526   Type *getTypeByID(unsigned ID);
    527   Type *getTypeByIDOrNull(unsigned ID);
    528   Value *getFnValueByID(unsigned ID, Type *Ty) {
    529     if (Ty && Ty->isMetadataTy())
    530       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
    531     return ValueList.getValueFwdRef(ID, Ty);
    532   }
    533   Metadata *getFnMetadataByID(unsigned ID) {
    534     return MDValueList.getValueFwdRef(ID);
    535   }
    536   BasicBlock *getBasicBlock(unsigned ID) const {
    537     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
    538     return FunctionBBs[ID];
    539   }
    540   AttributeSet getAttributes(unsigned i) const {
    541     if (i-1 < MAttributes.size())
    542       return MAttributes[i-1];
    543     return AttributeSet();
    544   }
    545 
    546   /// getValueTypePair - Read a value/type pair out of the specified record from
    547   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
    548   /// Return true on failure.
    549   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
    550                         unsigned InstNum, Value *&ResVal) {
    551     if (Slot == Record.size()) return true;
    552     unsigned ValNo = (unsigned)Record[Slot++];
    553     if (ValNo < InstNum) {
    554       // If this is not a forward reference, just return the value we already
    555       // have.
    556       ResVal = getFnValueByID(ValNo, nullptr);
    557       return ResVal == nullptr;
    558     } else if (Slot == Record.size()) {
    559       return true;
    560     }
    561 
    562     unsigned TypeNo = (unsigned)Record[Slot++];
    563     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
    564     return ResVal == nullptr;
    565   }
    566   bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
    567                 Type *Ty, Value *&ResVal) {
    568     if (Slot == Record.size()) return true;
    569     unsigned ValNo = (unsigned)Record[Slot++];
    570     ResVal = getFnValueByID(ValNo, Ty);
    571     return ResVal == 0;
    572   }
    573 
    574 
    575   std::error_code ParseModule(bool Resume);
    576   std::error_code ParseAttributeBlock();
    577   std::error_code ParseTypeTable();
    578   std::error_code ParseOldTypeTable();         // FIXME: Remove in LLVM 3.1
    579   std::error_code ParseTypeTableBody();
    580 
    581   std::error_code ParseOldTypeSymbolTable();   // FIXME: Remove in LLVM 3.1
    582   std::error_code ParseValueSymbolTable();
    583   std::error_code ParseConstants();
    584   std::error_code RememberAndSkipFunctionBody();
    585   std::error_code ParseFunctionBody(Function *F);
    586   std::error_code GlobalCleanup();
    587   std::error_code ResolveGlobalAndAliasInits();
    588   std::error_code ParseMetadata();
    589   std::error_code ParseMetadataAttachment();
    590   llvm::ErrorOr<std::string> parseModuleTriple();
    591   std::error_code InitStream();
    592   std::error_code InitStreamFromBuffer();
    593   std::error_code InitLazyStream();
    594 };
    595 
    596 } // end anonymous namespace
    597 
    598 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
    599                              std::error_code EC, const Twine &Message) {
    600   BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
    601   DiagnosticHandler(DI);
    602   return EC;
    603 }
    604 
    605 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
    606                              std::error_code EC) {
    607   return Error(DiagnosticHandler, EC, EC.message());
    608 }
    609 
    610 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
    611   return ::Error(DiagnosticHandler, make_error_code(E), Message);
    612 }
    613 
    614 std::error_code BitcodeReader::Error(const Twine &Message) {
    615   return ::Error(DiagnosticHandler,
    616                  make_error_code(BitcodeError::CorruptedBitcode), Message);
    617 }
    618 
    619 std::error_code BitcodeReader::Error(BitcodeError E) {
    620   return ::Error(DiagnosticHandler, make_error_code(E));
    621 }
    622 
    623 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
    624                                                 LLVMContext &C) {
    625   if (F)
    626     return F;
    627   return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
    628 }
    629 
    630 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
    631                              DiagnosticHandlerFunction DiagnosticHandler)
    632     : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
    633       TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
    634       NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
    635       MDValueList(C), SeenFirstFunctionBody(false) {}
    636 
    637 
    638 void BitcodeReader::FreeState() {
    639   Buffer = nullptr;
    640   std::vector<Type*>().swap(TypeList);
    641   ValueList.clear();
    642   MDValueList.clear();
    643 
    644   std::vector<AttributeSet>().swap(MAttributes);
    645   std::vector<BasicBlock*>().swap(FunctionBBs);
    646   std::vector<Function*>().swap(FunctionsWithBodies);
    647   DeferredFunctionInfo.clear();
    648   MDKindMap.clear();
    649 }
    650 
    651 //===----------------------------------------------------------------------===//
    652 //  Helper functions to implement forward reference resolution, etc.
    653 //===----------------------------------------------------------------------===//
    654 
    655 /// ConvertToString - Convert a string from a record into an std::string, return
    656 /// true on failure.
    657 template<typename StrTy>
    658 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
    659                             StrTy &Result) {
    660   if (Idx > Record.size())
    661     return true;
    662 
    663   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
    664     Result += (char)Record[i];
    665   return false;
    666 }
    667 
    668 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
    669   switch (Val) {
    670   default: // Map unknown/new linkages to external
    671   case 0:
    672     return GlobalValue::ExternalLinkage;
    673   case 1:
    674     return GlobalValue::WeakAnyLinkage;
    675   case 2:
    676     return GlobalValue::AppendingLinkage;
    677   case 3:
    678     return GlobalValue::InternalLinkage;
    679   case 4:
    680     return GlobalValue::LinkOnceAnyLinkage;
    681   case 5:
    682     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
    683   case 6:
    684     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
    685   case 7:
    686     return GlobalValue::ExternalWeakLinkage;
    687   case 8:
    688     return GlobalValue::CommonLinkage;
    689   case 9:
    690     return GlobalValue::PrivateLinkage;
    691   case 10:
    692     return GlobalValue::WeakODRLinkage;
    693   case 11:
    694     return GlobalValue::LinkOnceODRLinkage;
    695   case 12:
    696     return GlobalValue::AvailableExternallyLinkage;
    697   case 13:
    698     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
    699   case 14:
    700     return GlobalValue::ExternalWeakLinkage; // Obsolete LinkerPrivateWeakLinkage
    701   //ANDROID: convert LinkOnceODRAutoHideLinkage -> LinkOnceODRLinkage
    702   case 15:
    703     return GlobalValue::LinkOnceODRLinkage;
    704   }
    705 }
    706 
    707 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
    708   switch (Val) {
    709   default: // Map unknown visibilities to default.
    710   case 0: return GlobalValue::DefaultVisibility;
    711   case 1: return GlobalValue::HiddenVisibility;
    712   case 2: return GlobalValue::ProtectedVisibility;
    713   }
    714 }
    715 
    716 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
    717   switch (Val) {
    718     case 0: return GlobalVariable::NotThreadLocal;
    719     default: // Map unknown non-zero value to general dynamic.
    720     case 1: return GlobalVariable::GeneralDynamicTLSModel;
    721     case 2: return GlobalVariable::LocalDynamicTLSModel;
    722     case 3: return GlobalVariable::InitialExecTLSModel;
    723     case 4: return GlobalVariable::LocalExecTLSModel;
    724   }
    725 }
    726 
    727 static int GetDecodedCastOpcode(unsigned Val) {
    728   switch (Val) {
    729   default: return -1;
    730   case bitc::CAST_TRUNC   : return Instruction::Trunc;
    731   case bitc::CAST_ZEXT    : return Instruction::ZExt;
    732   case bitc::CAST_SEXT    : return Instruction::SExt;
    733   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
    734   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
    735   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
    736   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
    737   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
    738   case bitc::CAST_FPEXT   : return Instruction::FPExt;
    739   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
    740   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
    741   case bitc::CAST_BITCAST : return Instruction::BitCast;
    742   }
    743 }
    744 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
    745   switch (Val) {
    746   default: return -1;
    747   case bitc::BINOP_ADD:
    748     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
    749   case bitc::BINOP_SUB:
    750     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
    751   case bitc::BINOP_MUL:
    752     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
    753   case bitc::BINOP_UDIV: return Instruction::UDiv;
    754   case bitc::BINOP_SDIV:
    755     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
    756   case bitc::BINOP_UREM: return Instruction::URem;
    757   case bitc::BINOP_SREM:
    758     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
    759   case bitc::BINOP_SHL:  return Instruction::Shl;
    760   case bitc::BINOP_LSHR: return Instruction::LShr;
    761   case bitc::BINOP_ASHR: return Instruction::AShr;
    762   case bitc::BINOP_AND:  return Instruction::And;
    763   case bitc::BINOP_OR:   return Instruction::Or;
    764   case bitc::BINOP_XOR:  return Instruction::Xor;
    765   }
    766 }
    767 
    768 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
    769   switch (Val) {
    770   default: return AtomicRMWInst::BAD_BINOP;
    771   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
    772   case bitc::RMW_ADD: return AtomicRMWInst::Add;
    773   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
    774   case bitc::RMW_AND: return AtomicRMWInst::And;
    775   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
    776   case bitc::RMW_OR: return AtomicRMWInst::Or;
    777   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
    778   case bitc::RMW_MAX: return AtomicRMWInst::Max;
    779   case bitc::RMW_MIN: return AtomicRMWInst::Min;
    780   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
    781   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
    782   }
    783 }
    784 
    785 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
    786   switch (Val) {
    787   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
    788   case bitc::ORDERING_UNORDERED: return Unordered;
    789   case bitc::ORDERING_MONOTONIC: return Monotonic;
    790   case bitc::ORDERING_ACQUIRE: return Acquire;
    791   case bitc::ORDERING_RELEASE: return Release;
    792   case bitc::ORDERING_ACQREL: return AcquireRelease;
    793   default: // Map unknown orderings to sequentially-consistent.
    794   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
    795   }
    796 }
    797 
    798 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
    799   switch (Val) {
    800   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
    801   default: // Map unknown scopes to cross-thread.
    802   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
    803   }
    804 }
    805 
    806 namespace llvm {
    807 namespace {
    808   /// @brief A class for maintaining the slot number definition
    809   /// as a placeholder for the actual definition for forward constants defs.
    810   class ConstantPlaceHolder : public ConstantExpr {
    811     void operator=(const ConstantPlaceHolder &) = delete;
    812   public:
    813     // allocate space for exactly one operand
    814     void *operator new(size_t s) {
    815       return User::operator new(s, 1);
    816     }
    817     explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
    818       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
    819       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
    820     }
    821 
    822     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
    823     static bool classof(const Value *V) {
    824       return isa<ConstantExpr>(V) &&
    825              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
    826     }
    827 
    828 
    829     /// Provide fast operand accessors
    830     DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
    831   };
    832 }
    833 
    834 // FIXME: can we inherit this from ConstantExpr?
    835 template <>
    836 struct OperandTraits<ConstantPlaceHolder> :
    837   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
    838 };
    839 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
    840 }
    841 
    842 
    843 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
    844   if (Idx == size()) {
    845     push_back(V);
    846     return;
    847   }
    848 
    849   if (Idx >= size())
    850     resize(Idx+1);
    851 
    852   WeakVH &OldV = ValuePtrs[Idx];
    853   if (!OldV) {
    854     OldV = V;
    855     return;
    856   }
    857 
    858   // Handle constants and non-constants (e.g. instrs) differently for
    859   // efficiency.
    860   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
    861     ResolveConstants.push_back(std::make_pair(PHC, Idx));
    862     OldV = V;
    863   } else {
    864     // If there was a forward reference to this value, replace it.
    865     Value *PrevVal = OldV;
    866     OldV->replaceAllUsesWith(V);
    867     delete PrevVal;
    868   }
    869 }
    870 
    871 
    872 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
    873                                                     Type *Ty) {
    874   if (Idx >= size())
    875     resize(Idx + 1);
    876 
    877   if (Value *V = ValuePtrs[Idx]) {
    878     assert(Ty == V->getType() && "Type mismatch in constant table!");
    879     return cast<Constant>(V);
    880   }
    881 
    882   // Create and return a placeholder, which will later be RAUW'd.
    883   Constant *C = new ConstantPlaceHolder(Ty, Context);
    884   ValuePtrs[Idx] = C;
    885   return C;
    886 }
    887 
    888 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
    889   if (Idx >= size())
    890     resize(Idx + 1);
    891 
    892   if (Value *V = ValuePtrs[Idx]) {
    893     assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
    894     return V;
    895   }
    896 
    897   // No type specified, must be invalid reference.
    898   if (!Ty) return nullptr;
    899 
    900   // Create and return a placeholder, which will later be RAUW'd.
    901   Value *V = new Argument(Ty);
    902   ValuePtrs[Idx] = V;
    903   return V;
    904 }
    905 
    906 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
    907 /// resolves any forward references.  The idea behind this is that we sometimes
    908 /// get constants (such as large arrays) which reference *many* forward ref
    909 /// constants.  Replacing each of these causes a lot of thrashing when
    910 /// building/reuniquing the constant.  Instead of doing this, we look at all the
    911 /// uses and rewrite all the place holders at once for any constant that uses
    912 /// a placeholder.
    913 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
    914   // Sort the values by-pointer so that they are efficient to look up with a
    915   // binary search.
    916   std::sort(ResolveConstants.begin(), ResolveConstants.end());
    917 
    918   SmallVector<Constant*, 64> NewOps;
    919 
    920   while (!ResolveConstants.empty()) {
    921     Value *RealVal = operator[](ResolveConstants.back().second);
    922     Constant *Placeholder = ResolveConstants.back().first;
    923     ResolveConstants.pop_back();
    924 
    925     // Loop over all users of the placeholder, updating them to reference the
    926     // new value.  If they reference more than one placeholder, update them all
    927     // at once.
    928     while (!Placeholder->use_empty()) {
    929       auto UI = Placeholder->user_begin();
    930       User *U = *UI;
    931 
    932       // If the using object isn't uniqued, just update the operands.  This
    933       // handles instructions and initializers for global variables.
    934       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
    935         UI.getUse().set(RealVal);
    936         continue;
    937       }
    938 
    939       // Otherwise, we have a constant that uses the placeholder.  Replace that
    940       // constant with a new constant that has *all* placeholder uses updated.
    941       Constant *UserC = cast<Constant>(U);
    942       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
    943            I != E; ++I) {
    944         Value *NewOp;
    945         if (!isa<ConstantPlaceHolder>(*I)) {
    946           // Not a placeholder reference.
    947           NewOp = *I;
    948         } else if (*I == Placeholder) {
    949           // Common case is that it just references this one placeholder.
    950           NewOp = RealVal;
    951         } else {
    952           // Otherwise, look up the placeholder in ResolveConstants.
    953           ResolveConstantsTy::iterator It =
    954             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
    955                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
    956                                                             0));
    957           assert(It != ResolveConstants.end() && It->first == *I);
    958           NewOp = operator[](It->second);
    959         }
    960 
    961         NewOps.push_back(cast<Constant>(NewOp));
    962       }
    963 
    964       // Make the new constant.
    965       Constant *NewC;
    966       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
    967         NewC = ConstantArray::get(UserCA->getType(), NewOps);
    968       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
    969         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
    970       } else if (isa<ConstantVector>(UserC)) {
    971         NewC = ConstantVector::get(NewOps);
    972       } else {
    973         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
    974         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
    975       }
    976 
    977       UserC->replaceAllUsesWith(NewC);
    978       UserC->destroyConstant();
    979       NewOps.clear();
    980     }
    981 
    982     // Update all ValueHandles, they should be the only users at this point.
    983     Placeholder->replaceAllUsesWith(RealVal);
    984     delete Placeholder;
    985   }
    986 }
    987 
    988 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
    989   if (Idx == size()) {
    990     push_back(MD);
    991     return;
    992   }
    993 
    994   if (Idx >= size())
    995     resize(Idx+1);
    996 
    997   TrackingMDRef &OldMD = MDValuePtrs[Idx];
    998   if (!OldMD) {
    999     OldMD.reset(MD);
   1000     return;
   1001   }
   1002 
   1003   // If there was a forward reference to this value, replace it.
   1004   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
   1005   PrevMD->replaceAllUsesWith(MD);
   1006   --NumFwdRefs;
   1007 }
   1008 
   1009 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
   1010   if (Idx >= size())
   1011     resize(Idx + 1);
   1012 
   1013   if (Metadata *MD = MDValuePtrs[Idx])
   1014     return MD;
   1015 
   1016   // Create and return a placeholder, which will later be RAUW'd.
   1017   AnyFwdRefs = true;
   1018   ++NumFwdRefs;
   1019   Metadata *MD = MDNode::getTemporary(Context, None).release();
   1020   MDValuePtrs[Idx].reset(MD);
   1021   return MD;
   1022 }
   1023 
   1024 void BitcodeReaderMDValueList::tryToResolveCycles() {
   1025   if (!AnyFwdRefs)
   1026     // Nothing to do.
   1027     return;
   1028 
   1029   if (NumFwdRefs)
   1030     // Still forward references... can't resolve cycles.
   1031     return;
   1032 
   1033   // Resolve any cycles.
   1034   for (auto &MD : MDValuePtrs) {
   1035     auto *N = dyn_cast_or_null<MDNode>(MD);
   1036     if (!N)
   1037       continue;
   1038 
   1039     assert(!N->isTemporary() && "Unexpected forward reference");
   1040     N->resolveCycles();
   1041   }
   1042 }
   1043 
   1044 Type *BitcodeReader::getTypeByID(unsigned ID) {
   1045   // The type table size is always specified correctly.
   1046   if (ID >= TypeList.size())
   1047     return nullptr;
   1048 
   1049   if (Type *Ty = TypeList[ID])
   1050     return Ty;
   1051 
   1052   // If we have a forward reference, the only possible case is when it is to a
   1053   // named struct.  Just create a placeholder for now.
   1054   return TypeList[ID] = createIdentifiedStructType(Context);
   1055 }
   1056 
   1057 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
   1058                                                       StringRef Name) {
   1059   auto *Ret = StructType::create(Context, Name);
   1060   IdentifiedStructTypes.push_back(Ret);
   1061   return Ret;
   1062 }
   1063 
   1064 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
   1065   auto *Ret = StructType::create(Context);
   1066   IdentifiedStructTypes.push_back(Ret);
   1067   return Ret;
   1068 }
   1069 
   1070 
   1071 /// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable.
   1072 Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) {
   1073   if (ID >= TypeList.size())
   1074     TypeList.resize(ID+1);
   1075 
   1076   return TypeList[ID];
   1077 }
   1078 
   1079 //===----------------------------------------------------------------------===//
   1080 //  Functions for parsing blocks from the bitcode file
   1081 //===----------------------------------------------------------------------===//
   1082 
   1083 
   1084 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
   1085 /// been decoded from the given integer. This function must stay in sync with
   1086 /// 'encodeLLVMAttributesForBitcode'.
   1087 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
   1088                                            uint64_t EncodedAttrs) {
   1089   // FIXME: Remove in 4.0.
   1090 
   1091   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
   1092   // the bits above 31 down by 11 bits.
   1093   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
   1094   assert((!Alignment || isPowerOf2_32(Alignment)) &&
   1095          "Alignment must be a power of two.");
   1096 
   1097   if (Alignment)
   1098     B.addAlignmentAttr(Alignment);
   1099   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
   1100                 (EncodedAttrs & 0xffff));
   1101 }
   1102 
   1103 std::error_code BitcodeReader::ParseAttributeBlock() {
   1104   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
   1105     return Error("Invalid record");
   1106 
   1107   if (!MAttributes.empty())
   1108     return Error("Invalid multiple blocks");
   1109 
   1110   SmallVector<uint64_t, 64> Record;
   1111 
   1112   SmallVector<AttributeSet, 8> Attrs;
   1113 
   1114   // Read all the records.
   1115   while (1) {
   1116     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
   1117 
   1118     switch (Entry.Kind) {
   1119     case BitstreamEntry::SubBlock: // Handled for us already.
   1120     case BitstreamEntry::Error:
   1121       return Error("Malformed block");
   1122     case BitstreamEntry::EndBlock:
   1123       return std::error_code();
   1124     case BitstreamEntry::Record:
   1125       // The interesting case.
   1126       break;
   1127     }
   1128 
   1129     // Read a record.
   1130     Record.clear();
   1131     switch (Stream.readRecord(Entry.ID, Record)) {
   1132     default:  // Default behavior: ignore.
   1133       break;
   1134     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
   1135       // FIXME: Remove in 4.0.
   1136       if (Record.size() & 1)
   1137         return Error("Invalid record");
   1138 
   1139       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
   1140         AttrBuilder B;
   1141         decodeLLVMAttributesForBitcode(B, Record[i+1]);
   1142         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
   1143       }
   1144 
   1145       MAttributes.push_back(AttributeSet::get(Context, Attrs));
   1146       Attrs.clear();
   1147       break;
   1148     }
   1149     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
   1150       for (unsigned i = 0, e = Record.size(); i != e; ++i)
   1151         Attrs.push_back(MAttributeGroups[Record[i]]);
   1152 
   1153       MAttributes.push_back(AttributeSet::get(Context, Attrs));
   1154       Attrs.clear();
   1155       break;
   1156     }
   1157     }
   1158   }
   1159 }
   1160 
   1161 
   1162 std::error_code BitcodeReader::ParseTypeTable() {
   1163   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
   1164     return Error("Invalid record");
   1165 
   1166   return ParseTypeTableBody();
   1167 }
   1168 
   1169 std::error_code BitcodeReader::ParseTypeTableBody() {
   1170   if (!TypeList.empty())
   1171     return Error("Invalid multiple blocks");
   1172 
   1173   SmallVector<uint64_t, 64> Record;
   1174   unsigned NumRecords = 0;
   1175 
   1176   SmallString<64> TypeName;
   1177 
   1178   // Read all the records for this type table.
   1179   while (1) {
   1180     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
   1181 
   1182     switch (Entry.Kind) {
   1183     case BitstreamEntry::SubBlock: // Handled for us already.
   1184     case BitstreamEntry::Error:
   1185       return Error("Malformed block");
   1186     case BitstreamEntry::EndBlock:
   1187       if (NumRecords != TypeList.size())
   1188         return Error("Malformed block");
   1189       return std::error_code();
   1190     case BitstreamEntry::Record:
   1191       // The interesting case.
   1192       break;
   1193     }
   1194 
   1195     // Read a record.
   1196     Record.clear();
   1197     Type *ResultTy = nullptr;
   1198     switch (Stream.readRecord(Entry.ID, Record)) {
   1199     default:
   1200       return Error("Invalid value");
   1201     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
   1202       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
   1203       // type list.  This allows us to reserve space.
   1204       if (Record.size() < 1)
   1205         return Error("Invalid record");
   1206       TypeList.resize(Record[0]);
   1207       continue;
   1208     case bitc::TYPE_CODE_VOID:      // VOID
   1209       ResultTy = Type::getVoidTy(Context);
   1210       break;
   1211     case bitc::TYPE_CODE_HALF:     // HALF
   1212       ResultTy = Type::getHalfTy(Context);
   1213       break;
   1214     case bitc::TYPE_CODE_FLOAT:     // FLOAT
   1215       ResultTy = Type::getFloatTy(Context);
   1216       break;
   1217     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
   1218       ResultTy = Type::getDoubleTy(Context);
   1219       break;
   1220     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
   1221       ResultTy = Type::getX86_FP80Ty(Context);
   1222       break;
   1223     case bitc::TYPE_CODE_FP128:     // FP128
   1224       ResultTy = Type::getFP128Ty(Context);
   1225       break;
   1226     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
   1227       ResultTy = Type::getPPC_FP128Ty(Context);
   1228       break;
   1229     case bitc::TYPE_CODE_LABEL:     // LABEL
   1230       ResultTy = Type::getLabelTy(Context);
   1231       break;
   1232     case bitc::TYPE_CODE_METADATA:  // METADATA
   1233       ResultTy = Type::getMetadataTy(Context);
   1234       break;
   1235     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
   1236       ResultTy = Type::getX86_MMXTy(Context);
   1237       break;
   1238     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
   1239       if (Record.size() < 1)
   1240         return Error("Invalid record");
   1241 
   1242       ResultTy = IntegerType::get(Context, Record[0]);
   1243       break;
   1244     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
   1245                                     //          [pointee type, address space]
   1246       if (Record.size() < 1)
   1247         return Error("Invalid record");
   1248       unsigned AddressSpace = 0;
   1249       if (Record.size() == 2)
   1250         AddressSpace = Record[1];
   1251       ResultTy = getTypeByID(Record[0]);
   1252       if (!ResultTy)
   1253         return Error("Invalid type");
   1254       ResultTy = PointerType::get(ResultTy, AddressSpace);
   1255       break;
   1256     }
   1257     case bitc::TYPE_CODE_FUNCTION_OLD: {
   1258       // FIXME: attrid is dead, remove it in LLVM 4.0
   1259       // FUNCTION: [vararg, attrid, retty, paramty x N]
   1260       if (Record.size() < 3)
   1261         return Error("Invalid record");
   1262       SmallVector<Type*, 8> ArgTys;
   1263       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
   1264         if (Type *T = getTypeByID(Record[i]))
   1265           ArgTys.push_back(T);
   1266         else
   1267           break;
   1268       }
   1269 
   1270       ResultTy = getTypeByID(Record[2]);
   1271       if (!ResultTy || ArgTys.size() < Record.size()-3)
   1272         return Error("Invalid type");
   1273 
   1274       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
   1275       break;
   1276     }
   1277     case bitc::TYPE_CODE_FUNCTION: {
   1278       // FUNCTION: [vararg, retty, paramty x N]
   1279       if (Record.size() < 2)
   1280         return Error("Invalid record");
   1281       SmallVector<Type*, 8> ArgTys;
   1282       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
   1283         if (Type *T = getTypeByID(Record[i]))
   1284           ArgTys.push_back(T);
   1285         else
   1286           break;
   1287       }
   1288 
   1289       ResultTy = getTypeByID(Record[1]);
   1290       if (!ResultTy || ArgTys.size() < Record.size()-2)
   1291         return Error("Invalid type");
   1292 
   1293       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
   1294       break;
   1295     }
   1296     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
   1297       if (Record.size() < 1)
   1298         return Error("Invalid record");
   1299       SmallVector<Type*, 8> EltTys;
   1300       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
   1301         if (Type *T = getTypeByID(Record[i]))
   1302           EltTys.push_back(T);
   1303         else
   1304           break;
   1305       }
   1306       if (EltTys.size() != Record.size()-1)
   1307         return Error("Invalid type");
   1308       ResultTy = StructType::get(Context, EltTys, Record[0]);
   1309       break;
   1310     }
   1311     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
   1312       if (ConvertToString(Record, 0, TypeName))
   1313         return Error("Invalid record");
   1314       continue;
   1315 
   1316     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
   1317       if (Record.size() < 1)
   1318         return Error("Invalid record");
   1319 
   1320       if (NumRecords >= TypeList.size())
   1321         return Error("Invalid TYPE table");
   1322 
   1323       // Check to see if this was forward referenced, if so fill in the temp.
   1324       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
   1325       if (Res) {
   1326         Res->setName(TypeName);
   1327         TypeList[NumRecords] = nullptr;
   1328       } else  // Otherwise, create a new struct.
   1329         Res = createIdentifiedStructType(Context, TypeName);
   1330       TypeName.clear();
   1331 
   1332       SmallVector<Type*, 8> EltTys;
   1333       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
   1334         if (Type *T = getTypeByID(Record[i]))
   1335           EltTys.push_back(T);
   1336         else
   1337           break;
   1338       }
   1339       if (EltTys.size() != Record.size()-1)
   1340         return Error("Invalid record");
   1341       Res->setBody(EltTys, Record[0]);
   1342       ResultTy = Res;
   1343       break;
   1344     }
   1345     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
   1346       if (Record.size() != 1)
   1347         return Error("Invalid record");
   1348 
   1349       if (NumRecords >= TypeList.size())
   1350         return Error("Invalid TYPE table");
   1351 
   1352       // Check to see if this was forward referenced, if so fill in the temp.
   1353       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
   1354       if (Res) {
   1355         Res->setName(TypeName);
   1356         TypeList[NumRecords] = nullptr;
   1357       } else  // Otherwise, create a new struct with no body.
   1358         Res = createIdentifiedStructType(Context, TypeName);
   1359       TypeName.clear();
   1360       ResultTy = Res;
   1361       break;
   1362     }
   1363     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
   1364       if (Record.size() < 2)
   1365         return Error("Invalid record");
   1366       if ((ResultTy = getTypeByID(Record[1])))
   1367         ResultTy = ArrayType::get(ResultTy, Record[0]);
   1368       else
   1369         return Error("Invalid type");
   1370       break;
   1371     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
   1372       if (Record.size() < 2)
   1373         return Error("Invalid record");
   1374       if ((ResultTy = getTypeByID(Record[1])))
   1375         ResultTy = VectorType::get(ResultTy, Record[0]);
   1376       else
   1377         return Error("Invalid type");
   1378       break;
   1379     }
   1380 
   1381     if (NumRecords >= TypeList.size())
   1382       return Error("Invalid TYPE table");
   1383     assert(ResultTy && "Didn't read a type?");
   1384     assert(!TypeList[NumRecords] && "Already read type?");
   1385     TypeList[NumRecords++] = ResultTy;
   1386   }
   1387 }
   1388 
   1389 // FIXME: Remove in LLVM 3.1
   1390 std::error_code BitcodeReader::ParseOldTypeTable() {
   1391   if (Stream.EnterSubBlock(TYPE_BLOCK_ID_OLD_3_0))
   1392     return Error("Malformed block");
   1393 
   1394   if (!TypeList.empty())
   1395     return Error("Invalid TYPE table");
   1396 
   1397 
   1398   // While horrible, we have no good ordering of types in the bc file.  Just
   1399   // iteratively parse types out of the bc file in multiple passes until we get
   1400   // them all.  Do this by saving a cursor for the start of the type block.
   1401   BitstreamCursor StartOfTypeBlockCursor(Stream);
   1402 
   1403   unsigned NumTypesRead = 0;
   1404 
   1405   SmallVector<uint64_t, 64> Record;
   1406 RestartScan:
   1407   unsigned NextTypeID = 0;
   1408   bool ReadAnyTypes = false;
   1409 
   1410   // Read all the records for this type table.
   1411   while (1) {
   1412     unsigned Code = Stream.ReadCode();
   1413     if (Code == bitc::END_BLOCK) {
   1414       if (NextTypeID != TypeList.size())
   1415         return Error("Invalid TYPE table");
   1416 
   1417       // If we haven't read all of the types yet, iterate again.
   1418       if (NumTypesRead != TypeList.size()) {
   1419         // If we didn't successfully read any types in this pass, then we must
   1420         // have an unhandled forward reference.
   1421         if (!ReadAnyTypes)
   1422           return Error("Invalid TYPE table");
   1423 
   1424         Stream = StartOfTypeBlockCursor;
   1425         goto RestartScan;
   1426       }
   1427 
   1428       if (Stream.ReadBlockEnd())
   1429         return Error("Invalid TYPE table");
   1430       return std::error_code();
   1431     }
   1432 
   1433     if (Code == bitc::ENTER_SUBBLOCK) {
   1434       // No known subblocks, always skip them.
   1435       Stream.ReadSubBlockID();
   1436       if (Stream.SkipBlock())
   1437         return Error("Malformed block");
   1438       continue;
   1439     }
   1440 
   1441     if (Code == bitc::DEFINE_ABBREV) {
   1442       Stream.ReadAbbrevRecord();
   1443       continue;
   1444     }
   1445 
   1446     // Read a record.
   1447     Record.clear();
   1448     Type *ResultTy = nullptr;
   1449     switch (Stream.readRecord(Code, Record)) {
   1450     default: return Error("Invalid TYPE table");
   1451     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
   1452       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
   1453       // type list.  This allows us to reserve space.
   1454       if (Record.size() < 1)
   1455         return Error("Invalid TYPE table");
   1456       TypeList.resize(Record[0]);
   1457       continue;
   1458     case bitc::TYPE_CODE_VOID:      // VOID
   1459       ResultTy = Type::getVoidTy(Context);
   1460       break;
   1461     case bitc::TYPE_CODE_FLOAT:     // FLOAT
   1462       ResultTy = Type::getFloatTy(Context);
   1463       break;
   1464     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
   1465       ResultTy = Type::getDoubleTy(Context);
   1466       break;
   1467     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
   1468       ResultTy = Type::getX86_FP80Ty(Context);
   1469       break;
   1470     case bitc::TYPE_CODE_FP128:     // FP128
   1471       ResultTy = Type::getFP128Ty(Context);
   1472       break;
   1473     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
   1474       ResultTy = Type::getPPC_FP128Ty(Context);
   1475       break;
   1476     case bitc::TYPE_CODE_LABEL:     // LABEL
   1477       ResultTy = Type::getLabelTy(Context);
   1478       break;
   1479     case bitc::TYPE_CODE_METADATA:  // METADATA
   1480       ResultTy = Type::getMetadataTy(Context);
   1481       break;
   1482     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
   1483       ResultTy = Type::getX86_MMXTy(Context);
   1484       break;
   1485     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
   1486       if (Record.size() < 1)
   1487         return Error("Invalid TYPE table");
   1488       ResultTy = IntegerType::get(Context, Record[0]);
   1489       break;
   1490     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
   1491       if (NextTypeID < TypeList.size() && TypeList[NextTypeID] == 0)
   1492         ResultTy = StructType::create(Context, "");
   1493       break;
   1494     case TYPE_CODE_STRUCT_OLD_3_0: {// STRUCT_OLD
   1495       if (NextTypeID >= TypeList.size()) break;
   1496       // If we already read it, don't reprocess.
   1497       if (TypeList[NextTypeID] &&
   1498           !cast<StructType>(TypeList[NextTypeID])->isOpaque())
   1499         break;
   1500 
   1501       // Set a type.
   1502       if (TypeList[NextTypeID] == 0)
   1503         TypeList[NextTypeID] = StructType::create(Context, "");
   1504 
   1505       std::vector<Type*> EltTys;
   1506       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
   1507         if (Type *Elt = getTypeByIDOrNull(Record[i]))
   1508           EltTys.push_back(Elt);
   1509         else
   1510           break;
   1511       }
   1512 
   1513       if (EltTys.size() != Record.size()-1)
   1514         break;      // Not all elements are ready.
   1515 
   1516       cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]);
   1517       ResultTy = TypeList[NextTypeID];
   1518       TypeList[NextTypeID] = 0;
   1519       break;
   1520     }
   1521     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
   1522       //          [pointee type, address space]
   1523       if (Record.size() < 1)
   1524         return Error("Invalid TYPE table");
   1525       unsigned AddressSpace = 0;
   1526       if (Record.size() == 2)
   1527         AddressSpace = Record[1];
   1528       if ((ResultTy = getTypeByIDOrNull(Record[0])))
   1529         ResultTy = PointerType::get(ResultTy, AddressSpace);
   1530       break;
   1531     }
   1532     case bitc::TYPE_CODE_FUNCTION_OLD: {
   1533       // FIXME: attrid is dead, remove it in LLVM 3.0
   1534       // FUNCTION: [vararg, attrid, retty, paramty x N]
   1535       if (Record.size() < 3)
   1536         return Error("Invalid TYPE table");
   1537       std::vector<Type*> ArgTys;
   1538       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
   1539         if (Type *Elt = getTypeByIDOrNull(Record[i]))
   1540           ArgTys.push_back(Elt);
   1541         else
   1542           break;
   1543       }
   1544       if (ArgTys.size()+3 != Record.size())
   1545         break;  // Something was null.
   1546       if ((ResultTy = getTypeByIDOrNull(Record[2])))
   1547         ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
   1548       break;
   1549     }
   1550     case bitc::TYPE_CODE_FUNCTION: {
   1551       // FUNCTION: [vararg, retty, paramty x N]
   1552       if (Record.size() < 2)
   1553         return Error("Invalid TYPE table");
   1554       std::vector<Type*> ArgTys;
   1555       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
   1556         if (Type *Elt = getTypeByIDOrNull(Record[i]))
   1557           ArgTys.push_back(Elt);
   1558         else
   1559           break;
   1560       }
   1561       if (ArgTys.size()+2 != Record.size())
   1562         break;  // Something was null.
   1563       if ((ResultTy = getTypeByIDOrNull(Record[1])))
   1564         ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
   1565       break;
   1566     }
   1567     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
   1568       if (Record.size() < 2)
   1569         return Error("Invalid TYPE table");
   1570       if ((ResultTy = getTypeByIDOrNull(Record[1])))
   1571         ResultTy = ArrayType::get(ResultTy, Record[0]);
   1572       break;
   1573     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
   1574       if (Record.size() < 2)
   1575         return Error("Invalid TYPE table");
   1576       if ((ResultTy = getTypeByIDOrNull(Record[1])))
   1577         ResultTy = VectorType::get(ResultTy, Record[0]);
   1578       break;
   1579     }
   1580 
   1581     if (NextTypeID >= TypeList.size())
   1582       return Error("Invalid TYPE table");
   1583 
   1584     if (ResultTy && TypeList[NextTypeID] == 0) {
   1585       ++NumTypesRead;
   1586       ReadAnyTypes = true;
   1587 
   1588       TypeList[NextTypeID] = ResultTy;
   1589     }
   1590 
   1591     ++NextTypeID;
   1592   }
   1593 }
   1594 
   1595 
   1596 std::error_code BitcodeReader::ParseOldTypeSymbolTable() {
   1597   if (Stream.EnterSubBlock(TYPE_SYMTAB_BLOCK_ID_OLD_3_0))
   1598     return Error("Malformed block");
   1599 
   1600   SmallVector<uint64_t, 64> Record;
   1601 
   1602   // Read all the records for this type table.
   1603   std::string TypeName;
   1604   while (1) {
   1605     unsigned Code = Stream.ReadCode();
   1606     if (Code == bitc::END_BLOCK) {
   1607       if (Stream.ReadBlockEnd())
   1608         return Error("Malformed block");
   1609       return std::error_code();
   1610     }
   1611 
   1612     if (Code == bitc::ENTER_SUBBLOCK) {
   1613       // No known subblocks, always skip them.
   1614       Stream.ReadSubBlockID();
   1615       if (Stream.SkipBlock())
   1616         return Error("Malformed block");
   1617       continue;
   1618     }
   1619 
   1620     if (Code == bitc::DEFINE_ABBREV) {
   1621       Stream.ReadAbbrevRecord();
   1622       continue;
   1623     }
   1624 
   1625     // Read a record.
   1626     Record.clear();
   1627     switch (Stream.readRecord(Code, Record)) {
   1628     default:  // Default behavior: unknown type.
   1629       break;
   1630     case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
   1631       if (ConvertToString(Record, 1, TypeName))
   1632         return Error("Invalid record");
   1633       unsigned TypeID = Record[0];
   1634       if (TypeID >= TypeList.size())
   1635         return Error("Invalid record");
   1636 
   1637       // Only apply the type name to a struct type with no name.
   1638       if (StructType *STy = dyn_cast<StructType>(TypeList[TypeID]))
   1639         if (!STy->isLiteral() && !STy->hasName())
   1640           STy->setName(TypeName);
   1641       TypeName.clear();
   1642       break;
   1643     }
   1644   }
   1645 }
   1646 
   1647 std::error_code BitcodeReader::ParseValueSymbolTable() {
   1648   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
   1649     return Error("Invalid record");
   1650 
   1651   SmallVector<uint64_t, 64> Record;
   1652 
   1653   // Read all the records for this value table.
   1654   SmallString<128> ValueName;
   1655   while (1) {
   1656     unsigned Code = Stream.ReadCode();
   1657     if (Code == bitc::END_BLOCK) {
   1658       if (Stream.ReadBlockEnd())
   1659         return Error("Malformed block");
   1660       return std::error_code();
   1661     }
   1662     if (Code == bitc::ENTER_SUBBLOCK) {
   1663       // No known subblocks, always skip them.
   1664       Stream.ReadSubBlockID();
   1665       if (Stream.SkipBlock())
   1666         return Error("Malformed block");
   1667       continue;
   1668     }
   1669 
   1670     if (Code == bitc::DEFINE_ABBREV) {
   1671       Stream.ReadAbbrevRecord();
   1672       continue;
   1673     }
   1674 
   1675     // Read a record.
   1676     Record.clear();
   1677     switch (Stream.readRecord(Code, Record)) {
   1678     default:  // Default behavior: unknown type.
   1679       break;
   1680     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
   1681       if (ConvertToString(Record, 1, ValueName))
   1682         return Error("Invalid record");
   1683       unsigned ValueID = Record[0];
   1684       if (ValueID >= ValueList.size())
   1685         return Error("Invalid record");
   1686       Value *V = ValueList[ValueID];
   1687 
   1688       V->setName(StringRef(ValueName.data(), ValueName.size()));
   1689       ValueName.clear();
   1690       break;
   1691     }
   1692     case bitc::VST_CODE_BBENTRY: {
   1693       if (ConvertToString(Record, 1, ValueName))
   1694         return Error("Invalid record");
   1695       BasicBlock *BB = getBasicBlock(Record[0]);
   1696       if (!BB)
   1697         return Error("Invalid record");
   1698 
   1699       BB->setName(StringRef(ValueName.data(), ValueName.size()));
   1700       ValueName.clear();
   1701       break;
   1702     }
   1703     }
   1704   }
   1705 }
   1706 
   1707 std::error_code BitcodeReader::ParseMetadata() {
   1708   unsigned NextMDValueNo = MDValueList.size();
   1709 
   1710   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
   1711     return Error("Invalid record");
   1712 
   1713   SmallVector<uint64_t, 64> Record;
   1714 
   1715   // Read all the records.
   1716   while (1) {
   1717     unsigned Code = Stream.ReadCode();
   1718     if (Code == bitc::END_BLOCK) {
   1719       if (Stream.ReadBlockEnd())
   1720         return Error("Malformed block");
   1721       return std::error_code();
   1722     }
   1723 
   1724     if (Code == bitc::ENTER_SUBBLOCK) {
   1725       // No known subblocks, always skip them.
   1726       Stream.ReadSubBlockID();
   1727       if (Stream.SkipBlock())
   1728         return Error("Malformed block");
   1729       continue;
   1730     }
   1731 
   1732     if (Code == bitc::DEFINE_ABBREV) {
   1733       Stream.ReadAbbrevRecord();
   1734       continue;
   1735     }
   1736 
   1737     bool IsFunctionLocal = false;
   1738     // Read a record.
   1739     Record.clear();
   1740     Code = Stream.readRecord(Code, Record);
   1741     switch (Code) {
   1742     default:  // Default behavior: ignore.
   1743       break;
   1744     case bitc::METADATA_NAME: {
   1745       // Read name of the named metadata.
   1746       SmallString<8> Name(Record.begin(), Record.end());
   1747       Record.clear();
   1748       Code = Stream.ReadCode();
   1749 
   1750       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
   1751       unsigned NextBitCode = Stream.readRecord(Code, Record);
   1752       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
   1753 
   1754       // Read named metadata elements.
   1755       unsigned Size = Record.size();
   1756       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
   1757       for (unsigned i = 0; i != Size; ++i) {
   1758         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
   1759         if (!MD)
   1760           return Error("Invalid record");
   1761         NMD->addOperand(MD);
   1762       }
   1763       break;
   1764     }
   1765     case bitc::METADATA_OLD_FN_NODE:
   1766       IsFunctionLocal = true;
   1767       // fall-through
   1768     case bitc::METADATA_OLD_NODE: {
   1769       if (Record.size() % 2 == 1)
   1770         return Error("Invalid record");
   1771 
   1772       unsigned Size = Record.size();
   1773       SmallVector<Metadata *, 8> Elts;
   1774       for (unsigned i = 0; i != Size; i += 2) {
   1775         Type *Ty = getTypeByID(Record[i]);
   1776         if (!Ty)
   1777           return Error("Invalid record");
   1778         if (Ty->isMetadataTy())
   1779           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
   1780         else if (!Ty->isVoidTy()) {
   1781           auto *MD =
   1782               ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
   1783           assert(isa<ConstantAsMetadata>(MD) &&
   1784                  "Expected non-function-local metadata");
   1785           Elts.push_back(MD);
   1786         } else
   1787           Elts.push_back(nullptr);
   1788       }
   1789       MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
   1790       break;
   1791     }
   1792     case bitc::METADATA_STRING: {
   1793       std::string String(Record.begin(), Record.end());
   1794       llvm::UpgradeMDStringConstant(String);
   1795       Metadata *MD = MDString::get(Context, String);
   1796       MDValueList.AssignValue(MD, NextMDValueNo++);
   1797       break;
   1798     }
   1799     case bitc::METADATA_KIND: {
   1800       if (Record.size() < 2)
   1801         return Error("Invalid record");
   1802 
   1803       unsigned Kind = Record[0];
   1804       SmallString<8> Name(Record.begin()+1, Record.end());
   1805 
   1806       unsigned NewKind = TheModule->getMDKindID(Name.str());
   1807       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
   1808         return Error("Conflicting METADATA_KIND records");
   1809       break;
   1810     }
   1811     }
   1812   }
   1813 }
   1814 
   1815 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
   1816 /// the LSB for dense VBR encoding.
   1817 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
   1818   if ((V & 1) == 0)
   1819     return V >> 1;
   1820   if (V != 1)
   1821     return -(V >> 1);
   1822   // There is no such thing as -0 with integers.  "-0" really means MININT.
   1823   return 1ULL << 63;
   1824 }
   1825 
   1826 // FIXME: Delete this in LLVM 4.0 and just assert that the aliasee is a
   1827 // GlobalObject.
   1828 static GlobalObject &
   1829 getGlobalObjectInExpr(const DenseMap<GlobalAlias *, Constant *> &Map,
   1830                       Constant &C) {
   1831   auto *GO = dyn_cast<GlobalObject>(&C);
   1832   if (GO)
   1833     return *GO;
   1834 
   1835   auto *GA = dyn_cast<GlobalAlias>(&C);
   1836   if (GA)
   1837     return getGlobalObjectInExpr(Map, *Map.find(GA)->second);
   1838 
   1839   auto &CE = cast<ConstantExpr>(C);
   1840   assert(CE.getOpcode() == Instruction::BitCast ||
   1841          CE.getOpcode() == Instruction::GetElementPtr ||
   1842          CE.getOpcode() == Instruction::AddrSpaceCast);
   1843   if (CE.getOpcode() == Instruction::GetElementPtr)
   1844     assert(cast<GEPOperator>(CE).hasAllZeroIndices());
   1845   return getGlobalObjectInExpr(Map, *CE.getOperand(0));
   1846 }
   1847 
   1848 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
   1849 /// values and aliases that we can.
   1850 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
   1851   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
   1852   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
   1853 
   1854   GlobalInitWorklist.swap(GlobalInits);
   1855   AliasInitWorklist.swap(AliasInits);
   1856 
   1857   while (!GlobalInitWorklist.empty()) {
   1858     unsigned ValID = GlobalInitWorklist.back().second;
   1859     if (ValID >= ValueList.size()) {
   1860       // Not ready to resolve this yet, it requires something later in the file.
   1861       GlobalInits.push_back(GlobalInitWorklist.back());
   1862     } else {
   1863       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
   1864         GlobalInitWorklist.back().first->setInitializer(C);
   1865       else
   1866         return Error("Expected a constant");
   1867     }
   1868     GlobalInitWorklist.pop_back();
   1869   }
   1870 
   1871   // FIXME: Delete this in LLVM 4.0
   1872   // Older versions of llvm could write an alias pointing to another. We cannot
   1873   // construct those aliases, so we first collect an alias to aliasee expression
   1874   // and then compute the actual aliasee.
   1875   DenseMap<GlobalAlias *, Constant *> AliasInit;
   1876 
   1877   while (!AliasInitWorklist.empty()) {
   1878     unsigned ValID = AliasInitWorklist.back().second;
   1879     if (ValID >= ValueList.size()) {
   1880       AliasInits.push_back(AliasInitWorklist.back());
   1881     } else {
   1882       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
   1883         AliasInit.insert(std::make_pair(AliasInitWorklist.back().first, C));
   1884       else
   1885         return Error("Expected a constant");
   1886     }
   1887     AliasInitWorklist.pop_back();
   1888   }
   1889 
   1890   for (auto &Pair : AliasInit) {
   1891     auto &GO = getGlobalObjectInExpr(AliasInit, *Pair.second);
   1892     Pair.first->setAliasee(&GO);
   1893   }
   1894 
   1895   return std::error_code();
   1896 }
   1897 
   1898 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
   1899   SmallVector<uint64_t, 8> Words(Vals.size());
   1900   std::transform(Vals.begin(), Vals.end(), Words.begin(),
   1901                  BitcodeReader::decodeSignRotatedValue);
   1902 
   1903   return APInt(TypeBits, Words);
   1904 }
   1905 
   1906 std::error_code BitcodeReader::ParseConstants() {
   1907   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
   1908     return Error("Invalid record");
   1909 
   1910   SmallVector<uint64_t, 64> Record;
   1911 
   1912   // Read all the records for this value table.
   1913   Type *CurTy = Type::getInt32Ty(Context);
   1914   unsigned NextCstNo = ValueList.size();
   1915   while (1) {
   1916     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
   1917 
   1918     switch (Entry.Kind) {
   1919     case BitstreamEntry::SubBlock: // Handled for us already.
   1920     case BitstreamEntry::Error:
   1921       return Error("Malformed block");
   1922     case BitstreamEntry::EndBlock:
   1923       if (NextCstNo != ValueList.size())
   1924         return Error("Invalid constant reference");
   1925 
   1926       // Once all the constants have been read, go through and resolve forward
   1927       // references.
   1928       ValueList.ResolveConstantForwardRefs();
   1929       return std::error_code();
   1930     case BitstreamEntry::Record:
   1931       // The interesting case.
   1932       break;
   1933     }
   1934 
   1935     // Read a record.
   1936     Record.clear();
   1937     Value *V = nullptr;
   1938     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
   1939     switch (BitCode) {
   1940     default:  // Default behavior: unknown constant
   1941     case bitc::CST_CODE_UNDEF:     // UNDEF
   1942       V = UndefValue::get(CurTy);
   1943       break;
   1944     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
   1945       if (Record.empty())
   1946         return Error("Invalid record");
   1947       if (Record[0] >= TypeList.size())
   1948         return Error("Invalid record");
   1949       CurTy = TypeList[Record[0]];
   1950       continue;  // Skip the ValueList manipulation.
   1951     case bitc::CST_CODE_NULL:      // NULL
   1952       V = Constant::getNullValue(CurTy);
   1953       break;
   1954     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
   1955       if (!CurTy->isIntegerTy() || Record.empty())
   1956         return Error("Invalid record");
   1957       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
   1958       break;
   1959     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
   1960       if (!CurTy->isIntegerTy() || Record.empty())
   1961         return Error("Invalid record");
   1962 
   1963       APInt VInt = ReadWideAPInt(Record,
   1964                                  cast<IntegerType>(CurTy)->getBitWidth());
   1965       V = ConstantInt::get(Context, VInt);
   1966 
   1967       break;
   1968     }
   1969     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
   1970       if (Record.empty())
   1971         return Error("Invalid record");
   1972       if (CurTy->isHalfTy())
   1973         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
   1974                                              APInt(16, (uint16_t)Record[0])));
   1975       else if (CurTy->isFloatTy())
   1976         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
   1977                                              APInt(32, (uint32_t)Record[0])));
   1978       else if (CurTy->isDoubleTy())
   1979         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
   1980                                              APInt(64, Record[0])));
   1981       else if (CurTy->isX86_FP80Ty()) {
   1982         // Bits are not stored the same way as a normal i80 APInt, compensate.
   1983         uint64_t Rearrange[2];
   1984         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
   1985         Rearrange[1] = Record[0] >> 48;
   1986         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
   1987                                              APInt(80, Rearrange)));
   1988       } else if (CurTy->isFP128Ty())
   1989         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
   1990                                              APInt(128, Record)));
   1991       else if (CurTy->isPPC_FP128Ty())
   1992         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
   1993                                              APInt(128, Record)));
   1994       else
   1995         V = UndefValue::get(CurTy);
   1996       break;
   1997     }
   1998 
   1999     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
   2000       if (Record.empty())
   2001         return Error("Invalid record");
   2002 
   2003       unsigned Size = Record.size();
   2004       SmallVector<Constant*, 16> Elts;
   2005 
   2006       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
   2007         for (unsigned i = 0; i != Size; ++i)
   2008           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
   2009                                                      STy->getElementType(i)));
   2010         V = ConstantStruct::get(STy, Elts);
   2011       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
   2012         Type *EltTy = ATy->getElementType();
   2013         for (unsigned i = 0; i != Size; ++i)
   2014           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
   2015         V = ConstantArray::get(ATy, Elts);
   2016       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
   2017         Type *EltTy = VTy->getElementType();
   2018         for (unsigned i = 0; i != Size; ++i)
   2019           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
   2020         V = ConstantVector::get(Elts);
   2021       } else {
   2022         V = UndefValue::get(CurTy);
   2023       }
   2024       break;
   2025     }
   2026     case bitc::CST_CODE_STRING: { // STRING: [values]
   2027       if (Record.empty())
   2028         return Error("Invalid record");
   2029 
   2030       ArrayType *ATy = cast<ArrayType>(CurTy);
   2031       Type *EltTy = ATy->getElementType();
   2032 
   2033       unsigned Size = Record.size();
   2034       std::vector<Constant*> Elts;
   2035       for (unsigned i = 0; i != Size; ++i)
   2036         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
   2037       V = ConstantArray::get(ATy, Elts);
   2038       break;
   2039     }
   2040     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
   2041       if (Record.empty())
   2042         return Error("Invalid record");
   2043 
   2044       ArrayType *ATy = cast<ArrayType>(CurTy);
   2045       Type *EltTy = ATy->getElementType();
   2046 
   2047       unsigned Size = Record.size();
   2048       std::vector<Constant*> Elts;
   2049       for (unsigned i = 0; i != Size; ++i)
   2050         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
   2051       Elts.push_back(Constant::getNullValue(EltTy));
   2052       V = ConstantArray::get(ATy, Elts);
   2053       break;
   2054     }
   2055     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
   2056       if (Record.size() < 3)
   2057         return Error("Invalid record");
   2058       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
   2059       if (Opc < 0) {
   2060         V = UndefValue::get(CurTy);  // Unknown binop.
   2061       } else {
   2062         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
   2063         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
   2064         unsigned Flags = 0;
   2065         if (Record.size() >= 4) {
   2066           if (Opc == Instruction::Add ||
   2067               Opc == Instruction::Sub ||
   2068               Opc == Instruction::Mul ||
   2069               Opc == Instruction::Shl) {
   2070             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
   2071               Flags |= OverflowingBinaryOperator::NoSignedWrap;
   2072             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
   2073               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
   2074           } else if (Opc == Instruction::SDiv ||
   2075                      Opc == Instruction::UDiv ||
   2076                      Opc == Instruction::LShr ||
   2077                      Opc == Instruction::AShr) {
   2078             if (Record[3] & (1 << bitc::PEO_EXACT))
   2079               Flags |= SDivOperator::IsExact;
   2080           }
   2081         }
   2082         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
   2083       }
   2084       break;
   2085     }
   2086     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
   2087       if (Record.size() < 3)
   2088         return Error("Invalid record");
   2089       int Opc = GetDecodedCastOpcode(Record[0]);
   2090       if (Opc < 0) {
   2091         V = UndefValue::get(CurTy);  // Unknown cast.
   2092       } else {
   2093         Type *OpTy = getTypeByID(Record[1]);
   2094         if (!OpTy)
   2095           return Error("Invalid record");
   2096         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
   2097         V = ConstantExpr::getCast(Opc, Op, CurTy);
   2098       }
   2099       break;
   2100     }
   2101     case bitc::CST_CODE_CE_INBOUNDS_GEP:
   2102     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
   2103       Type *PointeeType = nullptr;
   2104       if (Record.size() & 1)
   2105         return Error("Invalid record");
   2106       SmallVector<Constant*, 16> Elts;
   2107       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
   2108         Type *ElTy = getTypeByID(Record[i]);
   2109         if (!ElTy)
   2110           return Error("Invalid record");
   2111         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
   2112       }
   2113       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
   2114       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
   2115                                          BitCode ==
   2116                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
   2117       break;
   2118     }
   2119     case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
   2120       if (Record.size() < 3)
   2121         return Error("Invalid record");
   2122       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
   2123                                                               Type::getInt1Ty(Context)),
   2124                                   ValueList.getConstantFwdRef(Record[1],CurTy),
   2125                                   ValueList.getConstantFwdRef(Record[2],CurTy));
   2126       break;
   2127     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
   2128       if (Record.size() < 3)
   2129         return Error("Invalid record");
   2130       VectorType *OpTy =
   2131         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
   2132       if (!OpTy)
   2133         return Error("Invalid record");
   2134       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
   2135       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
   2136       V = ConstantExpr::getExtractElement(Op0, Op1);
   2137       break;
   2138     }
   2139     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
   2140       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
   2141       if (Record.size() < 3 || !OpTy)
   2142         return Error("Invalid record");
   2143       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
   2144       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
   2145                                                   OpTy->getElementType());
   2146       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
   2147       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
   2148       break;
   2149     }
   2150     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
   2151       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
   2152       if (Record.size() < 3 || !OpTy)
   2153         return Error("Invalid record");
   2154       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
   2155       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
   2156       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
   2157                                                  OpTy->getNumElements());
   2158       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
   2159       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
   2160       break;
   2161     }
   2162     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
   2163       VectorType *RTy = dyn_cast<VectorType>(CurTy);
   2164       VectorType *OpTy =
   2165         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
   2166       if (Record.size() < 4 || !RTy || !OpTy)
   2167         return Error("Invalid record");
   2168       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
   2169       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
   2170       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
   2171                                                  RTy->getNumElements());
   2172       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
   2173       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
   2174       break;
   2175     }
   2176     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
   2177       if (Record.size() < 4)
   2178         return Error("Invalid record");
   2179       Type *OpTy = getTypeByID(Record[0]);
   2180       if (!OpTy)
   2181         return Error("Invalid record");
   2182       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
   2183       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
   2184 
   2185       if (OpTy->isFPOrFPVectorTy())
   2186         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
   2187       else
   2188         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
   2189       break;
   2190     }
   2191     case bitc::CST_CODE_INLINEASM:
   2192     case bitc::CST_CODE_INLINEASM_OLD: {
   2193       if (Record.size() < 2)
   2194         return Error("Invalid record");
   2195       std::string AsmStr, ConstrStr;
   2196       bool HasSideEffects = Record[0] & 1;
   2197       bool IsAlignStack = Record[0] >> 1;
   2198       unsigned AsmStrSize = Record[1];
   2199       if (2+AsmStrSize >= Record.size())
   2200         return Error("Invalid record");
   2201       unsigned ConstStrSize = Record[2+AsmStrSize];
   2202       if (3+AsmStrSize+ConstStrSize > Record.size())
   2203         return Error("Invalid record");
   2204 
   2205       for (unsigned i = 0; i != AsmStrSize; ++i)
   2206         AsmStr += (char)Record[2+i];
   2207       for (unsigned i = 0; i != ConstStrSize; ++i)
   2208         ConstrStr += (char)Record[3+AsmStrSize+i];
   2209       PointerType *PTy = cast<PointerType>(CurTy);
   2210       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
   2211                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
   2212       break;
   2213     }
   2214     case bitc::CST_CODE_BLOCKADDRESS:{
   2215       if (Record.size() < 3)
   2216         return Error("Invalid record");
   2217       Type *FnTy = getTypeByID(Record[0]);
   2218       if (!FnTy)
   2219         return Error("Invalid record");
   2220       Function *Fn =
   2221         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
   2222       if (!Fn)
   2223         return Error("Invalid record");
   2224 
   2225       GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
   2226                                                   Type::getInt8Ty(Context),
   2227                                             false, GlobalValue::InternalLinkage,
   2228                                                   0, "");
   2229       BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
   2230       V = FwdRef;
   2231       break;
   2232     }
   2233     }
   2234 
   2235     ValueList.AssignValue(V, NextCstNo);
   2236     ++NextCstNo;
   2237   }
   2238 
   2239   if (NextCstNo != ValueList.size())
   2240     return Error("Invalid constant reference");
   2241 
   2242   if (Stream.ReadBlockEnd())
   2243     return Error("Expected a constant");
   2244 
   2245   // Once all the constants have been read, go through and resolve forward
   2246   // references.
   2247   ValueList.ResolveConstantForwardRefs();
   2248   return std::error_code();
   2249 }
   2250 
   2251 std::error_code BitcodeReader::materializeMetadata() {
   2252   return std::error_code();
   2253 }
   2254 
   2255 void BitcodeReader::setStripDebugInfo() { }
   2256 
   2257 /// RememberAndSkipFunctionBody - When we see the block for a function body,
   2258 /// remember where it is and then skip it.  This lets us lazily deserialize the
   2259 /// functions.
   2260 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
   2261   // Get the function we are talking about.
   2262   if (FunctionsWithBodies.empty())
   2263     return Error("Insufficient function protos");
   2264 
   2265   Function *Fn = FunctionsWithBodies.back();
   2266   FunctionsWithBodies.pop_back();
   2267 
   2268   // Save the current stream state.
   2269   uint64_t CurBit = Stream.GetCurrentBitNo();
   2270   DeferredFunctionInfo[Fn] = CurBit;
   2271 
   2272   // Skip over the function block for now.
   2273   if (Stream.SkipBlock())
   2274     return Error("Invalid record");
   2275   return std::error_code();
   2276 }
   2277 
   2278 std::error_code BitcodeReader::GlobalCleanup() {
   2279   // Patch the initializers for globals and aliases up.
   2280   ResolveGlobalAndAliasInits();
   2281   if (!GlobalInits.empty() || !AliasInits.empty())
   2282     return Error("Malformed global initializer set");
   2283 
   2284   // Look for intrinsic functions which need to be upgraded at some point
   2285   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
   2286        FI != FE; ++FI) {
   2287     Function *NewFn;
   2288     if (UpgradeIntrinsicFunction(&*FI, NewFn))
   2289       UpgradedIntrinsics.push_back(std::make_pair(&*FI, NewFn));
   2290   }
   2291 
   2292   // Look for global variables which need to be renamed.
   2293   for (Module::global_iterator
   2294          GI = TheModule->global_begin(), GE = TheModule->global_end();
   2295        GI != GE; GI++) {
   2296     GlobalVariable *GV = &*GI;
   2297     UpgradeGlobalVariable(GV);
   2298   }
   2299 
   2300   // Force deallocation of memory for these vectors to favor the client that
   2301   // want lazy deserialization.
   2302   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
   2303   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
   2304   return std::error_code();
   2305 }
   2306 
   2307 std::error_code BitcodeReader::ParseModule(bool Resume) {
   2308   if (Resume)
   2309     Stream.JumpToBit(NextUnreadBit);
   2310   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
   2311     return Error("Invalid record");
   2312 
   2313   SmallVector<uint64_t, 64> Record;
   2314   std::vector<std::string> SectionTable;
   2315   std::vector<std::string> GCTable;
   2316 
   2317   // Read all the records for this module.
   2318   while (1) {
   2319     BitstreamEntry Entry = Stream.advance();
   2320 
   2321     switch (Entry.Kind) {
   2322     case BitstreamEntry::Error:
   2323       return Error("Malformed block");
   2324     case BitstreamEntry::EndBlock:
   2325       return GlobalCleanup();
   2326 
   2327     case BitstreamEntry::SubBlock:
   2328       switch (Entry.ID) {
   2329       default:  // Skip unknown content.
   2330         if (Stream.SkipBlock())
   2331           return Error("Invalid record");
   2332         break;
   2333       case bitc::BLOCKINFO_BLOCK_ID:
   2334         if (Stream.ReadBlockInfoBlock())
   2335           return Error("Malformed block");
   2336         break;
   2337       case bitc::PARAMATTR_BLOCK_ID:
   2338         if (std::error_code EC = ParseAttributeBlock())
   2339           return EC;
   2340         break;
   2341       case bitc::TYPE_BLOCK_ID_NEW:
   2342         if (std::error_code EC = ParseTypeTable())
   2343           return EC;
   2344         break;
   2345       case TYPE_BLOCK_ID_OLD_3_0:
   2346         if (std::error_code EC = ParseOldTypeTable())
   2347           return EC;
   2348         break;
   2349       case TYPE_SYMTAB_BLOCK_ID_OLD_3_0:
   2350         if (std::error_code EC = ParseOldTypeSymbolTable())
   2351           return EC;
   2352         break;
   2353       case bitc::VALUE_SYMTAB_BLOCK_ID:
   2354         if (std::error_code EC = ParseValueSymbolTable())
   2355           return EC;
   2356         SeenValueSymbolTable = true;
   2357         break;
   2358       case bitc::CONSTANTS_BLOCK_ID:
   2359         if (std::error_code EC = ParseConstants())
   2360           return EC;
   2361         if (std::error_code EC = ResolveGlobalAndAliasInits())
   2362           return EC;
   2363         break;
   2364       case bitc::METADATA_BLOCK_ID:
   2365         if (std::error_code EC = ParseMetadata())
   2366           return EC;
   2367         break;
   2368       case bitc::FUNCTION_BLOCK_ID:
   2369         // If this is the first function body we've seen, reverse the
   2370         // FunctionsWithBodies list.
   2371         if (!SeenFirstFunctionBody) {
   2372           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
   2373           if (std::error_code EC = GlobalCleanup())
   2374             return EC;
   2375           SeenFirstFunctionBody = true;
   2376         }
   2377 
   2378         if (std::error_code EC = RememberAndSkipFunctionBody())
   2379           return EC;
   2380         // For streaming bitcode, suspend parsing when we reach the function
   2381         // bodies. Subsequent materialization calls will resume it when
   2382         // necessary. For streaming, the function bodies must be at the end of
   2383         // the bitcode. If the bitcode file is old, the symbol table will be
   2384         // at the end instead and will not have been seen yet. In this case,
   2385         // just finish the parse now.
   2386         if (LazyStreamer && SeenValueSymbolTable) {
   2387           NextUnreadBit = Stream.GetCurrentBitNo();
   2388           return std::error_code();
   2389         }
   2390         break;
   2391         break;
   2392       }
   2393       continue;
   2394 
   2395     case BitstreamEntry::Record:
   2396       // The interesting case.
   2397       break;
   2398     }
   2399 
   2400 
   2401     // Read a record.
   2402     switch (Stream.readRecord(Entry.ID, Record)) {
   2403     default: break;  // Default behavior, ignore unknown content.
   2404     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
   2405       if (Record.size() < 1)
   2406         return Error("Invalid record");
   2407       // Only version #0 is supported so far.
   2408       if (Record[0] != 0)
   2409         return Error("Invalid value");
   2410       break;
   2411     }
   2412     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
   2413       std::string S;
   2414       if (ConvertToString(Record, 0, S))
   2415         return Error("Invalid record");
   2416       TheModule->setTargetTriple(S);
   2417       break;
   2418     }
   2419     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
   2420       std::string S;
   2421       if (ConvertToString(Record, 0, S))
   2422         return Error("Invalid record");
   2423       TheModule->setDataLayout(S);
   2424       break;
   2425     }
   2426     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
   2427       std::string S;
   2428       if (ConvertToString(Record, 0, S))
   2429         return Error("Invalid record");
   2430       TheModule->setModuleInlineAsm(S);
   2431       break;
   2432     }
   2433     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
   2434       std::string S;
   2435       if (ConvertToString(Record, 0, S))
   2436         return Error("Invalid record");
   2437       // ANDROID: Ignore value, since we never used it anyways.
   2438       // TheModule->addLibrary(S);
   2439       break;
   2440     }
   2441     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
   2442       std::string S;
   2443       if (ConvertToString(Record, 0, S))
   2444         return Error("Invalid record");
   2445       SectionTable.push_back(S);
   2446       break;
   2447     }
   2448     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
   2449       std::string S;
   2450       if (ConvertToString(Record, 0, S))
   2451         return Error("Invalid record");
   2452       GCTable.push_back(S);
   2453       break;
   2454     }
   2455     // GLOBALVAR: [pointer type, isconst, initid,
   2456     //             linkage, alignment, section, visibility, threadlocal,
   2457     //             unnamed_addr]
   2458     case bitc::MODULE_CODE_GLOBALVAR: {
   2459       if (Record.size() < 6)
   2460         return Error("Invalid record");
   2461       Type *Ty = getTypeByID(Record[0]);
   2462       if (!Ty)
   2463         return Error("Invalid record");
   2464       if (!Ty->isPointerTy())
   2465         return Error("Invalid type for value");
   2466       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
   2467       Ty = cast<PointerType>(Ty)->getElementType();
   2468 
   2469       bool isConstant = Record[1];
   2470       uint64_t RawLinkage = Record[3];
   2471       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
   2472       unsigned Alignment = (1 << Record[4]) >> 1;
   2473       std::string Section;
   2474       if (Record[5]) {
   2475         if (Record[5]-1 >= SectionTable.size())
   2476           return Error("Invalid ID");
   2477         Section = SectionTable[Record[5]-1];
   2478       }
   2479       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
   2480       if (Record.size() > 6)
   2481         Visibility = GetDecodedVisibility(Record[6]);
   2482 
   2483       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
   2484       if (Record.size() > 7)
   2485         TLM = GetDecodedThreadLocalMode(Record[7]);
   2486 
   2487       bool UnnamedAddr = false;
   2488       if (Record.size() > 8)
   2489         UnnamedAddr = Record[8];
   2490 
   2491       GlobalVariable *NewGV =
   2492         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
   2493                            TLM, AddressSpace);
   2494       NewGV->setAlignment(Alignment);
   2495       if (!Section.empty())
   2496         NewGV->setSection(Section);
   2497       NewGV->setVisibility(Visibility);
   2498       NewGV->setUnnamedAddr(UnnamedAddr);
   2499 
   2500       ValueList.push_back(NewGV);
   2501 
   2502       // Remember which value to use for the global initializer.
   2503       if (unsigned InitID = Record[2])
   2504         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
   2505       break;
   2506     }
   2507     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
   2508     //             alignment, section, visibility, gc, unnamed_addr]
   2509     case bitc::MODULE_CODE_FUNCTION: {
   2510       if (Record.size() < 8)
   2511         return Error("Invalid record");
   2512       Type *Ty = getTypeByID(Record[0]);
   2513       if (!Ty)
   2514         return Error("Invalid record");
   2515       if (!Ty->isPointerTy())
   2516         return Error("Invalid type for value");
   2517       FunctionType *FTy =
   2518         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
   2519       if (!FTy)
   2520         return Error("Invalid type for value");
   2521 
   2522       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
   2523                                         "", TheModule);
   2524 
   2525       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
   2526       bool isProto = Record[2];
   2527       uint64_t RawLinkage = Record[3];
   2528       Func->setLinkage(getDecodedLinkage(RawLinkage));
   2529       Func->setAttributes(getAttributes(Record[4]));
   2530 
   2531       Func->setAlignment((1 << Record[5]) >> 1);
   2532       if (Record[6]) {
   2533         if (Record[6]-1 >= SectionTable.size())
   2534           return Error("Invalid ID");
   2535         Func->setSection(SectionTable[Record[6]-1]);
   2536       }
   2537       Func->setVisibility(GetDecodedVisibility(Record[7]));
   2538       if (Record.size() > 8 && Record[8]) {
   2539         if (Record[8]-1 > GCTable.size())
   2540           return Error("Invalid ID");
   2541         Func->setGC(GCTable[Record[8]-1].c_str());
   2542       }
   2543       bool UnnamedAddr = false;
   2544       if (Record.size() > 9)
   2545         UnnamedAddr = Record[9];
   2546       Func->setUnnamedAddr(UnnamedAddr);
   2547       ValueList.push_back(Func);
   2548 
   2549       // If this is a function with a body, remember the prototype we are
   2550       // creating now, so that we can match up the body with them later.
   2551       if (!isProto) {
   2552         Func->setIsMaterializable(true);
   2553         FunctionsWithBodies.push_back(Func);
   2554         if (LazyStreamer)
   2555           DeferredFunctionInfo[Func] = 0;
   2556       }
   2557       break;
   2558     }
   2559     // ALIAS: [alias type, aliasee val#, linkage]
   2560     // ALIAS: [alias type, aliasee val#, linkage, visibility]
   2561     case bitc::MODULE_CODE_ALIAS_OLD: {
   2562       if (Record.size() < 3)
   2563         return Error("Invalid record");
   2564       Type *Ty = getTypeByID(Record[0]);
   2565       if (!Ty)
   2566         return Error("Invalid record");
   2567       auto *PTy = dyn_cast<PointerType>(Ty);
   2568       if (!PTy)
   2569         return Error("Invalid type for value");
   2570 
   2571       auto *NewGA =
   2572           GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
   2573                               getDecodedLinkage(Record[2]), "", TheModule);
   2574       // Old bitcode files didn't have visibility field.
   2575       if (Record.size() > 3)
   2576         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
   2577       ValueList.push_back(NewGA);
   2578       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
   2579       break;
   2580     }
   2581     /// MODULE_CODE_PURGEVALS: [numvals]
   2582     case bitc::MODULE_CODE_PURGEVALS:
   2583       // Trim down the value list to the specified size.
   2584       if (Record.size() < 1 || Record[0] > ValueList.size())
   2585         return Error("Invalid record");
   2586       ValueList.shrinkTo(Record[0]);
   2587       break;
   2588     }
   2589     Record.clear();
   2590   }
   2591 }
   2592 
   2593 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
   2594   TheModule = nullptr;
   2595 
   2596   if (std::error_code EC = InitStream())
   2597     return EC;
   2598 
   2599   // Sniff for the signature.
   2600   if (Stream.Read(8) != 'B' ||
   2601       Stream.Read(8) != 'C' ||
   2602       Stream.Read(4) != 0x0 ||
   2603       Stream.Read(4) != 0xC ||
   2604       Stream.Read(4) != 0xE ||
   2605       Stream.Read(4) != 0xD)
   2606     return Error("Invalid bitcode signature");
   2607 
   2608   // We expect a number of well-defined blocks, though we don't necessarily
   2609   // need to understand them all.
   2610   while (1) {
   2611     if (Stream.AtEndOfStream())
   2612       return std::error_code();
   2613 
   2614     BitstreamEntry Entry =
   2615       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
   2616 
   2617     switch (Entry.Kind) {
   2618     case BitstreamEntry::Error:
   2619       return Error("Malformed block");
   2620     case BitstreamEntry::EndBlock:
   2621       return std::error_code();
   2622 
   2623     case BitstreamEntry::SubBlock:
   2624       switch (Entry.ID) {
   2625       case bitc::BLOCKINFO_BLOCK_ID:
   2626         if (Stream.ReadBlockInfoBlock())
   2627           return Error("Malformed block");
   2628         break;
   2629       case bitc::MODULE_BLOCK_ID:
   2630         // Reject multiple MODULE_BLOCK's in a single bitstream.
   2631         if (TheModule)
   2632           return Error("Invalid multiple blocks");
   2633         TheModule = M;
   2634         if (std::error_code EC = ParseModule(false))
   2635           return EC;
   2636         if (LazyStreamer)
   2637           return std::error_code();
   2638         break;
   2639       default:
   2640         if (Stream.SkipBlock())
   2641           return Error("Invalid record");
   2642         break;
   2643       }
   2644       continue;
   2645     case BitstreamEntry::Record:
   2646       // There should be no records in the top-level of blocks.
   2647 
   2648       // The ranlib in Xcode 4 will align archive members by appending newlines
   2649       // to the end of them. If this file size is a multiple of 4 but not 8, we
   2650       // have to read and ignore these final 4 bytes :-(
   2651       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
   2652           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
   2653           Stream.AtEndOfStream())
   2654         return std::error_code();
   2655 
   2656       return Error("Invalid record");
   2657     }
   2658   }
   2659 }
   2660 
   2661 llvm::ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
   2662   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
   2663     return Error("Invalid record");
   2664 
   2665   SmallVector<uint64_t, 64> Record;
   2666 
   2667   std::string Triple;
   2668   // Read all the records for this module.
   2669   while (1) {
   2670     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
   2671 
   2672     switch (Entry.Kind) {
   2673     case BitstreamEntry::SubBlock: // Handled for us already.
   2674     case BitstreamEntry::Error:
   2675       return Error("Malformed block");
   2676     case BitstreamEntry::EndBlock:
   2677       return Triple;
   2678     case BitstreamEntry::Record:
   2679       // The interesting case.
   2680       break;
   2681     }
   2682 
   2683     // Read a record.
   2684     switch (Stream.readRecord(Entry.ID, Record)) {
   2685     default: break;  // Default behavior, ignore unknown content.
   2686     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
   2687       if (Record.size() < 1)
   2688         return Error("Invalid record");
   2689       // Only version #0 is supported so far.
   2690       if (Record[0] != 0)
   2691         return Error("Invalid record");
   2692       break;
   2693     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
   2694       std::string S;
   2695       if (ConvertToString(Record, 0, S))
   2696         return Error("Invalid record");
   2697       Triple = S;
   2698       break;
   2699     }
   2700     }
   2701     Record.clear();
   2702   }
   2703 
   2704   return Error("Invalid bitcode signature");
   2705 }
   2706 
   2707 llvm::ErrorOr<std::string> BitcodeReader::parseTriple() {
   2708   if (std::error_code EC = InitStream())
   2709     return EC;
   2710 
   2711   // Sniff for the signature.
   2712   if (Stream.Read(8) != 'B' ||
   2713       Stream.Read(8) != 'C' ||
   2714       Stream.Read(4) != 0x0 ||
   2715       Stream.Read(4) != 0xC ||
   2716       Stream.Read(4) != 0xE ||
   2717       Stream.Read(4) != 0xD)
   2718     return Error("Invalid bitcode signature");
   2719 
   2720   // We expect a number of well-defined blocks, though we don't necessarily
   2721   // need to understand them all.
   2722   while (1) {
   2723     BitstreamEntry Entry = Stream.advance();
   2724 
   2725     switch (Entry.Kind) {
   2726     case BitstreamEntry::Error:
   2727       return Error("Malformed block");
   2728     case BitstreamEntry::EndBlock:
   2729       return std::error_code();
   2730 
   2731     case BitstreamEntry::SubBlock:
   2732       if (Entry.ID == bitc::MODULE_BLOCK_ID)
   2733         return parseModuleTriple();
   2734 
   2735       // Ignore other sub-blocks.
   2736       if (Stream.SkipBlock())
   2737         return Error("Malformed block");
   2738       continue;
   2739 
   2740     case BitstreamEntry::Record:
   2741       Stream.skipRecord(Entry.ID);
   2742       continue;
   2743     }
   2744   }
   2745 }
   2746 
   2747 /// ParseMetadataAttachment - Parse metadata attachments.
   2748 std::error_code BitcodeReader::ParseMetadataAttachment() {
   2749   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
   2750     return Error("Invalid record");
   2751 
   2752   SmallVector<uint64_t, 64> Record;
   2753   while (1) {
   2754     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
   2755 
   2756     switch (Entry.Kind) {
   2757     case BitstreamEntry::SubBlock: // Handled for us already.
   2758     case BitstreamEntry::Error:
   2759       return Error("Malformed block");
   2760     case BitstreamEntry::EndBlock:
   2761       return std::error_code();
   2762     case BitstreamEntry::Record:
   2763       // The interesting case.
   2764       break;
   2765     }
   2766 
   2767     // Read a metadata attachment record.
   2768     Record.clear();
   2769     switch (Stream.readRecord(Entry.ID, Record)) {
   2770     default:  // Default behavior: ignore.
   2771       break;
   2772     case bitc::METADATA_ATTACHMENT: {
   2773       unsigned RecordLength = Record.size();
   2774       if (Record.empty() || (RecordLength - 1) % 2 == 1)
   2775         return Error("Invalid record");
   2776       Instruction *Inst = InstructionList[Record[0]];
   2777       for (unsigned i = 1; i != RecordLength; i = i+2) {
   2778         unsigned Kind = Record[i];
   2779         DenseMap<unsigned, unsigned>::iterator I =
   2780           MDKindMap.find(Kind);
   2781         if (I == MDKindMap.end())
   2782           return Error("Invalid ID");
   2783         Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
   2784         Inst->setMetadata(I->second, cast<MDNode>(Node));
   2785       }
   2786       break;
   2787     }
   2788     }
   2789   }
   2790 }
   2791 
   2792 /// ParseFunctionBody - Lazily parse the specified function body block.
   2793 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
   2794   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
   2795     return Error("Invalid record");
   2796 
   2797   InstructionList.clear();
   2798   unsigned ModuleValueListSize = ValueList.size();
   2799   unsigned ModuleMDValueListSize = MDValueList.size();
   2800 
   2801   // Add all the function arguments to the value table.
   2802   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
   2803     ValueList.push_back(&*I);
   2804 
   2805   unsigned NextValueNo = ValueList.size();
   2806   BasicBlock *CurBB = nullptr;
   2807   unsigned CurBBNo = 0;
   2808 
   2809   DebugLoc LastLoc;
   2810 
   2811   // Read all the records.
   2812   SmallVector<uint64_t, 64> Record;
   2813   while (1) {
   2814     unsigned Code = Stream.ReadCode();
   2815     if (Code == bitc::END_BLOCK) {
   2816       if (Stream.ReadBlockEnd())
   2817         return Error("Malformed block");
   2818       break;
   2819     }
   2820 
   2821     if (Code == bitc::ENTER_SUBBLOCK) {
   2822       switch (Stream.ReadSubBlockID()) {
   2823       default:  // Skip unknown content.
   2824         if (Stream.SkipBlock())
   2825           return Error("Invalid record");
   2826         break;
   2827       case bitc::CONSTANTS_BLOCK_ID:
   2828         if (std::error_code EC = ParseConstants())
   2829           return EC;
   2830         NextValueNo = ValueList.size();
   2831         break;
   2832       case bitc::VALUE_SYMTAB_BLOCK_ID:
   2833         if (std::error_code EC = ParseValueSymbolTable())
   2834           return EC;
   2835         break;
   2836       case bitc::METADATA_ATTACHMENT_ID:
   2837         if (std::error_code EC = ParseMetadataAttachment())
   2838           return EC;
   2839         break;
   2840       case bitc::METADATA_BLOCK_ID:
   2841         if (std::error_code EC = ParseMetadata())
   2842           return EC;
   2843         break;
   2844       }
   2845       continue;
   2846     }
   2847 
   2848     if (Code == bitc::DEFINE_ABBREV) {
   2849       Stream.ReadAbbrevRecord();
   2850       continue;
   2851     }
   2852 
   2853     // Read a record.
   2854     Record.clear();
   2855     Instruction *I = nullptr;
   2856     unsigned BitCode = Stream.readRecord(Code, Record);
   2857     switch (BitCode) {
   2858     default: // Default behavior: reject
   2859       return Error("Invalid value");
   2860     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
   2861       if (Record.size() < 1 || Record[0] == 0)
   2862         return Error("Invalid record");
   2863       // Create all the basic blocks for the function.
   2864       FunctionBBs.resize(Record[0]);
   2865       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
   2866         FunctionBBs[i] = BasicBlock::Create(Context, "", F);
   2867       CurBB = FunctionBBs[0];
   2868       continue;
   2869 
   2870     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
   2871       // This record indicates that the last instruction is at the same
   2872       // location as the previous instruction with a location.
   2873       I = nullptr;
   2874 
   2875       // Get the last instruction emitted.
   2876       if (CurBB && !CurBB->empty())
   2877         I = &CurBB->back();
   2878       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
   2879                !FunctionBBs[CurBBNo-1]->empty())
   2880         I = &FunctionBBs[CurBBNo-1]->back();
   2881 
   2882       if (!I)
   2883         return Error("Invalid record");
   2884       I->setDebugLoc(LastLoc);
   2885       I = nullptr;
   2886       continue;
   2887 
   2888     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
   2889       I = nullptr;     // Get the last instruction emitted.
   2890       if (CurBB && !CurBB->empty())
   2891         I = &CurBB->back();
   2892       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
   2893                !FunctionBBs[CurBBNo-1]->empty())
   2894         I = &FunctionBBs[CurBBNo-1]->back();
   2895       if (!I || Record.size() < 4)
   2896         return Error("Invalid record");
   2897 
   2898       unsigned Line = Record[0], Col = Record[1];
   2899       unsigned ScopeID = Record[2], IAID = Record[3];
   2900 
   2901       MDNode *Scope = nullptr, *IA = nullptr;
   2902       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
   2903       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
   2904       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
   2905       I->setDebugLoc(LastLoc);
   2906       I = nullptr;
   2907       continue;
   2908     }
   2909 
   2910     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
   2911       unsigned OpNum = 0;
   2912       Value *LHS, *RHS;
   2913       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
   2914           getValue(Record, OpNum, LHS->getType(), RHS) ||
   2915           OpNum+1 > Record.size())
   2916         return Error("Invalid record");
   2917 
   2918       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
   2919       if (Opc == -1)
   2920         return Error("Invalid record");
   2921       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
   2922       InstructionList.push_back(I);
   2923       if (OpNum < Record.size()) {
   2924         if (Opc == Instruction::Add ||
   2925             Opc == Instruction::Sub ||
   2926             Opc == Instruction::Mul ||
   2927             Opc == Instruction::Shl) {
   2928           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
   2929             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
   2930           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
   2931             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
   2932         } else if (Opc == Instruction::SDiv ||
   2933                    Opc == Instruction::UDiv ||
   2934                    Opc == Instruction::LShr ||
   2935                    Opc == Instruction::AShr) {
   2936           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
   2937             cast<BinaryOperator>(I)->setIsExact(true);
   2938         }
   2939       }
   2940       break;
   2941     }
   2942     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
   2943       unsigned OpNum = 0;
   2944       Value *Op;
   2945       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
   2946           OpNum+2 != Record.size())
   2947         return Error("Invalid record");
   2948 
   2949       Type *ResTy = getTypeByID(Record[OpNum]);
   2950       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
   2951       if (Opc == -1 || !ResTy)
   2952         return Error("Invalid record");
   2953       I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
   2954       InstructionList.push_back(I);
   2955       break;
   2956     }
   2957     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
   2958     case bitc::FUNC_CODE_INST_GEP_OLD: // GEP: [n x operands]
   2959     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
   2960       unsigned OpNum = 0;
   2961 
   2962       Type *Ty;
   2963       bool InBounds;
   2964 
   2965       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
   2966         InBounds = Record[OpNum++];
   2967         Ty = getTypeByID(Record[OpNum++]);
   2968       } else {
   2969         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
   2970         Ty = nullptr;
   2971       }
   2972 
   2973       Value *BasePtr;
   2974       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
   2975         return Error("Invalid record");
   2976 
   2977       if (Ty &&
   2978           Ty !=
   2979               cast<SequentialType>(BasePtr->getType()->getScalarType())
   2980                   ->getElementType())
   2981         return Error(
   2982             "Explicit gep type does not match pointee type of pointer operand");
   2983 
   2984       SmallVector<Value*, 16> GEPIdx;
   2985       while (OpNum != Record.size()) {
   2986         Value *Op;
   2987         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
   2988           return Error("Invalid record");
   2989         GEPIdx.push_back(Op);
   2990       }
   2991 
   2992       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
   2993 
   2994       InstructionList.push_back(I);
   2995       if (InBounds)
   2996         cast<GetElementPtrInst>(I)->setIsInBounds(true);
   2997       break;
   2998     }
   2999 
   3000     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
   3001                                        // EXTRACTVAL: [opty, opval, n x indices]
   3002       unsigned OpNum = 0;
   3003       Value *Agg;
   3004       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
   3005         return Error("Invalid record");
   3006 
   3007       SmallVector<unsigned, 4> EXTRACTVALIdx;
   3008       for (unsigned RecSize = Record.size();
   3009            OpNum != RecSize; ++OpNum) {
   3010         uint64_t Index = Record[OpNum];
   3011         if ((unsigned)Index != Index)
   3012           return Error("Invalid value");
   3013         EXTRACTVALIdx.push_back((unsigned)Index);
   3014       }
   3015 
   3016       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
   3017       InstructionList.push_back(I);
   3018       break;
   3019     }
   3020 
   3021     case bitc::FUNC_CODE_INST_INSERTVAL: {
   3022                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
   3023       unsigned OpNum = 0;
   3024       Value *Agg;
   3025       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
   3026         return Error("Invalid record");
   3027       Value *Val;
   3028       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
   3029         return Error("Invalid record");
   3030 
   3031       SmallVector<unsigned, 4> INSERTVALIdx;
   3032       for (unsigned RecSize = Record.size();
   3033            OpNum != RecSize; ++OpNum) {
   3034         uint64_t Index = Record[OpNum];
   3035         if ((unsigned)Index != Index)
   3036           return Error("Invalid value");
   3037         INSERTVALIdx.push_back((unsigned)Index);
   3038       }
   3039 
   3040       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
   3041       InstructionList.push_back(I);
   3042       break;
   3043     }
   3044 
   3045     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
   3046       // obsolete form of select
   3047       // handles select i1 ... in old bitcode
   3048       unsigned OpNum = 0;
   3049       Value *TrueVal, *FalseVal, *Cond;
   3050       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
   3051           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
   3052           getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
   3053         return Error("Invalid record");
   3054 
   3055       I = SelectInst::Create(Cond, TrueVal, FalseVal);
   3056       InstructionList.push_back(I);
   3057       break;
   3058     }
   3059 
   3060     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
   3061       // new form of select
   3062       // handles select i1 or select [N x i1]
   3063       unsigned OpNum = 0;
   3064       Value *TrueVal, *FalseVal, *Cond;
   3065       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
   3066           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
   3067           getValueTypePair(Record, OpNum, NextValueNo, Cond))
   3068         return Error("Invalid record");
   3069 
   3070       // select condition can be either i1 or [N x i1]
   3071       if (VectorType* vector_type =
   3072           dyn_cast<VectorType>(Cond->getType())) {
   3073         // expect <n x i1>
   3074         if (vector_type->getElementType() != Type::getInt1Ty(Context))
   3075           return Error("Invalid type for value");
   3076       } else {
   3077         // expect i1
   3078         if (Cond->getType() != Type::getInt1Ty(Context))
   3079           return Error("Invalid type for value");
   3080       }
   3081 
   3082       I = SelectInst::Create(Cond, TrueVal, FalseVal);
   3083       InstructionList.push_back(I);
   3084       break;
   3085     }
   3086 
   3087     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
   3088       unsigned OpNum = 0;
   3089       Value *Vec, *Idx;
   3090       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
   3091           getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
   3092         return Error("Invalid record");
   3093       I = ExtractElementInst::Create(Vec, Idx);
   3094       InstructionList.push_back(I);
   3095       break;
   3096     }
   3097 
   3098     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
   3099       unsigned OpNum = 0;
   3100       Value *Vec, *Elt, *Idx;
   3101       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
   3102           getValue(Record, OpNum,
   3103                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
   3104           getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
   3105         return Error("Invalid record");
   3106       I = InsertElementInst::Create(Vec, Elt, Idx);
   3107       InstructionList.push_back(I);
   3108       break;
   3109     }
   3110 
   3111     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
   3112       unsigned OpNum = 0;
   3113       Value *Vec1, *Vec2, *Mask;
   3114       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
   3115           getValue(Record, OpNum, Vec1->getType(), Vec2))
   3116         return Error("Invalid record");
   3117 
   3118       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
   3119         return Error("Invalid record");
   3120       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
   3121       InstructionList.push_back(I);
   3122       break;
   3123     }
   3124 
   3125     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
   3126       // Old form of ICmp/FCmp returning bool
   3127       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
   3128       // both legal on vectors but had different behaviour.
   3129     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
   3130       // FCmp/ICmp returning bool or vector of bool
   3131 
   3132       unsigned OpNum = 0;
   3133       Value *LHS, *RHS;
   3134       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
   3135           getValue(Record, OpNum, LHS->getType(), RHS) ||
   3136           OpNum+1 != Record.size())
   3137         return Error("Invalid record");
   3138 
   3139       if (LHS->getType()->isFPOrFPVectorTy())
   3140         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
   3141       else
   3142         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
   3143       InstructionList.push_back(I);
   3144       break;
   3145     }
   3146 
   3147     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
   3148       {
   3149         unsigned Size = Record.size();
   3150         if (Size == 0) {
   3151           I = ReturnInst::Create(Context);
   3152           InstructionList.push_back(I);
   3153           break;
   3154         }
   3155 
   3156         unsigned OpNum = 0;
   3157         Value *Op = nullptr;
   3158         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
   3159           return Error("Invalid record");
   3160         if (OpNum != Record.size())
   3161           return Error("Invalid record");
   3162 
   3163         I = ReturnInst::Create(Context, Op);
   3164         InstructionList.push_back(I);
   3165         break;
   3166       }
   3167     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
   3168       if (Record.size() != 1 && Record.size() != 3)
   3169         return Error("Invalid record");
   3170       BasicBlock *TrueDest = getBasicBlock(Record[0]);
   3171       if (!TrueDest)
   3172         return Error("Invalid record");
   3173 
   3174       if (Record.size() == 1) {
   3175         I = BranchInst::Create(TrueDest);
   3176         InstructionList.push_back(I);
   3177       }
   3178       else {
   3179         BasicBlock *FalseDest = getBasicBlock(Record[1]);
   3180         Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
   3181         if (!FalseDest || !Cond)
   3182           return Error("Invalid record");
   3183         I = BranchInst::Create(TrueDest, FalseDest, Cond);
   3184         InstructionList.push_back(I);
   3185       }
   3186       break;
   3187     }
   3188     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
   3189       if (Record.size() < 3 || (Record.size() & 1) == 0)
   3190         return Error("Invalid record");
   3191       Type *OpTy = getTypeByID(Record[0]);
   3192       Value *Cond = getFnValueByID(Record[1], OpTy);
   3193       BasicBlock *Default = getBasicBlock(Record[2]);
   3194       if (!OpTy || !Cond || !Default)
   3195         return Error("Invalid record");
   3196       unsigned NumCases = (Record.size()-3)/2;
   3197       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
   3198       InstructionList.push_back(SI);
   3199       for (unsigned i = 0, e = NumCases; i != e; ++i) {
   3200         ConstantInt *CaseVal =
   3201           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
   3202         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
   3203         if (!CaseVal || !DestBB) {
   3204           delete SI;
   3205           return Error("Invalid record");
   3206         }
   3207         SI->addCase(CaseVal, DestBB);
   3208       }
   3209       I = SI;
   3210       break;
   3211     }
   3212     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
   3213       if (Record.size() < 2)
   3214         return Error("Invalid record");
   3215       Type *OpTy = getTypeByID(Record[0]);
   3216       Value *Address = getFnValueByID(Record[1], OpTy);
   3217       if (!OpTy || !Address)
   3218         return Error("Invalid record");
   3219       unsigned NumDests = Record.size()-2;
   3220       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
   3221       InstructionList.push_back(IBI);
   3222       for (unsigned i = 0, e = NumDests; i != e; ++i) {
   3223         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
   3224           IBI->addDestination(DestBB);
   3225         } else {
   3226           delete IBI;
   3227           return Error("Invalid record");
   3228         }
   3229       }
   3230       I = IBI;
   3231       break;
   3232     }
   3233 
   3234     case bitc::FUNC_CODE_INST_INVOKE: {
   3235       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
   3236       if (Record.size() < 4)
   3237         return Error("Invalid record");
   3238       AttributeSet PAL = getAttributes(Record[0]);
   3239       unsigned CCInfo = Record[1];
   3240       BasicBlock *NormalBB = getBasicBlock(Record[2]);
   3241       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
   3242 
   3243       unsigned OpNum = 4;
   3244       Value *Callee;
   3245       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
   3246         return Error("Invalid record");
   3247 
   3248       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
   3249       FunctionType *FTy = !CalleeTy ? nullptr :
   3250         dyn_cast<FunctionType>(CalleeTy->getElementType());
   3251 
   3252       // Check that the right number of fixed parameters are here.
   3253       if (!FTy || !NormalBB || !UnwindBB ||
   3254           Record.size() < OpNum+FTy->getNumParams())
   3255         return Error("Invalid record");
   3256 
   3257       SmallVector<Value*, 16> Ops;
   3258       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
   3259         Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
   3260         if (!Ops.back())
   3261           return Error("Invalid record");
   3262       }
   3263 
   3264       if (!FTy->isVarArg()) {
   3265         if (Record.size() != OpNum)
   3266           return Error("Invalid record");
   3267       } else {
   3268         // Read type/value pairs for varargs params.
   3269         while (OpNum != Record.size()) {
   3270           Value *Op;
   3271           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
   3272             return Error("Invalid record");
   3273           Ops.push_back(Op);
   3274         }
   3275       }
   3276 
   3277       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
   3278       InstructionList.push_back(I);
   3279       cast<InvokeInst>(I)->setCallingConv(
   3280         static_cast<CallingConv::ID>(CCInfo));
   3281       cast<InvokeInst>(I)->setAttributes(PAL);
   3282       break;
   3283     }
   3284     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
   3285       unsigned Idx = 0;
   3286       Value *Val = nullptr;
   3287       if (getValueTypePair(Record, Idx, NextValueNo, Val))
   3288         return Error("Invalid record");
   3289       I = ResumeInst::Create(Val);
   3290       InstructionList.push_back(I);
   3291       break;
   3292     }
   3293     case FUNC_CODE_INST_UNWIND_2_7: { // UNWIND_OLD
   3294       // 'unwind' instruction has been removed in LLVM 3.1
   3295       // Replace 'unwind' with 'landingpad' and 'resume'.
   3296       Type *ExnTy = StructType::get(Type::getInt8PtrTy(Context),
   3297                                     Type::getInt32Ty(Context), nullptr);
   3298 
   3299       LandingPadInst *LP = LandingPadInst::Create(ExnTy, 1);
   3300       LP->setCleanup(true);
   3301 
   3302       CurBB->getInstList().push_back(LP);
   3303       I = ResumeInst::Create(LP);
   3304       InstructionList.push_back(I);
   3305       break;
   3306     }
   3307     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
   3308       I = new UnreachableInst(Context);
   3309       InstructionList.push_back(I);
   3310       break;
   3311     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
   3312       if (Record.size() < 1 || ((Record.size()-1)&1))
   3313         return Error("Invalid record");
   3314       Type *Ty = getTypeByID(Record[0]);
   3315       if (!Ty)
   3316         return Error("Invalid record");
   3317 
   3318       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
   3319       InstructionList.push_back(PN);
   3320 
   3321       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
   3322         Value *V = getFnValueByID(Record[1+i], Ty);
   3323         BasicBlock *BB = getBasicBlock(Record[2+i]);
   3324         if (!V || !BB)
   3325           return Error("Invalid record");
   3326         PN->addIncoming(V, BB);
   3327       }
   3328       I = PN;
   3329       break;
   3330     }
   3331 
   3332     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
   3333       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
   3334       unsigned Idx = 0;
   3335       if (Record.size() < 4)
   3336         return Error("Invalid record");
   3337       Type *Ty = getTypeByID(Record[Idx++]);
   3338       if (!Ty)
   3339         return Error("Invalid record");
   3340       Value *PersFn = nullptr;
   3341       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
   3342         return Error("Invalid record");
   3343 
   3344       bool IsCleanup = !!Record[Idx++];
   3345       unsigned NumClauses = Record[Idx++];
   3346       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
   3347       LP->setCleanup(IsCleanup);
   3348       for (unsigned J = 0; J != NumClauses; ++J) {
   3349         LandingPadInst::ClauseType CT =
   3350           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
   3351         Value *Val;
   3352 
   3353         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
   3354           delete LP;
   3355           return Error("Invalid record");
   3356         }
   3357 
   3358         assert((CT != LandingPadInst::Catch ||
   3359                 !isa<ArrayType>(Val->getType())) &&
   3360                "Catch clause has a invalid type!");
   3361         assert((CT != LandingPadInst::Filter ||
   3362                 isa<ArrayType>(Val->getType())) &&
   3363                "Filter clause has invalid type!");
   3364         LP->addClause(cast<Constant>(Val));
   3365       }
   3366 
   3367       I = LP;
   3368       InstructionList.push_back(I);
   3369       break;
   3370     }
   3371 
   3372     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
   3373       if (Record.size() != 4)
   3374         return Error("Invalid record");
   3375       PointerType *Ty =
   3376         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
   3377       Type *OpTy = getTypeByID(Record[1]);
   3378       Value *Size = getFnValueByID(Record[2], OpTy);
   3379       unsigned Align = Record[3];
   3380       if (!Ty || !Size)
   3381         return Error("Invalid record");
   3382       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
   3383       InstructionList.push_back(I);
   3384       break;
   3385     }
   3386     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
   3387       unsigned OpNum = 0;
   3388       Value *Op;
   3389       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
   3390           OpNum+2 != Record.size())
   3391         return Error("Invalid record");
   3392 
   3393       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
   3394       InstructionList.push_back(I);
   3395       break;
   3396     }
   3397     case bitc::FUNC_CODE_INST_LOADATOMIC: {
   3398        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
   3399       unsigned OpNum = 0;
   3400       Value *Op;
   3401       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
   3402           OpNum+4 != Record.size())
   3403         return Error("Invalid record");
   3404 
   3405       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
   3406       if (Ordering == NotAtomic || Ordering == Release ||
   3407           Ordering == AcquireRelease)
   3408         return Error("Invalid record");
   3409       if (Ordering != NotAtomic && Record[OpNum] == 0)
   3410         return Error("Invalid record");
   3411       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
   3412 
   3413       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
   3414                        Ordering, SynchScope);
   3415       InstructionList.push_back(I);
   3416       break;
   3417     }
   3418     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
   3419       unsigned OpNum = 0;
   3420       Value *Val, *Ptr;
   3421       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
   3422           getValue(Record, OpNum,
   3423                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
   3424           OpNum+2 != Record.size())
   3425         return Error("Invalid record");
   3426 
   3427       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
   3428       InstructionList.push_back(I);
   3429       break;
   3430     }
   3431     case bitc::FUNC_CODE_INST_STOREATOMIC: {
   3432       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
   3433       unsigned OpNum = 0;
   3434       Value *Val, *Ptr;
   3435       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
   3436           getValue(Record, OpNum,
   3437                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
   3438           OpNum+4 != Record.size())
   3439         return Error("Invalid record");
   3440 
   3441       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
   3442       if (Ordering == NotAtomic || Ordering == Acquire ||
   3443           Ordering == AcquireRelease)
   3444         return Error("Invalid record");
   3445       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
   3446       if (Ordering != NotAtomic && Record[OpNum] == 0)
   3447         return Error("Invalid record");
   3448 
   3449       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
   3450                         Ordering, SynchScope);
   3451       InstructionList.push_back(I);
   3452       break;
   3453     }
   3454     case bitc::FUNC_CODE_INST_CMPXCHG: {
   3455       // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
   3456       unsigned OpNum = 0;
   3457       Value *Ptr, *Cmp, *New;
   3458       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
   3459           getValue(Record, OpNum,
   3460                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
   3461           getValue(Record, OpNum,
   3462                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
   3463           OpNum+3 != Record.size())
   3464         return Error("Invalid record");
   3465       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
   3466       if (Ordering == NotAtomic || Ordering == Unordered)
   3467         return Error("Invalid record");
   3468       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
   3469       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Ordering, SynchScope);
   3470       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
   3471       InstructionList.push_back(I);
   3472       break;
   3473     }
   3474     case bitc::FUNC_CODE_INST_ATOMICRMW: {
   3475       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
   3476       unsigned OpNum = 0;
   3477       Value *Ptr, *Val;
   3478       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
   3479           getValue(Record, OpNum,
   3480                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
   3481           OpNum+4 != Record.size())
   3482         return Error("Invalid record");
   3483       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
   3484       if (Operation < AtomicRMWInst::FIRST_BINOP ||
   3485           Operation > AtomicRMWInst::LAST_BINOP)
   3486         return Error("Invalid record");
   3487       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
   3488       if (Ordering == NotAtomic || Ordering == Unordered)
   3489         return Error("Invalid record");
   3490       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
   3491       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
   3492       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
   3493       InstructionList.push_back(I);
   3494       break;
   3495     }
   3496     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
   3497       if (2 != Record.size())
   3498         return Error("Invalid record");
   3499       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
   3500       if (Ordering == NotAtomic || Ordering == Unordered ||
   3501           Ordering == Monotonic)
   3502         return Error("Invalid record");
   3503       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
   3504       I = new FenceInst(Context, Ordering, SynchScope);
   3505       InstructionList.push_back(I);
   3506       break;
   3507     }
   3508     case bitc::FUNC_CODE_INST_CALL: {
   3509       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
   3510       if (Record.size() < 3)
   3511         return Error("Invalid record");
   3512 
   3513       AttributeSet PAL = getAttributes(Record[0]);
   3514       unsigned CCInfo = Record[1];
   3515 
   3516       unsigned OpNum = 2;
   3517       Value *Callee;
   3518       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
   3519         return Error("Invalid record");
   3520 
   3521       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
   3522       FunctionType *FTy = nullptr;
   3523       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
   3524       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
   3525         return Error("Invalid record");
   3526 
   3527       SmallVector<Value*, 16> Args;
   3528       // Read the fixed params.
   3529       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
   3530         if (FTy->getParamType(i)->isLabelTy())
   3531           Args.push_back(getBasicBlock(Record[OpNum]));
   3532         else
   3533           Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
   3534         if (!Args.back())
   3535           return Error("Invalid record");
   3536       }
   3537 
   3538       // Read type/value pairs for varargs params.
   3539       if (!FTy->isVarArg()) {
   3540         if (OpNum != Record.size())
   3541           return Error("Invalid record");
   3542       } else {
   3543         while (OpNum != Record.size()) {
   3544           Value *Op;
   3545           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
   3546             return Error("Invalid record");
   3547           Args.push_back(Op);
   3548         }
   3549       }
   3550 
   3551       I = CallInst::Create(Callee, Args);
   3552       InstructionList.push_back(I);
   3553       cast<CallInst>(I)->setCallingConv(
   3554         static_cast<CallingConv::ID>(CCInfo>>1));
   3555       cast<CallInst>(I)->setTailCall(CCInfo & 1);
   3556       cast<CallInst>(I)->setAttributes(PAL);
   3557       break;
   3558     }
   3559     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
   3560       if (Record.size() < 3)
   3561         return Error("Invalid record");
   3562       Type *OpTy = getTypeByID(Record[0]);
   3563       Value *Op = getFnValueByID(Record[1], OpTy);
   3564       Type *ResTy = getTypeByID(Record[2]);
   3565       if (!OpTy || !Op || !ResTy)
   3566         return Error("Invalid record");
   3567       I = new VAArgInst(Op, ResTy);
   3568       InstructionList.push_back(I);
   3569       break;
   3570     }
   3571     }
   3572 
   3573     // Add instruction to end of current BB.  If there is no current BB, reject
   3574     // this file.
   3575     if (!CurBB) {
   3576       delete I;
   3577       return Error("Invalid instruction with no BB");
   3578     }
   3579     CurBB->getInstList().push_back(I);
   3580 
   3581     // If this was a terminator instruction, move to the next block.
   3582     if (isa<TerminatorInst>(I)) {
   3583       ++CurBBNo;
   3584       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
   3585     }
   3586 
   3587     // Non-void values get registered in the value table for future use.
   3588     if (I && !I->getType()->isVoidTy())
   3589       ValueList.AssignValue(I, NextValueNo++);
   3590   }
   3591 
   3592   // Check the function list for unresolved values.
   3593   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
   3594     if (!A->getParent()) {
   3595       // We found at least one unresolved value.  Nuke them all to avoid leaks.
   3596       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
   3597         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
   3598           A->replaceAllUsesWith(UndefValue::get(A->getType()));
   3599           delete A;
   3600         }
   3601       }
   3602       return Error("Never resolved value found in function");
   3603     }
   3604   }
   3605 
   3606   // FIXME: Check for unresolved forward-declared metadata references
   3607   // and clean up leaks.
   3608 
   3609   // See if anything took the address of blocks in this function.  If so,
   3610   // resolve them now.
   3611   DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
   3612     BlockAddrFwdRefs.find(F);
   3613   if (BAFRI != BlockAddrFwdRefs.end()) {
   3614     std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
   3615     for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
   3616       unsigned BlockIdx = RefList[i].first;
   3617       if (BlockIdx >= FunctionBBs.size())
   3618         return Error("Invalid ID");
   3619 
   3620       GlobalVariable *FwdRef = RefList[i].second;
   3621       FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
   3622       FwdRef->eraseFromParent();
   3623     }
   3624 
   3625     BlockAddrFwdRefs.erase(BAFRI);
   3626   }
   3627 
   3628   // Trim the value list down to the size it was before we parsed this function.
   3629   ValueList.shrinkTo(ModuleValueListSize);
   3630   MDValueList.shrinkTo(ModuleMDValueListSize);
   3631   std::vector<BasicBlock*>().swap(FunctionBBs);
   3632   return std::error_code();
   3633 }
   3634 
   3635 //===----------------------------------------------------------------------===//
   3636 // GVMaterializer implementation
   3637 //===----------------------------------------------------------------------===//
   3638 
   3639 void BitcodeReader::releaseBuffer() { Buffer.release(); }
   3640 
   3641 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
   3642   if (std::error_code EC = materializeMetadata())
   3643     return EC;
   3644 
   3645   Function *F = dyn_cast<Function>(GV);
   3646   // If it's not a function or is already material, ignore the request.
   3647   if (!F || !F->isMaterializable())
   3648     return std::error_code();
   3649 
   3650   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
   3651   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
   3652 
   3653   // Move the bit stream to the saved position of the deferred function body.
   3654   Stream.JumpToBit(DFII->second);
   3655 
   3656   if (std::error_code EC = ParseFunctionBody(F))
   3657     return EC;
   3658   F->setIsMaterializable(false);
   3659 
   3660   // Upgrade any old intrinsic calls in the function.
   3661   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
   3662        E = UpgradedIntrinsics.end(); I != E; ++I) {
   3663     if (I->first != I->second) {
   3664       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
   3665            UI != UE;) {
   3666         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
   3667           UpgradeIntrinsicCall(CI, I->second);
   3668       }
   3669     }
   3670   }
   3671 
   3672   return std::error_code();
   3673 }
   3674 
   3675 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
   3676   const Function *F = dyn_cast<Function>(GV);
   3677   if (!F || F->isDeclaration())
   3678     return false;
   3679   return DeferredFunctionInfo.count(const_cast<Function*>(F));
   3680 }
   3681 
   3682 void BitcodeReader::dematerialize(GlobalValue *GV) {
   3683   Function *F = dyn_cast<Function>(GV);
   3684   // If this function isn't dematerializable, this is a noop.
   3685   if (!F || !isDematerializable(F))
   3686     return;
   3687 
   3688   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
   3689 
   3690   // Just forget the function body, we can remat it later.
   3691   F->deleteBody();
   3692   F->setIsMaterializable(true);
   3693 }
   3694 
   3695 std::error_code BitcodeReader::materializeModule() {
   3696   // Iterate over the module, deserializing any functions that are still on
   3697   // disk.
   3698   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
   3699        F != E; ++F) {
   3700     if (std::error_code EC = materialize(&*F))
   3701       return EC;
   3702   }
   3703   // At this point, if there are any function bodies, the current bit is
   3704   // pointing to the END_BLOCK record after them. Now make sure the rest
   3705   // of the bits in the module have been read.
   3706   if (NextUnreadBit)
   3707     ParseModule(true);
   3708 
   3709   // Upgrade any intrinsic calls that slipped through (should not happen!) and
   3710   // delete the old functions to clean up. We can't do this unless the entire
   3711   // module is materialized because there could always be another function body
   3712   // with calls to the old function.
   3713   for (std::vector<std::pair<Function*, Function*> >::iterator I =
   3714        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
   3715     if (I->first != I->second) {
   3716       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
   3717            UI != UE;) {
   3718         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
   3719           UpgradeIntrinsicCall(CI, I->second);
   3720       }
   3721       if (!I->first->use_empty())
   3722         I->first->replaceAllUsesWith(I->second);
   3723       I->first->eraseFromParent();
   3724     }
   3725   }
   3726   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
   3727 
   3728   // Upgrade to new EH scheme. N.B. This will go away in 3.1.
   3729   UpgradeExceptionHandling(TheModule);
   3730 
   3731   // Check debug info intrinsics.
   3732   CheckDebugInfoIntrinsics(TheModule);
   3733 
   3734   return std::error_code();
   3735 }
   3736 
   3737 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
   3738   return IdentifiedStructTypes;
   3739 }
   3740 
   3741 std::error_code BitcodeReader::InitStream() {
   3742   if (LazyStreamer)
   3743     return InitLazyStream();
   3744   return InitStreamFromBuffer();
   3745 }
   3746 
   3747 std::error_code BitcodeReader::InitStreamFromBuffer() {
   3748   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
   3749   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
   3750 
   3751   if (Buffer->getBufferSize() & 3)
   3752     return Error("Invalid bitcode signature");
   3753 
   3754   // If we have a wrapper header, parse it and ignore the non-bc file contents.
   3755   // The magic number is 0x0B17C0DE stored in little endian.
   3756   if (isBitcodeWrapper(BufPtr, BufEnd))
   3757     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
   3758       return Error("Invalid bitcode wrapper header");
   3759 
   3760   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
   3761   Stream.init(&*StreamFile);
   3762 
   3763   return std::error_code();
   3764 }
   3765 
   3766 std::error_code BitcodeReader::InitLazyStream() {
   3767   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
   3768   // see it.
   3769   auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(
   3770       std::move(LazyStreamer));
   3771   StreamingMemoryObject &Bytes = *OwnedBytes;
   3772   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
   3773   Stream.init(&*StreamFile);
   3774 
   3775   unsigned char buf[16];
   3776   if (Bytes.readBytes(buf, 16, 0) != 16)
   3777     return Error("Invalid bitcode signature");
   3778 
   3779   if (!isBitcode(buf, buf + 16))
   3780     return Error("Invalid bitcode signature");
   3781 
   3782   if (isBitcodeWrapper(buf, buf + 4)) {
   3783     const unsigned char *bitcodeStart = buf;
   3784     const unsigned char *bitcodeEnd = buf + 16;
   3785     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
   3786     Bytes.dropLeadingBytes(bitcodeStart - buf);
   3787     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
   3788   }
   3789   return std::error_code();
   3790 }
   3791 
   3792 namespace {
   3793 class BitcodeErrorCategoryType : public std::error_category {
   3794   const char *name() const LLVM_NOEXCEPT override {
   3795     return "llvm.bitcode";
   3796   }
   3797   std::string message(int IE) const override {
   3798     BitcodeError E = static_cast<BitcodeError>(IE);
   3799     switch (E) {
   3800     case BitcodeError::InvalidBitcodeSignature:
   3801       return "Invalid bitcode signature";
   3802     case BitcodeError::CorruptedBitcode:
   3803       return "Corrupted bitcode";
   3804     }
   3805     llvm_unreachable("Unknown error type!");
   3806   }
   3807 };
   3808 }
   3809 
   3810 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
   3811 
   3812 const std::error_category &BitcodeReader::BitcodeErrorCategory() {
   3813   return *ErrorCategory;
   3814 }
   3815 
   3816 //===----------------------------------------------------------------------===//
   3817 // External interface
   3818 //===----------------------------------------------------------------------===//
   3819 
   3820 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
   3821 ///
   3822 static llvm::ErrorOr<llvm::Module *>
   3823 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
   3824                          LLVMContext &Context, bool WillMaterializeAll,
   3825                          DiagnosticHandlerFunction DiagnosticHandler) {
   3826   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
   3827   BitcodeReader *R =
   3828       new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
   3829   M->setMaterializer(R);
   3830 
   3831   auto cleanupOnError = [&](std::error_code EC) {
   3832     R->releaseBuffer(); // Never take ownership on error.
   3833     delete M;  // Also deletes R.
   3834     return EC;
   3835   };
   3836 
   3837   if (std::error_code EC = R->ParseBitcodeInto(M))
   3838     return cleanupOnError(EC);
   3839 
   3840   Buffer.release(); // The BitcodeReader owns it now.
   3841   return M;
   3842 }
   3843 
   3844 llvm::ErrorOr<Module *>
   3845 llvm_3_0::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
   3846                            LLVMContext &Context,
   3847                            DiagnosticHandlerFunction DiagnosticHandler) {
   3848   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
   3849                                   DiagnosticHandler);
   3850 }
   3851 
   3852 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
   3853 /// If an error occurs, return null and fill in *ErrMsg if non-null.
   3854 llvm::ErrorOr<llvm::Module *>
   3855 llvm_3_0::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
   3856                        DiagnosticHandlerFunction DiagnosticHandler) {
   3857   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
   3858   ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
   3859       std::move(Buf), Context, true, DiagnosticHandler);
   3860   if (!ModuleOrErr)
   3861     return ModuleOrErr;
   3862   Module *M = ModuleOrErr.get();
   3863   // Read in the entire module, and destroy the BitcodeReader.
   3864   if (std::error_code EC = M->materializeAll()) {
   3865     delete M;
   3866     return EC;
   3867   }
   3868 
   3869   return M;
   3870 }
   3871 
   3872 std::string
   3873 llvm_3_0::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
   3874                              DiagnosticHandlerFunction DiagnosticHandler) {
   3875   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
   3876   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
   3877                                             DiagnosticHandler);
   3878   ErrorOr<std::string> Triple = R->parseTriple();
   3879   if (Triple.getError())
   3880     return "";
   3881   return Triple.get();
   3882 }
   3883