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