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