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