BitcodeReader.cpp revision f8342b98663096186c3a367f7d0fd5ebb7064a52
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/Instructions.h"
20#include "llvm/Module.h"
21#include "llvm/ParamAttrsList.h"
22#include "llvm/AutoUpgrade.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/Support/MathExtras.h"
26#include "llvm/Support/MemoryBuffer.h"
27using namespace llvm;
28
29void BitcodeReader::FreeState() {
30  delete Buffer;
31  Buffer = 0;
32  std::vector<PATypeHolder>().swap(TypeList);
33  ValueList.clear();
34  std::vector<const ParamAttrsList*>().swap(ParamAttrs);
35  std::vector<BasicBlock*>().swap(FunctionBBs);
36  std::vector<Function*>().swap(FunctionsWithBodies);
37  DeferredFunctionInfo.clear();
38}
39
40//===----------------------------------------------------------------------===//
41//  Helper functions to implement forward reference resolution, etc.
42//===----------------------------------------------------------------------===//
43
44/// ConvertToString - Convert a string from a record into an std::string, return
45/// true on failure.
46template<typename StrTy>
47static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
48                            StrTy &Result) {
49  if (Idx > Record.size())
50    return true;
51
52  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
53    Result += (char)Record[i];
54  return false;
55}
56
57static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
58  switch (Val) {
59  default: // Map unknown/new linkages to external
60  case 0: return GlobalValue::ExternalLinkage;
61  case 1: return GlobalValue::WeakLinkage;
62  case 2: return GlobalValue::AppendingLinkage;
63  case 3: return GlobalValue::InternalLinkage;
64  case 4: return GlobalValue::LinkOnceLinkage;
65  case 5: return GlobalValue::DLLImportLinkage;
66  case 6: return GlobalValue::DLLExportLinkage;
67  case 7: return GlobalValue::ExternalWeakLinkage;
68  }
69}
70
71static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
72  switch (Val) {
73  default: // Map unknown visibilities to default.
74  case 0: return GlobalValue::DefaultVisibility;
75  case 1: return GlobalValue::HiddenVisibility;
76  case 2: return GlobalValue::ProtectedVisibility;
77  }
78}
79
80static int GetDecodedCastOpcode(unsigned Val) {
81  switch (Val) {
82  default: return -1;
83  case bitc::CAST_TRUNC   : return Instruction::Trunc;
84  case bitc::CAST_ZEXT    : return Instruction::ZExt;
85  case bitc::CAST_SEXT    : return Instruction::SExt;
86  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
87  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
88  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
89  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
90  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
91  case bitc::CAST_FPEXT   : return Instruction::FPExt;
92  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
93  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
94  case bitc::CAST_BITCAST : return Instruction::BitCast;
95  }
96}
97static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
98  switch (Val) {
99  default: return -1;
100  case bitc::BINOP_ADD:  return Instruction::Add;
101  case bitc::BINOP_SUB:  return Instruction::Sub;
102  case bitc::BINOP_MUL:  return Instruction::Mul;
103  case bitc::BINOP_UDIV: return Instruction::UDiv;
104  case bitc::BINOP_SDIV:
105    return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
106  case bitc::BINOP_UREM: return Instruction::URem;
107  case bitc::BINOP_SREM:
108    return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
109  case bitc::BINOP_SHL:  return Instruction::Shl;
110  case bitc::BINOP_LSHR: return Instruction::LShr;
111  case bitc::BINOP_ASHR: return Instruction::AShr;
112  case bitc::BINOP_AND:  return Instruction::And;
113  case bitc::BINOP_OR:   return Instruction::Or;
114  case bitc::BINOP_XOR:  return Instruction::Xor;
115  }
116}
117
118
119namespace {
120  /// @brief A class for maintaining the slot number definition
121  /// as a placeholder for the actual definition for forward constants defs.
122  class ConstantPlaceHolder : public ConstantExpr {
123    ConstantPlaceHolder();                       // DO NOT IMPLEMENT
124    void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
125  public:
126    Use Op;
127    explicit ConstantPlaceHolder(const Type *Ty)
128      : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
129        Op(UndefValue::get(Type::Int32Ty), this) {
130    }
131  };
132}
133
134Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
135                                                    const Type *Ty) {
136  if (Idx >= size()) {
137    // Insert a bunch of null values.
138    Uses.resize(Idx+1);
139    OperandList = &Uses[0];
140    NumOperands = Idx+1;
141  }
142
143  if (Value *V = Uses[Idx]) {
144    assert(Ty == V->getType() && "Type mismatch in constant table!");
145    return cast<Constant>(V);
146  }
147
148  // Create and return a placeholder, which will later be RAUW'd.
149  Constant *C = new ConstantPlaceHolder(Ty);
150  Uses[Idx].init(C, this);
151  return C;
152}
153
154Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
155  if (Idx >= size()) {
156    // Insert a bunch of null values.
157    Uses.resize(Idx+1);
158    OperandList = &Uses[0];
159    NumOperands = Idx+1;
160  }
161
162  if (Value *V = Uses[Idx]) {
163    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
164    return V;
165  }
166
167  // No type specified, must be invalid reference.
168  if (Ty == 0) return 0;
169
170  // Create and return a placeholder, which will later be RAUW'd.
171  Value *V = new Argument(Ty);
172  Uses[Idx].init(V, this);
173  return V;
174}
175
176
177const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
178  // If the TypeID is in range, return it.
179  if (ID < TypeList.size())
180    return TypeList[ID].get();
181  if (!isTypeTable) return 0;
182
183  // The type table allows forward references.  Push as many Opaque types as
184  // needed to get up to ID.
185  while (TypeList.size() <= ID)
186    TypeList.push_back(OpaqueType::get());
187  return TypeList.back().get();
188}
189
190//===----------------------------------------------------------------------===//
191//  Functions for parsing blocks from the bitcode file
192//===----------------------------------------------------------------------===//
193
194bool BitcodeReader::ParseParamAttrBlock() {
195  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
196    return Error("Malformed block record");
197
198  if (!ParamAttrs.empty())
199    return Error("Multiple PARAMATTR blocks found!");
200
201  SmallVector<uint64_t, 64> Record;
202
203  ParamAttrsVector Attrs;
204
205  // Read all the records.
206  while (1) {
207    unsigned Code = Stream.ReadCode();
208    if (Code == bitc::END_BLOCK) {
209      if (Stream.ReadBlockEnd())
210        return Error("Error at end of PARAMATTR block");
211      return false;
212    }
213
214    if (Code == bitc::ENTER_SUBBLOCK) {
215      // No known subblocks, always skip them.
216      Stream.ReadSubBlockID();
217      if (Stream.SkipBlock())
218        return Error("Malformed block record");
219      continue;
220    }
221
222    if (Code == bitc::DEFINE_ABBREV) {
223      Stream.ReadAbbrevRecord();
224      continue;
225    }
226
227    // Read a record.
228    Record.clear();
229    switch (Stream.ReadRecord(Code, Record)) {
230    default:  // Default behavior: ignore.
231      break;
232    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
233      if (Record.size() & 1)
234        return Error("Invalid ENTRY record");
235
236      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
237        if (Record[i+1] != ParamAttr::None)
238          Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
239      }
240      ParamAttrs.push_back(Attrs.empty() ? NULL : ParamAttrsList::get(Attrs));
241      Attrs.clear();
242      break;
243    }
244    }
245  }
246}
247
248
249bool BitcodeReader::ParseTypeTable() {
250  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
251    return Error("Malformed block record");
252
253  if (!TypeList.empty())
254    return Error("Multiple TYPE_BLOCKs found!");
255
256  SmallVector<uint64_t, 64> Record;
257  unsigned NumRecords = 0;
258
259  // Read all the records for this type table.
260  while (1) {
261    unsigned Code = Stream.ReadCode();
262    if (Code == bitc::END_BLOCK) {
263      if (NumRecords != TypeList.size())
264        return Error("Invalid type forward reference in TYPE_BLOCK");
265      if (Stream.ReadBlockEnd())
266        return Error("Error at end of type table block");
267      return false;
268    }
269
270    if (Code == bitc::ENTER_SUBBLOCK) {
271      // No known subblocks, always skip them.
272      Stream.ReadSubBlockID();
273      if (Stream.SkipBlock())
274        return Error("Malformed block record");
275      continue;
276    }
277
278    if (Code == bitc::DEFINE_ABBREV) {
279      Stream.ReadAbbrevRecord();
280      continue;
281    }
282
283    // Read a record.
284    Record.clear();
285    const Type *ResultTy = 0;
286    switch (Stream.ReadRecord(Code, Record)) {
287    default:  // Default behavior: unknown type.
288      ResultTy = 0;
289      break;
290    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
291      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
292      // type list.  This allows us to reserve space.
293      if (Record.size() < 1)
294        return Error("Invalid TYPE_CODE_NUMENTRY record");
295      TypeList.reserve(Record[0]);
296      continue;
297    case bitc::TYPE_CODE_VOID:      // VOID
298      ResultTy = Type::VoidTy;
299      break;
300    case bitc::TYPE_CODE_FLOAT:     // FLOAT
301      ResultTy = Type::FloatTy;
302      break;
303    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
304      ResultTy = Type::DoubleTy;
305      break;
306    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
307      ResultTy = Type::X86_FP80Ty;
308      break;
309    case bitc::TYPE_CODE_FP128:     // FP128
310      ResultTy = Type::FP128Ty;
311      break;
312    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
313      ResultTy = Type::PPC_FP128Ty;
314      break;
315    case bitc::TYPE_CODE_LABEL:     // LABEL
316      ResultTy = Type::LabelTy;
317      break;
318    case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
319      ResultTy = 0;
320      break;
321    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
322      if (Record.size() < 1)
323        return Error("Invalid Integer type record");
324
325      ResultTy = IntegerType::get(Record[0]);
326      break;
327    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
328                                    //          [pointee type, address space]
329      if (Record.size() < 1)
330        return Error("Invalid POINTER type record");
331      unsigned AddressSpace = 0;
332      if (Record.size() == 2)
333        AddressSpace = Record[1];
334      ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
335      break;
336    }
337    case bitc::TYPE_CODE_FUNCTION: {
338      // FIXME: attrid is dead, remove it in LLVM 3.0
339      // FUNCTION: [vararg, attrid, retty, paramty x N]
340      if (Record.size() < 3)
341        return Error("Invalid FUNCTION type record");
342      std::vector<const Type*> ArgTys;
343      for (unsigned i = 3, e = Record.size(); i != e; ++i)
344        ArgTys.push_back(getTypeByID(Record[i], true));
345
346      ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
347                                   Record[0]);
348      break;
349    }
350    case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
351      if (Record.size() < 1)
352        return Error("Invalid STRUCT type record");
353      std::vector<const Type*> EltTys;
354      for (unsigned i = 1, e = Record.size(); i != e; ++i)
355        EltTys.push_back(getTypeByID(Record[i], true));
356      ResultTy = StructType::get(EltTys, Record[0]);
357      break;
358    }
359    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
360      if (Record.size() < 2)
361        return Error("Invalid ARRAY type record");
362      ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
363      break;
364    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
365      if (Record.size() < 2)
366        return Error("Invalid VECTOR type record");
367      ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
368      break;
369    }
370
371    if (NumRecords == TypeList.size()) {
372      // If this is a new type slot, just append it.
373      TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
374      ++NumRecords;
375    } else if (ResultTy == 0) {
376      // Otherwise, this was forward referenced, so an opaque type was created,
377      // but the result type is actually just an opaque.  Leave the one we
378      // created previously.
379      ++NumRecords;
380    } else {
381      // Otherwise, this was forward referenced, so an opaque type was created.
382      // Resolve the opaque type to the real type now.
383      assert(NumRecords < TypeList.size() && "Typelist imbalance");
384      const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
385
386      // Don't directly push the new type on the Tab. Instead we want to replace
387      // the opaque type we previously inserted with the new concrete value. The
388      // refinement from the abstract (opaque) type to the new type causes all
389      // uses of the abstract type to use the concrete type (NewTy). This will
390      // also cause the opaque type to be deleted.
391      const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
392
393      // This should have replaced the old opaque type with the new type in the
394      // value table... or with a preexisting type that was already in the
395      // system.  Let's just make sure it did.
396      assert(TypeList[NumRecords-1].get() != OldTy &&
397             "refineAbstractType didn't work!");
398    }
399  }
400}
401
402
403bool BitcodeReader::ParseTypeSymbolTable() {
404  if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
405    return Error("Malformed block record");
406
407  SmallVector<uint64_t, 64> Record;
408
409  // Read all the records for this type table.
410  std::string TypeName;
411  while (1) {
412    unsigned Code = Stream.ReadCode();
413    if (Code == bitc::END_BLOCK) {
414      if (Stream.ReadBlockEnd())
415        return Error("Error at end of type symbol table block");
416      return false;
417    }
418
419    if (Code == bitc::ENTER_SUBBLOCK) {
420      // No known subblocks, always skip them.
421      Stream.ReadSubBlockID();
422      if (Stream.SkipBlock())
423        return Error("Malformed block record");
424      continue;
425    }
426
427    if (Code == bitc::DEFINE_ABBREV) {
428      Stream.ReadAbbrevRecord();
429      continue;
430    }
431
432    // Read a record.
433    Record.clear();
434    switch (Stream.ReadRecord(Code, Record)) {
435    default:  // Default behavior: unknown type.
436      break;
437    case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
438      if (ConvertToString(Record, 1, TypeName))
439        return Error("Invalid TST_ENTRY record");
440      unsigned TypeID = Record[0];
441      if (TypeID >= TypeList.size())
442        return Error("Invalid Type ID in TST_ENTRY record");
443
444      TheModule->addTypeName(TypeName, TypeList[TypeID].get());
445      TypeName.clear();
446      break;
447    }
448  }
449}
450
451bool BitcodeReader::ParseValueSymbolTable() {
452  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
453    return Error("Malformed block record");
454
455  SmallVector<uint64_t, 64> Record;
456
457  // Read all the records for this value table.
458  SmallString<128> ValueName;
459  while (1) {
460    unsigned Code = Stream.ReadCode();
461    if (Code == bitc::END_BLOCK) {
462      if (Stream.ReadBlockEnd())
463        return Error("Error at end of value symbol table block");
464      return false;
465    }
466    if (Code == bitc::ENTER_SUBBLOCK) {
467      // No known subblocks, always skip them.
468      Stream.ReadSubBlockID();
469      if (Stream.SkipBlock())
470        return Error("Malformed block record");
471      continue;
472    }
473
474    if (Code == bitc::DEFINE_ABBREV) {
475      Stream.ReadAbbrevRecord();
476      continue;
477    }
478
479    // Read a record.
480    Record.clear();
481    switch (Stream.ReadRecord(Code, Record)) {
482    default:  // Default behavior: unknown type.
483      break;
484    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
485      if (ConvertToString(Record, 1, ValueName))
486        return Error("Invalid TST_ENTRY record");
487      unsigned ValueID = Record[0];
488      if (ValueID >= ValueList.size())
489        return Error("Invalid Value ID in VST_ENTRY record");
490      Value *V = ValueList[ValueID];
491
492      V->setName(&ValueName[0], ValueName.size());
493      ValueName.clear();
494      break;
495    }
496    case bitc::VST_CODE_BBENTRY: {
497      if (ConvertToString(Record, 1, ValueName))
498        return Error("Invalid VST_BBENTRY record");
499      BasicBlock *BB = getBasicBlock(Record[0]);
500      if (BB == 0)
501        return Error("Invalid BB ID in VST_BBENTRY record");
502
503      BB->setName(&ValueName[0], ValueName.size());
504      ValueName.clear();
505      break;
506    }
507    }
508  }
509}
510
511/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
512/// the LSB for dense VBR encoding.
513static uint64_t DecodeSignRotatedValue(uint64_t V) {
514  if ((V & 1) == 0)
515    return V >> 1;
516  if (V != 1)
517    return -(V >> 1);
518  // There is no such thing as -0 with integers.  "-0" really means MININT.
519  return 1ULL << 63;
520}
521
522/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
523/// values and aliases that we can.
524bool BitcodeReader::ResolveGlobalAndAliasInits() {
525  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
526  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
527
528  GlobalInitWorklist.swap(GlobalInits);
529  AliasInitWorklist.swap(AliasInits);
530
531  while (!GlobalInitWorklist.empty()) {
532    unsigned ValID = GlobalInitWorklist.back().second;
533    if (ValID >= ValueList.size()) {
534      // Not ready to resolve this yet, it requires something later in the file.
535      GlobalInits.push_back(GlobalInitWorklist.back());
536    } else {
537      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
538        GlobalInitWorklist.back().first->setInitializer(C);
539      else
540        return Error("Global variable initializer is not a constant!");
541    }
542    GlobalInitWorklist.pop_back();
543  }
544
545  while (!AliasInitWorklist.empty()) {
546    unsigned ValID = AliasInitWorklist.back().second;
547    if (ValID >= ValueList.size()) {
548      AliasInits.push_back(AliasInitWorklist.back());
549    } else {
550      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
551        AliasInitWorklist.back().first->setAliasee(C);
552      else
553        return Error("Alias initializer is not a constant!");
554    }
555    AliasInitWorklist.pop_back();
556  }
557  return false;
558}
559
560
561bool BitcodeReader::ParseConstants() {
562  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
563    return Error("Malformed block record");
564
565  SmallVector<uint64_t, 64> Record;
566
567  // Read all the records for this value table.
568  const Type *CurTy = Type::Int32Ty;
569  unsigned NextCstNo = ValueList.size();
570  while (1) {
571    unsigned Code = Stream.ReadCode();
572    if (Code == bitc::END_BLOCK) {
573      if (NextCstNo != ValueList.size())
574        return Error("Invalid constant reference!");
575
576      if (Stream.ReadBlockEnd())
577        return Error("Error at end of constants block");
578      return false;
579    }
580
581    if (Code == bitc::ENTER_SUBBLOCK) {
582      // No known subblocks, always skip them.
583      Stream.ReadSubBlockID();
584      if (Stream.SkipBlock())
585        return Error("Malformed block record");
586      continue;
587    }
588
589    if (Code == bitc::DEFINE_ABBREV) {
590      Stream.ReadAbbrevRecord();
591      continue;
592    }
593
594    // Read a record.
595    Record.clear();
596    Value *V = 0;
597    switch (Stream.ReadRecord(Code, Record)) {
598    default:  // Default behavior: unknown constant
599    case bitc::CST_CODE_UNDEF:     // UNDEF
600      V = UndefValue::get(CurTy);
601      break;
602    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
603      if (Record.empty())
604        return Error("Malformed CST_SETTYPE record");
605      if (Record[0] >= TypeList.size())
606        return Error("Invalid Type ID in CST_SETTYPE record");
607      CurTy = TypeList[Record[0]];
608      continue;  // Skip the ValueList manipulation.
609    case bitc::CST_CODE_NULL:      // NULL
610      V = Constant::getNullValue(CurTy);
611      break;
612    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
613      if (!isa<IntegerType>(CurTy) || Record.empty())
614        return Error("Invalid CST_INTEGER record");
615      V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
616      break;
617    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
618      if (!isa<IntegerType>(CurTy) || Record.empty())
619        return Error("Invalid WIDE_INTEGER record");
620
621      unsigned NumWords = Record.size();
622      SmallVector<uint64_t, 8> Words;
623      Words.resize(NumWords);
624      for (unsigned i = 0; i != NumWords; ++i)
625        Words[i] = DecodeSignRotatedValue(Record[i]);
626      V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
627                                 NumWords, &Words[0]));
628      break;
629    }
630    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
631      if (Record.empty())
632        return Error("Invalid FLOAT record");
633      if (CurTy == Type::FloatTy)
634        V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
635      else if (CurTy == Type::DoubleTy)
636        V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
637      else if (CurTy == Type::X86_FP80Ty)
638        V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
639      else if (CurTy == Type::FP128Ty)
640        V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true));
641      else if (CurTy == Type::PPC_FP128Ty)
642        V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
643      else
644        V = UndefValue::get(CurTy);
645      break;
646    }
647
648    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
649      if (Record.empty())
650        return Error("Invalid CST_AGGREGATE record");
651
652      unsigned Size = Record.size();
653      std::vector<Constant*> Elts;
654
655      if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
656        for (unsigned i = 0; i != Size; ++i)
657          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
658                                                     STy->getElementType(i)));
659        V = ConstantStruct::get(STy, Elts);
660      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
661        const Type *EltTy = ATy->getElementType();
662        for (unsigned i = 0; i != Size; ++i)
663          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
664        V = ConstantArray::get(ATy, Elts);
665      } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
666        const Type *EltTy = VTy->getElementType();
667        for (unsigned i = 0; i != Size; ++i)
668          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
669        V = ConstantVector::get(Elts);
670      } else {
671        V = UndefValue::get(CurTy);
672      }
673      break;
674    }
675    case bitc::CST_CODE_STRING: { // STRING: [values]
676      if (Record.empty())
677        return Error("Invalid CST_AGGREGATE record");
678
679      const ArrayType *ATy = cast<ArrayType>(CurTy);
680      const Type *EltTy = ATy->getElementType();
681
682      unsigned Size = Record.size();
683      std::vector<Constant*> Elts;
684      for (unsigned i = 0; i != Size; ++i)
685        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
686      V = ConstantArray::get(ATy, Elts);
687      break;
688    }
689    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
690      if (Record.empty())
691        return Error("Invalid CST_AGGREGATE record");
692
693      const ArrayType *ATy = cast<ArrayType>(CurTy);
694      const Type *EltTy = ATy->getElementType();
695
696      unsigned Size = Record.size();
697      std::vector<Constant*> Elts;
698      for (unsigned i = 0; i != Size; ++i)
699        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
700      Elts.push_back(Constant::getNullValue(EltTy));
701      V = ConstantArray::get(ATy, Elts);
702      break;
703    }
704    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
705      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
706      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
707      if (Opc < 0) {
708        V = UndefValue::get(CurTy);  // Unknown binop.
709      } else {
710        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
711        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
712        V = ConstantExpr::get(Opc, LHS, RHS);
713      }
714      break;
715    }
716    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
717      if (Record.size() < 3) return Error("Invalid CE_CAST record");
718      int Opc = GetDecodedCastOpcode(Record[0]);
719      if (Opc < 0) {
720        V = UndefValue::get(CurTy);  // Unknown cast.
721      } else {
722        const Type *OpTy = getTypeByID(Record[1]);
723        if (!OpTy) return Error("Invalid CE_CAST record");
724        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
725        V = ConstantExpr::getCast(Opc, Op, CurTy);
726      }
727      break;
728    }
729    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
730      if (Record.size() & 1) return Error("Invalid CE_GEP record");
731      SmallVector<Constant*, 16> Elts;
732      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
733        const Type *ElTy = getTypeByID(Record[i]);
734        if (!ElTy) return Error("Invalid CE_GEP record");
735        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
736      }
737      V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
738      break;
739    }
740    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
741      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
742      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
743                                                              Type::Int1Ty),
744                                  ValueList.getConstantFwdRef(Record[1],CurTy),
745                                  ValueList.getConstantFwdRef(Record[2],CurTy));
746      break;
747    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
748      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
749      const VectorType *OpTy =
750        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
751      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
752      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
753      Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
754                                                  OpTy->getElementType());
755      V = ConstantExpr::getExtractElement(Op0, Op1);
756      break;
757    }
758    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
759      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
760      if (Record.size() < 3 || OpTy == 0)
761        return Error("Invalid CE_INSERTELT record");
762      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
763      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
764                                                  OpTy->getElementType());
765      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
766      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
767      break;
768    }
769    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
770      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
771      if (Record.size() < 3 || OpTy == 0)
772        return Error("Invalid CE_INSERTELT record");
773      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
774      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
775      const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
776      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
777      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
778      break;
779    }
780    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
781      if (Record.size() < 4) return Error("Invalid CE_CMP record");
782      const Type *OpTy = getTypeByID(Record[0]);
783      if (OpTy == 0) return Error("Invalid CE_CMP record");
784      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
785      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
786
787      if (OpTy->isFloatingPoint())
788        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
789      else
790        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
791      break;
792    }
793    case bitc::CST_CODE_INLINEASM: {
794      if (Record.size() < 2) return Error("Invalid INLINEASM record");
795      std::string AsmStr, ConstrStr;
796      bool HasSideEffects = Record[0];
797      unsigned AsmStrSize = Record[1];
798      if (2+AsmStrSize >= Record.size())
799        return Error("Invalid INLINEASM record");
800      unsigned ConstStrSize = Record[2+AsmStrSize];
801      if (3+AsmStrSize+ConstStrSize > Record.size())
802        return Error("Invalid INLINEASM record");
803
804      for (unsigned i = 0; i != AsmStrSize; ++i)
805        AsmStr += (char)Record[2+i];
806      for (unsigned i = 0; i != ConstStrSize; ++i)
807        ConstrStr += (char)Record[3+AsmStrSize+i];
808      const PointerType *PTy = cast<PointerType>(CurTy);
809      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
810                         AsmStr, ConstrStr, HasSideEffects);
811      break;
812    }
813    }
814
815    ValueList.AssignValue(V, NextCstNo);
816    ++NextCstNo;
817  }
818}
819
820/// RememberAndSkipFunctionBody - When we see the block for a function body,
821/// remember where it is and then skip it.  This lets us lazily deserialize the
822/// functions.
823bool BitcodeReader::RememberAndSkipFunctionBody() {
824  // Get the function we are talking about.
825  if (FunctionsWithBodies.empty())
826    return Error("Insufficient function protos");
827
828  Function *Fn = FunctionsWithBodies.back();
829  FunctionsWithBodies.pop_back();
830
831  // Save the current stream state.
832  uint64_t CurBit = Stream.GetCurrentBitNo();
833  DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
834
835  // Set the functions linkage to GhostLinkage so we know it is lazily
836  // deserialized.
837  Fn->setLinkage(GlobalValue::GhostLinkage);
838
839  // Skip over the function block for now.
840  if (Stream.SkipBlock())
841    return Error("Malformed block record");
842  return false;
843}
844
845bool BitcodeReader::ParseModule(const std::string &ModuleID) {
846  // Reject multiple MODULE_BLOCK's in a single bitstream.
847  if (TheModule)
848    return Error("Multiple MODULE_BLOCKs in same stream");
849
850  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
851    return Error("Malformed block record");
852
853  // Otherwise, create the module.
854  TheModule = new Module(ModuleID);
855
856  SmallVector<uint64_t, 64> Record;
857  std::vector<std::string> SectionTable;
858  std::vector<std::string> CollectorTable;
859
860  // Read all the records for this module.
861  while (!Stream.AtEndOfStream()) {
862    unsigned Code = Stream.ReadCode();
863    if (Code == bitc::END_BLOCK) {
864      if (Stream.ReadBlockEnd())
865        return Error("Error at end of module block");
866
867      // Patch the initializers for globals and aliases up.
868      ResolveGlobalAndAliasInits();
869      if (!GlobalInits.empty() || !AliasInits.empty())
870        return Error("Malformed global initializer set");
871      if (!FunctionsWithBodies.empty())
872        return Error("Too few function bodies found");
873
874      // Look for intrinsic functions which need to be upgraded at some point
875      for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
876           FI != FE; ++FI) {
877        Function* NewFn;
878        if (UpgradeIntrinsicFunction(FI, NewFn))
879          UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
880      }
881
882      // Force deallocation of memory for these vectors to favor the client that
883      // want lazy deserialization.
884      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
885      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
886      std::vector<Function*>().swap(FunctionsWithBodies);
887      return false;
888    }
889
890    if (Code == bitc::ENTER_SUBBLOCK) {
891      switch (Stream.ReadSubBlockID()) {
892      default:  // Skip unknown content.
893        if (Stream.SkipBlock())
894          return Error("Malformed block record");
895        break;
896      case bitc::BLOCKINFO_BLOCK_ID:
897        if (Stream.ReadBlockInfoBlock())
898          return Error("Malformed BlockInfoBlock");
899        break;
900      case bitc::PARAMATTR_BLOCK_ID:
901        if (ParseParamAttrBlock())
902          return true;
903        break;
904      case bitc::TYPE_BLOCK_ID:
905        if (ParseTypeTable())
906          return true;
907        break;
908      case bitc::TYPE_SYMTAB_BLOCK_ID:
909        if (ParseTypeSymbolTable())
910          return true;
911        break;
912      case bitc::VALUE_SYMTAB_BLOCK_ID:
913        if (ParseValueSymbolTable())
914          return true;
915        break;
916      case bitc::CONSTANTS_BLOCK_ID:
917        if (ParseConstants() || ResolveGlobalAndAliasInits())
918          return true;
919        break;
920      case bitc::FUNCTION_BLOCK_ID:
921        // If this is the first function body we've seen, reverse the
922        // FunctionsWithBodies list.
923        if (!HasReversedFunctionsWithBodies) {
924          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
925          HasReversedFunctionsWithBodies = true;
926        }
927
928        if (RememberAndSkipFunctionBody())
929          return true;
930        break;
931      }
932      continue;
933    }
934
935    if (Code == bitc::DEFINE_ABBREV) {
936      Stream.ReadAbbrevRecord();
937      continue;
938    }
939
940    // Read a record.
941    switch (Stream.ReadRecord(Code, Record)) {
942    default: break;  // Default behavior, ignore unknown content.
943    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
944      if (Record.size() < 1)
945        return Error("Malformed MODULE_CODE_VERSION");
946      // Only version #0 is supported so far.
947      if (Record[0] != 0)
948        return Error("Unknown bitstream version!");
949      break;
950    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
951      std::string S;
952      if (ConvertToString(Record, 0, S))
953        return Error("Invalid MODULE_CODE_TRIPLE record");
954      TheModule->setTargetTriple(S);
955      break;
956    }
957    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
958      std::string S;
959      if (ConvertToString(Record, 0, S))
960        return Error("Invalid MODULE_CODE_DATALAYOUT record");
961      TheModule->setDataLayout(S);
962      break;
963    }
964    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
965      std::string S;
966      if (ConvertToString(Record, 0, S))
967        return Error("Invalid MODULE_CODE_ASM record");
968      TheModule->setModuleInlineAsm(S);
969      break;
970    }
971    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
972      std::string S;
973      if (ConvertToString(Record, 0, S))
974        return Error("Invalid MODULE_CODE_DEPLIB record");
975      TheModule->addLibrary(S);
976      break;
977    }
978    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
979      std::string S;
980      if (ConvertToString(Record, 0, S))
981        return Error("Invalid MODULE_CODE_SECTIONNAME record");
982      SectionTable.push_back(S);
983      break;
984    }
985    case bitc::MODULE_CODE_COLLECTORNAME: {  // SECTIONNAME: [strchr x N]
986      std::string S;
987      if (ConvertToString(Record, 0, S))
988        return Error("Invalid MODULE_CODE_COLLECTORNAME record");
989      CollectorTable.push_back(S);
990      break;
991    }
992    // GLOBALVAR: [pointer type, isconst, initid,
993    //             linkage, alignment, section, visibility, threadlocal]
994    case bitc::MODULE_CODE_GLOBALVAR: {
995      if (Record.size() < 6)
996        return Error("Invalid MODULE_CODE_GLOBALVAR record");
997      const Type *Ty = getTypeByID(Record[0]);
998      if (!isa<PointerType>(Ty))
999        return Error("Global not a pointer type!");
1000      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1001      Ty = cast<PointerType>(Ty)->getElementType();
1002
1003      bool isConstant = Record[1];
1004      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1005      unsigned Alignment = (1 << Record[4]) >> 1;
1006      std::string Section;
1007      if (Record[5]) {
1008        if (Record[5]-1 >= SectionTable.size())
1009          return Error("Invalid section ID");
1010        Section = SectionTable[Record[5]-1];
1011      }
1012      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1013      if (Record.size() > 6)
1014        Visibility = GetDecodedVisibility(Record[6]);
1015      bool isThreadLocal = false;
1016      if (Record.size() > 7)
1017        isThreadLocal = Record[7];
1018
1019      GlobalVariable *NewGV =
1020        new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1021                           isThreadLocal, AddressSpace);
1022      NewGV->setAlignment(Alignment);
1023      if (!Section.empty())
1024        NewGV->setSection(Section);
1025      NewGV->setVisibility(Visibility);
1026      NewGV->setThreadLocal(isThreadLocal);
1027
1028      ValueList.push_back(NewGV);
1029
1030      // Remember which value to use for the global initializer.
1031      if (unsigned InitID = Record[2])
1032        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1033      break;
1034    }
1035    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1036    //             alignment, section, visibility, collector]
1037    case bitc::MODULE_CODE_FUNCTION: {
1038      if (Record.size() < 8)
1039        return Error("Invalid MODULE_CODE_FUNCTION record");
1040      const Type *Ty = getTypeByID(Record[0]);
1041      if (!isa<PointerType>(Ty))
1042        return Error("Function not a pointer type!");
1043      const FunctionType *FTy =
1044        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1045      if (!FTy)
1046        return Error("Function not a pointer to function type!");
1047
1048      Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1049                                    "", TheModule);
1050
1051      Func->setCallingConv(Record[1]);
1052      bool isProto = Record[2];
1053      Func->setLinkage(GetDecodedLinkage(Record[3]));
1054      const ParamAttrsList *PAL = getParamAttrs(Record[4]);
1055      Func->setParamAttrs(PAL);
1056
1057      Func->setAlignment((1 << Record[5]) >> 1);
1058      if (Record[6]) {
1059        if (Record[6]-1 >= SectionTable.size())
1060          return Error("Invalid section ID");
1061        Func->setSection(SectionTable[Record[6]-1]);
1062      }
1063      Func->setVisibility(GetDecodedVisibility(Record[7]));
1064      if (Record.size() > 8 && Record[8]) {
1065        if (Record[8]-1 > CollectorTable.size())
1066          return Error("Invalid collector ID");
1067        Func->setCollector(CollectorTable[Record[8]-1].c_str());
1068      }
1069
1070      ValueList.push_back(Func);
1071
1072      // If this is a function with a body, remember the prototype we are
1073      // creating now, so that we can match up the body with them later.
1074      if (!isProto)
1075        FunctionsWithBodies.push_back(Func);
1076      break;
1077    }
1078    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1079    case bitc::MODULE_CODE_ALIAS: {
1080      if (Record.size() < 3)
1081        return Error("Invalid MODULE_ALIAS record");
1082      const Type *Ty = getTypeByID(Record[0]);
1083      if (!isa<PointerType>(Ty))
1084        return Error("Function not a pointer type!");
1085
1086      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1087                                           "", 0, TheModule);
1088      NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1089      ValueList.push_back(NewGA);
1090      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1091      break;
1092    }
1093    /// MODULE_CODE_PURGEVALS: [numvals]
1094    case bitc::MODULE_CODE_PURGEVALS:
1095      // Trim down the value list to the specified size.
1096      if (Record.size() < 1 || Record[0] > ValueList.size())
1097        return Error("Invalid MODULE_PURGEVALS record");
1098      ValueList.shrinkTo(Record[0]);
1099      break;
1100    }
1101    Record.clear();
1102  }
1103
1104  return Error("Premature end of bitstream");
1105}
1106
1107
1108bool BitcodeReader::ParseBitcode() {
1109  TheModule = 0;
1110
1111  if (Buffer->getBufferSize() & 3)
1112    return Error("Bitcode stream should be a multiple of 4 bytes in length");
1113
1114  unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1115  Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1116
1117  // Sniff for the signature.
1118  if (Stream.Read(8) != 'B' ||
1119      Stream.Read(8) != 'C' ||
1120      Stream.Read(4) != 0x0 ||
1121      Stream.Read(4) != 0xC ||
1122      Stream.Read(4) != 0xE ||
1123      Stream.Read(4) != 0xD)
1124    return Error("Invalid bitcode signature");
1125
1126  // We expect a number of well-defined blocks, though we don't necessarily
1127  // need to understand them all.
1128  while (!Stream.AtEndOfStream()) {
1129    unsigned Code = Stream.ReadCode();
1130
1131    if (Code != bitc::ENTER_SUBBLOCK)
1132      return Error("Invalid record at top-level");
1133
1134    unsigned BlockID = Stream.ReadSubBlockID();
1135
1136    // We only know the MODULE subblock ID.
1137    switch (BlockID) {
1138    case bitc::BLOCKINFO_BLOCK_ID:
1139      if (Stream.ReadBlockInfoBlock())
1140        return Error("Malformed BlockInfoBlock");
1141      break;
1142    case bitc::MODULE_BLOCK_ID:
1143      if (ParseModule(Buffer->getBufferIdentifier()))
1144        return true;
1145      break;
1146    default:
1147      if (Stream.SkipBlock())
1148        return Error("Malformed block record");
1149      break;
1150    }
1151  }
1152
1153  return false;
1154}
1155
1156
1157/// ParseFunctionBody - Lazily parse the specified function body block.
1158bool BitcodeReader::ParseFunctionBody(Function *F) {
1159  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1160    return Error("Malformed block record");
1161
1162  unsigned ModuleValueListSize = ValueList.size();
1163
1164  // Add all the function arguments to the value table.
1165  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1166    ValueList.push_back(I);
1167
1168  unsigned NextValueNo = ValueList.size();
1169  BasicBlock *CurBB = 0;
1170  unsigned CurBBNo = 0;
1171
1172  // Read all the records.
1173  SmallVector<uint64_t, 64> Record;
1174  while (1) {
1175    unsigned Code = Stream.ReadCode();
1176    if (Code == bitc::END_BLOCK) {
1177      if (Stream.ReadBlockEnd())
1178        return Error("Error at end of function block");
1179      break;
1180    }
1181
1182    if (Code == bitc::ENTER_SUBBLOCK) {
1183      switch (Stream.ReadSubBlockID()) {
1184      default:  // Skip unknown content.
1185        if (Stream.SkipBlock())
1186          return Error("Malformed block record");
1187        break;
1188      case bitc::CONSTANTS_BLOCK_ID:
1189        if (ParseConstants()) return true;
1190        NextValueNo = ValueList.size();
1191        break;
1192      case bitc::VALUE_SYMTAB_BLOCK_ID:
1193        if (ParseValueSymbolTable()) return true;
1194        break;
1195      }
1196      continue;
1197    }
1198
1199    if (Code == bitc::DEFINE_ABBREV) {
1200      Stream.ReadAbbrevRecord();
1201      continue;
1202    }
1203
1204    // Read a record.
1205    Record.clear();
1206    Instruction *I = 0;
1207    switch (Stream.ReadRecord(Code, Record)) {
1208    default: // Default behavior: reject
1209      return Error("Unknown instruction");
1210    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1211      if (Record.size() < 1 || Record[0] == 0)
1212        return Error("Invalid DECLAREBLOCKS record");
1213      // Create all the basic blocks for the function.
1214      FunctionBBs.resize(Record[0]);
1215      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1216        FunctionBBs[i] = new BasicBlock("", F);
1217      CurBB = FunctionBBs[0];
1218      continue;
1219
1220    case bitc::FUNC_CODE_INST_BB_UNWINDDEST:   // BB_UNWINDDEST: [bb#]
1221      if (CurBB->getUnwindDest())
1222        return Error("Only permit one BB_UNWINDDEST per BB");
1223      if (Record.size() != 1)
1224        return Error("Invalid BB_UNWINDDEST record");
1225
1226      CurBB->setUnwindDest(getBasicBlock(Record[0]));
1227      continue;
1228
1229    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1230      unsigned OpNum = 0;
1231      Value *LHS, *RHS;
1232      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1233          getValue(Record, OpNum, LHS->getType(), RHS) ||
1234          OpNum+1 != Record.size())
1235        return Error("Invalid BINOP record");
1236
1237      int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1238      if (Opc == -1) return Error("Invalid BINOP record");
1239      I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1240      break;
1241    }
1242    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1243      unsigned OpNum = 0;
1244      Value *Op;
1245      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1246          OpNum+2 != Record.size())
1247        return Error("Invalid CAST record");
1248
1249      const Type *ResTy = getTypeByID(Record[OpNum]);
1250      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1251      if (Opc == -1 || ResTy == 0)
1252        return Error("Invalid CAST record");
1253      I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1254      break;
1255    }
1256    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1257      unsigned OpNum = 0;
1258      Value *BasePtr;
1259      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1260        return Error("Invalid GEP record");
1261
1262      SmallVector<Value*, 16> GEPIdx;
1263      while (OpNum != Record.size()) {
1264        Value *Op;
1265        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1266          return Error("Invalid GEP record");
1267        GEPIdx.push_back(Op);
1268      }
1269
1270      I = new GetElementPtrInst(BasePtr, GEPIdx.begin(), GEPIdx.end());
1271      break;
1272    }
1273
1274    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1275      unsigned OpNum = 0;
1276      Value *TrueVal, *FalseVal, *Cond;
1277      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1278          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1279          getValue(Record, OpNum, Type::Int1Ty, Cond))
1280        return Error("Invalid SELECT record");
1281
1282      I = new SelectInst(Cond, TrueVal, FalseVal);
1283      break;
1284    }
1285
1286    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1287      unsigned OpNum = 0;
1288      Value *Vec, *Idx;
1289      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1290          getValue(Record, OpNum, Type::Int32Ty, Idx))
1291        return Error("Invalid EXTRACTELT record");
1292      I = new ExtractElementInst(Vec, Idx);
1293      break;
1294    }
1295
1296    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1297      unsigned OpNum = 0;
1298      Value *Vec, *Elt, *Idx;
1299      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1300          getValue(Record, OpNum,
1301                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1302          getValue(Record, OpNum, Type::Int32Ty, Idx))
1303        return Error("Invalid INSERTELT record");
1304      I = new InsertElementInst(Vec, Elt, Idx);
1305      break;
1306    }
1307
1308    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1309      unsigned OpNum = 0;
1310      Value *Vec1, *Vec2, *Mask;
1311      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1312          getValue(Record, OpNum, Vec1->getType(), Vec2))
1313        return Error("Invalid SHUFFLEVEC record");
1314
1315      const Type *MaskTy =
1316        VectorType::get(Type::Int32Ty,
1317                        cast<VectorType>(Vec1->getType())->getNumElements());
1318
1319      if (getValue(Record, OpNum, MaskTy, Mask))
1320        return Error("Invalid SHUFFLEVEC record");
1321      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1322      break;
1323    }
1324
1325    case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1326      unsigned OpNum = 0;
1327      Value *LHS, *RHS;
1328      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1329          getValue(Record, OpNum, LHS->getType(), RHS) ||
1330          OpNum+1 != Record.size())
1331        return Error("Invalid CMP record");
1332
1333      if (LHS->getType()->isFPOrFPVector())
1334        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1335      else
1336        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1337      break;
1338    }
1339    case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1340      if (Record.size() != 2)
1341        return Error("Invalid GETRESULT record");
1342      unsigned OpNum = 0;
1343      Value *Op;
1344      getValueTypePair(Record, OpNum, NextValueNo, Op);
1345      unsigned Index = Record[1];
1346      I = new GetResultInst(Op, Index);
1347      break;
1348    }
1349
1350    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1351      {
1352        unsigned Size = Record.size();
1353        if (Size == 0) {
1354          I = new ReturnInst();
1355          break;
1356        } else {
1357          unsigned OpNum = 0;
1358          SmallVector<Value *,4> Vs;
1359          do {
1360            Value *Op = NULL;
1361            if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1362              return Error("Invalid RET record");
1363            Vs.push_back(Op);
1364          } while(OpNum != Record.size());
1365
1366          // SmallVector Vs has at least one element.
1367          I = new ReturnInst(&Vs[0], Vs.size());
1368          break;
1369        }
1370      }
1371    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1372      if (Record.size() != 1 && Record.size() != 3)
1373        return Error("Invalid BR record");
1374      BasicBlock *TrueDest = getBasicBlock(Record[0]);
1375      if (TrueDest == 0)
1376        return Error("Invalid BR record");
1377
1378      if (Record.size() == 1)
1379        I = new BranchInst(TrueDest);
1380      else {
1381        BasicBlock *FalseDest = getBasicBlock(Record[1]);
1382        Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1383        if (FalseDest == 0 || Cond == 0)
1384          return Error("Invalid BR record");
1385        I = new BranchInst(TrueDest, FalseDest, Cond);
1386      }
1387      break;
1388    }
1389    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1390      if (Record.size() < 3 || (Record.size() & 1) == 0)
1391        return Error("Invalid SWITCH record");
1392      const Type *OpTy = getTypeByID(Record[0]);
1393      Value *Cond = getFnValueByID(Record[1], OpTy);
1394      BasicBlock *Default = getBasicBlock(Record[2]);
1395      if (OpTy == 0 || Cond == 0 || Default == 0)
1396        return Error("Invalid SWITCH record");
1397      unsigned NumCases = (Record.size()-3)/2;
1398      SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1399      for (unsigned i = 0, e = NumCases; i != e; ++i) {
1400        ConstantInt *CaseVal =
1401          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1402        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1403        if (CaseVal == 0 || DestBB == 0) {
1404          delete SI;
1405          return Error("Invalid SWITCH record!");
1406        }
1407        SI->addCase(CaseVal, DestBB);
1408      }
1409      I = SI;
1410      break;
1411    }
1412
1413    case bitc::FUNC_CODE_INST_INVOKE: {
1414      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1415      if (Record.size() < 4) return Error("Invalid INVOKE record");
1416      const ParamAttrsList *PAL = getParamAttrs(Record[0]);
1417      unsigned CCInfo = Record[1];
1418      BasicBlock *NormalBB = getBasicBlock(Record[2]);
1419      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1420
1421      unsigned OpNum = 4;
1422      Value *Callee;
1423      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1424        return Error("Invalid INVOKE record");
1425
1426      const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1427      const FunctionType *FTy = !CalleeTy ? 0 :
1428        dyn_cast<FunctionType>(CalleeTy->getElementType());
1429
1430      // Check that the right number of fixed parameters are here.
1431      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1432          Record.size() < OpNum+FTy->getNumParams())
1433        return Error("Invalid INVOKE record");
1434
1435      SmallVector<Value*, 16> Ops;
1436      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1437        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1438        if (Ops.back() == 0) return Error("Invalid INVOKE record");
1439      }
1440
1441      if (!FTy->isVarArg()) {
1442        if (Record.size() != OpNum)
1443          return Error("Invalid INVOKE record");
1444      } else {
1445        // Read type/value pairs for varargs params.
1446        while (OpNum != Record.size()) {
1447          Value *Op;
1448          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1449            return Error("Invalid INVOKE record");
1450          Ops.push_back(Op);
1451        }
1452      }
1453
1454      I = new InvokeInst(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
1455      cast<InvokeInst>(I)->setCallingConv(CCInfo);
1456      cast<InvokeInst>(I)->setParamAttrs(PAL);
1457      break;
1458    }
1459    case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1460      I = new UnwindInst();
1461      break;
1462    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1463      I = new UnreachableInst();
1464      break;
1465    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1466      if (Record.size() < 1 || ((Record.size()-1)&1))
1467        return Error("Invalid PHI record");
1468      const Type *Ty = getTypeByID(Record[0]);
1469      if (!Ty) return Error("Invalid PHI record");
1470
1471      PHINode *PN = new PHINode(Ty);
1472      PN->reserveOperandSpace(Record.size()-1);
1473
1474      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1475        Value *V = getFnValueByID(Record[1+i], Ty);
1476        BasicBlock *BB = getBasicBlock(Record[2+i]);
1477        if (!V || !BB) return Error("Invalid PHI record");
1478        PN->addIncoming(V, BB);
1479      }
1480      I = PN;
1481      break;
1482    }
1483
1484    case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1485      if (Record.size() < 3)
1486        return Error("Invalid MALLOC record");
1487      const PointerType *Ty =
1488        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1489      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1490      unsigned Align = Record[2];
1491      if (!Ty || !Size) return Error("Invalid MALLOC record");
1492      I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1493      break;
1494    }
1495    case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1496      unsigned OpNum = 0;
1497      Value *Op;
1498      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1499          OpNum != Record.size())
1500        return Error("Invalid FREE record");
1501      I = new FreeInst(Op);
1502      break;
1503    }
1504    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1505      if (Record.size() < 3)
1506        return Error("Invalid ALLOCA record");
1507      const PointerType *Ty =
1508        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1509      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1510      unsigned Align = Record[2];
1511      if (!Ty || !Size) return Error("Invalid ALLOCA record");
1512      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1513      break;
1514    }
1515    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1516      unsigned OpNum = 0;
1517      Value *Op;
1518      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1519          OpNum+2 != Record.size())
1520        return Error("Invalid LOAD record");
1521
1522      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1523      break;
1524    }
1525    case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1526      unsigned OpNum = 0;
1527      Value *Val, *Ptr;
1528      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1529          getValue(Record, OpNum,
1530                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1531          OpNum+2 != Record.size())
1532        return Error("Invalid STORE record");
1533
1534      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1535      break;
1536    }
1537    case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1538      // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1539      unsigned OpNum = 0;
1540      Value *Val, *Ptr;
1541      if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1542          getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
1543          OpNum+2 != Record.size())
1544        return Error("Invalid STORE record");
1545
1546      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1547      break;
1548    }
1549    case bitc::FUNC_CODE_INST_CALL: {
1550      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1551      if (Record.size() < 3)
1552        return Error("Invalid CALL record");
1553
1554      const ParamAttrsList *PAL = getParamAttrs(Record[0]);
1555      unsigned CCInfo = Record[1];
1556
1557      unsigned OpNum = 2;
1558      Value *Callee;
1559      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1560        return Error("Invalid CALL record");
1561
1562      const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1563      const FunctionType *FTy = 0;
1564      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1565      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1566        return Error("Invalid CALL record");
1567
1568      SmallVector<Value*, 16> Args;
1569      // Read the fixed params.
1570      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1571        if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1572          Args.push_back(getBasicBlock(Record[OpNum]));
1573        else
1574          Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1575        if (Args.back() == 0) return Error("Invalid CALL record");
1576      }
1577
1578      // Read type/value pairs for varargs params.
1579      if (!FTy->isVarArg()) {
1580        if (OpNum != Record.size())
1581          return Error("Invalid CALL record");
1582      } else {
1583        while (OpNum != Record.size()) {
1584          Value *Op;
1585          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1586            return Error("Invalid CALL record");
1587          Args.push_back(Op);
1588        }
1589      }
1590
1591      I = new CallInst(Callee, Args.begin(), Args.end());
1592      cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1593      cast<CallInst>(I)->setTailCall(CCInfo & 1);
1594      cast<CallInst>(I)->setParamAttrs(PAL);
1595      break;
1596    }
1597    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1598      if (Record.size() < 3)
1599        return Error("Invalid VAARG record");
1600      const Type *OpTy = getTypeByID(Record[0]);
1601      Value *Op = getFnValueByID(Record[1], OpTy);
1602      const Type *ResTy = getTypeByID(Record[2]);
1603      if (!OpTy || !Op || !ResTy)
1604        return Error("Invalid VAARG record");
1605      I = new VAArgInst(Op, ResTy);
1606      break;
1607    }
1608    }
1609
1610    // Add instruction to end of current BB.  If there is no current BB, reject
1611    // this file.
1612    if (CurBB == 0) {
1613      delete I;
1614      return Error("Invalid instruction with no BB");
1615    }
1616    CurBB->getInstList().push_back(I);
1617
1618    // If this was a terminator instruction, move to the next block.
1619    if (isa<TerminatorInst>(I)) {
1620      ++CurBBNo;
1621      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1622    }
1623
1624    // Non-void values get registered in the value table for future use.
1625    if (I && I->getType() != Type::VoidTy)
1626      ValueList.AssignValue(I, NextValueNo++);
1627  }
1628
1629  // Check the function list for unresolved values.
1630  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1631    if (A->getParent() == 0) {
1632      // We found at least one unresolved value.  Nuke them all to avoid leaks.
1633      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1634        if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1635          A->replaceAllUsesWith(UndefValue::get(A->getType()));
1636          delete A;
1637        }
1638      }
1639      return Error("Never resolved value found in function!");
1640    }
1641  }
1642
1643  // Trim the value list down to the size it was before we parsed this function.
1644  ValueList.shrinkTo(ModuleValueListSize);
1645  std::vector<BasicBlock*>().swap(FunctionBBs);
1646
1647  return false;
1648}
1649
1650//===----------------------------------------------------------------------===//
1651// ModuleProvider implementation
1652//===----------------------------------------------------------------------===//
1653
1654
1655bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1656  // If it already is material, ignore the request.
1657  if (!F->hasNotBeenReadFromBitcode()) return false;
1658
1659  DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1660    DeferredFunctionInfo.find(F);
1661  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1662
1663  // Move the bit stream to the saved position of the deferred function body and
1664  // restore the real linkage type for the function.
1665  Stream.JumpToBit(DFII->second.first);
1666  F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1667
1668  if (ParseFunctionBody(F)) {
1669    if (ErrInfo) *ErrInfo = ErrorString;
1670    return true;
1671  }
1672
1673  // Upgrade any old intrinsic calls in the function.
1674  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1675       E = UpgradedIntrinsics.end(); I != E; ++I) {
1676    if (I->first != I->second) {
1677      for (Value::use_iterator UI = I->first->use_begin(),
1678           UE = I->first->use_end(); UI != UE; ) {
1679        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1680          UpgradeIntrinsicCall(CI, I->second);
1681      }
1682    }
1683  }
1684
1685  return false;
1686}
1687
1688void BitcodeReader::dematerializeFunction(Function *F) {
1689  // If this function isn't materialized, or if it is a proto, this is a noop.
1690  if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1691    return;
1692
1693  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1694
1695  // Just forget the function body, we can remat it later.
1696  F->deleteBody();
1697  F->setLinkage(GlobalValue::GhostLinkage);
1698}
1699
1700
1701Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1702  for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1703       DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1704       ++I) {
1705    Function *F = I->first;
1706    if (F->hasNotBeenReadFromBitcode() &&
1707        materializeFunction(F, ErrInfo))
1708      return 0;
1709  }
1710
1711  // Upgrade any intrinsic calls that slipped through (should not happen!) and
1712  // delete the old functions to clean up. We can't do this unless the entire
1713  // module is materialized because there could always be another function body
1714  // with calls to the old function.
1715  for (std::vector<std::pair<Function*, Function*> >::iterator I =
1716       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1717    if (I->first != I->second) {
1718      for (Value::use_iterator UI = I->first->use_begin(),
1719           UE = I->first->use_end(); UI != UE; ) {
1720        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1721          UpgradeIntrinsicCall(CI, I->second);
1722      }
1723      ValueList.replaceUsesOfWith(I->first, I->second);
1724      I->first->eraseFromParent();
1725    }
1726  }
1727  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1728
1729  return TheModule;
1730}
1731
1732
1733/// This method is provided by the parent ModuleProvde class and overriden
1734/// here. It simply releases the module from its provided and frees up our
1735/// state.
1736/// @brief Release our hold on the generated module
1737Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1738  // Since we're losing control of this Module, we must hand it back complete
1739  Module *M = ModuleProvider::releaseModule(ErrInfo);
1740  FreeState();
1741  return M;
1742}
1743
1744
1745//===----------------------------------------------------------------------===//
1746// External interface
1747//===----------------------------------------------------------------------===//
1748
1749/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1750///
1751ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1752                                               std::string *ErrMsg) {
1753  BitcodeReader *R = new BitcodeReader(Buffer);
1754  if (R->ParseBitcode()) {
1755    if (ErrMsg)
1756      *ErrMsg = R->getErrorString();
1757
1758    // Don't let the BitcodeReader dtor delete 'Buffer'.
1759    R->releaseMemoryBuffer();
1760    delete R;
1761    return 0;
1762  }
1763  return R;
1764}
1765
1766/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1767/// If an error occurs, return null and fill in *ErrMsg if non-null.
1768Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1769  BitcodeReader *R;
1770  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1771  if (!R) return 0;
1772
1773  // Read in the entire module.
1774  Module *M = R->materializeModule(ErrMsg);
1775
1776  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1777  // there was an error.
1778  R->releaseMemoryBuffer();
1779
1780  // If there was no error, tell ModuleProvider not to delete it when its dtor
1781  // is run.
1782  if (M)
1783    M = R->releaseModule(ErrMsg);
1784
1785  delete R;
1786  return M;
1787}
1788