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