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