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