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