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