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