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