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