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