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