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