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