BitcodeReader.cpp revision 85a4406959fe7794062d62d2f17226235630eee1
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/IntrinsicInst.h"
20#include "llvm/Module.h"
21#include "llvm/Operator.h"
22#include "llvm/AutoUpgrade.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/Support/DataStream.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/MemoryBuffer.h"
28#include "llvm/OperandTraits.h"
29using namespace llvm;
30
31enum {
32  SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
33};
34
35void BitcodeReader::materializeForwardReferencedFunctions() {
36  while (!BlockAddrFwdRefs.empty()) {
37    Function *F = BlockAddrFwdRefs.begin()->first;
38    F->Materialize();
39  }
40}
41
42void BitcodeReader::FreeState() {
43  if (BufferOwned)
44    delete Buffer;
45  Buffer = 0;
46  std::vector<Type*>().swap(TypeList);
47  ValueList.clear();
48  MDValueList.clear();
49
50  std::vector<AttrListPtr>().swap(MAttributes);
51  std::vector<BasicBlock*>().swap(FunctionBBs);
52  std::vector<Function*>().swap(FunctionsWithBodies);
53  DeferredFunctionInfo.clear();
54  MDKindMap.clear();
55}
56
57//===----------------------------------------------------------------------===//
58//  Helper functions to implement forward reference resolution, etc.
59//===----------------------------------------------------------------------===//
60
61/// ConvertToString - Convert a string from a record into an std::string, return
62/// true on failure.
63template<typename StrTy>
64static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
65                            StrTy &Result) {
66  if (Idx > Record.size())
67    return true;
68
69  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
70    Result += (char)Record[i];
71  return false;
72}
73
74static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
75  switch (Val) {
76  default: // Map unknown/new linkages to external
77  case 0:  return GlobalValue::ExternalLinkage;
78  case 1:  return GlobalValue::WeakAnyLinkage;
79  case 2:  return GlobalValue::AppendingLinkage;
80  case 3:  return GlobalValue::InternalLinkage;
81  case 4:  return GlobalValue::LinkOnceAnyLinkage;
82  case 5:  return GlobalValue::DLLImportLinkage;
83  case 6:  return GlobalValue::DLLExportLinkage;
84  case 7:  return GlobalValue::ExternalWeakLinkage;
85  case 8:  return GlobalValue::CommonLinkage;
86  case 9:  return GlobalValue::PrivateLinkage;
87  case 10: return GlobalValue::WeakODRLinkage;
88  case 11: return GlobalValue::LinkOnceODRLinkage;
89  case 12: return GlobalValue::AvailableExternallyLinkage;
90  case 13: return GlobalValue::LinkerPrivateLinkage;
91  case 14: return GlobalValue::LinkerPrivateWeakLinkage;
92  case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
93  }
94}
95
96static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
97  switch (Val) {
98  default: // Map unknown visibilities to default.
99  case 0: return GlobalValue::DefaultVisibility;
100  case 1: return GlobalValue::HiddenVisibility;
101  case 2: return GlobalValue::ProtectedVisibility;
102  }
103}
104
105static int GetDecodedCastOpcode(unsigned Val) {
106  switch (Val) {
107  default: return -1;
108  case bitc::CAST_TRUNC   : return Instruction::Trunc;
109  case bitc::CAST_ZEXT    : return Instruction::ZExt;
110  case bitc::CAST_SEXT    : return Instruction::SExt;
111  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
112  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
113  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
114  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
115  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
116  case bitc::CAST_FPEXT   : return Instruction::FPExt;
117  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
118  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
119  case bitc::CAST_BITCAST : return Instruction::BitCast;
120  }
121}
122static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
123  switch (Val) {
124  default: return -1;
125  case bitc::BINOP_ADD:
126    return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
127  case bitc::BINOP_SUB:
128    return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
129  case bitc::BINOP_MUL:
130    return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
131  case bitc::BINOP_UDIV: return Instruction::UDiv;
132  case bitc::BINOP_SDIV:
133    return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
134  case bitc::BINOP_UREM: return Instruction::URem;
135  case bitc::BINOP_SREM:
136    return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
137  case bitc::BINOP_SHL:  return Instruction::Shl;
138  case bitc::BINOP_LSHR: return Instruction::LShr;
139  case bitc::BINOP_ASHR: return Instruction::AShr;
140  case bitc::BINOP_AND:  return Instruction::And;
141  case bitc::BINOP_OR:   return Instruction::Or;
142  case bitc::BINOP_XOR:  return Instruction::Xor;
143  }
144}
145
146static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
147  switch (Val) {
148  default: return AtomicRMWInst::BAD_BINOP;
149  case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
150  case bitc::RMW_ADD: return AtomicRMWInst::Add;
151  case bitc::RMW_SUB: return AtomicRMWInst::Sub;
152  case bitc::RMW_AND: return AtomicRMWInst::And;
153  case bitc::RMW_NAND: return AtomicRMWInst::Nand;
154  case bitc::RMW_OR: return AtomicRMWInst::Or;
155  case bitc::RMW_XOR: return AtomicRMWInst::Xor;
156  case bitc::RMW_MAX: return AtomicRMWInst::Max;
157  case bitc::RMW_MIN: return AtomicRMWInst::Min;
158  case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
159  case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
160  }
161}
162
163static AtomicOrdering GetDecodedOrdering(unsigned Val) {
164  switch (Val) {
165  case bitc::ORDERING_NOTATOMIC: return NotAtomic;
166  case bitc::ORDERING_UNORDERED: return Unordered;
167  case bitc::ORDERING_MONOTONIC: return Monotonic;
168  case bitc::ORDERING_ACQUIRE: return Acquire;
169  case bitc::ORDERING_RELEASE: return Release;
170  case bitc::ORDERING_ACQREL: return AcquireRelease;
171  default: // Map unknown orderings to sequentially-consistent.
172  case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
173  }
174}
175
176static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
177  switch (Val) {
178  case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
179  default: // Map unknown scopes to cross-thread.
180  case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
181  }
182}
183
184namespace llvm {
185namespace {
186  /// @brief A class for maintaining the slot number definition
187  /// as a placeholder for the actual definition for forward constants defs.
188  class ConstantPlaceHolder : public ConstantExpr {
189    void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
190  public:
191    // allocate space for exactly one operand
192    void *operator new(size_t s) {
193      return User::operator new(s, 1);
194    }
195    explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
196      : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
197      Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
198    }
199
200    /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
201    //static inline bool classof(const ConstantPlaceHolder *) { return true; }
202    static bool classof(const Value *V) {
203      return isa<ConstantExpr>(V) &&
204             cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
205    }
206
207
208    /// Provide fast operand accessors
209    //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
210  };
211}
212
213// FIXME: can we inherit this from ConstantExpr?
214template <>
215struct OperandTraits<ConstantPlaceHolder> :
216  public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
217};
218}
219
220
221void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
222  if (Idx == size()) {
223    push_back(V);
224    return;
225  }
226
227  if (Idx >= size())
228    resize(Idx+1);
229
230  WeakVH &OldV = ValuePtrs[Idx];
231  if (OldV == 0) {
232    OldV = V;
233    return;
234  }
235
236  // Handle constants and non-constants (e.g. instrs) differently for
237  // efficiency.
238  if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
239    ResolveConstants.push_back(std::make_pair(PHC, Idx));
240    OldV = V;
241  } else {
242    // If there was a forward reference to this value, replace it.
243    Value *PrevVal = OldV;
244    OldV->replaceAllUsesWith(V);
245    delete PrevVal;
246  }
247}
248
249
250Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
251                                                    Type *Ty) {
252  if (Idx >= size())
253    resize(Idx + 1);
254
255  if (Value *V = ValuePtrs[Idx]) {
256    assert(Ty == V->getType() && "Type mismatch in constant table!");
257    return cast<Constant>(V);
258  }
259
260  // Create and return a placeholder, which will later be RAUW'd.
261  Constant *C = new ConstantPlaceHolder(Ty, Context);
262  ValuePtrs[Idx] = C;
263  return C;
264}
265
266Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
267  if (Idx >= size())
268    resize(Idx + 1);
269
270  if (Value *V = ValuePtrs[Idx]) {
271    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
272    return V;
273  }
274
275  // No type specified, must be invalid reference.
276  if (Ty == 0) return 0;
277
278  // Create and return a placeholder, which will later be RAUW'd.
279  Value *V = new Argument(Ty);
280  ValuePtrs[Idx] = V;
281  return V;
282}
283
284/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
285/// resolves any forward references.  The idea behind this is that we sometimes
286/// get constants (such as large arrays) which reference *many* forward ref
287/// constants.  Replacing each of these causes a lot of thrashing when
288/// building/reuniquing the constant.  Instead of doing this, we look at all the
289/// uses and rewrite all the place holders at once for any constant that uses
290/// a placeholder.
291void BitcodeReaderValueList::ResolveConstantForwardRefs() {
292  // Sort the values by-pointer so that they are efficient to look up with a
293  // binary search.
294  std::sort(ResolveConstants.begin(), ResolveConstants.end());
295
296  SmallVector<Constant*, 64> NewOps;
297
298  while (!ResolveConstants.empty()) {
299    Value *RealVal = operator[](ResolveConstants.back().second);
300    Constant *Placeholder = ResolveConstants.back().first;
301    ResolveConstants.pop_back();
302
303    // Loop over all users of the placeholder, updating them to reference the
304    // new value.  If they reference more than one placeholder, update them all
305    // at once.
306    while (!Placeholder->use_empty()) {
307      Value::use_iterator UI = Placeholder->use_begin();
308      User *U = *UI;
309
310      // If the using object isn't uniqued, just update the operands.  This
311      // handles instructions and initializers for global variables.
312      if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
313        UI.getUse().set(RealVal);
314        continue;
315      }
316
317      // Otherwise, we have a constant that uses the placeholder.  Replace that
318      // constant with a new constant that has *all* placeholder uses updated.
319      Constant *UserC = cast<Constant>(U);
320      for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
321           I != E; ++I) {
322        Value *NewOp;
323        if (!isa<ConstantPlaceHolder>(*I)) {
324          // Not a placeholder reference.
325          NewOp = *I;
326        } else if (*I == Placeholder) {
327          // Common case is that it just references this one placeholder.
328          NewOp = RealVal;
329        } else {
330          // Otherwise, look up the placeholder in ResolveConstants.
331          ResolveConstantsTy::iterator It =
332            std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
333                             std::pair<Constant*, unsigned>(cast<Constant>(*I),
334                                                            0));
335          assert(It != ResolveConstants.end() && It->first == *I);
336          NewOp = operator[](It->second);
337        }
338
339        NewOps.push_back(cast<Constant>(NewOp));
340      }
341
342      // Make the new constant.
343      Constant *NewC;
344      if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
345        NewC = ConstantArray::get(UserCA->getType(), NewOps);
346      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
347        NewC = ConstantStruct::get(UserCS->getType(), NewOps);
348      } else if (isa<ConstantVector>(UserC)) {
349        NewC = ConstantVector::get(NewOps);
350      } else {
351        assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
352        NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
353      }
354
355      UserC->replaceAllUsesWith(NewC);
356      UserC->destroyConstant();
357      NewOps.clear();
358    }
359
360    // Update all ValueHandles, they should be the only users at this point.
361    Placeholder->replaceAllUsesWith(RealVal);
362    delete Placeholder;
363  }
364}
365
366void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
367  if (Idx == size()) {
368    push_back(V);
369    return;
370  }
371
372  if (Idx >= size())
373    resize(Idx+1);
374
375  WeakVH &OldV = MDValuePtrs[Idx];
376  if (OldV == 0) {
377    OldV = V;
378    return;
379  }
380
381  // If there was a forward reference to this value, replace it.
382  MDNode *PrevVal = cast<MDNode>(OldV);
383  OldV->replaceAllUsesWith(V);
384  MDNode::deleteTemporary(PrevVal);
385  // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
386  // value for Idx.
387  MDValuePtrs[Idx] = V;
388}
389
390Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
391  if (Idx >= size())
392    resize(Idx + 1);
393
394  if (Value *V = MDValuePtrs[Idx]) {
395    assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
396    return V;
397  }
398
399  // Create and return a placeholder, which will later be RAUW'd.
400  Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
401  MDValuePtrs[Idx] = V;
402  return V;
403}
404
405Type *BitcodeReader::getTypeByID(unsigned ID) {
406  // The type table size is always specified correctly.
407  if (ID >= TypeList.size())
408    return 0;
409
410  if (Type *Ty = TypeList[ID])
411    return Ty;
412
413  // If we have a forward reference, the only possible case is when it is to a
414  // named struct.  Just create a placeholder for now.
415  return TypeList[ID] = StructType::create(Context);
416}
417
418
419//===----------------------------------------------------------------------===//
420//  Functions for parsing blocks from the bitcode file
421//===----------------------------------------------------------------------===//
422
423bool BitcodeReader::ParseAttributeBlock() {
424  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
425    return Error("Malformed block record");
426
427  if (!MAttributes.empty())
428    return Error("Multiple PARAMATTR blocks found!");
429
430  SmallVector<uint64_t, 64> Record;
431
432  SmallVector<AttributeWithIndex, 8> Attrs;
433
434  // Read all the records.
435  while (1) {
436    unsigned Code = Stream.ReadCode();
437    if (Code == bitc::END_BLOCK) {
438      if (Stream.ReadBlockEnd())
439        return Error("Error at end of PARAMATTR block");
440      return false;
441    }
442
443    if (Code == bitc::ENTER_SUBBLOCK) {
444      // No known subblocks, always skip them.
445      Stream.ReadSubBlockID();
446      if (Stream.SkipBlock())
447        return Error("Malformed block record");
448      continue;
449    }
450
451    if (Code == bitc::DEFINE_ABBREV) {
452      Stream.ReadAbbrevRecord();
453      continue;
454    }
455
456    // Read a record.
457    Record.clear();
458    switch (Stream.ReadRecord(Code, Record)) {
459    default:  // Default behavior: ignore.
460      break;
461    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
462      if (Record.size() & 1)
463        return Error("Invalid ENTRY record");
464
465      // FIXME : Remove this autoupgrade code in LLVM 3.0.
466      // If Function attributes are using index 0 then transfer them
467      // to index ~0. Index 0 is used for return value attributes but used to be
468      // used for function attributes.
469      Attributes RetAttribute;
470      Attributes FnAttribute;
471      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
472        // FIXME: remove in LLVM 3.0
473        // The alignment is stored as a 16-bit raw value from bits 31--16.
474        // We shift the bits above 31 down by 11 bits.
475
476        unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
477        if (Alignment && !isPowerOf2_32(Alignment))
478          return Error("Alignment is not a power of two.");
479
480        Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
481        if (Alignment)
482          ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
483        ReconstitutedAttr |=
484            Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
485
486        Record[i+1] = ReconstitutedAttr.Raw();
487        if (Record[i] == 0)
488          RetAttribute = ReconstitutedAttr;
489        else if (Record[i] == ~0U)
490          FnAttribute = ReconstitutedAttr;
491      }
492
493      Attributes OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
494                              Attribute::ReadOnly|Attribute::ReadNone);
495
496      if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
497          (RetAttribute & OldRetAttrs)) {
498        if (FnAttribute == Attribute::None) { // add a slot so they get added.
499          Record.push_back(~0U);
500          Record.push_back(0);
501        }
502
503        FnAttribute  |= RetAttribute & OldRetAttrs;
504        RetAttribute &= ~OldRetAttrs;
505      }
506
507      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
508        if (Record[i] == 0) {
509          if (RetAttribute != Attribute::None)
510            Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
511        } else if (Record[i] == ~0U) {
512          if (FnAttribute != Attribute::None)
513            Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
514        } else if (Attributes(Record[i+1]) != Attribute::None)
515          Attrs.push_back(AttributeWithIndex::get(Record[i],
516                                                  Attributes(Record[i+1])));
517      }
518
519      MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
520      Attrs.clear();
521      break;
522    }
523    }
524  }
525}
526
527bool BitcodeReader::ParseTypeTable() {
528  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
529    return Error("Malformed block record");
530
531  return ParseTypeTableBody();
532}
533
534bool BitcodeReader::ParseTypeTableBody() {
535  if (!TypeList.empty())
536    return Error("Multiple TYPE_BLOCKs found!");
537
538  SmallVector<uint64_t, 64> Record;
539  unsigned NumRecords = 0;
540
541  SmallString<64> TypeName;
542
543  // Read all the records for this type table.
544  while (1) {
545    unsigned Code = Stream.ReadCode();
546    if (Code == bitc::END_BLOCK) {
547      if (NumRecords != TypeList.size())
548        return Error("Invalid type forward reference in TYPE_BLOCK");
549      if (Stream.ReadBlockEnd())
550        return Error("Error at end of type table block");
551      return false;
552    }
553
554    if (Code == bitc::ENTER_SUBBLOCK) {
555      // No known subblocks, always skip them.
556      Stream.ReadSubBlockID();
557      if (Stream.SkipBlock())
558        return Error("Malformed block record");
559      continue;
560    }
561
562    if (Code == bitc::DEFINE_ABBREV) {
563      Stream.ReadAbbrevRecord();
564      continue;
565    }
566
567    // Read a record.
568    Record.clear();
569    Type *ResultTy = 0;
570    switch (Stream.ReadRecord(Code, Record)) {
571    default: return Error("unknown type in type table");
572    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
573      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
574      // type list.  This allows us to reserve space.
575      if (Record.size() < 1)
576        return Error("Invalid TYPE_CODE_NUMENTRY record");
577      TypeList.resize(Record[0]);
578      continue;
579    case bitc::TYPE_CODE_VOID:      // VOID
580      ResultTy = Type::getVoidTy(Context);
581      break;
582    case bitc::TYPE_CODE_HALF:     // HALF
583      ResultTy = Type::getHalfTy(Context);
584      break;
585    case bitc::TYPE_CODE_FLOAT:     // FLOAT
586      ResultTy = Type::getFloatTy(Context);
587      break;
588    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
589      ResultTy = Type::getDoubleTy(Context);
590      break;
591    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
592      ResultTy = Type::getX86_FP80Ty(Context);
593      break;
594    case bitc::TYPE_CODE_FP128:     // FP128
595      ResultTy = Type::getFP128Ty(Context);
596      break;
597    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
598      ResultTy = Type::getPPC_FP128Ty(Context);
599      break;
600    case bitc::TYPE_CODE_LABEL:     // LABEL
601      ResultTy = Type::getLabelTy(Context);
602      break;
603    case bitc::TYPE_CODE_METADATA:  // METADATA
604      ResultTy = Type::getMetadataTy(Context);
605      break;
606    case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
607      ResultTy = Type::getX86_MMXTy(Context);
608      break;
609    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
610      if (Record.size() < 1)
611        return Error("Invalid Integer type record");
612
613      ResultTy = IntegerType::get(Context, Record[0]);
614      break;
615    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
616                                    //          [pointee type, address space]
617      if (Record.size() < 1)
618        return Error("Invalid POINTER type record");
619      unsigned AddressSpace = 0;
620      if (Record.size() == 2)
621        AddressSpace = Record[1];
622      ResultTy = getTypeByID(Record[0]);
623      if (ResultTy == 0) return Error("invalid element type in pointer type");
624      ResultTy = PointerType::get(ResultTy, AddressSpace);
625      break;
626    }
627    case bitc::TYPE_CODE_FUNCTION_OLD: {
628      // FIXME: attrid is dead, remove it in LLVM 3.0
629      // FUNCTION: [vararg, attrid, retty, paramty x N]
630      if (Record.size() < 3)
631        return Error("Invalid FUNCTION type record");
632      SmallVector<Type*, 8> ArgTys;
633      for (unsigned i = 3, e = Record.size(); i != e; ++i) {
634        if (Type *T = getTypeByID(Record[i]))
635          ArgTys.push_back(T);
636        else
637          break;
638      }
639
640      ResultTy = getTypeByID(Record[2]);
641      if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
642        return Error("invalid type in function type");
643
644      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
645      break;
646    }
647    case bitc::TYPE_CODE_FUNCTION: {
648      // FUNCTION: [vararg, retty, paramty x N]
649      if (Record.size() < 2)
650        return Error("Invalid FUNCTION type record");
651      SmallVector<Type*, 8> ArgTys;
652      for (unsigned i = 2, e = Record.size(); i != e; ++i) {
653        if (Type *T = getTypeByID(Record[i]))
654          ArgTys.push_back(T);
655        else
656          break;
657      }
658
659      ResultTy = getTypeByID(Record[1]);
660      if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
661        return Error("invalid type in function type");
662
663      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
664      break;
665    }
666    case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
667      if (Record.size() < 1)
668        return Error("Invalid STRUCT type record");
669      SmallVector<Type*, 8> EltTys;
670      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
671        if (Type *T = getTypeByID(Record[i]))
672          EltTys.push_back(T);
673        else
674          break;
675      }
676      if (EltTys.size() != Record.size()-1)
677        return Error("invalid type in struct type");
678      ResultTy = StructType::get(Context, EltTys, Record[0]);
679      break;
680    }
681    case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
682      if (ConvertToString(Record, 0, TypeName))
683        return Error("Invalid STRUCT_NAME record");
684      continue;
685
686    case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
687      if (Record.size() < 1)
688        return Error("Invalid STRUCT type record");
689
690      if (NumRecords >= TypeList.size())
691        return Error("invalid TYPE table");
692
693      // Check to see if this was forward referenced, if so fill in the temp.
694      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
695      if (Res) {
696        Res->setName(TypeName);
697        TypeList[NumRecords] = 0;
698      } else  // Otherwise, create a new struct.
699        Res = StructType::create(Context, TypeName);
700      TypeName.clear();
701
702      SmallVector<Type*, 8> EltTys;
703      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
704        if (Type *T = getTypeByID(Record[i]))
705          EltTys.push_back(T);
706        else
707          break;
708      }
709      if (EltTys.size() != Record.size()-1)
710        return Error("invalid STRUCT type record");
711      Res->setBody(EltTys, Record[0]);
712      ResultTy = Res;
713      break;
714    }
715    case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
716      if (Record.size() != 1)
717        return Error("Invalid OPAQUE type record");
718
719      if (NumRecords >= TypeList.size())
720        return Error("invalid TYPE table");
721
722      // Check to see if this was forward referenced, if so fill in the temp.
723      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
724      if (Res) {
725        Res->setName(TypeName);
726        TypeList[NumRecords] = 0;
727      } else  // Otherwise, create a new struct with no body.
728        Res = StructType::create(Context, TypeName);
729      TypeName.clear();
730      ResultTy = Res;
731      break;
732    }
733    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
734      if (Record.size() < 2)
735        return Error("Invalid ARRAY type record");
736      if ((ResultTy = getTypeByID(Record[1])))
737        ResultTy = ArrayType::get(ResultTy, Record[0]);
738      else
739        return Error("Invalid ARRAY type element");
740      break;
741    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
742      if (Record.size() < 2)
743        return Error("Invalid VECTOR type record");
744      if ((ResultTy = getTypeByID(Record[1])))
745        ResultTy = VectorType::get(ResultTy, Record[0]);
746      else
747        return Error("Invalid ARRAY type element");
748      break;
749    }
750
751    if (NumRecords >= TypeList.size())
752      return Error("invalid TYPE table");
753    assert(ResultTy && "Didn't read a type?");
754    assert(TypeList[NumRecords] == 0 && "Already read type?");
755    TypeList[NumRecords++] = ResultTy;
756  }
757}
758
759bool BitcodeReader::ParseValueSymbolTable() {
760  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
761    return Error("Malformed block record");
762
763  SmallVector<uint64_t, 64> Record;
764
765  // Read all the records for this value table.
766  SmallString<128> ValueName;
767  while (1) {
768    unsigned Code = Stream.ReadCode();
769    if (Code == bitc::END_BLOCK) {
770      if (Stream.ReadBlockEnd())
771        return Error("Error at end of value symbol table block");
772      return false;
773    }
774    if (Code == bitc::ENTER_SUBBLOCK) {
775      // No known subblocks, always skip them.
776      Stream.ReadSubBlockID();
777      if (Stream.SkipBlock())
778        return Error("Malformed block record");
779      continue;
780    }
781
782    if (Code == bitc::DEFINE_ABBREV) {
783      Stream.ReadAbbrevRecord();
784      continue;
785    }
786
787    // Read a record.
788    Record.clear();
789    switch (Stream.ReadRecord(Code, Record)) {
790    default:  // Default behavior: unknown type.
791      break;
792    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
793      if (ConvertToString(Record, 1, ValueName))
794        return Error("Invalid VST_ENTRY record");
795      unsigned ValueID = Record[0];
796      if (ValueID >= ValueList.size())
797        return Error("Invalid Value ID in VST_ENTRY record");
798      Value *V = ValueList[ValueID];
799
800      V->setName(StringRef(ValueName.data(), ValueName.size()));
801      ValueName.clear();
802      break;
803    }
804    case bitc::VST_CODE_BBENTRY: {
805      if (ConvertToString(Record, 1, ValueName))
806        return Error("Invalid VST_BBENTRY record");
807      BasicBlock *BB = getBasicBlock(Record[0]);
808      if (BB == 0)
809        return Error("Invalid BB ID in VST_BBENTRY record");
810
811      BB->setName(StringRef(ValueName.data(), ValueName.size()));
812      ValueName.clear();
813      break;
814    }
815    }
816  }
817}
818
819bool BitcodeReader::ParseMetadata() {
820  unsigned NextMDValueNo = MDValueList.size();
821
822  if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
823    return Error("Malformed block record");
824
825  SmallVector<uint64_t, 64> Record;
826
827  // Read all the records.
828  while (1) {
829    unsigned Code = Stream.ReadCode();
830    if (Code == bitc::END_BLOCK) {
831      if (Stream.ReadBlockEnd())
832        return Error("Error at end of PARAMATTR block");
833      return false;
834    }
835
836    if (Code == bitc::ENTER_SUBBLOCK) {
837      // No known subblocks, always skip them.
838      Stream.ReadSubBlockID();
839      if (Stream.SkipBlock())
840        return Error("Malformed block record");
841      continue;
842    }
843
844    if (Code == bitc::DEFINE_ABBREV) {
845      Stream.ReadAbbrevRecord();
846      continue;
847    }
848
849    bool IsFunctionLocal = false;
850    // Read a record.
851    Record.clear();
852    Code = Stream.ReadRecord(Code, Record);
853    switch (Code) {
854    default:  // Default behavior: ignore.
855      break;
856    case bitc::METADATA_NAME: {
857      // Read named of the named metadata.
858      unsigned NameLength = Record.size();
859      SmallString<8> Name;
860      Name.resize(NameLength);
861      for (unsigned i = 0; i != NameLength; ++i)
862        Name[i] = Record[i];
863      Record.clear();
864      Code = Stream.ReadCode();
865
866      // METADATA_NAME is always followed by METADATA_NAMED_NODE.
867      unsigned NextBitCode = Stream.ReadRecord(Code, Record);
868      assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
869
870      // Read named metadata elements.
871      unsigned Size = Record.size();
872      NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
873      for (unsigned i = 0; i != Size; ++i) {
874        MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
875        if (MD == 0)
876          return Error("Malformed metadata record");
877        NMD->addOperand(MD);
878      }
879      break;
880    }
881    case bitc::METADATA_FN_NODE:
882      IsFunctionLocal = true;
883      // fall-through
884    case bitc::METADATA_NODE: {
885      if (Record.size() % 2 == 1)
886        return Error("Invalid METADATA_NODE record");
887
888      unsigned Size = Record.size();
889      SmallVector<Value*, 8> Elts;
890      for (unsigned i = 0; i != Size; i += 2) {
891        Type *Ty = getTypeByID(Record[i]);
892        if (!Ty) return Error("Invalid METADATA_NODE record");
893        if (Ty->isMetadataTy())
894          Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
895        else if (!Ty->isVoidTy())
896          Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
897        else
898          Elts.push_back(NULL);
899      }
900      Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
901      IsFunctionLocal = false;
902      MDValueList.AssignValue(V, NextMDValueNo++);
903      break;
904    }
905    case bitc::METADATA_STRING: {
906      unsigned MDStringLength = Record.size();
907      SmallString<8> String;
908      String.resize(MDStringLength);
909      for (unsigned i = 0; i != MDStringLength; ++i)
910        String[i] = Record[i];
911      Value *V = MDString::get(Context,
912                               StringRef(String.data(), String.size()));
913      MDValueList.AssignValue(V, NextMDValueNo++);
914      break;
915    }
916    case bitc::METADATA_KIND: {
917      unsigned RecordLength = Record.size();
918      if (Record.empty() || RecordLength < 2)
919        return Error("Invalid METADATA_KIND record");
920      SmallString<8> Name;
921      Name.resize(RecordLength-1);
922      unsigned Kind = Record[0];
923      for (unsigned i = 1; i != RecordLength; ++i)
924        Name[i-1] = Record[i];
925
926      unsigned NewKind = TheModule->getMDKindID(Name.str());
927      if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
928        return Error("Conflicting METADATA_KIND records");
929      break;
930    }
931    }
932  }
933}
934
935/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
936/// the LSB for dense VBR encoding.
937static uint64_t DecodeSignRotatedValue(uint64_t V) {
938  if ((V & 1) == 0)
939    return V >> 1;
940  if (V != 1)
941    return -(V >> 1);
942  // There is no such thing as -0 with integers.  "-0" really means MININT.
943  return 1ULL << 63;
944}
945
946/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
947/// values and aliases that we can.
948bool BitcodeReader::ResolveGlobalAndAliasInits() {
949  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
950  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
951
952  GlobalInitWorklist.swap(GlobalInits);
953  AliasInitWorklist.swap(AliasInits);
954
955  while (!GlobalInitWorklist.empty()) {
956    unsigned ValID = GlobalInitWorklist.back().second;
957    if (ValID >= ValueList.size()) {
958      // Not ready to resolve this yet, it requires something later in the file.
959      GlobalInits.push_back(GlobalInitWorklist.back());
960    } else {
961      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
962        GlobalInitWorklist.back().first->setInitializer(C);
963      else
964        return Error("Global variable initializer is not a constant!");
965    }
966    GlobalInitWorklist.pop_back();
967  }
968
969  while (!AliasInitWorklist.empty()) {
970    unsigned ValID = AliasInitWorklist.back().second;
971    if (ValID >= ValueList.size()) {
972      AliasInits.push_back(AliasInitWorklist.back());
973    } else {
974      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
975        AliasInitWorklist.back().first->setAliasee(C);
976      else
977        return Error("Alias initializer is not a constant!");
978    }
979    AliasInitWorklist.pop_back();
980  }
981  return false;
982}
983
984template <typename intty>
985APInt ReadWideAPInt(const intty *Vals, unsigned ActiveWords,
986                    unsigned TypeBits) {
987  SmallVector<uint64_t, 8> Words;
988  Words.resize(ActiveWords);
989  for (unsigned i = 0; i != ActiveWords; ++i)
990    Words[i] = DecodeSignRotatedValue(Vals[i]);
991
992  return APInt(TypeBits, Words);
993}
994
995bool BitcodeReader::ParseConstants() {
996  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
997    return Error("Malformed block record");
998
999  SmallVector<uint64_t, 64> Record;
1000
1001  // Read all the records for this value table.
1002  Type *CurTy = Type::getInt32Ty(Context);
1003  unsigned NextCstNo = ValueList.size();
1004  while (1) {
1005    unsigned Code = Stream.ReadCode();
1006    if (Code == bitc::END_BLOCK)
1007      break;
1008
1009    if (Code == bitc::ENTER_SUBBLOCK) {
1010      // No known subblocks, always skip them.
1011      Stream.ReadSubBlockID();
1012      if (Stream.SkipBlock())
1013        return Error("Malformed block record");
1014      continue;
1015    }
1016
1017    if (Code == bitc::DEFINE_ABBREV) {
1018      Stream.ReadAbbrevRecord();
1019      continue;
1020    }
1021
1022    // Read a record.
1023    Record.clear();
1024    Value *V = 0;
1025    unsigned BitCode = Stream.ReadRecord(Code, Record);
1026    switch (BitCode) {
1027    default:  // Default behavior: unknown constant
1028    case bitc::CST_CODE_UNDEF:     // UNDEF
1029      V = UndefValue::get(CurTy);
1030      break;
1031    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
1032      if (Record.empty())
1033        return Error("Malformed CST_SETTYPE record");
1034      if (Record[0] >= TypeList.size())
1035        return Error("Invalid Type ID in CST_SETTYPE record");
1036      CurTy = TypeList[Record[0]];
1037      continue;  // Skip the ValueList manipulation.
1038    case bitc::CST_CODE_NULL:      // NULL
1039      V = Constant::getNullValue(CurTy);
1040      break;
1041    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
1042      if (!CurTy->isIntegerTy() || Record.empty())
1043        return Error("Invalid CST_INTEGER record");
1044      V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
1045      break;
1046    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1047      if (!CurTy->isIntegerTy() || Record.empty())
1048        return Error("Invalid WIDE_INTEGER record");
1049
1050      unsigned NumWords = Record.size();
1051
1052      APInt VInt = ReadWideAPInt(&Record[0], NumWords,
1053          cast<IntegerType>(CurTy)->getBitWidth());
1054      V = ConstantInt::get(Context, VInt);
1055
1056      break;
1057    }
1058    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1059      if (Record.empty())
1060        return Error("Invalid FLOAT record");
1061      if (CurTy->isHalfTy())
1062        V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1063      else if (CurTy->isFloatTy())
1064        V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1065      else if (CurTy->isDoubleTy())
1066        V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1067      else if (CurTy->isX86_FP80Ty()) {
1068        // Bits are not stored the same way as a normal i80 APInt, compensate.
1069        uint64_t Rearrange[2];
1070        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1071        Rearrange[1] = Record[0] >> 48;
1072        V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1073      } else if (CurTy->isFP128Ty())
1074        V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1075      else if (CurTy->isPPC_FP128Ty())
1076        V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1077      else
1078        V = UndefValue::get(CurTy);
1079      break;
1080    }
1081
1082    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1083      if (Record.empty())
1084        return Error("Invalid CST_AGGREGATE record");
1085
1086      unsigned Size = Record.size();
1087      SmallVector<Constant*, 16> Elts;
1088
1089      if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1090        for (unsigned i = 0; i != Size; ++i)
1091          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1092                                                     STy->getElementType(i)));
1093        V = ConstantStruct::get(STy, Elts);
1094      } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1095        Type *EltTy = ATy->getElementType();
1096        for (unsigned i = 0; i != Size; ++i)
1097          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1098        V = ConstantArray::get(ATy, Elts);
1099      } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1100        Type *EltTy = VTy->getElementType();
1101        for (unsigned i = 0; i != Size; ++i)
1102          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1103        V = ConstantVector::get(Elts);
1104      } else {
1105        V = UndefValue::get(CurTy);
1106      }
1107      break;
1108    }
1109    case bitc::CST_CODE_STRING:    // STRING: [values]
1110    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1111      if (Record.empty())
1112        return Error("Invalid CST_STRING record");
1113
1114      unsigned Size = Record.size();
1115      SmallString<16> Elts;
1116      for (unsigned i = 0; i != Size; ++i)
1117        Elts.push_back(Record[i]);
1118      V = ConstantDataArray::getString(Context, Elts,
1119                                       BitCode == bitc::CST_CODE_CSTRING);
1120      break;
1121    }
1122    case bitc::CST_CODE_DATA: {// DATA: [n x value]
1123      if (Record.empty())
1124        return Error("Invalid CST_DATA record");
1125
1126      Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1127      unsigned Size = Record.size();
1128
1129      if (EltTy->isIntegerTy(8)) {
1130        SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1131        if (isa<VectorType>(CurTy))
1132          V = ConstantDataVector::get(Context, Elts);
1133        else
1134          V = ConstantDataArray::get(Context, Elts);
1135      } else if (EltTy->isIntegerTy(16)) {
1136        SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1137        if (isa<VectorType>(CurTy))
1138          V = ConstantDataVector::get(Context, Elts);
1139        else
1140          V = ConstantDataArray::get(Context, Elts);
1141      } else if (EltTy->isIntegerTy(32)) {
1142        SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1143        if (isa<VectorType>(CurTy))
1144          V = ConstantDataVector::get(Context, Elts);
1145        else
1146          V = ConstantDataArray::get(Context, Elts);
1147      } else if (EltTy->isIntegerTy(64)) {
1148        SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1149        if (isa<VectorType>(CurTy))
1150          V = ConstantDataVector::get(Context, Elts);
1151        else
1152          V = ConstantDataArray::get(Context, Elts);
1153      } else if (EltTy->isFloatTy()) {
1154        SmallVector<float, 16> Elts;
1155        for (unsigned i = 0; i != Size; ++i) {
1156          union { uint32_t I; float F; };
1157          I = Record[i];
1158          Elts.push_back(F);
1159        }
1160        if (isa<VectorType>(CurTy))
1161          V = ConstantDataVector::get(Context, Elts);
1162        else
1163          V = ConstantDataArray::get(Context, Elts);
1164      } else if (EltTy->isDoubleTy()) {
1165        SmallVector<double, 16> Elts;
1166        for (unsigned i = 0; i != Size; ++i) {
1167          union { uint64_t I; double F; };
1168          I = Record[i];
1169          Elts.push_back(F);
1170        }
1171        if (isa<VectorType>(CurTy))
1172          V = ConstantDataVector::get(Context, Elts);
1173        else
1174          V = ConstantDataArray::get(Context, Elts);
1175      } else {
1176        return Error("Unknown element type in CE_DATA");
1177      }
1178      break;
1179    }
1180
1181    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1182      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1183      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1184      if (Opc < 0) {
1185        V = UndefValue::get(CurTy);  // Unknown binop.
1186      } else {
1187        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1188        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1189        unsigned Flags = 0;
1190        if (Record.size() >= 4) {
1191          if (Opc == Instruction::Add ||
1192              Opc == Instruction::Sub ||
1193              Opc == Instruction::Mul ||
1194              Opc == Instruction::Shl) {
1195            if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1196              Flags |= OverflowingBinaryOperator::NoSignedWrap;
1197            if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1198              Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1199          } else if (Opc == Instruction::SDiv ||
1200                     Opc == Instruction::UDiv ||
1201                     Opc == Instruction::LShr ||
1202                     Opc == Instruction::AShr) {
1203            if (Record[3] & (1 << bitc::PEO_EXACT))
1204              Flags |= SDivOperator::IsExact;
1205          }
1206        }
1207        V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1208      }
1209      break;
1210    }
1211    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1212      if (Record.size() < 3) return Error("Invalid CE_CAST record");
1213      int Opc = GetDecodedCastOpcode(Record[0]);
1214      if (Opc < 0) {
1215        V = UndefValue::get(CurTy);  // Unknown cast.
1216      } else {
1217        Type *OpTy = getTypeByID(Record[1]);
1218        if (!OpTy) return Error("Invalid CE_CAST record");
1219        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1220        V = ConstantExpr::getCast(Opc, Op, CurTy);
1221      }
1222      break;
1223    }
1224    case bitc::CST_CODE_CE_INBOUNDS_GEP:
1225    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1226      if (Record.size() & 1) return Error("Invalid CE_GEP record");
1227      SmallVector<Constant*, 16> Elts;
1228      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1229        Type *ElTy = getTypeByID(Record[i]);
1230        if (!ElTy) return Error("Invalid CE_GEP record");
1231        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1232      }
1233      ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1234      V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1235                                         BitCode ==
1236                                           bitc::CST_CODE_CE_INBOUNDS_GEP);
1237      break;
1238    }
1239    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1240      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1241      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1242                                                              Type::getInt1Ty(Context)),
1243                                  ValueList.getConstantFwdRef(Record[1],CurTy),
1244                                  ValueList.getConstantFwdRef(Record[2],CurTy));
1245      break;
1246    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1247      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1248      VectorType *OpTy =
1249        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1250      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1251      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1252      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1253      V = ConstantExpr::getExtractElement(Op0, Op1);
1254      break;
1255    }
1256    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1257      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1258      if (Record.size() < 3 || OpTy == 0)
1259        return Error("Invalid CE_INSERTELT record");
1260      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1261      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1262                                                  OpTy->getElementType());
1263      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1264      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1265      break;
1266    }
1267    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1268      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1269      if (Record.size() < 3 || OpTy == 0)
1270        return Error("Invalid CE_SHUFFLEVEC record");
1271      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1272      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1273      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1274                                                 OpTy->getNumElements());
1275      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1276      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1277      break;
1278    }
1279    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1280      VectorType *RTy = dyn_cast<VectorType>(CurTy);
1281      VectorType *OpTy =
1282        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1283      if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1284        return Error("Invalid CE_SHUFVEC_EX record");
1285      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1286      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1287      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1288                                                 RTy->getNumElements());
1289      Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1290      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1291      break;
1292    }
1293    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1294      if (Record.size() < 4) return Error("Invalid CE_CMP record");
1295      Type *OpTy = getTypeByID(Record[0]);
1296      if (OpTy == 0) return Error("Invalid CE_CMP record");
1297      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1298      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1299
1300      if (OpTy->isFPOrFPVectorTy())
1301        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1302      else
1303        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1304      break;
1305    }
1306    case bitc::CST_CODE_INLINEASM: {
1307      if (Record.size() < 2) return Error("Invalid INLINEASM record");
1308      std::string AsmStr, ConstrStr;
1309      bool HasSideEffects = Record[0] & 1;
1310      bool IsAlignStack = Record[0] >> 1;
1311      unsigned AsmStrSize = Record[1];
1312      if (2+AsmStrSize >= Record.size())
1313        return Error("Invalid INLINEASM record");
1314      unsigned ConstStrSize = Record[2+AsmStrSize];
1315      if (3+AsmStrSize+ConstStrSize > Record.size())
1316        return Error("Invalid INLINEASM record");
1317
1318      for (unsigned i = 0; i != AsmStrSize; ++i)
1319        AsmStr += (char)Record[2+i];
1320      for (unsigned i = 0; i != ConstStrSize; ++i)
1321        ConstrStr += (char)Record[3+AsmStrSize+i];
1322      PointerType *PTy = cast<PointerType>(CurTy);
1323      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1324                         AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1325      break;
1326    }
1327    case bitc::CST_CODE_BLOCKADDRESS:{
1328      if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1329      Type *FnTy = getTypeByID(Record[0]);
1330      if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1331      Function *Fn =
1332        dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1333      if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1334
1335      GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1336                                                  Type::getInt8Ty(Context),
1337                                            false, GlobalValue::InternalLinkage,
1338                                                  0, "");
1339      BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1340      V = FwdRef;
1341      break;
1342    }
1343    }
1344
1345    ValueList.AssignValue(V, NextCstNo);
1346    ++NextCstNo;
1347  }
1348
1349  if (NextCstNo != ValueList.size())
1350    return Error("Invalid constant reference!");
1351
1352  if (Stream.ReadBlockEnd())
1353    return Error("Error at end of constants block");
1354
1355  // Once all the constants have been read, go through and resolve forward
1356  // references.
1357  ValueList.ResolveConstantForwardRefs();
1358  return false;
1359}
1360
1361bool BitcodeReader::ParseUseLists() {
1362  if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1363    return Error("Malformed block record");
1364
1365  SmallVector<uint64_t, 64> Record;
1366
1367  // Read all the records.
1368  while (1) {
1369    unsigned Code = Stream.ReadCode();
1370    if (Code == bitc::END_BLOCK) {
1371      if (Stream.ReadBlockEnd())
1372        return Error("Error at end of use-list table block");
1373      return false;
1374    }
1375
1376    if (Code == bitc::ENTER_SUBBLOCK) {
1377      // No known subblocks, always skip them.
1378      Stream.ReadSubBlockID();
1379      if (Stream.SkipBlock())
1380        return Error("Malformed block record");
1381      continue;
1382    }
1383
1384    if (Code == bitc::DEFINE_ABBREV) {
1385      Stream.ReadAbbrevRecord();
1386      continue;
1387    }
1388
1389    // Read a use list record.
1390    Record.clear();
1391    switch (Stream.ReadRecord(Code, Record)) {
1392    default:  // Default behavior: unknown type.
1393      break;
1394    case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1395      unsigned RecordLength = Record.size();
1396      if (RecordLength < 1)
1397        return Error ("Invalid UseList reader!");
1398      UseListRecords.push_back(Record);
1399      break;
1400    }
1401    }
1402  }
1403}
1404
1405/// RememberAndSkipFunctionBody - When we see the block for a function body,
1406/// remember where it is and then skip it.  This lets us lazily deserialize the
1407/// functions.
1408bool BitcodeReader::RememberAndSkipFunctionBody() {
1409  // Get the function we are talking about.
1410  if (FunctionsWithBodies.empty())
1411    return Error("Insufficient function protos");
1412
1413  Function *Fn = FunctionsWithBodies.back();
1414  FunctionsWithBodies.pop_back();
1415
1416  // Save the current stream state.
1417  uint64_t CurBit = Stream.GetCurrentBitNo();
1418  DeferredFunctionInfo[Fn] = CurBit;
1419
1420  // Skip over the function block for now.
1421  if (Stream.SkipBlock())
1422    return Error("Malformed block record");
1423  return false;
1424}
1425
1426bool BitcodeReader::GlobalCleanup() {
1427  // Patch the initializers for globals and aliases up.
1428  ResolveGlobalAndAliasInits();
1429  if (!GlobalInits.empty() || !AliasInits.empty())
1430    return Error("Malformed global initializer set");
1431
1432  // Look for intrinsic functions which need to be upgraded at some point
1433  for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1434       FI != FE; ++FI) {
1435    Function *NewFn;
1436    if (UpgradeIntrinsicFunction(FI, NewFn))
1437      UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1438  }
1439
1440  // Look for global variables which need to be renamed.
1441  for (Module::global_iterator
1442         GI = TheModule->global_begin(), GE = TheModule->global_end();
1443       GI != GE; ++GI)
1444    UpgradeGlobalVariable(GI);
1445  // Force deallocation of memory for these vectors to favor the client that
1446  // want lazy deserialization.
1447  std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1448  std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1449  return false;
1450}
1451
1452bool BitcodeReader::ParseModule(bool Resume) {
1453  if (Resume)
1454    Stream.JumpToBit(NextUnreadBit);
1455  else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1456    return Error("Malformed block record");
1457
1458  SmallVector<uint64_t, 64> Record;
1459  std::vector<std::string> SectionTable;
1460  std::vector<std::string> GCTable;
1461
1462  // Read all the records for this module.
1463  while (!Stream.AtEndOfStream()) {
1464    unsigned Code = Stream.ReadCode();
1465    if (Code == bitc::END_BLOCK) {
1466      if (Stream.ReadBlockEnd())
1467        return Error("Error at end of module block");
1468
1469      return GlobalCleanup();
1470    }
1471
1472    if (Code == bitc::ENTER_SUBBLOCK) {
1473      switch (Stream.ReadSubBlockID()) {
1474      default:  // Skip unknown content.
1475        if (Stream.SkipBlock())
1476          return Error("Malformed block record");
1477        break;
1478      case bitc::BLOCKINFO_BLOCK_ID:
1479        if (Stream.ReadBlockInfoBlock())
1480          return Error("Malformed BlockInfoBlock");
1481        break;
1482      case bitc::PARAMATTR_BLOCK_ID:
1483        if (ParseAttributeBlock())
1484          return true;
1485        break;
1486      case bitc::TYPE_BLOCK_ID_NEW:
1487        if (ParseTypeTable())
1488          return true;
1489        break;
1490      case bitc::VALUE_SYMTAB_BLOCK_ID:
1491        if (ParseValueSymbolTable())
1492          return true;
1493        SeenValueSymbolTable = true;
1494        break;
1495      case bitc::CONSTANTS_BLOCK_ID:
1496        if (ParseConstants() || ResolveGlobalAndAliasInits())
1497          return true;
1498        break;
1499      case bitc::METADATA_BLOCK_ID:
1500        if (ParseMetadata())
1501          return true;
1502        break;
1503      case bitc::FUNCTION_BLOCK_ID:
1504        // If this is the first function body we've seen, reverse the
1505        // FunctionsWithBodies list.
1506        if (!SeenFirstFunctionBody) {
1507          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1508          if (GlobalCleanup())
1509            return true;
1510          SeenFirstFunctionBody = true;
1511        }
1512
1513        if (RememberAndSkipFunctionBody())
1514          return true;
1515        // For streaming bitcode, suspend parsing when we reach the function
1516        // bodies. Subsequent materialization calls will resume it when
1517        // necessary. For streaming, the function bodies must be at the end of
1518        // the bitcode. If the bitcode file is old, the symbol table will be
1519        // at the end instead and will not have been seen yet. In this case,
1520        // just finish the parse now.
1521        if (LazyStreamer && SeenValueSymbolTable) {
1522          NextUnreadBit = Stream.GetCurrentBitNo();
1523          return false;
1524        }
1525        break;
1526      case bitc::USELIST_BLOCK_ID:
1527        if (ParseUseLists())
1528          return true;
1529        break;
1530      }
1531      continue;
1532    }
1533
1534    if (Code == bitc::DEFINE_ABBREV) {
1535      Stream.ReadAbbrevRecord();
1536      continue;
1537    }
1538
1539    // Read a record.
1540    switch (Stream.ReadRecord(Code, Record)) {
1541    default: break;  // Default behavior, ignore unknown content.
1542    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1543      if (Record.size() < 1)
1544        return Error("Malformed MODULE_CODE_VERSION");
1545      // Only version #0 is supported so far.
1546      if (Record[0] != 0)
1547        return Error("Unknown bitstream version!");
1548      break;
1549    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1550      std::string S;
1551      if (ConvertToString(Record, 0, S))
1552        return Error("Invalid MODULE_CODE_TRIPLE record");
1553      TheModule->setTargetTriple(S);
1554      break;
1555    }
1556    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1557      std::string S;
1558      if (ConvertToString(Record, 0, S))
1559        return Error("Invalid MODULE_CODE_DATALAYOUT record");
1560      TheModule->setDataLayout(S);
1561      break;
1562    }
1563    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1564      std::string S;
1565      if (ConvertToString(Record, 0, S))
1566        return Error("Invalid MODULE_CODE_ASM record");
1567      TheModule->setModuleInlineAsm(S);
1568      break;
1569    }
1570    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1571      std::string S;
1572      if (ConvertToString(Record, 0, S))
1573        return Error("Invalid MODULE_CODE_DEPLIB record");
1574      TheModule->addLibrary(S);
1575      break;
1576    }
1577    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1578      std::string S;
1579      if (ConvertToString(Record, 0, S))
1580        return Error("Invalid MODULE_CODE_SECTIONNAME record");
1581      SectionTable.push_back(S);
1582      break;
1583    }
1584    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1585      std::string S;
1586      if (ConvertToString(Record, 0, S))
1587        return Error("Invalid MODULE_CODE_GCNAME record");
1588      GCTable.push_back(S);
1589      break;
1590    }
1591    // GLOBALVAR: [pointer type, isconst, initid,
1592    //             linkage, alignment, section, visibility, threadlocal,
1593    //             unnamed_addr]
1594    case bitc::MODULE_CODE_GLOBALVAR: {
1595      if (Record.size() < 6)
1596        return Error("Invalid MODULE_CODE_GLOBALVAR record");
1597      Type *Ty = getTypeByID(Record[0]);
1598      if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1599      if (!Ty->isPointerTy())
1600        return Error("Global not a pointer type!");
1601      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1602      Ty = cast<PointerType>(Ty)->getElementType();
1603
1604      bool isConstant = Record[1];
1605      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1606      unsigned Alignment = (1 << Record[4]) >> 1;
1607      std::string Section;
1608      if (Record[5]) {
1609        if (Record[5]-1 >= SectionTable.size())
1610          return Error("Invalid section ID");
1611        Section = SectionTable[Record[5]-1];
1612      }
1613      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1614      if (Record.size() > 6)
1615        Visibility = GetDecodedVisibility(Record[6]);
1616      bool isThreadLocal = false;
1617      if (Record.size() > 7)
1618        isThreadLocal = Record[7];
1619
1620      bool UnnamedAddr = false;
1621      if (Record.size() > 8)
1622        UnnamedAddr = Record[8];
1623
1624      GlobalVariable *NewGV =
1625        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1626                           isThreadLocal, AddressSpace);
1627      NewGV->setAlignment(Alignment);
1628      if (!Section.empty())
1629        NewGV->setSection(Section);
1630      NewGV->setVisibility(Visibility);
1631      NewGV->setThreadLocal(isThreadLocal);
1632      NewGV->setUnnamedAddr(UnnamedAddr);
1633
1634      ValueList.push_back(NewGV);
1635
1636      // Remember which value to use for the global initializer.
1637      if (unsigned InitID = Record[2])
1638        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1639      break;
1640    }
1641    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1642    //             alignment, section, visibility, gc, unnamed_addr]
1643    case bitc::MODULE_CODE_FUNCTION: {
1644      if (Record.size() < 8)
1645        return Error("Invalid MODULE_CODE_FUNCTION record");
1646      Type *Ty = getTypeByID(Record[0]);
1647      if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1648      if (!Ty->isPointerTy())
1649        return Error("Function not a pointer type!");
1650      FunctionType *FTy =
1651        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1652      if (!FTy)
1653        return Error("Function not a pointer to function type!");
1654
1655      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1656                                        "", TheModule);
1657
1658      Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1659      bool isProto = Record[2];
1660      Func->setLinkage(GetDecodedLinkage(Record[3]));
1661      Func->setAttributes(getAttributes(Record[4]));
1662
1663      Func->setAlignment((1 << Record[5]) >> 1);
1664      if (Record[6]) {
1665        if (Record[6]-1 >= SectionTable.size())
1666          return Error("Invalid section ID");
1667        Func->setSection(SectionTable[Record[6]-1]);
1668      }
1669      Func->setVisibility(GetDecodedVisibility(Record[7]));
1670      if (Record.size() > 8 && Record[8]) {
1671        if (Record[8]-1 > GCTable.size())
1672          return Error("Invalid GC ID");
1673        Func->setGC(GCTable[Record[8]-1].c_str());
1674      }
1675      bool UnnamedAddr = false;
1676      if (Record.size() > 9)
1677        UnnamedAddr = Record[9];
1678      Func->setUnnamedAddr(UnnamedAddr);
1679      ValueList.push_back(Func);
1680
1681      // If this is a function with a body, remember the prototype we are
1682      // creating now, so that we can match up the body with them later.
1683      if (!isProto) {
1684        FunctionsWithBodies.push_back(Func);
1685        if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1686      }
1687      break;
1688    }
1689    // ALIAS: [alias type, aliasee val#, linkage]
1690    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1691    case bitc::MODULE_CODE_ALIAS: {
1692      if (Record.size() < 3)
1693        return Error("Invalid MODULE_ALIAS record");
1694      Type *Ty = getTypeByID(Record[0]);
1695      if (!Ty) return Error("Invalid MODULE_ALIAS record");
1696      if (!Ty->isPointerTy())
1697        return Error("Function not a pointer type!");
1698
1699      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1700                                           "", 0, TheModule);
1701      // Old bitcode files didn't have visibility field.
1702      if (Record.size() > 3)
1703        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1704      ValueList.push_back(NewGA);
1705      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1706      break;
1707    }
1708    /// MODULE_CODE_PURGEVALS: [numvals]
1709    case bitc::MODULE_CODE_PURGEVALS:
1710      // Trim down the value list to the specified size.
1711      if (Record.size() < 1 || Record[0] > ValueList.size())
1712        return Error("Invalid MODULE_PURGEVALS record");
1713      ValueList.shrinkTo(Record[0]);
1714      break;
1715    }
1716    Record.clear();
1717  }
1718
1719  return Error("Premature end of bitstream");
1720}
1721
1722bool BitcodeReader::ParseBitcodeInto(Module *M) {
1723  TheModule = 0;
1724
1725  if (InitStream()) return true;
1726
1727  // Sniff for the signature.
1728  if (Stream.Read(8) != 'B' ||
1729      Stream.Read(8) != 'C' ||
1730      Stream.Read(4) != 0x0 ||
1731      Stream.Read(4) != 0xC ||
1732      Stream.Read(4) != 0xE ||
1733      Stream.Read(4) != 0xD)
1734    return Error("Invalid bitcode signature");
1735
1736  // We expect a number of well-defined blocks, though we don't necessarily
1737  // need to understand them all.
1738  while (!Stream.AtEndOfStream()) {
1739    unsigned Code = Stream.ReadCode();
1740
1741    if (Code != bitc::ENTER_SUBBLOCK) {
1742
1743      // The ranlib in xcode 4 will align archive members by appending newlines
1744      // to the end of them. If this file size is a multiple of 4 but not 8, we
1745      // have to read and ignore these final 4 bytes :-(
1746      if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1747          Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1748	  Stream.AtEndOfStream())
1749        return false;
1750
1751      return Error("Invalid record at top-level");
1752    }
1753
1754    unsigned BlockID = Stream.ReadSubBlockID();
1755
1756    // We only know the MODULE subblock ID.
1757    switch (BlockID) {
1758    case bitc::BLOCKINFO_BLOCK_ID:
1759      if (Stream.ReadBlockInfoBlock())
1760        return Error("Malformed BlockInfoBlock");
1761      break;
1762    case bitc::MODULE_BLOCK_ID:
1763      // Reject multiple MODULE_BLOCK's in a single bitstream.
1764      if (TheModule)
1765        return Error("Multiple MODULE_BLOCKs in same stream");
1766      TheModule = M;
1767      if (ParseModule(false))
1768        return true;
1769      if (LazyStreamer) return false;
1770      break;
1771    default:
1772      if (Stream.SkipBlock())
1773        return Error("Malformed block record");
1774      break;
1775    }
1776  }
1777
1778  return false;
1779}
1780
1781bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1782  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1783    return Error("Malformed block record");
1784
1785  SmallVector<uint64_t, 64> Record;
1786
1787  // Read all the records for this module.
1788  while (!Stream.AtEndOfStream()) {
1789    unsigned Code = Stream.ReadCode();
1790    if (Code == bitc::END_BLOCK) {
1791      if (Stream.ReadBlockEnd())
1792        return Error("Error at end of module block");
1793
1794      return false;
1795    }
1796
1797    if (Code == bitc::ENTER_SUBBLOCK) {
1798      switch (Stream.ReadSubBlockID()) {
1799      default:  // Skip unknown content.
1800        if (Stream.SkipBlock())
1801          return Error("Malformed block record");
1802        break;
1803      }
1804      continue;
1805    }
1806
1807    if (Code == bitc::DEFINE_ABBREV) {
1808      Stream.ReadAbbrevRecord();
1809      continue;
1810    }
1811
1812    // Read a record.
1813    switch (Stream.ReadRecord(Code, Record)) {
1814    default: break;  // Default behavior, ignore unknown content.
1815    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1816      if (Record.size() < 1)
1817        return Error("Malformed MODULE_CODE_VERSION");
1818      // Only version #0 is supported so far.
1819      if (Record[0] != 0)
1820        return Error("Unknown bitstream version!");
1821      break;
1822    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1823      std::string S;
1824      if (ConvertToString(Record, 0, S))
1825        return Error("Invalid MODULE_CODE_TRIPLE record");
1826      Triple = S;
1827      break;
1828    }
1829    }
1830    Record.clear();
1831  }
1832
1833  return Error("Premature end of bitstream");
1834}
1835
1836bool BitcodeReader::ParseTriple(std::string &Triple) {
1837  if (InitStream()) return true;
1838
1839  // Sniff for the signature.
1840  if (Stream.Read(8) != 'B' ||
1841      Stream.Read(8) != 'C' ||
1842      Stream.Read(4) != 0x0 ||
1843      Stream.Read(4) != 0xC ||
1844      Stream.Read(4) != 0xE ||
1845      Stream.Read(4) != 0xD)
1846    return Error("Invalid bitcode signature");
1847
1848  // We expect a number of well-defined blocks, though we don't necessarily
1849  // need to understand them all.
1850  while (!Stream.AtEndOfStream()) {
1851    unsigned Code = Stream.ReadCode();
1852
1853    if (Code != bitc::ENTER_SUBBLOCK)
1854      return Error("Invalid record at top-level");
1855
1856    unsigned BlockID = Stream.ReadSubBlockID();
1857
1858    // We only know the MODULE subblock ID.
1859    switch (BlockID) {
1860    case bitc::MODULE_BLOCK_ID:
1861      if (ParseModuleTriple(Triple))
1862        return true;
1863      break;
1864    default:
1865      if (Stream.SkipBlock())
1866        return Error("Malformed block record");
1867      break;
1868    }
1869  }
1870
1871  return false;
1872}
1873
1874/// ParseMetadataAttachment - Parse metadata attachments.
1875bool BitcodeReader::ParseMetadataAttachment() {
1876  if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1877    return Error("Malformed block record");
1878
1879  SmallVector<uint64_t, 64> Record;
1880  while(1) {
1881    unsigned Code = Stream.ReadCode();
1882    if (Code == bitc::END_BLOCK) {
1883      if (Stream.ReadBlockEnd())
1884        return Error("Error at end of PARAMATTR block");
1885      break;
1886    }
1887    if (Code == bitc::DEFINE_ABBREV) {
1888      Stream.ReadAbbrevRecord();
1889      continue;
1890    }
1891    // Read a metadata attachment record.
1892    Record.clear();
1893    switch (Stream.ReadRecord(Code, Record)) {
1894    default:  // Default behavior: ignore.
1895      break;
1896    case bitc::METADATA_ATTACHMENT: {
1897      unsigned RecordLength = Record.size();
1898      if (Record.empty() || (RecordLength - 1) % 2 == 1)
1899        return Error ("Invalid METADATA_ATTACHMENT reader!");
1900      Instruction *Inst = InstructionList[Record[0]];
1901      for (unsigned i = 1; i != RecordLength; i = i+2) {
1902        unsigned Kind = Record[i];
1903        DenseMap<unsigned, unsigned>::iterator I =
1904          MDKindMap.find(Kind);
1905        if (I == MDKindMap.end())
1906          return Error("Invalid metadata kind ID");
1907        Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1908        Inst->setMetadata(I->second, cast<MDNode>(Node));
1909      }
1910      break;
1911    }
1912    }
1913  }
1914  return false;
1915}
1916
1917/// ParseFunctionBody - Lazily parse the specified function body block.
1918bool BitcodeReader::ParseFunctionBody(Function *F) {
1919  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1920    return Error("Malformed block record");
1921
1922  InstructionList.clear();
1923  unsigned ModuleValueListSize = ValueList.size();
1924  unsigned ModuleMDValueListSize = MDValueList.size();
1925
1926  // Add all the function arguments to the value table.
1927  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1928    ValueList.push_back(I);
1929
1930  unsigned NextValueNo = ValueList.size();
1931  BasicBlock *CurBB = 0;
1932  unsigned CurBBNo = 0;
1933
1934  DebugLoc LastLoc;
1935
1936  // Read all the records.
1937  SmallVector<uint64_t, 64> Record;
1938  while (1) {
1939    unsigned Code = Stream.ReadCode();
1940    if (Code == bitc::END_BLOCK) {
1941      if (Stream.ReadBlockEnd())
1942        return Error("Error at end of function block");
1943      break;
1944    }
1945
1946    if (Code == bitc::ENTER_SUBBLOCK) {
1947      switch (Stream.ReadSubBlockID()) {
1948      default:  // Skip unknown content.
1949        if (Stream.SkipBlock())
1950          return Error("Malformed block record");
1951        break;
1952      case bitc::CONSTANTS_BLOCK_ID:
1953        if (ParseConstants()) return true;
1954        NextValueNo = ValueList.size();
1955        break;
1956      case bitc::VALUE_SYMTAB_BLOCK_ID:
1957        if (ParseValueSymbolTable()) return true;
1958        break;
1959      case bitc::METADATA_ATTACHMENT_ID:
1960        if (ParseMetadataAttachment()) return true;
1961        break;
1962      case bitc::METADATA_BLOCK_ID:
1963        if (ParseMetadata()) return true;
1964        break;
1965      }
1966      continue;
1967    }
1968
1969    if (Code == bitc::DEFINE_ABBREV) {
1970      Stream.ReadAbbrevRecord();
1971      continue;
1972    }
1973
1974    // Read a record.
1975    Record.clear();
1976    Instruction *I = 0;
1977    unsigned BitCode = Stream.ReadRecord(Code, Record);
1978    switch (BitCode) {
1979    default: // Default behavior: reject
1980      return Error("Unknown instruction");
1981    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1982      if (Record.size() < 1 || Record[0] == 0)
1983        return Error("Invalid DECLAREBLOCKS record");
1984      // Create all the basic blocks for the function.
1985      FunctionBBs.resize(Record[0]);
1986      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1987        FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1988      CurBB = FunctionBBs[0];
1989      continue;
1990
1991    case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
1992      // This record indicates that the last instruction is at the same
1993      // location as the previous instruction with a location.
1994      I = 0;
1995
1996      // Get the last instruction emitted.
1997      if (CurBB && !CurBB->empty())
1998        I = &CurBB->back();
1999      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2000               !FunctionBBs[CurBBNo-1]->empty())
2001        I = &FunctionBBs[CurBBNo-1]->back();
2002
2003      if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2004      I->setDebugLoc(LastLoc);
2005      I = 0;
2006      continue;
2007
2008    case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
2009      I = 0;     // Get the last instruction emitted.
2010      if (CurBB && !CurBB->empty())
2011        I = &CurBB->back();
2012      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2013               !FunctionBBs[CurBBNo-1]->empty())
2014        I = &FunctionBBs[CurBBNo-1]->back();
2015      if (I == 0 || Record.size() < 4)
2016        return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2017
2018      unsigned Line = Record[0], Col = Record[1];
2019      unsigned ScopeID = Record[2], IAID = Record[3];
2020
2021      MDNode *Scope = 0, *IA = 0;
2022      if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2023      if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2024      LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2025      I->setDebugLoc(LastLoc);
2026      I = 0;
2027      continue;
2028    }
2029
2030    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
2031      unsigned OpNum = 0;
2032      Value *LHS, *RHS;
2033      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2034          getValue(Record, OpNum, LHS->getType(), RHS) ||
2035          OpNum+1 > Record.size())
2036        return Error("Invalid BINOP record");
2037
2038      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2039      if (Opc == -1) return Error("Invalid BINOP record");
2040      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2041      InstructionList.push_back(I);
2042      if (OpNum < Record.size()) {
2043        if (Opc == Instruction::Add ||
2044            Opc == Instruction::Sub ||
2045            Opc == Instruction::Mul ||
2046            Opc == Instruction::Shl) {
2047          if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2048            cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2049          if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2050            cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2051        } else if (Opc == Instruction::SDiv ||
2052                   Opc == Instruction::UDiv ||
2053                   Opc == Instruction::LShr ||
2054                   Opc == Instruction::AShr) {
2055          if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2056            cast<BinaryOperator>(I)->setIsExact(true);
2057        }
2058      }
2059      break;
2060    }
2061    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2062      unsigned OpNum = 0;
2063      Value *Op;
2064      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2065          OpNum+2 != Record.size())
2066        return Error("Invalid CAST record");
2067
2068      Type *ResTy = getTypeByID(Record[OpNum]);
2069      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2070      if (Opc == -1 || ResTy == 0)
2071        return Error("Invalid CAST record");
2072      I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2073      InstructionList.push_back(I);
2074      break;
2075    }
2076    case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2077    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2078      unsigned OpNum = 0;
2079      Value *BasePtr;
2080      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2081        return Error("Invalid GEP record");
2082
2083      SmallVector<Value*, 16> GEPIdx;
2084      while (OpNum != Record.size()) {
2085        Value *Op;
2086        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2087          return Error("Invalid GEP record");
2088        GEPIdx.push_back(Op);
2089      }
2090
2091      I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2092      InstructionList.push_back(I);
2093      if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2094        cast<GetElementPtrInst>(I)->setIsInBounds(true);
2095      break;
2096    }
2097
2098    case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2099                                       // EXTRACTVAL: [opty, opval, n x indices]
2100      unsigned OpNum = 0;
2101      Value *Agg;
2102      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2103        return Error("Invalid EXTRACTVAL record");
2104
2105      SmallVector<unsigned, 4> EXTRACTVALIdx;
2106      for (unsigned RecSize = Record.size();
2107           OpNum != RecSize; ++OpNum) {
2108        uint64_t Index = Record[OpNum];
2109        if ((unsigned)Index != Index)
2110          return Error("Invalid EXTRACTVAL index");
2111        EXTRACTVALIdx.push_back((unsigned)Index);
2112      }
2113
2114      I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2115      InstructionList.push_back(I);
2116      break;
2117    }
2118
2119    case bitc::FUNC_CODE_INST_INSERTVAL: {
2120                           // INSERTVAL: [opty, opval, opty, opval, n x indices]
2121      unsigned OpNum = 0;
2122      Value *Agg;
2123      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2124        return Error("Invalid INSERTVAL record");
2125      Value *Val;
2126      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2127        return Error("Invalid INSERTVAL record");
2128
2129      SmallVector<unsigned, 4> INSERTVALIdx;
2130      for (unsigned RecSize = Record.size();
2131           OpNum != RecSize; ++OpNum) {
2132        uint64_t Index = Record[OpNum];
2133        if ((unsigned)Index != Index)
2134          return Error("Invalid INSERTVAL index");
2135        INSERTVALIdx.push_back((unsigned)Index);
2136      }
2137
2138      I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2139      InstructionList.push_back(I);
2140      break;
2141    }
2142
2143    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2144      // obsolete form of select
2145      // handles select i1 ... in old bitcode
2146      unsigned OpNum = 0;
2147      Value *TrueVal, *FalseVal, *Cond;
2148      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2149          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2150          getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2151        return Error("Invalid SELECT record");
2152
2153      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2154      InstructionList.push_back(I);
2155      break;
2156    }
2157
2158    case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2159      // new form of select
2160      // handles select i1 or select [N x i1]
2161      unsigned OpNum = 0;
2162      Value *TrueVal, *FalseVal, *Cond;
2163      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2164          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2165          getValueTypePair(Record, OpNum, NextValueNo, Cond))
2166        return Error("Invalid SELECT record");
2167
2168      // select condition can be either i1 or [N x i1]
2169      if (VectorType* vector_type =
2170          dyn_cast<VectorType>(Cond->getType())) {
2171        // expect <n x i1>
2172        if (vector_type->getElementType() != Type::getInt1Ty(Context))
2173          return Error("Invalid SELECT condition type");
2174      } else {
2175        // expect i1
2176        if (Cond->getType() != Type::getInt1Ty(Context))
2177          return Error("Invalid SELECT condition type");
2178      }
2179
2180      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2181      InstructionList.push_back(I);
2182      break;
2183    }
2184
2185    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2186      unsigned OpNum = 0;
2187      Value *Vec, *Idx;
2188      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2189          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2190        return Error("Invalid EXTRACTELT record");
2191      I = ExtractElementInst::Create(Vec, Idx);
2192      InstructionList.push_back(I);
2193      break;
2194    }
2195
2196    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2197      unsigned OpNum = 0;
2198      Value *Vec, *Elt, *Idx;
2199      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2200          getValue(Record, OpNum,
2201                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2202          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2203        return Error("Invalid INSERTELT record");
2204      I = InsertElementInst::Create(Vec, Elt, Idx);
2205      InstructionList.push_back(I);
2206      break;
2207    }
2208
2209    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2210      unsigned OpNum = 0;
2211      Value *Vec1, *Vec2, *Mask;
2212      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2213          getValue(Record, OpNum, Vec1->getType(), Vec2))
2214        return Error("Invalid SHUFFLEVEC record");
2215
2216      if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2217        return Error("Invalid SHUFFLEVEC record");
2218      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2219      InstructionList.push_back(I);
2220      break;
2221    }
2222
2223    case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2224      // Old form of ICmp/FCmp returning bool
2225      // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2226      // both legal on vectors but had different behaviour.
2227    case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2228      // FCmp/ICmp returning bool or vector of bool
2229
2230      unsigned OpNum = 0;
2231      Value *LHS, *RHS;
2232      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2233          getValue(Record, OpNum, LHS->getType(), RHS) ||
2234          OpNum+1 != Record.size())
2235        return Error("Invalid CMP record");
2236
2237      if (LHS->getType()->isFPOrFPVectorTy())
2238        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2239      else
2240        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2241      InstructionList.push_back(I);
2242      break;
2243    }
2244
2245    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2246      {
2247        unsigned Size = Record.size();
2248        if (Size == 0) {
2249          I = ReturnInst::Create(Context);
2250          InstructionList.push_back(I);
2251          break;
2252        }
2253
2254        unsigned OpNum = 0;
2255        Value *Op = NULL;
2256        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2257          return Error("Invalid RET record");
2258        if (OpNum != Record.size())
2259          return Error("Invalid RET record");
2260
2261        I = ReturnInst::Create(Context, Op);
2262        InstructionList.push_back(I);
2263        break;
2264      }
2265    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2266      if (Record.size() != 1 && Record.size() != 3)
2267        return Error("Invalid BR record");
2268      BasicBlock *TrueDest = getBasicBlock(Record[0]);
2269      if (TrueDest == 0)
2270        return Error("Invalid BR record");
2271
2272      if (Record.size() == 1) {
2273        I = BranchInst::Create(TrueDest);
2274        InstructionList.push_back(I);
2275      }
2276      else {
2277        BasicBlock *FalseDest = getBasicBlock(Record[1]);
2278        Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2279        if (FalseDest == 0 || Cond == 0)
2280          return Error("Invalid BR record");
2281        I = BranchInst::Create(TrueDest, FalseDest, Cond);
2282        InstructionList.push_back(I);
2283      }
2284      break;
2285    }
2286    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2287      // Check magic
2288      if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2289        // New SwitchInst format with case ranges.
2290
2291        Type *OpTy = getTypeByID(Record[1]);
2292        unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2293
2294        Value *Cond = getFnValueByID(Record[2], OpTy);
2295        BasicBlock *Default = getBasicBlock(Record[3]);
2296        if (OpTy == 0 || Cond == 0 || Default == 0)
2297          return Error("Invalid SWITCH record");
2298
2299        unsigned NumCases = Record[4];
2300
2301        SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2302
2303        unsigned CurIdx = 5;
2304        for (unsigned i = 0; i != NumCases; ++i) {
2305          CRSBuilder CaseBuilder;
2306          unsigned NumItems = Record[CurIdx++];
2307          for (unsigned ci = 0; ci != NumItems; ++ci) {
2308            bool isSingleNumber = Record[CurIdx++];
2309
2310            APInt Low;
2311            unsigned ActiveWords = 1;
2312            if (ValueBitWidth > 64)
2313              ActiveWords = Record[CurIdx++];
2314            Low = ReadWideAPInt(&Record[CurIdx], ActiveWords, ValueBitWidth);
2315            CurIdx += ActiveWords;
2316
2317            if (!isSingleNumber) {
2318              ActiveWords = 1;
2319              if (ValueBitWidth > 64)
2320                ActiveWords = Record[CurIdx++];
2321              APInt High =
2322                  ReadWideAPInt(&Record[CurIdx], ActiveWords, ValueBitWidth);
2323              CaseBuilder.add(cast<ConstantInt>(ConstantInt::get(OpTy, Low)),
2324                              cast<ConstantInt>(ConstantInt::get(OpTy, High)));
2325              CurIdx += ActiveWords;
2326            } else
2327              CaseBuilder.add(cast<ConstantInt>(ConstantInt::get(OpTy, Low)));
2328          }
2329          BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2330          ConstantRangesSet Case = CaseBuilder.getCase();
2331          SI->addCase(Case, DestBB);
2332        }
2333        uint16_t Hash = SI->Hash();
2334        if (Hash != (Record[0] & 0xFFFF))
2335          return Error("Invalid SWITCH record");
2336        I = SI;
2337        break;
2338      }
2339
2340      // Old SwitchInst format without case ranges.
2341
2342      if (Record.size() < 3 || (Record.size() & 1) == 0)
2343        return Error("Invalid SWITCH record");
2344      Type *OpTy = getTypeByID(Record[0]);
2345      Value *Cond = getFnValueByID(Record[1], OpTy);
2346      BasicBlock *Default = getBasicBlock(Record[2]);
2347      if (OpTy == 0 || Cond == 0 || Default == 0)
2348        return Error("Invalid SWITCH record");
2349      unsigned NumCases = (Record.size()-3)/2;
2350      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2351      InstructionList.push_back(SI);
2352      for (unsigned i = 0, e = NumCases; i != e; ++i) {
2353        ConstantInt *CaseVal =
2354          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2355        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2356        if (CaseVal == 0 || DestBB == 0) {
2357          delete SI;
2358          return Error("Invalid SWITCH record!");
2359        }
2360        SI->addCase(CaseVal, DestBB);
2361      }
2362      I = SI;
2363      break;
2364    }
2365    case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2366      if (Record.size() < 2)
2367        return Error("Invalid INDIRECTBR record");
2368      Type *OpTy = getTypeByID(Record[0]);
2369      Value *Address = getFnValueByID(Record[1], OpTy);
2370      if (OpTy == 0 || Address == 0)
2371        return Error("Invalid INDIRECTBR record");
2372      unsigned NumDests = Record.size()-2;
2373      IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2374      InstructionList.push_back(IBI);
2375      for (unsigned i = 0, e = NumDests; i != e; ++i) {
2376        if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2377          IBI->addDestination(DestBB);
2378        } else {
2379          delete IBI;
2380          return Error("Invalid INDIRECTBR record!");
2381        }
2382      }
2383      I = IBI;
2384      break;
2385    }
2386
2387    case bitc::FUNC_CODE_INST_INVOKE: {
2388      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2389      if (Record.size() < 4) return Error("Invalid INVOKE record");
2390      AttrListPtr PAL = getAttributes(Record[0]);
2391      unsigned CCInfo = Record[1];
2392      BasicBlock *NormalBB = getBasicBlock(Record[2]);
2393      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2394
2395      unsigned OpNum = 4;
2396      Value *Callee;
2397      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2398        return Error("Invalid INVOKE record");
2399
2400      PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2401      FunctionType *FTy = !CalleeTy ? 0 :
2402        dyn_cast<FunctionType>(CalleeTy->getElementType());
2403
2404      // Check that the right number of fixed parameters are here.
2405      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2406          Record.size() < OpNum+FTy->getNumParams())
2407        return Error("Invalid INVOKE record");
2408
2409      SmallVector<Value*, 16> Ops;
2410      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2411        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2412        if (Ops.back() == 0) return Error("Invalid INVOKE record");
2413      }
2414
2415      if (!FTy->isVarArg()) {
2416        if (Record.size() != OpNum)
2417          return Error("Invalid INVOKE record");
2418      } else {
2419        // Read type/value pairs for varargs params.
2420        while (OpNum != Record.size()) {
2421          Value *Op;
2422          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2423            return Error("Invalid INVOKE record");
2424          Ops.push_back(Op);
2425        }
2426      }
2427
2428      I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2429      InstructionList.push_back(I);
2430      cast<InvokeInst>(I)->setCallingConv(
2431        static_cast<CallingConv::ID>(CCInfo));
2432      cast<InvokeInst>(I)->setAttributes(PAL);
2433      break;
2434    }
2435    case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2436      unsigned Idx = 0;
2437      Value *Val = 0;
2438      if (getValueTypePair(Record, Idx, NextValueNo, Val))
2439        return Error("Invalid RESUME record");
2440      I = ResumeInst::Create(Val);
2441      InstructionList.push_back(I);
2442      break;
2443    }
2444    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2445      I = new UnreachableInst(Context);
2446      InstructionList.push_back(I);
2447      break;
2448    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2449      if (Record.size() < 1 || ((Record.size()-1)&1))
2450        return Error("Invalid PHI record");
2451      Type *Ty = getTypeByID(Record[0]);
2452      if (!Ty) return Error("Invalid PHI record");
2453
2454      PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2455      InstructionList.push_back(PN);
2456
2457      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2458        Value *V = getFnValueByID(Record[1+i], Ty);
2459        BasicBlock *BB = getBasicBlock(Record[2+i]);
2460        if (!V || !BB) return Error("Invalid PHI record");
2461        PN->addIncoming(V, BB);
2462      }
2463      I = PN;
2464      break;
2465    }
2466
2467    case bitc::FUNC_CODE_INST_LANDINGPAD: {
2468      // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2469      unsigned Idx = 0;
2470      if (Record.size() < 4)
2471        return Error("Invalid LANDINGPAD record");
2472      Type *Ty = getTypeByID(Record[Idx++]);
2473      if (!Ty) return Error("Invalid LANDINGPAD record");
2474      Value *PersFn = 0;
2475      if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2476        return Error("Invalid LANDINGPAD record");
2477
2478      bool IsCleanup = !!Record[Idx++];
2479      unsigned NumClauses = Record[Idx++];
2480      LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2481      LP->setCleanup(IsCleanup);
2482      for (unsigned J = 0; J != NumClauses; ++J) {
2483        LandingPadInst::ClauseType CT =
2484          LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2485        Value *Val;
2486
2487        if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2488          delete LP;
2489          return Error("Invalid LANDINGPAD record");
2490        }
2491
2492        assert((CT != LandingPadInst::Catch ||
2493                !isa<ArrayType>(Val->getType())) &&
2494               "Catch clause has a invalid type!");
2495        assert((CT != LandingPadInst::Filter ||
2496                isa<ArrayType>(Val->getType())) &&
2497               "Filter clause has invalid type!");
2498        LP->addClause(Val);
2499      }
2500
2501      I = LP;
2502      InstructionList.push_back(I);
2503      break;
2504    }
2505
2506    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2507      if (Record.size() != 4)
2508        return Error("Invalid ALLOCA record");
2509      PointerType *Ty =
2510        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2511      Type *OpTy = getTypeByID(Record[1]);
2512      Value *Size = getFnValueByID(Record[2], OpTy);
2513      unsigned Align = Record[3];
2514      if (!Ty || !Size) return Error("Invalid ALLOCA record");
2515      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2516      InstructionList.push_back(I);
2517      break;
2518    }
2519    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2520      unsigned OpNum = 0;
2521      Value *Op;
2522      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2523          OpNum+2 != Record.size())
2524        return Error("Invalid LOAD record");
2525
2526      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2527      InstructionList.push_back(I);
2528      break;
2529    }
2530    case bitc::FUNC_CODE_INST_LOADATOMIC: {
2531       // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2532      unsigned OpNum = 0;
2533      Value *Op;
2534      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2535          OpNum+4 != Record.size())
2536        return Error("Invalid LOADATOMIC record");
2537
2538
2539      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2540      if (Ordering == NotAtomic || Ordering == Release ||
2541          Ordering == AcquireRelease)
2542        return Error("Invalid LOADATOMIC record");
2543      if (Ordering != NotAtomic && Record[OpNum] == 0)
2544        return Error("Invalid LOADATOMIC record");
2545      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2546
2547      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2548                       Ordering, SynchScope);
2549      InstructionList.push_back(I);
2550      break;
2551    }
2552    case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2553      unsigned OpNum = 0;
2554      Value *Val, *Ptr;
2555      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2556          getValue(Record, OpNum,
2557                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2558          OpNum+2 != Record.size())
2559        return Error("Invalid STORE record");
2560
2561      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2562      InstructionList.push_back(I);
2563      break;
2564    }
2565    case bitc::FUNC_CODE_INST_STOREATOMIC: {
2566      // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2567      unsigned OpNum = 0;
2568      Value *Val, *Ptr;
2569      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2570          getValue(Record, OpNum,
2571                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2572          OpNum+4 != Record.size())
2573        return Error("Invalid STOREATOMIC record");
2574
2575      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2576      if (Ordering == NotAtomic || Ordering == Acquire ||
2577          Ordering == AcquireRelease)
2578        return Error("Invalid STOREATOMIC record");
2579      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2580      if (Ordering != NotAtomic && Record[OpNum] == 0)
2581        return Error("Invalid STOREATOMIC record");
2582
2583      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2584                        Ordering, SynchScope);
2585      InstructionList.push_back(I);
2586      break;
2587    }
2588    case bitc::FUNC_CODE_INST_CMPXCHG: {
2589      // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2590      unsigned OpNum = 0;
2591      Value *Ptr, *Cmp, *New;
2592      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2593          getValue(Record, OpNum,
2594                    cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2595          getValue(Record, OpNum,
2596                    cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2597          OpNum+3 != Record.size())
2598        return Error("Invalid CMPXCHG record");
2599      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2600      if (Ordering == NotAtomic || Ordering == Unordered)
2601        return Error("Invalid CMPXCHG record");
2602      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2603      I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2604      cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2605      InstructionList.push_back(I);
2606      break;
2607    }
2608    case bitc::FUNC_CODE_INST_ATOMICRMW: {
2609      // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2610      unsigned OpNum = 0;
2611      Value *Ptr, *Val;
2612      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2613          getValue(Record, OpNum,
2614                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2615          OpNum+4 != Record.size())
2616        return Error("Invalid ATOMICRMW record");
2617      AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2618      if (Operation < AtomicRMWInst::FIRST_BINOP ||
2619          Operation > AtomicRMWInst::LAST_BINOP)
2620        return Error("Invalid ATOMICRMW record");
2621      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2622      if (Ordering == NotAtomic || Ordering == Unordered)
2623        return Error("Invalid ATOMICRMW record");
2624      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2625      I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2626      cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2627      InstructionList.push_back(I);
2628      break;
2629    }
2630    case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2631      if (2 != Record.size())
2632        return Error("Invalid FENCE record");
2633      AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2634      if (Ordering == NotAtomic || Ordering == Unordered ||
2635          Ordering == Monotonic)
2636        return Error("Invalid FENCE record");
2637      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2638      I = new FenceInst(Context, Ordering, SynchScope);
2639      InstructionList.push_back(I);
2640      break;
2641    }
2642    case bitc::FUNC_CODE_INST_CALL: {
2643      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2644      if (Record.size() < 3)
2645        return Error("Invalid CALL record");
2646
2647      AttrListPtr PAL = getAttributes(Record[0]);
2648      unsigned CCInfo = Record[1];
2649
2650      unsigned OpNum = 2;
2651      Value *Callee;
2652      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2653        return Error("Invalid CALL record");
2654
2655      PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2656      FunctionType *FTy = 0;
2657      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2658      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2659        return Error("Invalid CALL record");
2660
2661      SmallVector<Value*, 16> Args;
2662      // Read the fixed params.
2663      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2664        if (FTy->getParamType(i)->isLabelTy())
2665          Args.push_back(getBasicBlock(Record[OpNum]));
2666        else
2667          Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2668        if (Args.back() == 0) return Error("Invalid CALL record");
2669      }
2670
2671      // Read type/value pairs for varargs params.
2672      if (!FTy->isVarArg()) {
2673        if (OpNum != Record.size())
2674          return Error("Invalid CALL record");
2675      } else {
2676        while (OpNum != Record.size()) {
2677          Value *Op;
2678          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2679            return Error("Invalid CALL record");
2680          Args.push_back(Op);
2681        }
2682      }
2683
2684      I = CallInst::Create(Callee, Args);
2685      InstructionList.push_back(I);
2686      cast<CallInst>(I)->setCallingConv(
2687        static_cast<CallingConv::ID>(CCInfo>>1));
2688      cast<CallInst>(I)->setTailCall(CCInfo & 1);
2689      cast<CallInst>(I)->setAttributes(PAL);
2690      break;
2691    }
2692    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2693      if (Record.size() < 3)
2694        return Error("Invalid VAARG record");
2695      Type *OpTy = getTypeByID(Record[0]);
2696      Value *Op = getFnValueByID(Record[1], OpTy);
2697      Type *ResTy = getTypeByID(Record[2]);
2698      if (!OpTy || !Op || !ResTy)
2699        return Error("Invalid VAARG record");
2700      I = new VAArgInst(Op, ResTy);
2701      InstructionList.push_back(I);
2702      break;
2703    }
2704    }
2705
2706    // Add instruction to end of current BB.  If there is no current BB, reject
2707    // this file.
2708    if (CurBB == 0) {
2709      delete I;
2710      return Error("Invalid instruction with no BB");
2711    }
2712    CurBB->getInstList().push_back(I);
2713
2714    // If this was a terminator instruction, move to the next block.
2715    if (isa<TerminatorInst>(I)) {
2716      ++CurBBNo;
2717      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2718    }
2719
2720    // Non-void values get registered in the value table for future use.
2721    if (I && !I->getType()->isVoidTy())
2722      ValueList.AssignValue(I, NextValueNo++);
2723  }
2724
2725  // Check the function list for unresolved values.
2726  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2727    if (A->getParent() == 0) {
2728      // We found at least one unresolved value.  Nuke them all to avoid leaks.
2729      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2730        if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2731          A->replaceAllUsesWith(UndefValue::get(A->getType()));
2732          delete A;
2733        }
2734      }
2735      return Error("Never resolved value found in function!");
2736    }
2737  }
2738
2739  // FIXME: Check for unresolved forward-declared metadata references
2740  // and clean up leaks.
2741
2742  // See if anything took the address of blocks in this function.  If so,
2743  // resolve them now.
2744  DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2745    BlockAddrFwdRefs.find(F);
2746  if (BAFRI != BlockAddrFwdRefs.end()) {
2747    std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2748    for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2749      unsigned BlockIdx = RefList[i].first;
2750      if (BlockIdx >= FunctionBBs.size())
2751        return Error("Invalid blockaddress block #");
2752
2753      GlobalVariable *FwdRef = RefList[i].second;
2754      FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2755      FwdRef->eraseFromParent();
2756    }
2757
2758    BlockAddrFwdRefs.erase(BAFRI);
2759  }
2760
2761  // Trim the value list down to the size it was before we parsed this function.
2762  ValueList.shrinkTo(ModuleValueListSize);
2763  MDValueList.shrinkTo(ModuleMDValueListSize);
2764  std::vector<BasicBlock*>().swap(FunctionBBs);
2765  return false;
2766}
2767
2768/// FindFunctionInStream - Find the function body in the bitcode stream
2769bool BitcodeReader::FindFunctionInStream(Function *F,
2770       DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2771  while (DeferredFunctionInfoIterator->second == 0) {
2772    if (Stream.AtEndOfStream())
2773      return Error("Could not find Function in stream");
2774    // ParseModule will parse the next body in the stream and set its
2775    // position in the DeferredFunctionInfo map.
2776    if (ParseModule(true)) return true;
2777  }
2778  return false;
2779}
2780
2781//===----------------------------------------------------------------------===//
2782// GVMaterializer implementation
2783//===----------------------------------------------------------------------===//
2784
2785
2786bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2787  if (const Function *F = dyn_cast<Function>(GV)) {
2788    return F->isDeclaration() &&
2789      DeferredFunctionInfo.count(const_cast<Function*>(F));
2790  }
2791  return false;
2792}
2793
2794bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2795  Function *F = dyn_cast<Function>(GV);
2796  // If it's not a function or is already material, ignore the request.
2797  if (!F || !F->isMaterializable()) return false;
2798
2799  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2800  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2801  // If its position is recorded as 0, its body is somewhere in the stream
2802  // but we haven't seen it yet.
2803  if (DFII->second == 0)
2804    if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
2805
2806  // Move the bit stream to the saved position of the deferred function body.
2807  Stream.JumpToBit(DFII->second);
2808
2809  if (ParseFunctionBody(F)) {
2810    if (ErrInfo) *ErrInfo = ErrorString;
2811    return true;
2812  }
2813
2814  // Upgrade any old intrinsic calls in the function.
2815  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2816       E = UpgradedIntrinsics.end(); I != E; ++I) {
2817    if (I->first != I->second) {
2818      for (Value::use_iterator UI = I->first->use_begin(),
2819           UE = I->first->use_end(); UI != UE; ) {
2820        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2821          UpgradeIntrinsicCall(CI, I->second);
2822      }
2823    }
2824  }
2825
2826  return false;
2827}
2828
2829bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2830  const Function *F = dyn_cast<Function>(GV);
2831  if (!F || F->isDeclaration())
2832    return false;
2833  return DeferredFunctionInfo.count(const_cast<Function*>(F));
2834}
2835
2836void BitcodeReader::Dematerialize(GlobalValue *GV) {
2837  Function *F = dyn_cast<Function>(GV);
2838  // If this function isn't dematerializable, this is a noop.
2839  if (!F || !isDematerializable(F))
2840    return;
2841
2842  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2843
2844  // Just forget the function body, we can remat it later.
2845  F->deleteBody();
2846}
2847
2848
2849bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2850  assert(M == TheModule &&
2851         "Can only Materialize the Module this BitcodeReader is attached to.");
2852  // Iterate over the module, deserializing any functions that are still on
2853  // disk.
2854  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2855       F != E; ++F)
2856    if (F->isMaterializable() &&
2857        Materialize(F, ErrInfo))
2858      return true;
2859
2860  // At this point, if there are any function bodies, the current bit is
2861  // pointing to the END_BLOCK record after them. Now make sure the rest
2862  // of the bits in the module have been read.
2863  if (NextUnreadBit)
2864    ParseModule(true);
2865
2866  // Upgrade any intrinsic calls that slipped through (should not happen!) and
2867  // delete the old functions to clean up. We can't do this unless the entire
2868  // module is materialized because there could always be another function body
2869  // with calls to the old function.
2870  for (std::vector<std::pair<Function*, Function*> >::iterator I =
2871       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2872    if (I->first != I->second) {
2873      for (Value::use_iterator UI = I->first->use_begin(),
2874           UE = I->first->use_end(); UI != UE; ) {
2875        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2876          UpgradeIntrinsicCall(CI, I->second);
2877      }
2878      if (!I->first->use_empty())
2879        I->first->replaceAllUsesWith(I->second);
2880      I->first->eraseFromParent();
2881    }
2882  }
2883  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2884
2885  return false;
2886}
2887
2888bool BitcodeReader::InitStream() {
2889  if (LazyStreamer) return InitLazyStream();
2890  return InitStreamFromBuffer();
2891}
2892
2893bool BitcodeReader::InitStreamFromBuffer() {
2894  const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2895  const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2896
2897  if (Buffer->getBufferSize() & 3) {
2898    if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2899      return Error("Invalid bitcode signature");
2900    else
2901      return Error("Bitcode stream should be a multiple of 4 bytes in length");
2902  }
2903
2904  // If we have a wrapper header, parse it and ignore the non-bc file contents.
2905  // The magic number is 0x0B17C0DE stored in little endian.
2906  if (isBitcodeWrapper(BufPtr, BufEnd))
2907    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2908      return Error("Invalid bitcode wrapper header");
2909
2910  StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2911  Stream.init(*StreamFile);
2912
2913  return false;
2914}
2915
2916bool BitcodeReader::InitLazyStream() {
2917  // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2918  // see it.
2919  StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2920  StreamFile.reset(new BitstreamReader(Bytes));
2921  Stream.init(*StreamFile);
2922
2923  unsigned char buf[16];
2924  if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2925    return Error("Bitcode stream must be at least 16 bytes in length");
2926
2927  if (!isBitcode(buf, buf + 16))
2928    return Error("Invalid bitcode signature");
2929
2930  if (isBitcodeWrapper(buf, buf + 4)) {
2931    const unsigned char *bitcodeStart = buf;
2932    const unsigned char *bitcodeEnd = buf + 16;
2933    SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2934    Bytes->dropLeadingBytes(bitcodeStart - buf);
2935    Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2936  }
2937  return false;
2938}
2939
2940//===----------------------------------------------------------------------===//
2941// External interface
2942//===----------------------------------------------------------------------===//
2943
2944/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2945///
2946Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2947                                   LLVMContext& Context,
2948                                   std::string *ErrMsg) {
2949  Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2950  BitcodeReader *R = new BitcodeReader(Buffer, Context);
2951  M->setMaterializer(R);
2952  if (R->ParseBitcodeInto(M)) {
2953    if (ErrMsg)
2954      *ErrMsg = R->getErrorString();
2955
2956    delete M;  // Also deletes R.
2957    return 0;
2958  }
2959  // Have the BitcodeReader dtor delete 'Buffer'.
2960  R->setBufferOwned(true);
2961
2962  R->materializeForwardReferencedFunctions();
2963
2964  return M;
2965}
2966
2967
2968Module *llvm::getStreamedBitcodeModule(const std::string &name,
2969                                       DataStreamer *streamer,
2970                                       LLVMContext &Context,
2971                                       std::string *ErrMsg) {
2972  Module *M = new Module(name, Context);
2973  BitcodeReader *R = new BitcodeReader(streamer, Context);
2974  M->setMaterializer(R);
2975  if (R->ParseBitcodeInto(M)) {
2976    if (ErrMsg)
2977      *ErrMsg = R->getErrorString();
2978    delete M;  // Also deletes R.
2979    return 0;
2980  }
2981  R->setBufferOwned(false); // no buffer to delete
2982  return M;
2983}
2984
2985/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2986/// If an error occurs, return null and fill in *ErrMsg if non-null.
2987Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2988                               std::string *ErrMsg){
2989  Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2990  if (!M) return 0;
2991
2992  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2993  // there was an error.
2994  static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2995
2996  // Read in the entire module, and destroy the BitcodeReader.
2997  if (M->MaterializeAllPermanently(ErrMsg)) {
2998    delete M;
2999    return 0;
3000  }
3001
3002  // TODO: Restore the use-lists to the in-memory state when the bitcode was
3003  // written.  We must defer until the Module has been fully materialized.
3004
3005  return M;
3006}
3007
3008std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3009                                         LLVMContext& Context,
3010                                         std::string *ErrMsg) {
3011  BitcodeReader *R = new BitcodeReader(Buffer, Context);
3012  // Don't let the BitcodeReader dtor delete 'Buffer'.
3013  R->setBufferOwned(false);
3014
3015  std::string Triple("");
3016  if (R->ParseTriple(Triple))
3017    if (ErrMsg)
3018      *ErrMsg = R->getErrorString();
3019
3020  delete R;
3021  return Triple;
3022}
3023