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