BitcodeReader.cpp revision 34edb8ad024934c13741550bc825c9b352453ad8
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
30using namespace llvm;
31using 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
49namespace {
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
85void BitcodeReader::FreeState() {
86  Buffer = nullptr;
87  std::vector<Type*>().swap(TypeList);
88  ValueList.clear();
89  MDValueList.clear();
90
91  std::vector<AttributeSet>().swap(MAttributes);
92  std::vector<BasicBlock*>().swap(FunctionBBs);
93  std::vector<Function*>().swap(FunctionsWithBodies);
94  DeferredFunctionInfo.clear();
95  MDKindMap.clear();
96}
97
98//===----------------------------------------------------------------------===//
99//  Helper functions to implement forward reference resolution, etc.
100//===----------------------------------------------------------------------===//
101
102/// ConvertToString - Convert a string from a record into an std::string, return
103/// true on failure.
104template<typename StrTy>
105static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
106                            StrTy &Result) {
107  if (Idx > Record.size())
108    return true;
109
110  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
111    Result += (char)Record[i];
112  return false;
113}
114
115static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
116  switch (Val) {
117  default: // Map unknown/new linkages to external
118  case 0:  return GlobalValue::ExternalLinkage;
119  case 1:  return GlobalValue::WeakAnyLinkage;
120  case 2:  return GlobalValue::AppendingLinkage;
121  case 3:  return GlobalValue::InternalLinkage;
122  case 4:  return GlobalValue::LinkOnceAnyLinkage;
123  case 5:  return GlobalValue::ExternalLinkage; // Was DLLImportLinkage;
124  case 6:  return GlobalValue::ExternalLinkage; // Was DLLExportLinkage;
125  case 7:  return GlobalValue::ExternalWeakLinkage;
126  case 8:  return GlobalValue::CommonLinkage;
127  case 9:  return GlobalValue::PrivateLinkage;
128  case 10: return GlobalValue::WeakODRLinkage;
129  case 11: return GlobalValue::LinkOnceODRLinkage;
130  case 12: return GlobalValue::AvailableExternallyLinkage;
131  case 13: return GlobalValue::PrivateLinkage; // Was LinkerPrivateLinkage;
132  case 14: return GlobalValue::ExternalWeakLinkage; // Was LinkerPrivateWeakLinkage;
133  //ANDROID: convert LinkOnceODRAutoHideLinkage -> LinkOnceODRLinkage
134  case 15: return GlobalValue::LinkOnceODRLinkage;
135  }
136}
137
138static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
139  switch (Val) {
140  default: // Map unknown visibilities to default.
141  case 0: return GlobalValue::DefaultVisibility;
142  case 1: return GlobalValue::HiddenVisibility;
143  case 2: return GlobalValue::ProtectedVisibility;
144  }
145}
146
147static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
148  switch (Val) {
149    case 0: return GlobalVariable::NotThreadLocal;
150    default: // Map unknown non-zero value to general dynamic.
151    case 1: return GlobalVariable::GeneralDynamicTLSModel;
152    case 2: return GlobalVariable::LocalDynamicTLSModel;
153    case 3: return GlobalVariable::InitialExecTLSModel;
154    case 4: return GlobalVariable::LocalExecTLSModel;
155  }
156}
157
158static int GetDecodedCastOpcode(unsigned Val) {
159  switch (Val) {
160  default: return -1;
161  case bitc::CAST_TRUNC   : return Instruction::Trunc;
162  case bitc::CAST_ZEXT    : return Instruction::ZExt;
163  case bitc::CAST_SEXT    : return Instruction::SExt;
164  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
165  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
166  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
167  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
168  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
169  case bitc::CAST_FPEXT   : return Instruction::FPExt;
170  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
171  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
172  case bitc::CAST_BITCAST : return Instruction::BitCast;
173  }
174}
175static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
176  switch (Val) {
177  default: return -1;
178  case bitc::BINOP_ADD:
179    return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
180  case bitc::BINOP_SUB:
181    return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
182  case bitc::BINOP_MUL:
183    return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
184  case bitc::BINOP_UDIV: return Instruction::UDiv;
185  case bitc::BINOP_SDIV:
186    return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
187  case bitc::BINOP_UREM: return Instruction::URem;
188  case bitc::BINOP_SREM:
189    return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
190  case bitc::BINOP_SHL:  return Instruction::Shl;
191  case bitc::BINOP_LSHR: return Instruction::LShr;
192  case bitc::BINOP_ASHR: return Instruction::AShr;
193  case bitc::BINOP_AND:  return Instruction::And;
194  case bitc::BINOP_OR:   return Instruction::Or;
195  case bitc::BINOP_XOR:  return Instruction::Xor;
196  }
197}
198
199namespace llvm {
200namespace {
201  /// @brief A class for maintaining the slot number definition
202  /// as a placeholder for the actual definition for forward constants defs.
203  class ConstantPlaceHolder : public ConstantExpr {
204    void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
205  public:
206    // allocate space for exactly one operand
207    void *operator new(size_t s) {
208      return User::operator new(s, 1);
209    }
210    explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
211      : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
212      Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
213    }
214
215    /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
216    //static inline bool classof(const ConstantPlaceHolder *) { return true; }
217    static bool classof(const Value *V) {
218      return isa<ConstantExpr>(V) &&
219             cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
220    }
221
222
223    /// Provide fast operand accessors
224    //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
225  };
226}
227
228// FIXME: can we inherit this from ConstantExpr?
229template <>
230struct OperandTraits<ConstantPlaceHolder> :
231  public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
232};
233}
234
235
236void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
237  if (Idx == size()) {
238    push_back(V);
239    return;
240  }
241
242  if (Idx >= size())
243    resize(Idx+1);
244
245  WeakVH &OldV = ValuePtrs[Idx];
246  if (!OldV) {
247    OldV = V;
248    return;
249  }
250
251  // Handle constants and non-constants (e.g. instrs) differently for
252  // efficiency.
253  if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
254    ResolveConstants.push_back(std::make_pair(PHC, Idx));
255    OldV = V;
256  } else {
257    // If there was a forward reference to this value, replace it.
258    Value *PrevVal = OldV;
259    OldV->replaceAllUsesWith(V);
260    delete PrevVal;
261  }
262}
263
264
265Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
266                                                    Type *Ty) {
267  if (Idx >= size())
268    resize(Idx + 1);
269
270  if (Value *V = ValuePtrs[Idx]) {
271    assert(Ty == V->getType() && "Type mismatch in constant table!");
272    return cast<Constant>(V);
273  }
274
275  // Create and return a placeholder, which will later be RAUW'd.
276  Constant *C = new ConstantPlaceHolder(Ty, Context);
277  ValuePtrs[Idx] = C;
278  return C;
279}
280
281Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
282  if (Idx >= size())
283    resize(Idx + 1);
284
285  if (Value *V = ValuePtrs[Idx]) {
286    assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
287    return V;
288  }
289
290  // No type specified, must be invalid reference.
291  if (!Ty) return nullptr;
292
293  // Create and return a placeholder, which will later be RAUW'd.
294  Value *V = new Argument(Ty);
295  ValuePtrs[Idx] = V;
296  return V;
297}
298
299/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
300/// resolves any forward references.  The idea behind this is that we sometimes
301/// get constants (such as large arrays) which reference *many* forward ref
302/// constants.  Replacing each of these causes a lot of thrashing when
303/// building/reuniquing the constant.  Instead of doing this, we look at all the
304/// uses and rewrite all the place holders at once for any constant that uses
305/// a placeholder.
306void BitcodeReaderValueList::ResolveConstantForwardRefs() {
307  // Sort the values by-pointer so that they are efficient to look up with a
308  // binary search.
309  std::sort(ResolveConstants.begin(), ResolveConstants.end());
310
311  SmallVector<Constant*, 64> NewOps;
312
313  while (!ResolveConstants.empty()) {
314    Value *RealVal = operator[](ResolveConstants.back().second);
315    Constant *Placeholder = ResolveConstants.back().first;
316    ResolveConstants.pop_back();
317
318    // Loop over all users of the placeholder, updating them to reference the
319    // new value.  If they reference more than one placeholder, update them all
320    // at once.
321    while (!Placeholder->use_empty()) {
322      Value::use_iterator UI = Placeholder->use_begin();
323      Use &use = *UI;
324      User *U = use.getUser();
325
326      // If the using object isn't uniqued, just update the operands.  This
327      // handles instructions and initializers for global variables.
328      if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
329        use.set(RealVal);
330        continue;
331      }
332
333      // Otherwise, we have a constant that uses the placeholder.  Replace that
334      // constant with a new constant that has *all* placeholder uses updated.
335      Constant *UserC = cast<Constant>(U);
336      for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
337           I != E; ++I) {
338        Value *NewOp;
339        if (!isa<ConstantPlaceHolder>(*I)) {
340          // Not a placeholder reference.
341          NewOp = *I;
342        } else if (*I == Placeholder) {
343          // Common case is that it just references this one placeholder.
344          NewOp = RealVal;
345        } else {
346          // Otherwise, look up the placeholder in ResolveConstants.
347          ResolveConstantsTy::iterator It =
348            std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
349                             std::pair<Constant*, unsigned>(cast<Constant>(*I),
350                                                            0));
351          assert(It != ResolveConstants.end() && It->first == *I);
352          NewOp = operator[](It->second);
353        }
354
355        NewOps.push_back(cast<Constant>(NewOp));
356      }
357
358      // Make the new constant.
359      Constant *NewC;
360      if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
361        NewC = ConstantArray::get(UserCA->getType(), NewOps);
362      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
363        NewC = ConstantStruct::get(UserCS->getType(), NewOps);
364      } else if (isa<ConstantVector>(UserC)) {
365        NewC = ConstantVector::get(NewOps);
366      } else {
367        assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
368        NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
369      }
370
371      UserC->replaceAllUsesWith(NewC);
372      UserC->destroyConstant();
373      NewOps.clear();
374    }
375
376    // Update all ValueHandles, they should be the only users at this point.
377    Placeholder->replaceAllUsesWith(RealVal);
378    delete Placeholder;
379  }
380}
381
382void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
383  if (Idx == size()) {
384    push_back(V);
385    return;
386  }
387
388  if (Idx >= size())
389    resize(Idx+1);
390
391  WeakVH &OldV = MDValuePtrs[Idx];
392  if (OldV == 0) {
393    OldV = V;
394    return;
395  }
396
397  // If there was a forward reference to this value, replace it.
398  MDNode *PrevVal = cast<MDNode>(OldV);
399  OldV->replaceAllUsesWith(V);
400  MDNode::deleteTemporary(PrevVal);
401  // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
402  // value for Idx.
403  MDValuePtrs[Idx] = V;
404}
405
406Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
407  if (Idx >= size())
408    resize(Idx + 1);
409
410  if (Value *V = MDValuePtrs[Idx]) {
411    assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
412    return V;
413  }
414
415  // Create and return a placeholder, which will later be RAUW'd.
416  Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
417  MDValuePtrs[Idx] = V;
418  return V;
419}
420
421Type *BitcodeReader::getTypeByID(unsigned ID) {
422  // The type table size is always specified correctly.
423  if (ID >= TypeList.size())
424    return nullptr;
425
426  if (Type *Ty = TypeList[ID])
427    return Ty;
428
429  // If we have a forward reference, the only possible case is when it is to a
430  // named struct.  Just create a placeholder for now.
431  return TypeList[ID] = StructType::create(Context);
432}
433
434/// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable.
435Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) {
436  if (ID >= TypeList.size())
437    TypeList.resize(ID+1);
438
439  return TypeList[ID];
440}
441
442
443//===----------------------------------------------------------------------===//
444//  Functions for parsing blocks from the bitcode file
445//===----------------------------------------------------------------------===//
446
447
448/// \brief This fills an AttrBuilder object with the LLVM attributes that have
449/// been decoded from the given integer. This function must stay in sync with
450/// 'encodeLLVMAttributesForBitcode'.
451static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
452                                           uint64_t EncodedAttrs) {
453  // FIXME: Remove in 4.0.
454
455  // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
456  // the bits above 31 down by 11 bits.
457  unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
458  assert((!Alignment || isPowerOf2_32(Alignment)) &&
459         "Alignment must be a power of two.");
460
461  if (Alignment)
462    B.addAlignmentAttr(Alignment);
463  B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
464                (EncodedAttrs & 0xffff));
465}
466
467std::error_code BitcodeReader::ParseAttributeBlock() {
468  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
469    return Error(BitcodeError::InvalidRecord);
470
471  if (!MAttributes.empty())
472    return Error(BitcodeError::InvalidMultipleBlocks);
473
474  SmallVector<uint64_t, 64> Record;
475
476  SmallVector<AttributeSet, 8> Attrs;
477
478  // Read all the records.
479  while (1) {
480    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
481
482    switch (Entry.Kind) {
483    case BitstreamEntry::SubBlock: // Handled for us already.
484    case BitstreamEntry::Error:
485      return Error(BitcodeError::MalformedBlock);
486    case BitstreamEntry::EndBlock:
487      return std::error_code();
488    case BitstreamEntry::Record:
489      // The interesting case.
490      break;
491    }
492
493    // Read a record.
494    Record.clear();
495    switch (Stream.readRecord(Entry.ID, Record)) {
496    default:  // Default behavior: ignore.
497      break;
498    case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
499      if (Record.size() & 1)
500        return Error(BitcodeError::InvalidRecord);
501
502      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
503        AttrBuilder B;
504        decodeLLVMAttributesForBitcode(B, Record[i+1]);
505        Attrs.push_back(AttributeSet::get(Context, Record[i], B));
506      }
507
508      MAttributes.push_back(AttributeSet::get(Context, Attrs));
509      Attrs.clear();
510      break;
511    }
512    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
513      for (unsigned i = 0, e = Record.size(); i != e; ++i)
514        Attrs.push_back(MAttributeGroups[Record[i]]);
515
516      MAttributes.push_back(AttributeSet::get(Context, Attrs));
517      Attrs.clear();
518      break;
519    }
520    }
521  }
522}
523
524
525std::error_code BitcodeReader::ParseTypeTable() {
526  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
527    return Error(BitcodeError::InvalidRecord);
528
529  return ParseTypeTableBody();
530}
531
532std::error_code BitcodeReader::ParseTypeTableBody() {
533  if (!TypeList.empty())
534    return Error(BitcodeError::InvalidMultipleBlocks);
535
536  SmallVector<uint64_t, 64> Record;
537  unsigned NumRecords = 0;
538
539  SmallString<64> TypeName;
540
541  // Read all the records for this type table.
542  while (1) {
543    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
544
545    switch (Entry.Kind) {
546    case BitstreamEntry::SubBlock: // Handled for us already.
547    case BitstreamEntry::Error:
548      return Error(BitcodeError::MalformedBlock);
549    case BitstreamEntry::EndBlock:
550      if (NumRecords != TypeList.size())
551        return Error(BitcodeError::MalformedBlock);
552      return std::error_code();
553    case BitstreamEntry::Record:
554      // The interesting case.
555      break;
556    }
557
558    // Read a record.
559    Record.clear();
560    Type *ResultTy = nullptr;
561    switch (Stream.readRecord(Entry.ID, Record)) {
562    default:
563      return Error(BitcodeError::InvalidValue);
564    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
565      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
566      // type list.  This allows us to reserve space.
567      if (Record.size() < 1)
568        return Error(BitcodeError::InvalidRecord);
569      TypeList.resize(Record[0]);
570      continue;
571    case bitc::TYPE_CODE_VOID:      // VOID
572      ResultTy = Type::getVoidTy(Context);
573      break;
574    case bitc::TYPE_CODE_HALF:     // HALF
575      ResultTy = Type::getHalfTy(Context);
576      break;
577    case bitc::TYPE_CODE_FLOAT:     // FLOAT
578      ResultTy = Type::getFloatTy(Context);
579      break;
580    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
581      ResultTy = Type::getDoubleTy(Context);
582      break;
583    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
584      ResultTy = Type::getX86_FP80Ty(Context);
585      break;
586    case bitc::TYPE_CODE_FP128:     // FP128
587      ResultTy = Type::getFP128Ty(Context);
588      break;
589    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
590      ResultTy = Type::getPPC_FP128Ty(Context);
591      break;
592    case bitc::TYPE_CODE_LABEL:     // LABEL
593      ResultTy = Type::getLabelTy(Context);
594      break;
595    case bitc::TYPE_CODE_METADATA:  // METADATA
596      ResultTy = Type::getMetadataTy(Context);
597      break;
598    case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
599      ResultTy = Type::getX86_MMXTy(Context);
600      break;
601    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
602      if (Record.size() < 1)
603        return Error(BitcodeError::InvalidRecord);
604
605      ResultTy = IntegerType::get(Context, Record[0]);
606      break;
607    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
608                                    //          [pointee type, address space]
609      if (Record.size() < 1)
610        return Error(BitcodeError::InvalidRecord);
611      unsigned AddressSpace = 0;
612      if (Record.size() == 2)
613        AddressSpace = Record[1];
614      ResultTy = getTypeByID(Record[0]);
615      if (!ResultTy)
616        return Error(BitcodeError::InvalidType);
617      ResultTy = PointerType::get(ResultTy, AddressSpace);
618      break;
619    }
620    case bitc::TYPE_CODE_FUNCTION_OLD: {
621      // FIXME: attrid is dead, remove it in LLVM 4.0
622      // FUNCTION: [vararg, attrid, retty, paramty x N]
623      if (Record.size() < 3)
624        return Error(BitcodeError::InvalidRecord);
625      SmallVector<Type*, 8> ArgTys;
626      for (unsigned i = 3, e = Record.size(); i != e; ++i) {
627        if (Type *T = getTypeByID(Record[i]))
628          ArgTys.push_back(T);
629        else
630          break;
631      }
632
633      ResultTy = getTypeByID(Record[2]);
634      if (!ResultTy || ArgTys.size() < Record.size()-3)
635        return Error(BitcodeError::InvalidType);
636
637      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
638      break;
639    }
640    case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
641      if (Record.size() < 1)
642        return Error(BitcodeError::InvalidRecord);
643      SmallVector<Type*, 8> EltTys;
644      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
645        if (Type *T = getTypeByID(Record[i]))
646          EltTys.push_back(T);
647        else
648          break;
649      }
650      if (EltTys.size() != Record.size()-1)
651        return Error(BitcodeError::InvalidType);
652      ResultTy = StructType::get(Context, EltTys, Record[0]);
653      break;
654    }
655    case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
656      if (ConvertToString(Record, 0, TypeName))
657        return Error(BitcodeError::InvalidRecord);
658      continue;
659
660    case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
661      if (Record.size() < 1)
662        return Error(BitcodeError::InvalidRecord);
663
664      if (NumRecords >= TypeList.size())
665        return Error(BitcodeError::InvalidTYPETable);
666
667      // Check to see if this was forward referenced, if so fill in the temp.
668      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
669      if (Res) {
670        Res->setName(TypeName);
671        TypeList[NumRecords] = nullptr;
672      } else  // Otherwise, create a new struct.
673        Res = StructType::create(Context, TypeName);
674      TypeName.clear();
675
676      SmallVector<Type*, 8> EltTys;
677      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
678        if (Type *T = getTypeByID(Record[i]))
679          EltTys.push_back(T);
680        else
681          break;
682      }
683      if (EltTys.size() != Record.size()-1)
684        return Error(BitcodeError::InvalidRecord);
685      Res->setBody(EltTys, Record[0]);
686      ResultTy = Res;
687      break;
688    }
689    case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
690      if (Record.size() != 1)
691        return Error(BitcodeError::InvalidRecord);
692
693      if (NumRecords >= TypeList.size())
694        return Error(BitcodeError::InvalidTYPETable);
695
696      // Check to see if this was forward referenced, if so fill in the temp.
697      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
698      if (Res) {
699        Res->setName(TypeName);
700        TypeList[NumRecords] = nullptr;
701      } else  // Otherwise, create a new struct with no body.
702        Res = StructType::create(Context, TypeName);
703      TypeName.clear();
704      ResultTy = Res;
705      break;
706    }
707    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
708      if (Record.size() < 2)
709        return Error(BitcodeError::InvalidRecord);
710      if ((ResultTy = getTypeByID(Record[1])))
711        ResultTy = ArrayType::get(ResultTy, Record[0]);
712      else
713        return Error(BitcodeError::InvalidType);
714      break;
715    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
716      if (Record.size() < 2)
717        return Error(BitcodeError::InvalidRecord);
718      if ((ResultTy = getTypeByID(Record[1])))
719        ResultTy = VectorType::get(ResultTy, Record[0]);
720      else
721        return Error(BitcodeError::InvalidType);
722      break;
723    }
724
725    if (NumRecords >= TypeList.size())
726      return Error(BitcodeError::InvalidTYPETable);
727    assert(ResultTy && "Didn't read a type?");
728    assert(!TypeList[NumRecords] && "Already read type?");
729    TypeList[NumRecords++] = ResultTy;
730  }
731}
732
733// FIXME: Remove in LLVM 3.1
734std::error_code BitcodeReader::ParseOldTypeTable() {
735  if (Stream.EnterSubBlock(TYPE_BLOCK_ID_OLD_3_0))
736    return Error(BitcodeError::MalformedBlock);
737
738  if (!TypeList.empty())
739    return Error(BitcodeError::InvalidTYPETable);
740
741
742  // While horrible, we have no good ordering of types in the bc file.  Just
743  // iteratively parse types out of the bc file in multiple passes until we get
744  // them all.  Do this by saving a cursor for the start of the type block.
745  BitstreamCursor StartOfTypeBlockCursor(Stream);
746
747  unsigned NumTypesRead = 0;
748
749  SmallVector<uint64_t, 64> Record;
750RestartScan:
751  unsigned NextTypeID = 0;
752  bool ReadAnyTypes = false;
753
754  // Read all the records for this type table.
755  while (1) {
756    unsigned Code = Stream.ReadCode();
757    if (Code == bitc::END_BLOCK) {
758      if (NextTypeID != TypeList.size())
759        return Error(BitcodeError::InvalidTYPETable);
760
761      // If we haven't read all of the types yet, iterate again.
762      if (NumTypesRead != TypeList.size()) {
763        // If we didn't successfully read any types in this pass, then we must
764        // have an unhandled forward reference.
765        if (!ReadAnyTypes)
766          return Error(BitcodeError::InvalidTYPETable);
767
768        Stream = StartOfTypeBlockCursor;
769        goto RestartScan;
770      }
771
772      if (Stream.ReadBlockEnd())
773        return Error(BitcodeError::InvalidTYPETable);
774      return std::error_code();
775    }
776
777    if (Code == bitc::ENTER_SUBBLOCK) {
778      // No known subblocks, always skip them.
779      Stream.ReadSubBlockID();
780      if (Stream.SkipBlock())
781        return Error(BitcodeError::MalformedBlock);
782      continue;
783    }
784
785    if (Code == bitc::DEFINE_ABBREV) {
786      Stream.ReadAbbrevRecord();
787      continue;
788    }
789
790    // Read a record.
791    Record.clear();
792    Type *ResultTy = nullptr;
793    switch (Stream.readRecord(Code, Record)) {
794    default: return Error(BitcodeError::InvalidTYPETable);
795    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
796      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
797      // type list.  This allows us to reserve space.
798      if (Record.size() < 1)
799        return Error(BitcodeError::InvalidTYPETable);
800      TypeList.resize(Record[0]);
801      continue;
802    case bitc::TYPE_CODE_VOID:      // VOID
803      ResultTy = Type::getVoidTy(Context);
804      break;
805    case bitc::TYPE_CODE_FLOAT:     // FLOAT
806      ResultTy = Type::getFloatTy(Context);
807      break;
808    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
809      ResultTy = Type::getDoubleTy(Context);
810      break;
811    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
812      ResultTy = Type::getX86_FP80Ty(Context);
813      break;
814    case bitc::TYPE_CODE_FP128:     // FP128
815      ResultTy = Type::getFP128Ty(Context);
816      break;
817    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
818      ResultTy = Type::getPPC_FP128Ty(Context);
819      break;
820    case bitc::TYPE_CODE_LABEL:     // LABEL
821      ResultTy = Type::getLabelTy(Context);
822      break;
823    case bitc::TYPE_CODE_METADATA:  // METADATA
824      ResultTy = Type::getMetadataTy(Context);
825      break;
826    case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
827      ResultTy = Type::getX86_MMXTy(Context);
828      break;
829    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
830      if (Record.size() < 1)
831        return Error(BitcodeError::InvalidTYPETable);
832      ResultTy = IntegerType::get(Context, Record[0]);
833      break;
834    case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
835      if (NextTypeID < TypeList.size() && TypeList[NextTypeID] == 0)
836        ResultTy = StructType::create(Context, "");
837      break;
838    case TYPE_CODE_STRUCT_OLD_3_0: {// STRUCT_OLD
839      if (NextTypeID >= TypeList.size()) break;
840      // If we already read it, don't reprocess.
841      if (TypeList[NextTypeID] &&
842          !cast<StructType>(TypeList[NextTypeID])->isOpaque())
843        break;
844
845      // Set a type.
846      if (TypeList[NextTypeID] == 0)
847        TypeList[NextTypeID] = StructType::create(Context, "");
848
849      std::vector<Type*> EltTys;
850      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
851        if (Type *Elt = getTypeByIDOrNull(Record[i]))
852          EltTys.push_back(Elt);
853        else
854          break;
855      }
856
857      if (EltTys.size() != Record.size()-1)
858        break;      // Not all elements are ready.
859
860      cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]);
861      ResultTy = TypeList[NextTypeID];
862      TypeList[NextTypeID] = 0;
863      break;
864    }
865    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
866      //          [pointee type, address space]
867      if (Record.size() < 1)
868        return Error(BitcodeError::InvalidTYPETable);
869      unsigned AddressSpace = 0;
870      if (Record.size() == 2)
871        AddressSpace = Record[1];
872      if ((ResultTy = getTypeByIDOrNull(Record[0])))
873        ResultTy = PointerType::get(ResultTy, AddressSpace);
874      break;
875    }
876    case bitc::TYPE_CODE_FUNCTION_OLD: {
877      // FIXME: attrid is dead, remove it in LLVM 3.0
878      // FUNCTION: [vararg, attrid, retty, paramty x N]
879      if (Record.size() < 3)
880        return Error(BitcodeError::InvalidTYPETable);
881      std::vector<Type*> ArgTys;
882      for (unsigned i = 3, e = Record.size(); i != e; ++i) {
883        if (Type *Elt = getTypeByIDOrNull(Record[i]))
884          ArgTys.push_back(Elt);
885        else
886          break;
887      }
888      if (ArgTys.size()+3 != Record.size())
889        break;  // Something was null.
890      if ((ResultTy = getTypeByIDOrNull(Record[2])))
891        ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
892      break;
893    }
894    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
895      if (Record.size() < 2)
896        return Error(BitcodeError::InvalidTYPETable);
897      if ((ResultTy = getTypeByIDOrNull(Record[1])))
898        ResultTy = ArrayType::get(ResultTy, Record[0]);
899      break;
900    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
901      if (Record.size() < 2)
902        return Error(BitcodeError::InvalidTYPETable);
903      if ((ResultTy = getTypeByIDOrNull(Record[1])))
904        ResultTy = VectorType::get(ResultTy, Record[0]);
905      break;
906    }
907
908    if (NextTypeID >= TypeList.size())
909      return Error(BitcodeError::InvalidTYPETable);
910
911    if (ResultTy && TypeList[NextTypeID] == 0) {
912      ++NumTypesRead;
913      ReadAnyTypes = true;
914
915      TypeList[NextTypeID] = ResultTy;
916    }
917
918    ++NextTypeID;
919  }
920}
921
922
923std::error_code BitcodeReader::ParseOldTypeSymbolTable() {
924  if (Stream.EnterSubBlock(TYPE_SYMTAB_BLOCK_ID_OLD_3_0))
925    return Error(BitcodeError::MalformedBlock);
926
927  SmallVector<uint64_t, 64> Record;
928
929  // Read all the records for this type table.
930  std::string TypeName;
931  while (1) {
932    unsigned Code = Stream.ReadCode();
933    if (Code == bitc::END_BLOCK) {
934      if (Stream.ReadBlockEnd())
935        return Error(BitcodeError::MalformedBlock);
936      return std::error_code();
937    }
938
939    if (Code == bitc::ENTER_SUBBLOCK) {
940      // No known subblocks, always skip them.
941      Stream.ReadSubBlockID();
942      if (Stream.SkipBlock())
943        return Error(BitcodeError::MalformedBlock);
944      continue;
945    }
946
947    if (Code == bitc::DEFINE_ABBREV) {
948      Stream.ReadAbbrevRecord();
949      continue;
950    }
951
952    // Read a record.
953    Record.clear();
954    switch (Stream.readRecord(Code, Record)) {
955    default:  // Default behavior: unknown type.
956      break;
957    case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
958      if (ConvertToString(Record, 1, TypeName))
959        return Error(BitcodeError::InvalidRecord);
960      unsigned TypeID = Record[0];
961      if (TypeID >= TypeList.size())
962        return Error(BitcodeError::InvalidRecord);
963
964      // Only apply the type name to a struct type with no name.
965      if (StructType *STy = dyn_cast<StructType>(TypeList[TypeID]))
966        if (!STy->isLiteral() && !STy->hasName())
967          STy->setName(TypeName);
968      TypeName.clear();
969      break;
970    }
971  }
972}
973
974std::error_code BitcodeReader::ParseValueSymbolTable() {
975  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
976    return Error(BitcodeError::InvalidRecord);
977
978  SmallVector<uint64_t, 64> Record;
979
980  // Read all the records for this value table.
981  SmallString<128> ValueName;
982  while (1) {
983    unsigned Code = Stream.ReadCode();
984    if (Code == bitc::END_BLOCK) {
985      if (Stream.ReadBlockEnd())
986        return Error(BitcodeError::MalformedBlock);
987      return std::error_code();
988    }
989    if (Code == bitc::ENTER_SUBBLOCK) {
990      // No known subblocks, always skip them.
991      Stream.ReadSubBlockID();
992      if (Stream.SkipBlock())
993        return Error(BitcodeError::MalformedBlock);
994      continue;
995    }
996
997    if (Code == bitc::DEFINE_ABBREV) {
998      Stream.ReadAbbrevRecord();
999      continue;
1000    }
1001
1002    // Read a record.
1003    Record.clear();
1004    switch (Stream.readRecord(Code, Record)) {
1005    default:  // Default behavior: unknown type.
1006      break;
1007    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
1008      if (ConvertToString(Record, 1, ValueName))
1009        return Error(BitcodeError::InvalidRecord);
1010      unsigned ValueID = Record[0];
1011      if (ValueID >= ValueList.size())
1012        return Error(BitcodeError::InvalidRecord);
1013      Value *V = ValueList[ValueID];
1014
1015      V->setName(StringRef(ValueName.data(), ValueName.size()));
1016      ValueName.clear();
1017      break;
1018    }
1019    case bitc::VST_CODE_BBENTRY: {
1020      if (ConvertToString(Record, 1, ValueName))
1021        return Error(BitcodeError::InvalidRecord);
1022      BasicBlock *BB = getBasicBlock(Record[0]);
1023      if (!BB)
1024        return Error(BitcodeError::InvalidRecord);
1025
1026      BB->setName(StringRef(ValueName.data(), ValueName.size()));
1027      ValueName.clear();
1028      break;
1029    }
1030    }
1031  }
1032}
1033
1034std::error_code BitcodeReader::ParseMetadata() {
1035  unsigned NextMDValueNo = MDValueList.size();
1036
1037  if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1038    return Error(BitcodeError::InvalidRecord);
1039
1040  SmallVector<uint64_t, 64> Record;
1041
1042  // Read all the records.
1043  while (1) {
1044    unsigned Code = Stream.ReadCode();
1045    if (Code == bitc::END_BLOCK) {
1046      if (Stream.ReadBlockEnd())
1047        return Error(BitcodeError::MalformedBlock);
1048      return std::error_code();
1049    }
1050
1051    if (Code == bitc::ENTER_SUBBLOCK) {
1052      // No known subblocks, always skip them.
1053      Stream.ReadSubBlockID();
1054      if (Stream.SkipBlock())
1055        return Error(BitcodeError::MalformedBlock);
1056      continue;
1057    }
1058
1059    if (Code == bitc::DEFINE_ABBREV) {
1060      Stream.ReadAbbrevRecord();
1061      continue;
1062    }
1063
1064    bool IsFunctionLocal = false;
1065    // Read a record.
1066    Record.clear();
1067    Code = Stream.readRecord(Code, Record);
1068    switch (Code) {
1069    default:  // Default behavior: ignore.
1070      break;
1071    case bitc::METADATA_NAME: {
1072      // Read named of the named metadata.
1073      unsigned NameLength = Record.size();
1074      SmallString<8> Name;
1075      Name.resize(NameLength);
1076      for (unsigned i = 0; i != NameLength; ++i)
1077        Name[i] = Record[i];
1078      Record.clear();
1079      Code = Stream.ReadCode();
1080
1081      // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1082      unsigned NextBitCode = Stream.readRecord(Code, Record);
1083      if (NextBitCode == METADATA_NAMED_NODE_2_7) {
1084        LLVM2_7MetadataDetected = true;
1085      } else if (NextBitCode != bitc::METADATA_NAMED_NODE) {
1086        assert(!"Invalid Named Metadata record.");  (void)NextBitCode;
1087      }
1088
1089      // Read named metadata elements.
1090      unsigned Size = Record.size();
1091      NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1092      for (unsigned i = 0; i != Size; ++i) {
1093        MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1094        if (!MD)
1095          return Error(BitcodeError::InvalidRecord);
1096        NMD->addOperand(MD);
1097      }
1098
1099      if (LLVM2_7MetadataDetected) {
1100        MDValueList.AssignValue(0, NextMDValueNo++);
1101      }
1102      break;
1103    }
1104    case METADATA_FN_NODE_2_7:
1105    case bitc::METADATA_FN_NODE:
1106      IsFunctionLocal = true;
1107      // fall-through
1108    case METADATA_NODE_2_7:
1109    case bitc::METADATA_NODE: {
1110      if (Code == METADATA_FN_NODE_2_7 ||
1111          Code == METADATA_NODE_2_7) {
1112        LLVM2_7MetadataDetected = true;
1113      }
1114
1115      if (Record.size() % 2 == 1)
1116        return Error(BitcodeError::InvalidRecord);
1117
1118      unsigned Size = Record.size();
1119      SmallVector<Value*, 8> Elts;
1120      for (unsigned i = 0; i != Size; i += 2) {
1121        Type *Ty = getTypeByID(Record[i]);
1122        if (!Ty)
1123          return Error(BitcodeError::InvalidRecord);
1124        if (Ty->isMetadataTy())
1125          Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1126        else if (!Ty->isVoidTy())
1127          Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1128        else
1129          Elts.push_back(nullptr);
1130      }
1131      Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1132      IsFunctionLocal = false;
1133      MDValueList.AssignValue(V, NextMDValueNo++);
1134      break;
1135    }
1136    case bitc::METADATA_STRING: {
1137      unsigned MDStringLength = Record.size();
1138      SmallString<8> String;
1139      String.resize(MDStringLength);
1140      for (unsigned i = 0; i != MDStringLength; ++i)
1141        String[i] = Record[i];
1142      Value *V = MDString::get(Context,
1143                               StringRef(String.data(), String.size()));
1144      MDValueList.AssignValue(V, NextMDValueNo++);
1145      break;
1146    }
1147    case bitc::METADATA_KIND: {
1148      unsigned RecordLength = Record.size();
1149      if (Record.empty() || RecordLength < 2)
1150        return Error(BitcodeError::InvalidRecord);
1151      SmallString<8> Name;
1152      Name.resize(RecordLength-1);
1153      unsigned Kind = Record[0];
1154      for (unsigned i = 1; i != RecordLength; ++i)
1155        Name[i-1] = Record[i];
1156
1157      unsigned NewKind = TheModule->getMDKindID(Name.str());
1158      if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1159        return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1160      break;
1161    }
1162    }
1163  }
1164}
1165
1166/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1167/// the LSB for dense VBR encoding.
1168uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1169  if ((V & 1) == 0)
1170    return V >> 1;
1171  if (V != 1)
1172    return -(V >> 1);
1173  // There is no such thing as -0 with integers.  "-0" really means MININT.
1174  return 1ULL << 63;
1175}
1176
1177// FIXME: Delete this in LLVM 4.0 and just assert that the aliasee is a
1178// GlobalObject.
1179static GlobalObject &
1180getGlobalObjectInExpr(const DenseMap<GlobalAlias *, Constant *> &Map,
1181                      Constant &C) {
1182  auto *GO = dyn_cast<GlobalObject>(&C);
1183  if (GO)
1184    return *GO;
1185
1186  auto *GA = dyn_cast<GlobalAlias>(&C);
1187  if (GA)
1188    return getGlobalObjectInExpr(Map, *Map.find(GA)->second);
1189
1190  auto &CE = cast<ConstantExpr>(C);
1191  assert(CE.getOpcode() == Instruction::BitCast ||
1192         CE.getOpcode() == Instruction::GetElementPtr ||
1193         CE.getOpcode() == Instruction::AddrSpaceCast);
1194  if (CE.getOpcode() == Instruction::GetElementPtr)
1195    assert(cast<GEPOperator>(CE).hasAllZeroIndices());
1196  return getGlobalObjectInExpr(Map, *CE.getOperand(0));
1197}
1198
1199/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1200/// values and aliases that we can.
1201std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1202  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1203  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1204
1205  GlobalInitWorklist.swap(GlobalInits);
1206  AliasInitWorklist.swap(AliasInits);
1207
1208  while (!GlobalInitWorklist.empty()) {
1209    unsigned ValID = GlobalInitWorklist.back().second;
1210    if (ValID >= ValueList.size()) {
1211      // Not ready to resolve this yet, it requires something later in the file.
1212      GlobalInits.push_back(GlobalInitWorklist.back());
1213    } else {
1214      if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1215        GlobalInitWorklist.back().first->setInitializer(C);
1216      else
1217        return Error(BitcodeError::ExpectedConstant);
1218    }
1219    GlobalInitWorklist.pop_back();
1220  }
1221
1222  // FIXME: Delete this in LLVM 4.0
1223  // Older versions of llvm could write an alias pointing to another. We cannot
1224  // construct those aliases, so we first collect an alias to aliasee expression
1225  // and then compute the actual aliasee.
1226  DenseMap<GlobalAlias *, Constant *> AliasInit;
1227
1228  while (!AliasInitWorklist.empty()) {
1229    unsigned ValID = AliasInitWorklist.back().second;
1230    if (ValID >= ValueList.size()) {
1231      AliasInits.push_back(AliasInitWorklist.back());
1232    } else {
1233      if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1234        AliasInit.insert(std::make_pair(AliasInitWorklist.back().first, C));
1235      else
1236        return Error(BitcodeError::ExpectedConstant);
1237    }
1238    AliasInitWorklist.pop_back();
1239  }
1240
1241  for (auto &Pair : AliasInit) {
1242    auto &GO = getGlobalObjectInExpr(AliasInit, *Pair.second);
1243    Pair.first->setAliasee(&GO);
1244  }
1245
1246  return std::error_code();
1247}
1248
1249static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1250  SmallVector<uint64_t, 8> Words(Vals.size());
1251  std::transform(Vals.begin(), Vals.end(), Words.begin(),
1252                 BitcodeReader::decodeSignRotatedValue);
1253
1254  return APInt(TypeBits, Words);
1255}
1256
1257std::error_code BitcodeReader::ParseConstants() {
1258  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1259    return Error(BitcodeError::InvalidRecord);
1260
1261  SmallVector<uint64_t, 64> Record;
1262
1263  // Read all the records for this value table.
1264  Type *CurTy = Type::getInt32Ty(Context);
1265  unsigned NextCstNo = ValueList.size();
1266  while (1) {
1267    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1268
1269    switch (Entry.Kind) {
1270    case BitstreamEntry::SubBlock: // Handled for us already.
1271    case BitstreamEntry::Error:
1272      return Error(BitcodeError::MalformedBlock);
1273    case BitstreamEntry::EndBlock:
1274      if (NextCstNo != ValueList.size())
1275        return Error(BitcodeError::InvalidConstantReference);
1276
1277      // Once all the constants have been read, go through and resolve forward
1278      // references.
1279      ValueList.ResolveConstantForwardRefs();
1280      return std::error_code();
1281    case BitstreamEntry::Record:
1282      // The interesting case.
1283      break;
1284    }
1285
1286    // Read a record.
1287    Record.clear();
1288    Value *V = nullptr;
1289    unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1290    switch (BitCode) {
1291    default:  // Default behavior: unknown constant
1292    case bitc::CST_CODE_UNDEF:     // UNDEF
1293      V = UndefValue::get(CurTy);
1294      break;
1295    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
1296      if (Record.empty())
1297        return Error(BitcodeError::InvalidRecord);
1298      if (Record[0] >= TypeList.size())
1299        return Error(BitcodeError::InvalidRecord);
1300      CurTy = TypeList[Record[0]];
1301      continue;  // Skip the ValueList manipulation.
1302    case bitc::CST_CODE_NULL:      // NULL
1303      V = Constant::getNullValue(CurTy);
1304      break;
1305    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
1306      if (!CurTy->isIntegerTy() || Record.empty())
1307        return Error(BitcodeError::InvalidRecord);
1308      V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1309      break;
1310    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1311      if (!CurTy->isIntegerTy() || Record.empty())
1312        return Error(BitcodeError::InvalidRecord);
1313
1314      APInt VInt = ReadWideAPInt(Record,
1315                                 cast<IntegerType>(CurTy)->getBitWidth());
1316      V = ConstantInt::get(Context, VInt);
1317
1318      break;
1319    }
1320    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1321      if (Record.empty())
1322        return Error(BitcodeError::InvalidRecord);
1323      if (CurTy->isHalfTy())
1324        V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1325                                             APInt(16, (uint16_t)Record[0])));
1326      else if (CurTy->isFloatTy())
1327        V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1328                                             APInt(32, (uint32_t)Record[0])));
1329      else if (CurTy->isDoubleTy())
1330        V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1331                                             APInt(64, Record[0])));
1332      else if (CurTy->isX86_FP80Ty()) {
1333        // Bits are not stored the same way as a normal i80 APInt, compensate.
1334        uint64_t Rearrange[2];
1335        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1336        Rearrange[1] = Record[0] >> 48;
1337        V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1338                                             APInt(80, Rearrange)));
1339      } else if (CurTy->isFP128Ty())
1340        V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1341                                             APInt(128, Record)));
1342      else if (CurTy->isPPC_FP128Ty())
1343        V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1344                                             APInt(128, Record)));
1345      else
1346        V = UndefValue::get(CurTy);
1347      break;
1348    }
1349
1350    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1351      if (Record.empty())
1352        return Error(BitcodeError::InvalidRecord);
1353
1354      unsigned Size = Record.size();
1355      SmallVector<Constant*, 16> Elts;
1356
1357      if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1358        for (unsigned i = 0; i != Size; ++i)
1359          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1360                                                     STy->getElementType(i)));
1361        V = ConstantStruct::get(STy, Elts);
1362      } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1363        Type *EltTy = ATy->getElementType();
1364        for (unsigned i = 0; i != Size; ++i)
1365          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1366        V = ConstantArray::get(ATy, Elts);
1367      } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1368        Type *EltTy = VTy->getElementType();
1369        for (unsigned i = 0; i != Size; ++i)
1370          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1371        V = ConstantVector::get(Elts);
1372      } else {
1373        V = UndefValue::get(CurTy);
1374      }
1375      break;
1376    }
1377    case bitc::CST_CODE_STRING: { // STRING: [values]
1378      if (Record.empty())
1379        return Error(BitcodeError::InvalidRecord);
1380
1381      ArrayType *ATy = cast<ArrayType>(CurTy);
1382      Type *EltTy = ATy->getElementType();
1383
1384      unsigned Size = Record.size();
1385      std::vector<Constant*> Elts;
1386      for (unsigned i = 0; i != Size; ++i)
1387        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1388      V = ConstantArray::get(ATy, Elts);
1389      break;
1390    }
1391    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1392      if (Record.empty())
1393        return Error(BitcodeError::InvalidRecord);
1394
1395      ArrayType *ATy = cast<ArrayType>(CurTy);
1396      Type *EltTy = ATy->getElementType();
1397
1398      unsigned Size = Record.size();
1399      std::vector<Constant*> Elts;
1400      for (unsigned i = 0; i != Size; ++i)
1401        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1402      Elts.push_back(Constant::getNullValue(EltTy));
1403      V = ConstantArray::get(ATy, Elts);
1404      break;
1405    }
1406    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1407      if (Record.size() < 3)
1408        return Error(BitcodeError::InvalidRecord);
1409      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1410      if (Opc < 0) {
1411        V = UndefValue::get(CurTy);  // Unknown binop.
1412      } else {
1413        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1414        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1415        unsigned Flags = 0;
1416        if (Record.size() >= 4) {
1417          if (Opc == Instruction::Add ||
1418              Opc == Instruction::Sub ||
1419              Opc == Instruction::Mul ||
1420              Opc == Instruction::Shl) {
1421            if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1422              Flags |= OverflowingBinaryOperator::NoSignedWrap;
1423            if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1424              Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1425          } else if (Opc == Instruction::SDiv ||
1426                     Opc == Instruction::UDiv ||
1427                     Opc == Instruction::LShr ||
1428                     Opc == Instruction::AShr) {
1429            if (Record[3] & (1 << bitc::PEO_EXACT))
1430              Flags |= SDivOperator::IsExact;
1431          }
1432        }
1433        V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1434      }
1435      break;
1436    }
1437    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1438      if (Record.size() < 3)
1439        return Error(BitcodeError::InvalidRecord);
1440      int Opc = GetDecodedCastOpcode(Record[0]);
1441      if (Opc < 0) {
1442        V = UndefValue::get(CurTy);  // Unknown cast.
1443      } else {
1444        Type *OpTy = getTypeByID(Record[1]);
1445        if (!OpTy)
1446          return Error(BitcodeError::InvalidRecord);
1447        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1448        V = ConstantExpr::getCast(Opc, Op, CurTy);
1449      }
1450      break;
1451    }
1452    case bitc::CST_CODE_CE_INBOUNDS_GEP:
1453    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1454      if (Record.size() & 1)
1455        return Error(BitcodeError::InvalidRecord);
1456      SmallVector<Constant*, 16> Elts;
1457      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1458        Type *ElTy = getTypeByID(Record[i]);
1459        if (!ElTy)
1460          return Error(BitcodeError::InvalidRecord);
1461        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1462      }
1463      if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1464        V = ConstantExpr::getInBoundsGetElementPtr(Elts[0],
1465          llvm::ArrayRef<llvm::Constant*>(&Elts[1], Elts.size() - 1));
1466      else
1467        V = ConstantExpr::getGetElementPtr(Elts[0],
1468          llvm::ArrayRef<llvm::Constant*>(&Elts[1], Elts.size() - 1));
1469      break;
1470    }
1471    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1472      if (Record.size() < 3)
1473        return Error(BitcodeError::InvalidRecord);
1474      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1475                                                              Type::getInt1Ty(Context)),
1476                                  ValueList.getConstantFwdRef(Record[1],CurTy),
1477                                  ValueList.getConstantFwdRef(Record[2],CurTy));
1478      break;
1479    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1480      if (Record.size() < 3)
1481        return Error(BitcodeError::InvalidRecord);
1482      VectorType *OpTy =
1483        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1484      if (!OpTy)
1485        return Error(BitcodeError::InvalidRecord);
1486      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1487      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1488      V = ConstantExpr::getExtractElement(Op0, Op1);
1489      break;
1490    }
1491    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1492      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1493      if (Record.size() < 3 || !OpTy)
1494        return Error(BitcodeError::InvalidRecord);
1495      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1496      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1497                                                  OpTy->getElementType());
1498      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1499      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1500      break;
1501    }
1502    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1503      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1504      if (Record.size() < 3 || !OpTy)
1505        return Error(BitcodeError::InvalidRecord);
1506      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1507      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1508      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1509                                                 OpTy->getNumElements());
1510      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1511      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1512      break;
1513    }
1514    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1515      VectorType *RTy = dyn_cast<VectorType>(CurTy);
1516      VectorType *OpTy =
1517        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1518      if (Record.size() < 4 || !RTy || !OpTy)
1519        return Error(BitcodeError::InvalidRecord);
1520      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1521      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1522      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1523                                                 RTy->getNumElements());
1524      Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1525      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1526      break;
1527    }
1528    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1529      if (Record.size() < 4)
1530        return Error(BitcodeError::InvalidRecord);
1531      Type *OpTy = getTypeByID(Record[0]);
1532      if (!OpTy)
1533        return Error(BitcodeError::InvalidRecord);
1534      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1535      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1536
1537      if (OpTy->isFPOrFPVectorTy())
1538        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1539      else
1540        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1541      break;
1542    }
1543    case bitc::CST_CODE_INLINEASM: {
1544      if (Record.size() < 2)
1545        return Error(BitcodeError::InvalidRecord);
1546      std::string AsmStr, ConstrStr;
1547      bool HasSideEffects = Record[0] & 1;
1548      bool IsAlignStack = Record[0] >> 1;
1549      unsigned AsmStrSize = Record[1];
1550      if (2+AsmStrSize >= Record.size())
1551        return Error(BitcodeError::InvalidRecord);
1552      unsigned ConstStrSize = Record[2+AsmStrSize];
1553      if (3+AsmStrSize+ConstStrSize > Record.size())
1554        return Error(BitcodeError::InvalidRecord);
1555
1556      for (unsigned i = 0; i != AsmStrSize; ++i)
1557        AsmStr += (char)Record[2+i];
1558      for (unsigned i = 0; i != ConstStrSize; ++i)
1559        ConstrStr += (char)Record[3+AsmStrSize+i];
1560      PointerType *PTy = cast<PointerType>(CurTy);
1561      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1562                         AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1563      break;
1564    }
1565    case bitc::CST_CODE_BLOCKADDRESS:{
1566      if (Record.size() < 3)
1567        return Error(BitcodeError::InvalidRecord);
1568      Type *FnTy = getTypeByID(Record[0]);
1569      if (!FnTy)
1570        return Error(BitcodeError::InvalidRecord);
1571      Function *Fn =
1572        dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1573      if (!Fn)
1574        return Error(BitcodeError::InvalidRecord);
1575
1576      GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1577                                                  Type::getInt8Ty(Context),
1578                                            false, GlobalValue::InternalLinkage,
1579                                                  0, "");
1580      BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1581      V = FwdRef;
1582      break;
1583    }
1584    }
1585
1586    ValueList.AssignValue(V, NextCstNo);
1587    ++NextCstNo;
1588  }
1589
1590  if (NextCstNo != ValueList.size())
1591    return Error(BitcodeError::InvalidConstantReference);
1592
1593  if (Stream.ReadBlockEnd())
1594    return Error(BitcodeError::ExpectedConstant);
1595
1596  // Once all the constants have been read, go through and resolve forward
1597  // references.
1598  ValueList.ResolveConstantForwardRefs();
1599  return std::error_code();
1600}
1601
1602/// RememberAndSkipFunctionBody - When we see the block for a function body,
1603/// remember where it is and then skip it.  This lets us lazily deserialize the
1604/// functions.
1605std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1606  // Get the function we are talking about.
1607  if (FunctionsWithBodies.empty())
1608    return Error(BitcodeError::InsufficientFunctionProtos);
1609
1610  Function *Fn = FunctionsWithBodies.back();
1611  FunctionsWithBodies.pop_back();
1612
1613  // Save the current stream state.
1614  uint64_t CurBit = Stream.GetCurrentBitNo();
1615  DeferredFunctionInfo[Fn] = CurBit;
1616
1617  // Skip over the function block for now.
1618  if (Stream.SkipBlock())
1619    return Error(BitcodeError::InvalidRecord);
1620  return std::error_code();
1621}
1622
1623std::error_code BitcodeReader::GlobalCleanup() {
1624  // Patch the initializers for globals and aliases up.
1625  ResolveGlobalAndAliasInits();
1626  if (!GlobalInits.empty() || !AliasInits.empty())
1627    return Error(BitcodeError::MalformedGlobalInitializerSet);
1628
1629  // Look for intrinsic functions which need to be upgraded at some point
1630  for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1631       FI != FE; ++FI) {
1632    Function *NewFn;
1633    if (UpgradeIntrinsicFunction(FI, NewFn))
1634      UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1635  }
1636
1637  // Look for global variables which need to be renamed.
1638  for (Module::global_iterator
1639         GI = TheModule->global_begin(), GE = TheModule->global_end();
1640       GI != GE; ++GI)
1641    UpgradeGlobalVariable(GI);
1642  // Force deallocation of memory for these vectors to favor the client that
1643  // want lazy deserialization.
1644  std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1645  std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1646  return std::error_code();
1647}
1648
1649std::error_code BitcodeReader::ParseModule(bool Resume) {
1650  if (Resume)
1651    Stream.JumpToBit(NextUnreadBit);
1652  else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1653    return Error(BitcodeError::InvalidRecord);
1654
1655  SmallVector<uint64_t, 64> Record;
1656  std::vector<std::string> SectionTable;
1657  std::vector<std::string> GCTable;
1658
1659  // Read all the records for this module.
1660  while (!Stream.AtEndOfStream()) {
1661    unsigned Code = Stream.ReadCode();
1662    if (Code == bitc::END_BLOCK) {
1663      if (Stream.ReadBlockEnd())
1664        return Error(BitcodeError::MalformedBlock);
1665
1666      // Patch the initializers for globals and aliases up.
1667      ResolveGlobalAndAliasInits();
1668      if (!GlobalInits.empty() || !AliasInits.empty())
1669        return Error(BitcodeError::MalformedGlobalInitializerSet);
1670      if (!FunctionsWithBodies.empty())
1671        return Error(BitcodeError::InsufficientFunctionProtos);
1672
1673      // Look for intrinsic functions which need to be upgraded at some point
1674      for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1675           FI != FE; ++FI) {
1676        Function* NewFn;
1677        if (UpgradeIntrinsicFunction(FI, NewFn))
1678          UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1679      }
1680
1681      // Look for global variables which need to be renamed.
1682      for (Module::global_iterator
1683             GI = TheModule->global_begin(), GE = TheModule->global_end();
1684           GI != GE; ++GI)
1685        UpgradeGlobalVariable(GI);
1686
1687      // Force deallocation of memory for these vectors to favor the client that
1688      // want lazy deserialization.
1689      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1690      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1691      std::vector<Function*>().swap(FunctionsWithBodies);
1692      return std::error_code();
1693    }
1694
1695    if (Code == bitc::ENTER_SUBBLOCK) {
1696      switch (Stream.ReadSubBlockID()) {
1697      default:  // Skip unknown content.
1698        if (Stream.SkipBlock())
1699          return Error(BitcodeError::InvalidRecord);
1700        break;
1701      case bitc::BLOCKINFO_BLOCK_ID:
1702        if (Stream.ReadBlockInfoBlock())
1703          return Error(BitcodeError::MalformedBlock);
1704        break;
1705      case bitc::PARAMATTR_BLOCK_ID:
1706        if (std::error_code EC = ParseAttributeBlock())
1707          return EC;
1708        break;
1709      case bitc::TYPE_BLOCK_ID_NEW:
1710        if (std::error_code EC = ParseTypeTable())
1711          return EC;
1712        break;
1713      case TYPE_BLOCK_ID_OLD_3_0:
1714        if (std::error_code EC = ParseOldTypeTable())
1715          return EC;
1716        break;
1717      case TYPE_SYMTAB_BLOCK_ID_OLD_3_0:
1718        if (std::error_code EC = ParseOldTypeSymbolTable())
1719          return EC;
1720        break;
1721      case bitc::VALUE_SYMTAB_BLOCK_ID:
1722        if (std::error_code EC = ParseValueSymbolTable())
1723          return EC;
1724        SeenValueSymbolTable = true;
1725        break;
1726      case bitc::CONSTANTS_BLOCK_ID:
1727        if (std::error_code EC = ParseConstants())
1728          return EC;
1729        if (std::error_code EC = ResolveGlobalAndAliasInits())
1730          return EC;
1731        break;
1732      case bitc::METADATA_BLOCK_ID:
1733        if (std::error_code EC = ParseMetadata())
1734          return EC;
1735        break;
1736      case bitc::FUNCTION_BLOCK_ID:
1737        // If this is the first function body we've seen, reverse the
1738        // FunctionsWithBodies list.
1739        if (!SeenFirstFunctionBody) {
1740          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1741          if (std::error_code EC = GlobalCleanup())
1742            return EC;
1743          SeenFirstFunctionBody = true;
1744        }
1745
1746        if (std::error_code EC = RememberAndSkipFunctionBody())
1747          return EC;
1748        // For streaming bitcode, suspend parsing when we reach the function
1749        // bodies. Subsequent materialization calls will resume it when
1750        // necessary. For streaming, the function bodies must be at the end of
1751        // the bitcode. If the bitcode file is old, the symbol table will be
1752        // at the end instead and will not have been seen yet. In this case,
1753        // just finish the parse now.
1754        if (LazyStreamer && SeenValueSymbolTable) {
1755          NextUnreadBit = Stream.GetCurrentBitNo();
1756          return std::error_code();
1757        }
1758        break;
1759        break;
1760      }
1761      continue;
1762    }
1763
1764    if (Code == bitc::DEFINE_ABBREV) {
1765      Stream.ReadAbbrevRecord();
1766      continue;
1767    }
1768
1769    // Read a record.
1770    switch (Stream.readRecord(Code, Record)) {
1771    default: break;  // Default behavior, ignore unknown content.
1772    case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
1773      if (Record.size() < 1)
1774        return Error(BitcodeError::InvalidRecord);
1775      // Only version #0 is supported so far.
1776      if (Record[0] != 0)
1777        return Error(BitcodeError::InvalidValue);
1778      break;
1779    }
1780    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1781      std::string S;
1782      if (ConvertToString(Record, 0, S))
1783        return Error(BitcodeError::InvalidRecord);
1784      TheModule->setTargetTriple(S);
1785      break;
1786    }
1787    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1788      std::string S;
1789      if (ConvertToString(Record, 0, S))
1790        return Error(BitcodeError::InvalidRecord);
1791      TheModule->setDataLayout(S);
1792      break;
1793    }
1794    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1795      std::string S;
1796      if (ConvertToString(Record, 0, S))
1797        return Error(BitcodeError::InvalidRecord);
1798      TheModule->setModuleInlineAsm(S);
1799      break;
1800    }
1801    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1802      std::string S;
1803      if (ConvertToString(Record, 0, S))
1804        return Error(BitcodeError::InvalidRecord);
1805      // ANDROID: Ignore value, since we never used it anyways.
1806      // TheModule->addLibrary(S);
1807      break;
1808    }
1809    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1810      std::string S;
1811      if (ConvertToString(Record, 0, S))
1812        return Error(BitcodeError::InvalidRecord);
1813      SectionTable.push_back(S);
1814      break;
1815    }
1816    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1817      std::string S;
1818      if (ConvertToString(Record, 0, S))
1819        return Error(BitcodeError::InvalidRecord);
1820      GCTable.push_back(S);
1821      break;
1822    }
1823    // GLOBALVAR: [pointer type, isconst, initid,
1824    //             linkage, alignment, section, visibility, threadlocal,
1825    //             unnamed_addr]
1826    case bitc::MODULE_CODE_GLOBALVAR: {
1827      if (Record.size() < 6)
1828        return Error(BitcodeError::InvalidRecord);
1829      Type *Ty = getTypeByID(Record[0]);
1830      if (!Ty)
1831        return Error(BitcodeError::InvalidRecord);
1832      if (!Ty->isPointerTy())
1833        return Error(BitcodeError::InvalidTypeForValue);
1834      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1835      Ty = cast<PointerType>(Ty)->getElementType();
1836
1837      bool isConstant = Record[1];
1838      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1839      unsigned Alignment = (1 << Record[4]) >> 1;
1840      std::string Section;
1841      if (Record[5]) {
1842        if (Record[5]-1 >= SectionTable.size())
1843          return Error(BitcodeError::InvalidID);
1844        Section = SectionTable[Record[5]-1];
1845      }
1846      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1847      if (Record.size() > 6)
1848        Visibility = GetDecodedVisibility(Record[6]);
1849
1850      GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1851      if (Record.size() > 7)
1852        TLM = GetDecodedThreadLocalMode(Record[7]);
1853
1854      bool UnnamedAddr = false;
1855      if (Record.size() > 8)
1856        UnnamedAddr = Record[8];
1857
1858      GlobalVariable *NewGV =
1859        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1860                           TLM, AddressSpace);
1861      NewGV->setAlignment(Alignment);
1862      if (!Section.empty())
1863        NewGV->setSection(Section);
1864      NewGV->setVisibility(Visibility);
1865      NewGV->setUnnamedAddr(UnnamedAddr);
1866
1867      ValueList.push_back(NewGV);
1868
1869      // Remember which value to use for the global initializer.
1870      if (unsigned InitID = Record[2])
1871        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1872      break;
1873    }
1874    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1875    //             alignment, section, visibility, gc, unnamed_addr]
1876    case bitc::MODULE_CODE_FUNCTION: {
1877      if (Record.size() < 8)
1878        return Error(BitcodeError::InvalidRecord);
1879      Type *Ty = getTypeByID(Record[0]);
1880      if (!Ty)
1881        return Error(BitcodeError::InvalidRecord);
1882      if (!Ty->isPointerTy())
1883        return Error(BitcodeError::InvalidTypeForValue);
1884      FunctionType *FTy =
1885        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1886      if (!FTy)
1887        return Error(BitcodeError::InvalidTypeForValue);
1888
1889      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1890                                        "", TheModule);
1891
1892      Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1893      bool isProto = Record[2];
1894      Func->setLinkage(GetDecodedLinkage(Record[3]));
1895      Func->setAttributes(getAttributes(Record[4]));
1896
1897      Func->setAlignment((1 << Record[5]) >> 1);
1898      if (Record[6]) {
1899        if (Record[6]-1 >= SectionTable.size())
1900          return Error(BitcodeError::InvalidID);
1901        Func->setSection(SectionTable[Record[6]-1]);
1902      }
1903      Func->setVisibility(GetDecodedVisibility(Record[7]));
1904      if (Record.size() > 8 && Record[8]) {
1905        if (Record[8]-1 > GCTable.size())
1906          return Error(BitcodeError::InvalidID);
1907        Func->setGC(GCTable[Record[8]-1].c_str());
1908      }
1909      bool UnnamedAddr = false;
1910      if (Record.size() > 9)
1911        UnnamedAddr = Record[9];
1912      Func->setUnnamedAddr(UnnamedAddr);
1913      ValueList.push_back(Func);
1914
1915      // If this is a function with a body, remember the prototype we are
1916      // creating now, so that we can match up the body with them later.
1917      if (!isProto) {
1918        Func->setIsMaterializable(true);
1919        FunctionsWithBodies.push_back(Func);
1920        if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1921      }
1922      break;
1923    }
1924    // ALIAS: [alias type, aliasee val#, linkage]
1925    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1926    case bitc::MODULE_CODE_ALIAS: {
1927      if (Record.size() < 3)
1928        return Error(BitcodeError::InvalidRecord);
1929      Type *Ty = getTypeByID(Record[0]);
1930      if (!Ty)
1931        return Error(BitcodeError::InvalidRecord);
1932      auto *PTy = dyn_cast<PointerType>(Ty);
1933      if (!PTy)
1934        return Error(BitcodeError::InvalidTypeForValue);
1935
1936      GlobalAlias *NewGA =
1937          GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1938                              GetDecodedLinkage(Record[2]), "", 0, TheModule);
1939      // Old bitcode files didn't have visibility field.
1940      if (Record.size() > 3)
1941        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1942      ValueList.push_back(NewGA);
1943      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1944      break;
1945    }
1946    /// MODULE_CODE_PURGEVALS: [numvals]
1947    case bitc::MODULE_CODE_PURGEVALS:
1948      // Trim down the value list to the specified size.
1949      if (Record.size() < 1 || Record[0] > ValueList.size())
1950        return Error(BitcodeError::InvalidRecord);
1951      ValueList.shrinkTo(Record[0]);
1952      break;
1953    }
1954    Record.clear();
1955  }
1956
1957  return Error(BitcodeError::InvalidBitcodeSignature);
1958}
1959
1960std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
1961  TheModule = nullptr;
1962
1963  if (std::error_code EC = InitStream())
1964    return EC;
1965
1966  // Sniff for the signature.
1967  if (Stream.Read(8) != 'B' ||
1968      Stream.Read(8) != 'C' ||
1969      Stream.Read(4) != 0x0 ||
1970      Stream.Read(4) != 0xC ||
1971      Stream.Read(4) != 0xE ||
1972      Stream.Read(4) != 0xD)
1973    return Error(BitcodeError::InvalidBitcodeSignature);
1974
1975  // We expect a number of well-defined blocks, though we don't necessarily
1976  // need to understand them all.
1977  while (1) {
1978    if (Stream.AtEndOfStream())
1979      return std::error_code();
1980
1981    BitstreamEntry Entry =
1982      Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1983
1984    switch (Entry.Kind) {
1985    case BitstreamEntry::Error:
1986      return Error(BitcodeError::MalformedBlock);
1987    case BitstreamEntry::EndBlock:
1988      return std::error_code();
1989
1990    case BitstreamEntry::SubBlock:
1991      switch (Entry.ID) {
1992      case bitc::BLOCKINFO_BLOCK_ID:
1993        if (Stream.ReadBlockInfoBlock())
1994          return Error(BitcodeError::MalformedBlock);
1995        break;
1996      case bitc::MODULE_BLOCK_ID:
1997        // Reject multiple MODULE_BLOCK's in a single bitstream.
1998        if (TheModule)
1999          return Error(BitcodeError::InvalidMultipleBlocks);
2000        TheModule = M;
2001        if (std::error_code EC = ParseModule(false))
2002          return EC;
2003        if (LazyStreamer)
2004          return std::error_code();
2005        break;
2006      default:
2007        if (Stream.SkipBlock())
2008          return Error(BitcodeError::InvalidRecord);
2009        break;
2010      }
2011      continue;
2012    case BitstreamEntry::Record:
2013      // There should be no records in the top-level of blocks.
2014
2015      // The ranlib in Xcode 4 will align archive members by appending newlines
2016      // to the end of them. If this file size is a multiple of 4 but not 8, we
2017      // have to read and ignore these final 4 bytes :-(
2018      if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2019          Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2020          Stream.AtEndOfStream())
2021        return std::error_code();
2022
2023      return Error(BitcodeError::InvalidRecord);
2024    }
2025  }
2026}
2027
2028llvm::ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2029  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2030    return Error(BitcodeError::InvalidRecord);
2031
2032  SmallVector<uint64_t, 64> Record;
2033
2034  std::string Triple;
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(BitcodeError::MalformedBlock);
2043    case BitstreamEntry::EndBlock:
2044      return Triple;
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(BitcodeError::InvalidRecord);
2056      // Only version #0 is supported so far.
2057      if (Record[0] != 0)
2058        return Error(BitcodeError::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(BitcodeError::InvalidRecord);
2064      Triple = S;
2065      break;
2066    }
2067    }
2068    Record.clear();
2069  }
2070
2071  return Error(BitcodeError::InvalidBitcodeSignature);
2072}
2073
2074llvm::ErrorOr<std::string> BitcodeReader::parseTriple() {
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(BitcodeError::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(BitcodeError::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();
2101
2102      // Ignore other sub-blocks.
2103      if (Stream.SkipBlock())
2104        return Error(BitcodeError::MalformedBlock);
2105      continue;
2106
2107    case BitstreamEntry::Record:
2108      Stream.skipRecord(Entry.ID);
2109      continue;
2110    }
2111  }
2112}
2113
2114/// ParseMetadataAttachment - Parse metadata attachments.
2115std::error_code BitcodeReader::ParseMetadataAttachment() {
2116  if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2117    return Error(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::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.
2162std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2163  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2164    return Error(BitcodeError::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 = nullptr;
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(BitcodeError::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(BitcodeError::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 = nullptr;
2225    unsigned BitCode = Stream.readRecord(Code, Record);
2226    switch (BitCode) {
2227    default: // Default behavior: reject
2228      return Error(BitcodeError::InvalidValue);
2229    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
2230      if (Record.size() < 1 || Record[0] == 0)
2231        return Error(BitcodeError::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 = nullptr;
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)
2252        return Error(BitcodeError::InvalidRecord);
2253      I->setDebugLoc(LastLoc);
2254      I = nullptr;
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 = nullptr;     // 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 || Record.size() < 4)
2267        return Error(BitcodeError::InvalidRecord);
2268
2269      unsigned Line = Record[0], Col = Record[1];
2270      unsigned ScopeID = Record[2], IAID = Record[3];
2271
2272      MDNode *Scope = nullptr, *IA = nullptr;
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 = nullptr;
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(BitcodeError::InvalidRecord);
2288
2289      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2290      if (Opc == -1)
2291        return Error(BitcodeError::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(BitcodeError::InvalidRecord);
2319
2320      Type *ResTy = getTypeByID(Record[OpNum]);
2321      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2322      if (Opc == -1 || !ResTy)
2323        return Error(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::InvalidRecord);
2377      Value *Val;
2378      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2379        return Error(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::InvalidTypeForValue);
2426      } else {
2427        // expect i1
2428        if (Cond->getType() != Type::getInt1Ty(Context))
2429          return Error(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::InvalidRecord);
2467
2468      if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2469        return Error(BitcodeError::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(BitcodeError::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(BitcodeError::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 = nullptr;
2521        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2522          return Error(BitcodeError::InvalidRecord);
2523        if (OpNum != Record.size())
2524          return Error(BitcodeError::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(BitcodeError::InvalidRecord);
2533      BasicBlock *TrueDest = getBasicBlock(Record[0]);
2534      if (!TrueDest)
2535        return Error(BitcodeError::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 || !Cond)
2545          return Error(BitcodeError::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(BitcodeError::InvalidRecord);
2554      Type *OpTy = getTypeByID(Record[0]);
2555      Value *Cond = getFnValueByID(Record[1], OpTy);
2556      BasicBlock *Default = getBasicBlock(Record[2]);
2557      if (!OpTy || !Cond || !Default)
2558        return Error(BitcodeError::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 || !DestBB) {
2567          delete SI;
2568          return Error(BitcodeError::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(BitcodeError::InvalidRecord);
2578      Type *OpTy = getTypeByID(Record[0]);
2579      Value *Address = getFnValueByID(Record[1], OpTy);
2580      if (!OpTy || !Address)
2581        return Error(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::InvalidRecord);
2610
2611      PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2612      FunctionType *FTy = !CalleeTy ? nullptr :
2613        dyn_cast<FunctionType>(CalleeTy->getElementType());
2614
2615      // Check that the right number of fixed parameters are here.
2616      if (!FTy || !NormalBB || !UnwindBB ||
2617          Record.size() < OpNum+FTy->getNumParams())
2618        return Error(BitcodeError::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())
2624          return Error(BitcodeError::InvalidRecord);
2625      }
2626
2627      if (!FTy->isVarArg()) {
2628        if (Record.size() != OpNum)
2629          return Error(BitcodeError::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(BitcodeError::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), nullptr);
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(BitcodeError::InvalidRecord);
2672      Type *Ty = getTypeByID(Record[0]);
2673      if (!Ty)
2674        return Error(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::InvalidRecord);
2701      if (!CurBB)
2702        return Error(BitcodeError::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, nullptr);
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(BitcodeError::InvalidRecord);
2717      }
2718      if (!CurBB)
2719        return Error(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::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(BitcodeError::InvalidRecord);
2795
2796      PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2797      FunctionType *FTy = nullptr;
2798      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2799      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2800        return Error(BitcodeError::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())
2810          return Error(BitcodeError::InvalidRecord);
2811      }
2812
2813      // Read type/value pairs for varargs params.
2814      if (!FTy->isVarArg()) {
2815        if (OpNum != Record.size())
2816          return Error(BitcodeError::InvalidRecord);
2817      } else {
2818        while (OpNum != Record.size()) {
2819          Value *Op;
2820          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2821            return Error(BitcodeError::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(BitcodeError::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(BitcodeError::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) {
2851      delete I;
2852      return Error(BitcodeError::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()) {
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_or_null<Argument>(ValueList[i])) && !A->getParent()) {
2873          A->replaceAllUsesWith(UndefValue::get(A->getType()));
2874          delete A;
2875        }
2876      }
2877      return Error(BitcodeError::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(BitcodeError::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
2921std::error_code BitcodeReader::materialize(GlobalValue *GV) {
2922  Function *F = dyn_cast<Function>(GV);
2923  // If it's not a function or is already material, ignore the request.
2924  if (!F || !F->isMaterializable())
2925    return std::error_code();
2926
2927  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2928  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2929
2930  // Move the bit stream to the saved position of the deferred function body.
2931  Stream.JumpToBit(DFII->second);
2932
2933  if (std::error_code EC = ParseFunctionBody(F))
2934    return EC;
2935  F->setIsMaterializable(false);
2936
2937  // Upgrade any old intrinsic calls in the function.
2938  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2939       E = UpgradedIntrinsics.end(); I != E; ++I) {
2940    if (I->first != I->second) {
2941      for (Value::use_iterator UI = I->first->use_begin(),
2942           UE = I->first->use_end(); UI != UE; ) {
2943        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2944          UpgradeIntrinsicCall(CI, I->second);
2945      }
2946    }
2947  }
2948
2949  return std::error_code();
2950}
2951
2952bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2953  const Function *F = dyn_cast<Function>(GV);
2954  if (!F || F->isDeclaration())
2955    return false;
2956  return DeferredFunctionInfo.count(const_cast<Function*>(F));
2957}
2958
2959void BitcodeReader::Dematerialize(GlobalValue *GV) {
2960  Function *F = dyn_cast<Function>(GV);
2961  // If this function isn't dematerializable, this is a noop.
2962  if (!F || !isDematerializable(F))
2963    return;
2964
2965  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2966
2967  // Just forget the function body, we can remat it later.
2968  F->deleteBody();
2969  F->setIsMaterializable(true);
2970}
2971
2972
2973std::error_code BitcodeReader::MaterializeModule(Module *M) {
2974  assert(M == TheModule &&
2975         "Can only Materialize the Module this BitcodeReader is attached to.");
2976  // Iterate over the module, deserializing any functions that are still on
2977  // disk.
2978  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2979       F != E; ++F) {
2980    if (std::error_code EC = materialize(F))
2981      return EC;
2982  }
2983  // At this point, if there are any function bodies, the current bit is
2984  // pointing to the END_BLOCK record after them. Now make sure the rest
2985  // of the bits in the module have been read.
2986  if (NextUnreadBit)
2987    ParseModule(true);
2988
2989  // Upgrade any intrinsic calls that slipped through (should not happen!) and
2990  // delete the old functions to clean up. We can't do this unless the entire
2991  // module is materialized because there could always be another function body
2992  // with calls to the old function.
2993  for (std::vector<std::pair<Function*, Function*> >::iterator I =
2994       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2995    if (I->first != I->second) {
2996      for (Value::use_iterator UI = I->first->use_begin(),
2997           UE = I->first->use_end(); UI != UE; ) {
2998        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2999          UpgradeIntrinsicCall(CI, I->second);
3000      }
3001      if (!I->first->use_empty())
3002        I->first->replaceAllUsesWith(I->second);
3003      I->first->eraseFromParent();
3004    }
3005  }
3006  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3007
3008  // Check debug info intrinsics.
3009  CheckDebugInfoIntrinsics(TheModule);
3010
3011  return std::error_code();
3012}
3013
3014std::error_code BitcodeReader::InitStream() {
3015  if (LazyStreamer)
3016    return InitLazyStream();
3017  return InitStreamFromBuffer();
3018}
3019
3020std::error_code BitcodeReader::InitStreamFromBuffer() {
3021  const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3022  const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3023
3024  if (Buffer->getBufferSize() & 3)
3025    return Error(BitcodeError::InvalidBitcodeSignature);
3026
3027  // If we have a wrapper header, parse it and ignore the non-bc file contents.
3028  // The magic number is 0x0B17C0DE stored in little endian.
3029  if (isBitcodeWrapper(BufPtr, BufEnd))
3030    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3031      return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3032
3033  StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3034  Stream.init(&*StreamFile);
3035
3036  return std::error_code();
3037}
3038
3039std::error_code BitcodeReader::InitLazyStream() {
3040  // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3041  // see it.
3042  StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3043  StreamFile.reset(new BitstreamReader(Bytes));
3044  Stream.init(&*StreamFile);
3045
3046  unsigned char buf[16];
3047  if (Bytes->readBytes(buf, 16, 0) != 16)
3048    return Error(BitcodeError::InvalidBitcodeSignature);
3049
3050  if (!isBitcode(buf, buf + 16))
3051    return Error(BitcodeError::InvalidBitcodeSignature);
3052
3053  if (isBitcodeWrapper(buf, buf + 4)) {
3054    const unsigned char *bitcodeStart = buf;
3055    const unsigned char *bitcodeEnd = buf + 16;
3056    SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3057    Bytes->dropLeadingBytes(bitcodeStart - buf);
3058    Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3059  }
3060  return std::error_code();
3061}
3062
3063namespace {
3064class BitcodeErrorCategoryType : public std::error_category {
3065  const char *name() const LLVM_NOEXCEPT override {
3066    return "llvm.bitcode";
3067  }
3068  std::string message(int IE) const override {
3069    BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE);
3070    switch (E) {
3071    case BitcodeReader::ConflictingMETADATA_KINDRecords:
3072      return "Conflicting METADATA_KIND records";
3073    case BitcodeReader::CouldNotFindFunctionInStream:
3074      return "Could not find function in stream";
3075    case BitcodeReader::ExpectedConstant:
3076      return "Expected a constant";
3077    case BitcodeReader::InsufficientFunctionProtos:
3078      return "Insufficient function protos";
3079    case BitcodeReader::InvalidBitcodeSignature:
3080      return "Invalid bitcode signature";
3081    case BitcodeReader::InvalidBitcodeWrapperHeader:
3082      return "Invalid bitcode wrapper header";
3083    case BitcodeReader::InvalidConstantReference:
3084      return "Invalid ronstant reference";
3085    case BitcodeReader::InvalidID:
3086      return "Invalid ID";
3087    case BitcodeReader::InvalidInstructionWithNoBB:
3088      return "Invalid instruction with no BB";
3089    case BitcodeReader::InvalidRecord:
3090      return "Invalid record";
3091    case BitcodeReader::InvalidTypeForValue:
3092      return "Invalid type for value";
3093    case BitcodeReader::InvalidTYPETable:
3094      return "Invalid TYPE table";
3095    case BitcodeReader::InvalidType:
3096      return "Invalid type";
3097    case BitcodeReader::MalformedBlock:
3098      return "Malformed block";
3099    case BitcodeReader::MalformedGlobalInitializerSet:
3100      return "Malformed global initializer set";
3101    case BitcodeReader::InvalidMultipleBlocks:
3102      return "Invalid multiple blocks";
3103    case BitcodeReader::NeverResolvedValueFoundInFunction:
3104      return "Never resolved value found in function";
3105    case BitcodeReader::InvalidValue:
3106      return "Invalid value";
3107    }
3108    llvm_unreachable("Unknown error type!");
3109  }
3110};
3111}
3112
3113const std::error_category &BitcodeReader::BitcodeErrorCategory() {
3114  static BitcodeErrorCategoryType O;
3115  return O;
3116}
3117
3118//===----------------------------------------------------------------------===//
3119// External interface
3120//===----------------------------------------------------------------------===//
3121
3122/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3123///
3124llvm::ErrorOr<llvm::Module *>
3125llvm_2_7::getLazyBitcodeModule(std::unique_ptr<llvm::MemoryBuffer> &&Buffer,
3126                               llvm::LLVMContext &Context) {
3127  Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3128  BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3129  M->setMaterializer(R);
3130
3131  auto cleanupOnError = [&](std::error_code EC) {
3132    R->releaseBuffer(); // Never take ownership on error.
3133    delete M;  // Also deletes R.
3134    return EC;
3135  };
3136
3137  if (std::error_code EC = R->ParseBitcodeInto(M))
3138    return cleanupOnError(EC);
3139
3140  Buffer.release(); // The BitcodeReader owns it now.
3141  return M;
3142}
3143
3144/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3145/// If an error occurs, return null and fill in *ErrMsg if non-null.
3146llvm::ErrorOr<llvm::Module *> llvm_2_7::parseBitcodeFile(llvm::MemoryBufferRef Buffer,
3147                                                         llvm::LLVMContext &Context) {
3148
3149
3150  std::unique_ptr<llvm::MemoryBuffer> Buf = llvm::MemoryBuffer::getMemBuffer(Buffer, false);
3151  llvm::ErrorOr<llvm::Module *> ModuleOrErr =
3152      llvm_2_7::getLazyBitcodeModule(std::move(Buf), Context);
3153  if (!ModuleOrErr)
3154    return ModuleOrErr;
3155  Module *M = ModuleOrErr.get();
3156  // Read in the entire module, and destroy the BitcodeReader.
3157  if (std::error_code EC = M->materializeAllPermanently()) {
3158    delete M;
3159    return EC;
3160  }
3161
3162  return M;
3163}
3164
3165std::string llvm_2_7::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3166                                             LLVMContext &Context) {
3167  std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3168  auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3169  ErrorOr<std::string> Triple = R->parseTriple();
3170  if (Triple.getError())
3171    return "";
3172  return Triple.get();
3173}
3174