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