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