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