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