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