AsmWriter/Bitcode: MDLexicalBlockFile
[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_STRING: {
1494       std::string String(Record.begin(), Record.end());
1495       llvm::UpgradeMDStringConstant(String);
1496       Metadata *MD = MDString::get(Context, String);
1497       MDValueList.AssignValue(MD, NextMDValueNo++);
1498       break;
1499     }
1500     case bitc::METADATA_KIND: {
1501       if (Record.size() < 2)
1502         return Error("Invalid record");
1503
1504       unsigned Kind = Record[0];
1505       SmallString<8> Name(Record.begin()+1, Record.end());
1506
1507       unsigned NewKind = TheModule->getMDKindID(Name.str());
1508       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1509         return Error("Conflicting METADATA_KIND records");
1510       break;
1511     }
1512     }
1513   }
1514 #undef GET_OR_DISTINCT
1515 }
1516
1517 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1518 /// the LSB for dense VBR encoding.
1519 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1520   if ((V & 1) == 0)
1521     return V >> 1;
1522   if (V != 1)
1523     return -(V >> 1);
1524   // There is no such thing as -0 with integers.  "-0" really means MININT.
1525   return 1ULL << 63;
1526 }
1527
1528 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1529 /// values and aliases that we can.
1530 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1531   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1532   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1533   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1534   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1535
1536   GlobalInitWorklist.swap(GlobalInits);
1537   AliasInitWorklist.swap(AliasInits);
1538   FunctionPrefixWorklist.swap(FunctionPrefixes);
1539   FunctionPrologueWorklist.swap(FunctionPrologues);
1540
1541   while (!GlobalInitWorklist.empty()) {
1542     unsigned ValID = GlobalInitWorklist.back().second;
1543     if (ValID >= ValueList.size()) {
1544       // Not ready to resolve this yet, it requires something later in the file.
1545       GlobalInits.push_back(GlobalInitWorklist.back());
1546     } else {
1547       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1548         GlobalInitWorklist.back().first->setInitializer(C);
1549       else
1550         return Error("Expected a constant");
1551     }
1552     GlobalInitWorklist.pop_back();
1553   }
1554
1555   while (!AliasInitWorklist.empty()) {
1556     unsigned ValID = AliasInitWorklist.back().second;
1557     if (ValID >= ValueList.size()) {
1558       AliasInits.push_back(AliasInitWorklist.back());
1559     } else {
1560       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1561         AliasInitWorklist.back().first->setAliasee(C);
1562       else
1563         return Error("Expected a constant");
1564     }
1565     AliasInitWorklist.pop_back();
1566   }
1567
1568   while (!FunctionPrefixWorklist.empty()) {
1569     unsigned ValID = FunctionPrefixWorklist.back().second;
1570     if (ValID >= ValueList.size()) {
1571       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1572     } else {
1573       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1574         FunctionPrefixWorklist.back().first->setPrefixData(C);
1575       else
1576         return Error("Expected a constant");
1577     }
1578     FunctionPrefixWorklist.pop_back();
1579   }
1580
1581   while (!FunctionPrologueWorklist.empty()) {
1582     unsigned ValID = FunctionPrologueWorklist.back().second;
1583     if (ValID >= ValueList.size()) {
1584       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1585     } else {
1586       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1587         FunctionPrologueWorklist.back().first->setPrologueData(C);
1588       else
1589         return Error("Expected a constant");
1590     }
1591     FunctionPrologueWorklist.pop_back();
1592   }
1593
1594   return std::error_code();
1595 }
1596
1597 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1598   SmallVector<uint64_t, 8> Words(Vals.size());
1599   std::transform(Vals.begin(), Vals.end(), Words.begin(),
1600                  BitcodeReader::decodeSignRotatedValue);
1601
1602   return APInt(TypeBits, Words);
1603 }
1604
1605 std::error_code BitcodeReader::ParseConstants() {
1606   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1607     return Error("Invalid record");
1608
1609   SmallVector<uint64_t, 64> Record;
1610
1611   // Read all the records for this value table.
1612   Type *CurTy = Type::getInt32Ty(Context);
1613   unsigned NextCstNo = ValueList.size();
1614   while (1) {
1615     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1616
1617     switch (Entry.Kind) {
1618     case BitstreamEntry::SubBlock: // Handled for us already.
1619     case BitstreamEntry::Error:
1620       return Error("Malformed block");
1621     case BitstreamEntry::EndBlock:
1622       if (NextCstNo != ValueList.size())
1623         return Error("Invalid ronstant reference");
1624
1625       // Once all the constants have been read, go through and resolve forward
1626       // references.
1627       ValueList.ResolveConstantForwardRefs();
1628       return std::error_code();
1629     case BitstreamEntry::Record:
1630       // The interesting case.
1631       break;
1632     }
1633
1634     // Read a record.
1635     Record.clear();
1636     Value *V = nullptr;
1637     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1638     switch (BitCode) {
1639     default:  // Default behavior: unknown constant
1640     case bitc::CST_CODE_UNDEF:     // UNDEF
1641       V = UndefValue::get(CurTy);
1642       break;
1643     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
1644       if (Record.empty())
1645         return Error("Invalid record");
1646       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1647         return Error("Invalid record");
1648       CurTy = TypeList[Record[0]];
1649       continue;  // Skip the ValueList manipulation.
1650     case bitc::CST_CODE_NULL:      // NULL
1651       V = Constant::getNullValue(CurTy);
1652       break;
1653     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
1654       if (!CurTy->isIntegerTy() || Record.empty())
1655         return Error("Invalid record");
1656       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1657       break;
1658     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1659       if (!CurTy->isIntegerTy() || Record.empty())
1660         return Error("Invalid record");
1661
1662       APInt VInt = ReadWideAPInt(Record,
1663                                  cast<IntegerType>(CurTy)->getBitWidth());
1664       V = ConstantInt::get(Context, VInt);
1665
1666       break;
1667     }
1668     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1669       if (Record.empty())
1670         return Error("Invalid record");
1671       if (CurTy->isHalfTy())
1672         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1673                                              APInt(16, (uint16_t)Record[0])));
1674       else if (CurTy->isFloatTy())
1675         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1676                                              APInt(32, (uint32_t)Record[0])));
1677       else if (CurTy->isDoubleTy())
1678         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1679                                              APInt(64, Record[0])));
1680       else if (CurTy->isX86_FP80Ty()) {
1681         // Bits are not stored the same way as a normal i80 APInt, compensate.
1682         uint64_t Rearrange[2];
1683         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1684         Rearrange[1] = Record[0] >> 48;
1685         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1686                                              APInt(80, Rearrange)));
1687       } else if (CurTy->isFP128Ty())
1688         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1689                                              APInt(128, Record)));
1690       else if (CurTy->isPPC_FP128Ty())
1691         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1692                                              APInt(128, Record)));
1693       else
1694         V = UndefValue::get(CurTy);
1695       break;
1696     }
1697
1698     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1699       if (Record.empty())
1700         return Error("Invalid record");
1701
1702       unsigned Size = Record.size();
1703       SmallVector<Constant*, 16> Elts;
1704
1705       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1706         for (unsigned i = 0; i != Size; ++i)
1707           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1708                                                      STy->getElementType(i)));
1709         V = ConstantStruct::get(STy, Elts);
1710       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1711         Type *EltTy = ATy->getElementType();
1712         for (unsigned i = 0; i != Size; ++i)
1713           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1714         V = ConstantArray::get(ATy, Elts);
1715       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1716         Type *EltTy = VTy->getElementType();
1717         for (unsigned i = 0; i != Size; ++i)
1718           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1719         V = ConstantVector::get(Elts);
1720       } else {
1721         V = UndefValue::get(CurTy);
1722       }
1723       break;
1724     }
1725     case bitc::CST_CODE_STRING:    // STRING: [values]
1726     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1727       if (Record.empty())
1728         return Error("Invalid record");
1729
1730       SmallString<16> Elts(Record.begin(), Record.end());
1731       V = ConstantDataArray::getString(Context, Elts,
1732                                        BitCode == bitc::CST_CODE_CSTRING);
1733       break;
1734     }
1735     case bitc::CST_CODE_DATA: {// DATA: [n x value]
1736       if (Record.empty())
1737         return Error("Invalid record");
1738
1739       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1740       unsigned Size = Record.size();
1741
1742       if (EltTy->isIntegerTy(8)) {
1743         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1744         if (isa<VectorType>(CurTy))
1745           V = ConstantDataVector::get(Context, Elts);
1746         else
1747           V = ConstantDataArray::get(Context, Elts);
1748       } else if (EltTy->isIntegerTy(16)) {
1749         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1750         if (isa<VectorType>(CurTy))
1751           V = ConstantDataVector::get(Context, Elts);
1752         else
1753           V = ConstantDataArray::get(Context, Elts);
1754       } else if (EltTy->isIntegerTy(32)) {
1755         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1756         if (isa<VectorType>(CurTy))
1757           V = ConstantDataVector::get(Context, Elts);
1758         else
1759           V = ConstantDataArray::get(Context, Elts);
1760       } else if (EltTy->isIntegerTy(64)) {
1761         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1762         if (isa<VectorType>(CurTy))
1763           V = ConstantDataVector::get(Context, Elts);
1764         else
1765           V = ConstantDataArray::get(Context, Elts);
1766       } else if (EltTy->isFloatTy()) {
1767         SmallVector<float, 16> Elts(Size);
1768         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1769         if (isa<VectorType>(CurTy))
1770           V = ConstantDataVector::get(Context, Elts);
1771         else
1772           V = ConstantDataArray::get(Context, Elts);
1773       } else if (EltTy->isDoubleTy()) {
1774         SmallVector<double, 16> Elts(Size);
1775         std::transform(Record.begin(), Record.end(), Elts.begin(),
1776                        BitsToDouble);
1777         if (isa<VectorType>(CurTy))
1778           V = ConstantDataVector::get(Context, Elts);
1779         else
1780           V = ConstantDataArray::get(Context, Elts);
1781       } else {
1782         return Error("Invalid type for value");
1783       }
1784       break;
1785     }
1786
1787     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1788       if (Record.size() < 3)
1789         return Error("Invalid record");
1790       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1791       if (Opc < 0) {
1792         V = UndefValue::get(CurTy);  // Unknown binop.
1793       } else {
1794         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1795         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1796         unsigned Flags = 0;
1797         if (Record.size() >= 4) {
1798           if (Opc == Instruction::Add ||
1799               Opc == Instruction::Sub ||
1800               Opc == Instruction::Mul ||
1801               Opc == Instruction::Shl) {
1802             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1803               Flags |= OverflowingBinaryOperator::NoSignedWrap;
1804             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1805               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1806           } else if (Opc == Instruction::SDiv ||
1807                      Opc == Instruction::UDiv ||
1808                      Opc == Instruction::LShr ||
1809                      Opc == Instruction::AShr) {
1810             if (Record[3] & (1 << bitc::PEO_EXACT))
1811               Flags |= SDivOperator::IsExact;
1812           }
1813         }
1814         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1815       }
1816       break;
1817     }
1818     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1819       if (Record.size() < 3)
1820         return Error("Invalid record");
1821       int Opc = GetDecodedCastOpcode(Record[0]);
1822       if (Opc < 0) {
1823         V = UndefValue::get(CurTy);  // Unknown cast.
1824       } else {
1825         Type *OpTy = getTypeByID(Record[1]);
1826         if (!OpTy)
1827           return Error("Invalid record");
1828         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1829         V = UpgradeBitCastExpr(Opc, Op, CurTy);
1830         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1831       }
1832       break;
1833     }
1834     case bitc::CST_CODE_CE_INBOUNDS_GEP:
1835     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1836       if (Record.size() & 1)
1837         return Error("Invalid record");
1838       SmallVector<Constant*, 16> Elts;
1839       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1840         Type *ElTy = getTypeByID(Record[i]);
1841         if (!ElTy)
1842           return Error("Invalid record");
1843         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1844       }
1845       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1846       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1847                                          BitCode ==
1848                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
1849       break;
1850     }
1851     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
1852       if (Record.size() < 3)
1853         return Error("Invalid record");
1854
1855       Type *SelectorTy = Type::getInt1Ty(Context);
1856
1857       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1858       // vector. Otherwise, it must be a single bit.
1859       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1860         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1861                                      VTy->getNumElements());
1862
1863       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1864                                                               SelectorTy),
1865                                   ValueList.getConstantFwdRef(Record[1],CurTy),
1866                                   ValueList.getConstantFwdRef(Record[2],CurTy));
1867       break;
1868     }
1869     case bitc::CST_CODE_CE_EXTRACTELT
1870         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1871       if (Record.size() < 3)
1872         return Error("Invalid record");
1873       VectorType *OpTy =
1874         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1875       if (!OpTy)
1876         return Error("Invalid record");
1877       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1878       Constant *Op1 = nullptr;
1879       if (Record.size() == 4) {
1880         Type *IdxTy = getTypeByID(Record[2]);
1881         if (!IdxTy)
1882           return Error("Invalid record");
1883         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1884       } else // TODO: Remove with llvm 4.0
1885         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1886       if (!Op1)
1887         return Error("Invalid record");
1888       V = ConstantExpr::getExtractElement(Op0, Op1);
1889       break;
1890     }
1891     case bitc::CST_CODE_CE_INSERTELT
1892         : { // CE_INSERTELT: [opval, opval, opty, opval]
1893       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1894       if (Record.size() < 3 || !OpTy)
1895         return Error("Invalid record");
1896       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1897       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1898                                                   OpTy->getElementType());
1899       Constant *Op2 = nullptr;
1900       if (Record.size() == 4) {
1901         Type *IdxTy = getTypeByID(Record[2]);
1902         if (!IdxTy)
1903           return Error("Invalid record");
1904         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1905       } else // TODO: Remove with llvm 4.0
1906         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1907       if (!Op2)
1908         return Error("Invalid record");
1909       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1910       break;
1911     }
1912     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1913       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1914       if (Record.size() < 3 || !OpTy)
1915         return Error("Invalid record");
1916       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1917       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1918       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1919                                                  OpTy->getNumElements());
1920       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1921       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1922       break;
1923     }
1924     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1925       VectorType *RTy = dyn_cast<VectorType>(CurTy);
1926       VectorType *OpTy =
1927         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1928       if (Record.size() < 4 || !RTy || !OpTy)
1929         return Error("Invalid record");
1930       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1931       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1932       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1933                                                  RTy->getNumElements());
1934       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1935       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1936       break;
1937     }
1938     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1939       if (Record.size() < 4)
1940         return Error("Invalid record");
1941       Type *OpTy = getTypeByID(Record[0]);
1942       if (!OpTy)
1943         return Error("Invalid record");
1944       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1945       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1946
1947       if (OpTy->isFPOrFPVectorTy())
1948         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1949       else
1950         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1951       break;
1952     }
1953     // This maintains backward compatibility, pre-asm dialect keywords.
1954     // FIXME: Remove with the 4.0 release.
1955     case bitc::CST_CODE_INLINEASM_OLD: {
1956       if (Record.size() < 2)
1957         return Error("Invalid record");
1958       std::string AsmStr, ConstrStr;
1959       bool HasSideEffects = Record[0] & 1;
1960       bool IsAlignStack = Record[0] >> 1;
1961       unsigned AsmStrSize = Record[1];
1962       if (2+AsmStrSize >= Record.size())
1963         return Error("Invalid record");
1964       unsigned ConstStrSize = Record[2+AsmStrSize];
1965       if (3+AsmStrSize+ConstStrSize > Record.size())
1966         return Error("Invalid record");
1967
1968       for (unsigned i = 0; i != AsmStrSize; ++i)
1969         AsmStr += (char)Record[2+i];
1970       for (unsigned i = 0; i != ConstStrSize; ++i)
1971         ConstrStr += (char)Record[3+AsmStrSize+i];
1972       PointerType *PTy = cast<PointerType>(CurTy);
1973       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1974                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1975       break;
1976     }
1977     // This version adds support for the asm dialect keywords (e.g.,
1978     // inteldialect).
1979     case bitc::CST_CODE_INLINEASM: {
1980       if (Record.size() < 2)
1981         return Error("Invalid record");
1982       std::string AsmStr, ConstrStr;
1983       bool HasSideEffects = Record[0] & 1;
1984       bool IsAlignStack = (Record[0] >> 1) & 1;
1985       unsigned AsmDialect = Record[0] >> 2;
1986       unsigned AsmStrSize = Record[1];
1987       if (2+AsmStrSize >= Record.size())
1988         return Error("Invalid record");
1989       unsigned ConstStrSize = Record[2+AsmStrSize];
1990       if (3+AsmStrSize+ConstStrSize > Record.size())
1991         return Error("Invalid record");
1992
1993       for (unsigned i = 0; i != AsmStrSize; ++i)
1994         AsmStr += (char)Record[2+i];
1995       for (unsigned i = 0; i != ConstStrSize; ++i)
1996         ConstrStr += (char)Record[3+AsmStrSize+i];
1997       PointerType *PTy = cast<PointerType>(CurTy);
1998       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1999                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2000                          InlineAsm::AsmDialect(AsmDialect));
2001       break;
2002     }
2003     case bitc::CST_CODE_BLOCKADDRESS:{
2004       if (Record.size() < 3)
2005         return Error("Invalid record");
2006       Type *FnTy = getTypeByID(Record[0]);
2007       if (!FnTy)
2008         return Error("Invalid record");
2009       Function *Fn =
2010         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2011       if (!Fn)
2012         return Error("Invalid record");
2013
2014       // Don't let Fn get dematerialized.
2015       BlockAddressesTaken.insert(Fn);
2016
2017       // If the function is already parsed we can insert the block address right
2018       // away.
2019       BasicBlock *BB;
2020       unsigned BBID = Record[2];
2021       if (!BBID)
2022         // Invalid reference to entry block.
2023         return Error("Invalid ID");
2024       if (!Fn->empty()) {
2025         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2026         for (size_t I = 0, E = BBID; I != E; ++I) {
2027           if (BBI == BBE)
2028             return Error("Invalid ID");
2029           ++BBI;
2030         }
2031         BB = BBI;
2032       } else {
2033         // Otherwise insert a placeholder and remember it so it can be inserted
2034         // when the function is parsed.
2035         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2036         if (FwdBBs.empty())
2037           BasicBlockFwdRefQueue.push_back(Fn);
2038         if (FwdBBs.size() < BBID + 1)
2039           FwdBBs.resize(BBID + 1);
2040         if (!FwdBBs[BBID])
2041           FwdBBs[BBID] = BasicBlock::Create(Context);
2042         BB = FwdBBs[BBID];
2043       }
2044       V = BlockAddress::get(Fn, BB);
2045       break;
2046     }
2047     }
2048
2049     ValueList.AssignValue(V, NextCstNo);
2050     ++NextCstNo;
2051   }
2052 }
2053
2054 std::error_code BitcodeReader::ParseUseLists() {
2055   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2056     return Error("Invalid record");
2057
2058   // Read all the records.
2059   SmallVector<uint64_t, 64> Record;
2060   while (1) {
2061     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2062
2063     switch (Entry.Kind) {
2064     case BitstreamEntry::SubBlock: // Handled for us already.
2065     case BitstreamEntry::Error:
2066       return Error("Malformed block");
2067     case BitstreamEntry::EndBlock:
2068       return std::error_code();
2069     case BitstreamEntry::Record:
2070       // The interesting case.
2071       break;
2072     }
2073
2074     // Read a use list record.
2075     Record.clear();
2076     bool IsBB = false;
2077     switch (Stream.readRecord(Entry.ID, Record)) {
2078     default:  // Default behavior: unknown type.
2079       break;
2080     case bitc::USELIST_CODE_BB:
2081       IsBB = true;
2082       // fallthrough
2083     case bitc::USELIST_CODE_DEFAULT: {
2084       unsigned RecordLength = Record.size();
2085       if (RecordLength < 3)
2086         // Records should have at least an ID and two indexes.
2087         return Error("Invalid record");
2088       unsigned ID = Record.back();
2089       Record.pop_back();
2090
2091       Value *V;
2092       if (IsBB) {
2093         assert(ID < FunctionBBs.size() && "Basic block not found");
2094         V = FunctionBBs[ID];
2095       } else
2096         V = ValueList[ID];
2097       unsigned NumUses = 0;
2098       SmallDenseMap<const Use *, unsigned, 16> Order;
2099       for (const Use &U : V->uses()) {
2100         if (++NumUses > Record.size())
2101           break;
2102         Order[&U] = Record[NumUses - 1];
2103       }
2104       if (Order.size() != Record.size() || NumUses > Record.size())
2105         // Mismatches can happen if the functions are being materialized lazily
2106         // (out-of-order), or a value has been upgraded.
2107         break;
2108
2109       V->sortUseList([&](const Use &L, const Use &R) {
2110         return Order.lookup(&L) < Order.lookup(&R);
2111       });
2112       break;
2113     }
2114     }
2115   }
2116 }
2117
2118 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2119 /// remember where it is and then skip it.  This lets us lazily deserialize the
2120 /// functions.
2121 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2122   // Get the function we are talking about.
2123   if (FunctionsWithBodies.empty())
2124     return Error("Insufficient function protos");
2125
2126   Function *Fn = FunctionsWithBodies.back();
2127   FunctionsWithBodies.pop_back();
2128
2129   // Save the current stream state.
2130   uint64_t CurBit = Stream.GetCurrentBitNo();
2131   DeferredFunctionInfo[Fn] = CurBit;
2132
2133   // Skip over the function block for now.
2134   if (Stream.SkipBlock())
2135     return Error("Invalid record");
2136   return std::error_code();
2137 }
2138
2139 std::error_code BitcodeReader::GlobalCleanup() {
2140   // Patch the initializers for globals and aliases up.
2141   ResolveGlobalAndAliasInits();
2142   if (!GlobalInits.empty() || !AliasInits.empty())
2143     return Error("Malformed global initializer set");
2144
2145   // Look for intrinsic functions which need to be upgraded at some point
2146   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2147        FI != FE; ++FI) {
2148     Function *NewFn;
2149     if (UpgradeIntrinsicFunction(FI, NewFn))
2150       UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2151   }
2152
2153   // Look for global variables which need to be renamed.
2154   for (Module::global_iterator
2155          GI = TheModule->global_begin(), GE = TheModule->global_end();
2156        GI != GE;) {
2157     GlobalVariable *GV = GI++;
2158     UpgradeGlobalVariable(GV);
2159   }
2160
2161   // Force deallocation of memory for these vectors to favor the client that
2162   // want lazy deserialization.
2163   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2164   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2165   return std::error_code();
2166 }
2167
2168 std::error_code BitcodeReader::ParseModule(bool Resume) {
2169   if (Resume)
2170     Stream.JumpToBit(NextUnreadBit);
2171   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2172     return Error("Invalid record");
2173
2174   SmallVector<uint64_t, 64> Record;
2175   std::vector<std::string> SectionTable;
2176   std::vector<std::string> GCTable;
2177
2178   // Read all the records for this module.
2179   while (1) {
2180     BitstreamEntry Entry = Stream.advance();
2181
2182     switch (Entry.Kind) {
2183     case BitstreamEntry::Error:
2184       return Error("Malformed block");
2185     case BitstreamEntry::EndBlock:
2186       return GlobalCleanup();
2187
2188     case BitstreamEntry::SubBlock:
2189       switch (Entry.ID) {
2190       default:  // Skip unknown content.
2191         if (Stream.SkipBlock())
2192           return Error("Invalid record");
2193         break;
2194       case bitc::BLOCKINFO_BLOCK_ID:
2195         if (Stream.ReadBlockInfoBlock())
2196           return Error("Malformed block");
2197         break;
2198       case bitc::PARAMATTR_BLOCK_ID:
2199         if (std::error_code EC = ParseAttributeBlock())
2200           return EC;
2201         break;
2202       case bitc::PARAMATTR_GROUP_BLOCK_ID:
2203         if (std::error_code EC = ParseAttributeGroupBlock())
2204           return EC;
2205         break;
2206       case bitc::TYPE_BLOCK_ID_NEW:
2207         if (std::error_code EC = ParseTypeTable())
2208           return EC;
2209         break;
2210       case bitc::VALUE_SYMTAB_BLOCK_ID:
2211         if (std::error_code EC = ParseValueSymbolTable())
2212           return EC;
2213         SeenValueSymbolTable = true;
2214         break;
2215       case bitc::CONSTANTS_BLOCK_ID:
2216         if (std::error_code EC = ParseConstants())
2217           return EC;
2218         if (std::error_code EC = ResolveGlobalAndAliasInits())
2219           return EC;
2220         break;
2221       case bitc::METADATA_BLOCK_ID:
2222         if (std::error_code EC = ParseMetadata())
2223           return EC;
2224         break;
2225       case bitc::FUNCTION_BLOCK_ID:
2226         // If this is the first function body we've seen, reverse the
2227         // FunctionsWithBodies list.
2228         if (!SeenFirstFunctionBody) {
2229           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2230           if (std::error_code EC = GlobalCleanup())
2231             return EC;
2232           SeenFirstFunctionBody = true;
2233         }
2234
2235         if (std::error_code EC = RememberAndSkipFunctionBody())
2236           return EC;
2237         // For streaming bitcode, suspend parsing when we reach the function
2238         // bodies. Subsequent materialization calls will resume it when
2239         // necessary. For streaming, the function bodies must be at the end of
2240         // the bitcode. If the bitcode file is old, the symbol table will be
2241         // at the end instead and will not have been seen yet. In this case,
2242         // just finish the parse now.
2243         if (LazyStreamer && SeenValueSymbolTable) {
2244           NextUnreadBit = Stream.GetCurrentBitNo();
2245           return std::error_code();
2246         }
2247         break;
2248       case bitc::USELIST_BLOCK_ID:
2249         if (std::error_code EC = ParseUseLists())
2250           return EC;
2251         break;
2252       }
2253       continue;
2254
2255     case BitstreamEntry::Record:
2256       // The interesting case.
2257       break;
2258     }
2259
2260
2261     // Read a record.
2262     switch (Stream.readRecord(Entry.ID, Record)) {
2263     default: break;  // Default behavior, ignore unknown content.
2264     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
2265       if (Record.size() < 1)
2266         return Error("Invalid record");
2267       // Only version #0 and #1 are supported so far.
2268       unsigned module_version = Record[0];
2269       switch (module_version) {
2270         default:
2271           return Error("Invalid value");
2272         case 0:
2273           UseRelativeIDs = false;
2274           break;
2275         case 1:
2276           UseRelativeIDs = true;
2277           break;
2278       }
2279       break;
2280     }
2281     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2282       std::string S;
2283       if (ConvertToString(Record, 0, S))
2284         return Error("Invalid record");
2285       TheModule->setTargetTriple(S);
2286       break;
2287     }
2288     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
2289       std::string S;
2290       if (ConvertToString(Record, 0, S))
2291         return Error("Invalid record");
2292       TheModule->setDataLayout(S);
2293       break;
2294     }
2295     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
2296       std::string S;
2297       if (ConvertToString(Record, 0, S))
2298         return Error("Invalid record");
2299       TheModule->setModuleInlineAsm(S);
2300       break;
2301     }
2302     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
2303       // FIXME: Remove in 4.0.
2304       std::string S;
2305       if (ConvertToString(Record, 0, S))
2306         return Error("Invalid record");
2307       // Ignore value.
2308       break;
2309     }
2310     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
2311       std::string S;
2312       if (ConvertToString(Record, 0, S))
2313         return Error("Invalid record");
2314       SectionTable.push_back(S);
2315       break;
2316     }
2317     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
2318       std::string S;
2319       if (ConvertToString(Record, 0, S))
2320         return Error("Invalid record");
2321       GCTable.push_back(S);
2322       break;
2323     }
2324     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2325       if (Record.size() < 2)
2326         return Error("Invalid record");
2327       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2328       unsigned ComdatNameSize = Record[1];
2329       std::string ComdatName;
2330       ComdatName.reserve(ComdatNameSize);
2331       for (unsigned i = 0; i != ComdatNameSize; ++i)
2332         ComdatName += (char)Record[2 + i];
2333       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2334       C->setSelectionKind(SK);
2335       ComdatList.push_back(C);
2336       break;
2337     }
2338     // GLOBALVAR: [pointer type, isconst, initid,
2339     //             linkage, alignment, section, visibility, threadlocal,
2340     //             unnamed_addr, externally_initialized, dllstorageclass,
2341     //             comdat]
2342     case bitc::MODULE_CODE_GLOBALVAR: {
2343       if (Record.size() < 6)
2344         return Error("Invalid record");
2345       Type *Ty = getTypeByID(Record[0]);
2346       if (!Ty)
2347         return Error("Invalid record");
2348       if (!Ty->isPointerTy())
2349         return Error("Invalid type for value");
2350       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2351       Ty = cast<PointerType>(Ty)->getElementType();
2352
2353       bool isConstant = Record[1];
2354       uint64_t RawLinkage = Record[3];
2355       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2356       unsigned Alignment = (1 << Record[4]) >> 1;
2357       std::string Section;
2358       if (Record[5]) {
2359         if (Record[5]-1 >= SectionTable.size())
2360           return Error("Invalid ID");
2361         Section = SectionTable[Record[5]-1];
2362       }
2363       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2364       // Local linkage must have default visibility.
2365       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2366         // FIXME: Change to an error if non-default in 4.0.
2367         Visibility = GetDecodedVisibility(Record[6]);
2368
2369       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2370       if (Record.size() > 7)
2371         TLM = GetDecodedThreadLocalMode(Record[7]);
2372
2373       bool UnnamedAddr = false;
2374       if (Record.size() > 8)
2375         UnnamedAddr = Record[8];
2376
2377       bool ExternallyInitialized = false;
2378       if (Record.size() > 9)
2379         ExternallyInitialized = Record[9];
2380
2381       GlobalVariable *NewGV =
2382         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2383                            TLM, AddressSpace, ExternallyInitialized);
2384       NewGV->setAlignment(Alignment);
2385       if (!Section.empty())
2386         NewGV->setSection(Section);
2387       NewGV->setVisibility(Visibility);
2388       NewGV->setUnnamedAddr(UnnamedAddr);
2389
2390       if (Record.size() > 10)
2391         NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2392       else
2393         UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2394
2395       ValueList.push_back(NewGV);
2396
2397       // Remember which value to use for the global initializer.
2398       if (unsigned InitID = Record[2])
2399         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2400
2401       if (Record.size() > 11) {
2402         if (unsigned ComdatID = Record[11]) {
2403           assert(ComdatID <= ComdatList.size());
2404           NewGV->setComdat(ComdatList[ComdatID - 1]);
2405         }
2406       } else if (hasImplicitComdat(RawLinkage)) {
2407         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2408       }
2409       break;
2410     }
2411     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
2412     //             alignment, section, visibility, gc, unnamed_addr,
2413     //             prologuedata, dllstorageclass, comdat, prefixdata]
2414     case bitc::MODULE_CODE_FUNCTION: {
2415       if (Record.size() < 8)
2416         return Error("Invalid record");
2417       Type *Ty = getTypeByID(Record[0]);
2418       if (!Ty)
2419         return Error("Invalid record");
2420       if (!Ty->isPointerTy())
2421         return Error("Invalid type for value");
2422       FunctionType *FTy =
2423         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2424       if (!FTy)
2425         return Error("Invalid type for value");
2426
2427       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2428                                         "", TheModule);
2429
2430       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2431       bool isProto = Record[2];
2432       uint64_t RawLinkage = Record[3];
2433       Func->setLinkage(getDecodedLinkage(RawLinkage));
2434       Func->setAttributes(getAttributes(Record[4]));
2435
2436       Func->setAlignment((1 << Record[5]) >> 1);
2437       if (Record[6]) {
2438         if (Record[6]-1 >= SectionTable.size())
2439           return Error("Invalid ID");
2440         Func->setSection(SectionTable[Record[6]-1]);
2441       }
2442       // Local linkage must have default visibility.
2443       if (!Func->hasLocalLinkage())
2444         // FIXME: Change to an error if non-default in 4.0.
2445         Func->setVisibility(GetDecodedVisibility(Record[7]));
2446       if (Record.size() > 8 && Record[8]) {
2447         if (Record[8]-1 > GCTable.size())
2448           return Error("Invalid ID");
2449         Func->setGC(GCTable[Record[8]-1].c_str());
2450       }
2451       bool UnnamedAddr = false;
2452       if (Record.size() > 9)
2453         UnnamedAddr = Record[9];
2454       Func->setUnnamedAddr(UnnamedAddr);
2455       if (Record.size() > 10 && Record[10] != 0)
2456         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2457
2458       if (Record.size() > 11)
2459         Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2460       else
2461         UpgradeDLLImportExportLinkage(Func, RawLinkage);
2462
2463       if (Record.size() > 12) {
2464         if (unsigned ComdatID = Record[12]) {
2465           assert(ComdatID <= ComdatList.size());
2466           Func->setComdat(ComdatList[ComdatID - 1]);
2467         }
2468       } else if (hasImplicitComdat(RawLinkage)) {
2469         Func->setComdat(reinterpret_cast<Comdat *>(1));
2470       }
2471
2472       if (Record.size() > 13 && Record[13] != 0)
2473         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2474
2475       ValueList.push_back(Func);
2476
2477       // If this is a function with a body, remember the prototype we are
2478       // creating now, so that we can match up the body with them later.
2479       if (!isProto) {
2480         Func->setIsMaterializable(true);
2481         FunctionsWithBodies.push_back(Func);
2482         if (LazyStreamer)
2483           DeferredFunctionInfo[Func] = 0;
2484       }
2485       break;
2486     }
2487     // ALIAS: [alias type, aliasee val#, linkage]
2488     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2489     case bitc::MODULE_CODE_ALIAS: {
2490       if (Record.size() < 3)
2491         return Error("Invalid record");
2492       Type *Ty = getTypeByID(Record[0]);
2493       if (!Ty)
2494         return Error("Invalid record");
2495       auto *PTy = dyn_cast<PointerType>(Ty);
2496       if (!PTy)
2497         return Error("Invalid type for value");
2498
2499       auto *NewGA =
2500           GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2501                               getDecodedLinkage(Record[2]), "", TheModule);
2502       // Old bitcode files didn't have visibility field.
2503       // Local linkage must have default visibility.
2504       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2505         // FIXME: Change to an error if non-default in 4.0.
2506         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2507       if (Record.size() > 4)
2508         NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2509       else
2510         UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2511       if (Record.size() > 5)
2512         NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2513       if (Record.size() > 6)
2514         NewGA->setUnnamedAddr(Record[6]);
2515       ValueList.push_back(NewGA);
2516       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2517       break;
2518     }
2519     /// MODULE_CODE_PURGEVALS: [numvals]
2520     case bitc::MODULE_CODE_PURGEVALS:
2521       // Trim down the value list to the specified size.
2522       if (Record.size() < 1 || Record[0] > ValueList.size())
2523         return Error("Invalid record");
2524       ValueList.shrinkTo(Record[0]);
2525       break;
2526     }
2527     Record.clear();
2528   }
2529 }
2530
2531 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2532   TheModule = nullptr;
2533
2534   if (std::error_code EC = InitStream())
2535     return EC;
2536
2537   // Sniff for the signature.
2538   if (Stream.Read(8) != 'B' ||
2539       Stream.Read(8) != 'C' ||
2540       Stream.Read(4) != 0x0 ||
2541       Stream.Read(4) != 0xC ||
2542       Stream.Read(4) != 0xE ||
2543       Stream.Read(4) != 0xD)
2544     return Error("Invalid bitcode signature");
2545
2546   // We expect a number of well-defined blocks, though we don't necessarily
2547   // need to understand them all.
2548   while (1) {
2549     if (Stream.AtEndOfStream())
2550       return std::error_code();
2551
2552     BitstreamEntry Entry =
2553       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2554
2555     switch (Entry.Kind) {
2556     case BitstreamEntry::Error:
2557       return Error("Malformed block");
2558     case BitstreamEntry::EndBlock:
2559       return std::error_code();
2560
2561     case BitstreamEntry::SubBlock:
2562       switch (Entry.ID) {
2563       case bitc::BLOCKINFO_BLOCK_ID:
2564         if (Stream.ReadBlockInfoBlock())
2565           return Error("Malformed block");
2566         break;
2567       case bitc::MODULE_BLOCK_ID:
2568         // Reject multiple MODULE_BLOCK's in a single bitstream.
2569         if (TheModule)
2570           return Error("Invalid multiple blocks");
2571         TheModule = M;
2572         if (std::error_code EC = ParseModule(false))
2573           return EC;
2574         if (LazyStreamer)
2575           return std::error_code();
2576         break;
2577       default:
2578         if (Stream.SkipBlock())
2579           return Error("Invalid record");
2580         break;
2581       }
2582       continue;
2583     case BitstreamEntry::Record:
2584       // There should be no records in the top-level of blocks.
2585
2586       // The ranlib in Xcode 4 will align archive members by appending newlines
2587       // to the end of them. If this file size is a multiple of 4 but not 8, we
2588       // have to read and ignore these final 4 bytes :-(
2589       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2590           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2591           Stream.AtEndOfStream())
2592         return std::error_code();
2593
2594       return Error("Invalid record");
2595     }
2596   }
2597 }
2598
2599 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2600   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2601     return Error("Invalid record");
2602
2603   SmallVector<uint64_t, 64> Record;
2604
2605   std::string Triple;
2606   // Read all the records for this module.
2607   while (1) {
2608     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2609
2610     switch (Entry.Kind) {
2611     case BitstreamEntry::SubBlock: // Handled for us already.
2612     case BitstreamEntry::Error:
2613       return Error("Malformed block");
2614     case BitstreamEntry::EndBlock:
2615       return Triple;
2616     case BitstreamEntry::Record:
2617       // The interesting case.
2618       break;
2619     }
2620
2621     // Read a record.
2622     switch (Stream.readRecord(Entry.ID, Record)) {
2623     default: break;  // Default behavior, ignore unknown content.
2624     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2625       std::string S;
2626       if (ConvertToString(Record, 0, S))
2627         return Error("Invalid record");
2628       Triple = S;
2629       break;
2630     }
2631     }
2632     Record.clear();
2633   }
2634   llvm_unreachable("Exit infinite loop");
2635 }
2636
2637 ErrorOr<std::string> BitcodeReader::parseTriple() {
2638   if (std::error_code EC = InitStream())
2639     return EC;
2640
2641   // Sniff for the signature.
2642   if (Stream.Read(8) != 'B' ||
2643       Stream.Read(8) != 'C' ||
2644       Stream.Read(4) != 0x0 ||
2645       Stream.Read(4) != 0xC ||
2646       Stream.Read(4) != 0xE ||
2647       Stream.Read(4) != 0xD)
2648     return Error("Invalid bitcode signature");
2649
2650   // We expect a number of well-defined blocks, though we don't necessarily
2651   // need to understand them all.
2652   while (1) {
2653     BitstreamEntry Entry = Stream.advance();
2654
2655     switch (Entry.Kind) {
2656     case BitstreamEntry::Error:
2657       return Error("Malformed block");
2658     case BitstreamEntry::EndBlock:
2659       return std::error_code();
2660
2661     case BitstreamEntry::SubBlock:
2662       if (Entry.ID == bitc::MODULE_BLOCK_ID)
2663         return parseModuleTriple();
2664
2665       // Ignore other sub-blocks.
2666       if (Stream.SkipBlock())
2667         return Error("Malformed block");
2668       continue;
2669
2670     case BitstreamEntry::Record:
2671       Stream.skipRecord(Entry.ID);
2672       continue;
2673     }
2674   }
2675 }
2676
2677 /// ParseMetadataAttachment - Parse metadata attachments.
2678 std::error_code BitcodeReader::ParseMetadataAttachment() {
2679   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2680     return Error("Invalid record");
2681
2682   SmallVector<uint64_t, 64> Record;
2683   while (1) {
2684     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2685
2686     switch (Entry.Kind) {
2687     case BitstreamEntry::SubBlock: // Handled for us already.
2688     case BitstreamEntry::Error:
2689       return Error("Malformed block");
2690     case BitstreamEntry::EndBlock:
2691       return std::error_code();
2692     case BitstreamEntry::Record:
2693       // The interesting case.
2694       break;
2695     }
2696
2697     // Read a metadata attachment record.
2698     Record.clear();
2699     switch (Stream.readRecord(Entry.ID, Record)) {
2700     default:  // Default behavior: ignore.
2701       break;
2702     case bitc::METADATA_ATTACHMENT: {
2703       unsigned RecordLength = Record.size();
2704       if (Record.empty() || (RecordLength - 1) % 2 == 1)
2705         return Error("Invalid record");
2706       Instruction *Inst = InstructionList[Record[0]];
2707       for (unsigned i = 1; i != RecordLength; i = i+2) {
2708         unsigned Kind = Record[i];
2709         DenseMap<unsigned, unsigned>::iterator I =
2710           MDKindMap.find(Kind);
2711         if (I == MDKindMap.end())
2712           return Error("Invalid ID");
2713         Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2714         if (isa<LocalAsMetadata>(Node))
2715           // Drop the attachment.  This used to be legal, but there's no
2716           // upgrade path.
2717           break;
2718         Inst->setMetadata(I->second, cast<MDNode>(Node));
2719         if (I->second == LLVMContext::MD_tbaa)
2720           InstsWithTBAATag.push_back(Inst);
2721       }
2722       break;
2723     }
2724     }
2725   }
2726 }
2727
2728 /// ParseFunctionBody - Lazily parse the specified function body block.
2729 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2730   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2731     return Error("Invalid record");
2732
2733   InstructionList.clear();
2734   unsigned ModuleValueListSize = ValueList.size();
2735   unsigned ModuleMDValueListSize = MDValueList.size();
2736
2737   // Add all the function arguments to the value table.
2738   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2739     ValueList.push_back(I);
2740
2741   unsigned NextValueNo = ValueList.size();
2742   BasicBlock *CurBB = nullptr;
2743   unsigned CurBBNo = 0;
2744
2745   DebugLoc LastLoc;
2746   auto getLastInstruction = [&]() -> Instruction * {
2747     if (CurBB && !CurBB->empty())
2748       return &CurBB->back();
2749     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2750              !FunctionBBs[CurBBNo - 1]->empty())
2751       return &FunctionBBs[CurBBNo - 1]->back();
2752     return nullptr;
2753   };
2754
2755   // Read all the records.
2756   SmallVector<uint64_t, 64> Record;
2757   while (1) {
2758     BitstreamEntry Entry = Stream.advance();
2759
2760     switch (Entry.Kind) {
2761     case BitstreamEntry::Error:
2762       return Error("Malformed block");
2763     case BitstreamEntry::EndBlock:
2764       goto OutOfRecordLoop;
2765
2766     case BitstreamEntry::SubBlock:
2767       switch (Entry.ID) {
2768       default:  // Skip unknown content.
2769         if (Stream.SkipBlock())
2770           return Error("Invalid record");
2771         break;
2772       case bitc::CONSTANTS_BLOCK_ID:
2773         if (std::error_code EC = ParseConstants())
2774           return EC;
2775         NextValueNo = ValueList.size();
2776         break;
2777       case bitc::VALUE_SYMTAB_BLOCK_ID:
2778         if (std::error_code EC = ParseValueSymbolTable())
2779           return EC;
2780         break;
2781       case bitc::METADATA_ATTACHMENT_ID:
2782         if (std::error_code EC = ParseMetadataAttachment())
2783           return EC;
2784         break;
2785       case bitc::METADATA_BLOCK_ID:
2786         if (std::error_code EC = ParseMetadata())
2787           return EC;
2788         break;
2789       case bitc::USELIST_BLOCK_ID:
2790         if (std::error_code EC = ParseUseLists())
2791           return EC;
2792         break;
2793       }
2794       continue;
2795
2796     case BitstreamEntry::Record:
2797       // The interesting case.
2798       break;
2799     }
2800
2801     // Read a record.
2802     Record.clear();
2803     Instruction *I = nullptr;
2804     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2805     switch (BitCode) {
2806     default: // Default behavior: reject
2807       return Error("Invalid value");
2808     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
2809       if (Record.size() < 1 || Record[0] == 0)
2810         return Error("Invalid record");
2811       // Create all the basic blocks for the function.
2812       FunctionBBs.resize(Record[0]);
2813
2814       // See if anything took the address of blocks in this function.
2815       auto BBFRI = BasicBlockFwdRefs.find(F);
2816       if (BBFRI == BasicBlockFwdRefs.end()) {
2817         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2818           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2819       } else {
2820         auto &BBRefs = BBFRI->second;
2821         // Check for invalid basic block references.
2822         if (BBRefs.size() > FunctionBBs.size())
2823           return Error("Invalid ID");
2824         assert(!BBRefs.empty() && "Unexpected empty array");
2825         assert(!BBRefs.front() && "Invalid reference to entry block");
2826         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2827              ++I)
2828           if (I < RE && BBRefs[I]) {
2829             BBRefs[I]->insertInto(F);
2830             FunctionBBs[I] = BBRefs[I];
2831           } else {
2832             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2833           }
2834
2835         // Erase from the table.
2836         BasicBlockFwdRefs.erase(BBFRI);
2837       }
2838
2839       CurBB = FunctionBBs[0];
2840       continue;
2841     }
2842
2843     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
2844       // This record indicates that the last instruction is at the same
2845       // location as the previous instruction with a location.
2846       I = getLastInstruction();
2847
2848       if (!I)
2849         return Error("Invalid record");
2850       I->setDebugLoc(LastLoc);
2851       I = nullptr;
2852       continue;
2853
2854     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
2855       I = getLastInstruction();
2856       if (!I || Record.size() < 4)
2857         return Error("Invalid record");
2858
2859       unsigned Line = Record[0], Col = Record[1];
2860       unsigned ScopeID = Record[2], IAID = Record[3];
2861
2862       MDNode *Scope = nullptr, *IA = nullptr;
2863       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2864       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2865       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2866       I->setDebugLoc(LastLoc);
2867       I = nullptr;
2868       continue;
2869     }
2870
2871     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
2872       unsigned OpNum = 0;
2873       Value *LHS, *RHS;
2874       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2875           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2876           OpNum+1 > Record.size())
2877         return Error("Invalid record");
2878
2879       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2880       if (Opc == -1)
2881         return Error("Invalid record");
2882       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2883       InstructionList.push_back(I);
2884       if (OpNum < Record.size()) {
2885         if (Opc == Instruction::Add ||
2886             Opc == Instruction::Sub ||
2887             Opc == Instruction::Mul ||
2888             Opc == Instruction::Shl) {
2889           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2890             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2891           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2892             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2893         } else if (Opc == Instruction::SDiv ||
2894                    Opc == Instruction::UDiv ||
2895                    Opc == Instruction::LShr ||
2896                    Opc == Instruction::AShr) {
2897           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2898             cast<BinaryOperator>(I)->setIsExact(true);
2899         } else if (isa<FPMathOperator>(I)) {
2900           FastMathFlags FMF;
2901           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2902             FMF.setUnsafeAlgebra();
2903           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2904             FMF.setNoNaNs();
2905           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2906             FMF.setNoInfs();
2907           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2908             FMF.setNoSignedZeros();
2909           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2910             FMF.setAllowReciprocal();
2911           if (FMF.any())
2912             I->setFastMathFlags(FMF);
2913         }
2914
2915       }
2916       break;
2917     }
2918     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2919       unsigned OpNum = 0;
2920       Value *Op;
2921       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2922           OpNum+2 != Record.size())
2923         return Error("Invalid record");
2924
2925       Type *ResTy = getTypeByID(Record[OpNum]);
2926       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2927       if (Opc == -1 || !ResTy)
2928         return Error("Invalid record");
2929       Instruction *Temp = nullptr;
2930       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2931         if (Temp) {
2932           InstructionList.push_back(Temp);
2933           CurBB->getInstList().push_back(Temp);
2934         }
2935       } else {
2936         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2937       }
2938       InstructionList.push_back(I);
2939       break;
2940     }
2941     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2942     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2943       unsigned OpNum = 0;
2944       Value *BasePtr;
2945       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2946         return Error("Invalid record");
2947
2948       SmallVector<Value*, 16> GEPIdx;
2949       while (OpNum != Record.size()) {
2950         Value *Op;
2951         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2952           return Error("Invalid record");
2953         GEPIdx.push_back(Op);
2954       }
2955
2956       I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2957       InstructionList.push_back(I);
2958       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2959         cast<GetElementPtrInst>(I)->setIsInBounds(true);
2960       break;
2961     }
2962
2963     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2964                                        // EXTRACTVAL: [opty, opval, n x indices]
2965       unsigned OpNum = 0;
2966       Value *Agg;
2967       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2968         return Error("Invalid record");
2969
2970       SmallVector<unsigned, 4> EXTRACTVALIdx;
2971       for (unsigned RecSize = Record.size();
2972            OpNum != RecSize; ++OpNum) {
2973         uint64_t Index = Record[OpNum];
2974         if ((unsigned)Index != Index)
2975           return Error("Invalid value");
2976         EXTRACTVALIdx.push_back((unsigned)Index);
2977       }
2978
2979       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2980       InstructionList.push_back(I);
2981       break;
2982     }
2983
2984     case bitc::FUNC_CODE_INST_INSERTVAL: {
2985                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
2986       unsigned OpNum = 0;
2987       Value *Agg;
2988       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2989         return Error("Invalid record");
2990       Value *Val;
2991       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2992         return Error("Invalid record");
2993
2994       SmallVector<unsigned, 4> INSERTVALIdx;
2995       for (unsigned RecSize = Record.size();
2996            OpNum != RecSize; ++OpNum) {
2997         uint64_t Index = Record[OpNum];
2998         if ((unsigned)Index != Index)
2999           return Error("Invalid value");
3000         INSERTVALIdx.push_back((unsigned)Index);
3001       }
3002
3003       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3004       InstructionList.push_back(I);
3005       break;
3006     }
3007
3008     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3009       // obsolete form of select
3010       // handles select i1 ... in old bitcode
3011       unsigned OpNum = 0;
3012       Value *TrueVal, *FalseVal, *Cond;
3013       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3014           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3015           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3016         return Error("Invalid record");
3017
3018       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3019       InstructionList.push_back(I);
3020       break;
3021     }
3022
3023     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3024       // new form of select
3025       // handles select i1 or select [N x i1]
3026       unsigned OpNum = 0;
3027       Value *TrueVal, *FalseVal, *Cond;
3028       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3029           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3030           getValueTypePair(Record, OpNum, NextValueNo, Cond))
3031         return Error("Invalid record");
3032
3033       // select condition can be either i1 or [N x i1]
3034       if (VectorType* vector_type =
3035           dyn_cast<VectorType>(Cond->getType())) {
3036         // expect <n x i1>
3037         if (vector_type->getElementType() != Type::getInt1Ty(Context))
3038           return Error("Invalid type for value");
3039       } else {
3040         // expect i1
3041         if (Cond->getType() != Type::getInt1Ty(Context))
3042           return Error("Invalid type for value");
3043       }
3044
3045       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3046       InstructionList.push_back(I);
3047       break;
3048     }
3049
3050     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3051       unsigned OpNum = 0;
3052       Value *Vec, *Idx;
3053       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3054           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3055         return Error("Invalid record");
3056       I = ExtractElementInst::Create(Vec, Idx);
3057       InstructionList.push_back(I);
3058       break;
3059     }
3060
3061     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3062       unsigned OpNum = 0;
3063       Value *Vec, *Elt, *Idx;
3064       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3065           popValue(Record, OpNum, NextValueNo,
3066                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3067           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3068         return Error("Invalid record");
3069       I = InsertElementInst::Create(Vec, Elt, Idx);
3070       InstructionList.push_back(I);
3071       break;
3072     }
3073
3074     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3075       unsigned OpNum = 0;
3076       Value *Vec1, *Vec2, *Mask;
3077       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3078           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3079         return Error("Invalid record");
3080
3081       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3082         return Error("Invalid record");
3083       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3084       InstructionList.push_back(I);
3085       break;
3086     }
3087
3088     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
3089       // Old form of ICmp/FCmp returning bool
3090       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3091       // both legal on vectors but had different behaviour.
3092     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3093       // FCmp/ICmp returning bool or vector of bool
3094
3095       unsigned OpNum = 0;
3096       Value *LHS, *RHS;
3097       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3098           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3099           OpNum+1 != Record.size())
3100         return Error("Invalid record");
3101
3102       if (LHS->getType()->isFPOrFPVectorTy())
3103         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3104       else
3105         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3106       InstructionList.push_back(I);
3107       break;
3108     }
3109
3110     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3111       {
3112         unsigned Size = Record.size();
3113         if (Size == 0) {
3114           I = ReturnInst::Create(Context);
3115           InstructionList.push_back(I);
3116           break;
3117         }
3118
3119         unsigned OpNum = 0;
3120         Value *Op = nullptr;
3121         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3122           return Error("Invalid record");
3123         if (OpNum != Record.size())
3124           return Error("Invalid record");
3125
3126         I = ReturnInst::Create(Context, Op);
3127         InstructionList.push_back(I);
3128         break;
3129       }
3130     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3131       if (Record.size() != 1 && Record.size() != 3)
3132         return Error("Invalid record");
3133       BasicBlock *TrueDest = getBasicBlock(Record[0]);
3134       if (!TrueDest)
3135         return Error("Invalid record");
3136
3137       if (Record.size() == 1) {
3138         I = BranchInst::Create(TrueDest);
3139         InstructionList.push_back(I);
3140       }
3141       else {
3142         BasicBlock *FalseDest = getBasicBlock(Record[1]);
3143         Value *Cond = getValue(Record, 2, NextValueNo,
3144                                Type::getInt1Ty(Context));
3145         if (!FalseDest || !Cond)
3146           return Error("Invalid record");
3147         I = BranchInst::Create(TrueDest, FalseDest, Cond);
3148         InstructionList.push_back(I);
3149       }
3150       break;
3151     }
3152     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3153       // Check magic
3154       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3155         // "New" SwitchInst format with case ranges. The changes to write this
3156         // format were reverted but we still recognize bitcode that uses it.
3157         // Hopefully someday we will have support for case ranges and can use
3158         // this format again.
3159
3160         Type *OpTy = getTypeByID(Record[1]);
3161         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3162
3163         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3164         BasicBlock *Default = getBasicBlock(Record[3]);
3165         if (!OpTy || !Cond || !Default)
3166           return Error("Invalid record");
3167
3168         unsigned NumCases = Record[4];
3169
3170         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3171         InstructionList.push_back(SI);
3172
3173         unsigned CurIdx = 5;
3174         for (unsigned i = 0; i != NumCases; ++i) {
3175           SmallVector<ConstantInt*, 1> CaseVals;
3176           unsigned NumItems = Record[CurIdx++];
3177           for (unsigned ci = 0; ci != NumItems; ++ci) {
3178             bool isSingleNumber = Record[CurIdx++];
3179
3180             APInt Low;
3181             unsigned ActiveWords = 1;
3182             if (ValueBitWidth > 64)
3183               ActiveWords = Record[CurIdx++];
3184             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3185                                 ValueBitWidth);
3186             CurIdx += ActiveWords;
3187
3188             if (!isSingleNumber) {
3189               ActiveWords = 1;
3190               if (ValueBitWidth > 64)
3191                 ActiveWords = Record[CurIdx++];
3192               APInt High =
3193                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3194                                 ValueBitWidth);
3195               CurIdx += ActiveWords;
3196
3197               // FIXME: It is not clear whether values in the range should be
3198               // compared as signed or unsigned values. The partially
3199               // implemented changes that used this format in the past used
3200               // unsigned comparisons.
3201               for ( ; Low.ule(High); ++Low)
3202                 CaseVals.push_back(ConstantInt::get(Context, Low));
3203             } else
3204               CaseVals.push_back(ConstantInt::get(Context, Low));
3205           }
3206           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3207           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3208                  cve = CaseVals.end(); cvi != cve; ++cvi)
3209             SI->addCase(*cvi, DestBB);
3210         }
3211         I = SI;
3212         break;
3213       }
3214
3215       // Old SwitchInst format without case ranges.
3216
3217       if (Record.size() < 3 || (Record.size() & 1) == 0)
3218         return Error("Invalid record");
3219       Type *OpTy = getTypeByID(Record[0]);
3220       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3221       BasicBlock *Default = getBasicBlock(Record[2]);
3222       if (!OpTy || !Cond || !Default)
3223         return Error("Invalid record");
3224       unsigned NumCases = (Record.size()-3)/2;
3225       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3226       InstructionList.push_back(SI);
3227       for (unsigned i = 0, e = NumCases; i != e; ++i) {
3228         ConstantInt *CaseVal =
3229           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3230         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3231         if (!CaseVal || !DestBB) {
3232           delete SI;
3233           return Error("Invalid record");
3234         }
3235         SI->addCase(CaseVal, DestBB);
3236       }
3237       I = SI;
3238       break;
3239     }
3240     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3241       if (Record.size() < 2)
3242         return Error("Invalid record");
3243       Type *OpTy = getTypeByID(Record[0]);
3244       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3245       if (!OpTy || !Address)
3246         return Error("Invalid record");
3247       unsigned NumDests = Record.size()-2;
3248       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3249       InstructionList.push_back(IBI);
3250       for (unsigned i = 0, e = NumDests; i != e; ++i) {
3251         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3252           IBI->addDestination(DestBB);
3253         } else {
3254           delete IBI;
3255           return Error("Invalid record");
3256         }
3257       }
3258       I = IBI;
3259       break;
3260     }
3261
3262     case bitc::FUNC_CODE_INST_INVOKE: {
3263       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3264       if (Record.size() < 4)
3265         return Error("Invalid record");
3266       AttributeSet PAL = getAttributes(Record[0]);
3267       unsigned CCInfo = Record[1];
3268       BasicBlock *NormalBB = getBasicBlock(Record[2]);
3269       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3270
3271       unsigned OpNum = 4;
3272       Value *Callee;
3273       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3274         return Error("Invalid record");
3275
3276       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3277       FunctionType *FTy = !CalleeTy ? nullptr :
3278         dyn_cast<FunctionType>(CalleeTy->getElementType());
3279
3280       // Check that the right number of fixed parameters are here.
3281       if (!FTy || !NormalBB || !UnwindBB ||
3282           Record.size() < OpNum+FTy->getNumParams())
3283         return Error("Invalid record");
3284
3285       SmallVector<Value*, 16> Ops;
3286       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3287         Ops.push_back(getValue(Record, OpNum, NextValueNo,
3288                                FTy->getParamType(i)));
3289         if (!Ops.back())
3290           return Error("Invalid record");
3291       }
3292
3293       if (!FTy->isVarArg()) {
3294         if (Record.size() != OpNum)
3295           return Error("Invalid record");
3296       } else {
3297         // Read type/value pairs for varargs params.
3298         while (OpNum != Record.size()) {
3299           Value *Op;
3300           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3301             return Error("Invalid record");
3302           Ops.push_back(Op);
3303         }
3304       }
3305
3306       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3307       InstructionList.push_back(I);
3308       cast<InvokeInst>(I)->setCallingConv(
3309         static_cast<CallingConv::ID>(CCInfo));
3310       cast<InvokeInst>(I)->setAttributes(PAL);
3311       break;
3312     }
3313     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3314       unsigned Idx = 0;
3315       Value *Val = nullptr;
3316       if (getValueTypePair(Record, Idx, NextValueNo, Val))
3317         return Error("Invalid record");
3318       I = ResumeInst::Create(Val);
3319       InstructionList.push_back(I);
3320       break;
3321     }
3322     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3323       I = new UnreachableInst(Context);
3324       InstructionList.push_back(I);
3325       break;
3326     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3327       if (Record.size() < 1 || ((Record.size()-1)&1))
3328         return Error("Invalid record");
3329       Type *Ty = getTypeByID(Record[0]);
3330       if (!Ty)
3331         return Error("Invalid record");
3332
3333       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3334       InstructionList.push_back(PN);
3335
3336       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3337         Value *V;
3338         // With the new function encoding, it is possible that operands have
3339         // negative IDs (for forward references).  Use a signed VBR
3340         // representation to keep the encoding small.
3341         if (UseRelativeIDs)
3342           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3343         else
3344           V = getValue(Record, 1+i, NextValueNo, Ty);
3345         BasicBlock *BB = getBasicBlock(Record[2+i]);
3346         if (!V || !BB)
3347           return Error("Invalid record");
3348         PN->addIncoming(V, BB);
3349       }
3350       I = PN;
3351       break;
3352     }
3353
3354     case bitc::FUNC_CODE_INST_LANDINGPAD: {
3355       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3356       unsigned Idx = 0;
3357       if (Record.size() < 4)
3358         return Error("Invalid record");
3359       Type *Ty = getTypeByID(Record[Idx++]);
3360       if (!Ty)
3361         return Error("Invalid record");
3362       Value *PersFn = nullptr;
3363       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3364         return Error("Invalid record");
3365
3366       bool IsCleanup = !!Record[Idx++];
3367       unsigned NumClauses = Record[Idx++];
3368       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3369       LP->setCleanup(IsCleanup);
3370       for (unsigned J = 0; J != NumClauses; ++J) {
3371         LandingPadInst::ClauseType CT =
3372           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3373         Value *Val;
3374
3375         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3376           delete LP;
3377           return Error("Invalid record");
3378         }
3379
3380         assert((CT != LandingPadInst::Catch ||
3381                 !isa<ArrayType>(Val->getType())) &&
3382                "Catch clause has a invalid type!");
3383         assert((CT != LandingPadInst::Filter ||
3384                 isa<ArrayType>(Val->getType())) &&
3385                "Filter clause has invalid type!");
3386         LP->addClause(cast<Constant>(Val));
3387       }
3388
3389       I = LP;
3390       InstructionList.push_back(I);
3391       break;
3392     }
3393
3394     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3395       if (Record.size() != 4)
3396         return Error("Invalid record");
3397       PointerType *Ty =
3398         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3399       Type *OpTy = getTypeByID(Record[1]);
3400       Value *Size = getFnValueByID(Record[2], OpTy);
3401       unsigned AlignRecord = Record[3];
3402       bool InAlloca = AlignRecord & (1 << 5);
3403       unsigned Align = AlignRecord & ((1 << 5) - 1);
3404       if (!Ty || !Size)
3405         return Error("Invalid record");
3406       AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3407       AI->setUsedWithInAlloca(InAlloca);
3408       I = AI;
3409       InstructionList.push_back(I);
3410       break;
3411     }
3412     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3413       unsigned OpNum = 0;
3414       Value *Op;
3415       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3416           OpNum+2 != Record.size())
3417         return Error("Invalid record");
3418
3419       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3420       InstructionList.push_back(I);
3421       break;
3422     }
3423     case bitc::FUNC_CODE_INST_LOADATOMIC: {
3424        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3425       unsigned OpNum = 0;
3426       Value *Op;
3427       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3428           OpNum+4 != Record.size())
3429         return Error("Invalid record");
3430
3431       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3432       if (Ordering == NotAtomic || Ordering == Release ||
3433           Ordering == AcquireRelease)
3434         return Error("Invalid record");
3435       if (Ordering != NotAtomic && Record[OpNum] == 0)
3436         return Error("Invalid record");
3437       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3438
3439       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3440                        Ordering, SynchScope);
3441       InstructionList.push_back(I);
3442       break;
3443     }
3444     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3445       unsigned OpNum = 0;
3446       Value *Val, *Ptr;
3447       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3448           popValue(Record, OpNum, NextValueNo,
3449                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3450           OpNum+2 != Record.size())
3451         return Error("Invalid record");
3452
3453       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3454       InstructionList.push_back(I);
3455       break;
3456     }
3457     case bitc::FUNC_CODE_INST_STOREATOMIC: {
3458       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3459       unsigned OpNum = 0;
3460       Value *Val, *Ptr;
3461       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3462           popValue(Record, OpNum, NextValueNo,
3463                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3464           OpNum+4 != Record.size())
3465         return Error("Invalid record");
3466
3467       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3468       if (Ordering == NotAtomic || Ordering == Acquire ||
3469           Ordering == AcquireRelease)
3470         return Error("Invalid record");
3471       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3472       if (Ordering != NotAtomic && Record[OpNum] == 0)
3473         return Error("Invalid record");
3474
3475       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3476                         Ordering, SynchScope);
3477       InstructionList.push_back(I);
3478       break;
3479     }
3480     case bitc::FUNC_CODE_INST_CMPXCHG: {
3481       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3482       //          failureordering?, isweak?]
3483       unsigned OpNum = 0;
3484       Value *Ptr, *Cmp, *New;
3485       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3486           popValue(Record, OpNum, NextValueNo,
3487                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3488           popValue(Record, OpNum, NextValueNo,
3489                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3490           (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3491         return Error("Invalid record");
3492       AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3493       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3494         return Error("Invalid record");
3495       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3496
3497       AtomicOrdering FailureOrdering;
3498       if (Record.size() < 7)
3499         FailureOrdering =
3500             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3501       else
3502         FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3503
3504       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3505                                 SynchScope);
3506       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3507
3508       if (Record.size() < 8) {
3509         // Before weak cmpxchgs existed, the instruction simply returned the
3510         // value loaded from memory, so bitcode files from that era will be
3511         // expecting the first component of a modern cmpxchg.
3512         CurBB->getInstList().push_back(I);
3513         I = ExtractValueInst::Create(I, 0);
3514       } else {
3515         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3516       }
3517
3518       InstructionList.push_back(I);
3519       break;
3520     }
3521     case bitc::FUNC_CODE_INST_ATOMICRMW: {
3522       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3523       unsigned OpNum = 0;
3524       Value *Ptr, *Val;
3525       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3526           popValue(Record, OpNum, NextValueNo,
3527                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3528           OpNum+4 != Record.size())
3529         return Error("Invalid record");
3530       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3531       if (Operation < AtomicRMWInst::FIRST_BINOP ||
3532           Operation > AtomicRMWInst::LAST_BINOP)
3533         return Error("Invalid record");
3534       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3535       if (Ordering == NotAtomic || Ordering == Unordered)
3536         return Error("Invalid record");
3537       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3538       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3539       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3540       InstructionList.push_back(I);
3541       break;
3542     }
3543     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3544       if (2 != Record.size())
3545         return Error("Invalid record");
3546       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3547       if (Ordering == NotAtomic || Ordering == Unordered ||
3548           Ordering == Monotonic)
3549         return Error("Invalid record");
3550       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3551       I = new FenceInst(Context, Ordering, SynchScope);
3552       InstructionList.push_back(I);
3553       break;
3554     }
3555     case bitc::FUNC_CODE_INST_CALL: {
3556       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3557       if (Record.size() < 3)
3558         return Error("Invalid record");
3559
3560       AttributeSet PAL = getAttributes(Record[0]);
3561       unsigned CCInfo = Record[1];
3562
3563       unsigned OpNum = 2;
3564       Value *Callee;
3565       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3566         return Error("Invalid record");
3567
3568       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3569       FunctionType *FTy = nullptr;
3570       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3571       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3572         return Error("Invalid record");
3573
3574       SmallVector<Value*, 16> Args;
3575       // Read the fixed params.
3576       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3577         if (FTy->getParamType(i)->isLabelTy())
3578           Args.push_back(getBasicBlock(Record[OpNum]));
3579         else
3580           Args.push_back(getValue(Record, OpNum, NextValueNo,
3581                                   FTy->getParamType(i)));
3582         if (!Args.back())
3583           return Error("Invalid record");
3584       }
3585
3586       // Read type/value pairs for varargs params.
3587       if (!FTy->isVarArg()) {
3588         if (OpNum != Record.size())
3589           return Error("Invalid record");
3590       } else {
3591         while (OpNum != Record.size()) {
3592           Value *Op;
3593           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3594             return Error("Invalid record");
3595           Args.push_back(Op);
3596         }
3597       }
3598
3599       I = CallInst::Create(Callee, Args);
3600       InstructionList.push_back(I);
3601       cast<CallInst>(I)->setCallingConv(
3602           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3603       CallInst::TailCallKind TCK = CallInst::TCK_None;
3604       if (CCInfo & 1)
3605         TCK = CallInst::TCK_Tail;
3606       if (CCInfo & (1 << 14))
3607         TCK = CallInst::TCK_MustTail;
3608       cast<CallInst>(I)->setTailCallKind(TCK);
3609       cast<CallInst>(I)->setAttributes(PAL);
3610       break;
3611     }
3612     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3613       if (Record.size() < 3)
3614         return Error("Invalid record");
3615       Type *OpTy = getTypeByID(Record[0]);
3616       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3617       Type *ResTy = getTypeByID(Record[2]);
3618       if (!OpTy || !Op || !ResTy)
3619         return Error("Invalid record");
3620       I = new VAArgInst(Op, ResTy);
3621       InstructionList.push_back(I);
3622       break;
3623     }
3624     }
3625
3626     // Add instruction to end of current BB.  If there is no current BB, reject
3627     // this file.
3628     if (!CurBB) {
3629       delete I;
3630       return Error("Invalid instruction with no BB");
3631     }
3632     CurBB->getInstList().push_back(I);
3633
3634     // If this was a terminator instruction, move to the next block.
3635     if (isa<TerminatorInst>(I)) {
3636       ++CurBBNo;
3637       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3638     }
3639
3640     // Non-void values get registered in the value table for future use.
3641     if (I && !I->getType()->isVoidTy())
3642       ValueList.AssignValue(I, NextValueNo++);
3643   }
3644
3645 OutOfRecordLoop:
3646
3647   // Check the function list for unresolved values.
3648   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3649     if (!A->getParent()) {
3650       // We found at least one unresolved value.  Nuke them all to avoid leaks.
3651       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3652         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3653           A->replaceAllUsesWith(UndefValue::get(A->getType()));
3654           delete A;
3655         }
3656       }
3657       return Error("Never resolved value found in function");
3658     }
3659   }
3660
3661   // FIXME: Check for unresolved forward-declared metadata references
3662   // and clean up leaks.
3663
3664   // Trim the value list down to the size it was before we parsed this function.
3665   ValueList.shrinkTo(ModuleValueListSize);
3666   MDValueList.shrinkTo(ModuleMDValueListSize);
3667   std::vector<BasicBlock*>().swap(FunctionBBs);
3668   return std::error_code();
3669 }
3670
3671 /// Find the function body in the bitcode stream
3672 std::error_code BitcodeReader::FindFunctionInStream(
3673     Function *F,
3674     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3675   while (DeferredFunctionInfoIterator->second == 0) {
3676     if (Stream.AtEndOfStream())
3677       return Error("Could not find function in stream");
3678     // ParseModule will parse the next body in the stream and set its
3679     // position in the DeferredFunctionInfo map.
3680     if (std::error_code EC = ParseModule(true))
3681       return EC;
3682   }
3683   return std::error_code();
3684 }
3685
3686 //===----------------------------------------------------------------------===//
3687 // GVMaterializer implementation
3688 //===----------------------------------------------------------------------===//
3689
3690 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3691
3692 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3693   Function *F = dyn_cast<Function>(GV);
3694   // If it's not a function or is already material, ignore the request.
3695   if (!F || !F->isMaterializable())
3696     return std::error_code();
3697
3698   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3699   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3700   // If its position is recorded as 0, its body is somewhere in the stream
3701   // but we haven't seen it yet.
3702   if (DFII->second == 0 && LazyStreamer)
3703     if (std::error_code EC = FindFunctionInStream(F, DFII))
3704       return EC;
3705
3706   // Move the bit stream to the saved position of the deferred function body.
3707   Stream.JumpToBit(DFII->second);
3708
3709   if (std::error_code EC = ParseFunctionBody(F))
3710     return EC;
3711   F->setIsMaterializable(false);
3712
3713   // Upgrade any old intrinsic calls in the function.
3714   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3715        E = UpgradedIntrinsics.end(); I != E; ++I) {
3716     if (I->first != I->second) {
3717       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3718            UI != UE;) {
3719         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3720           UpgradeIntrinsicCall(CI, I->second);
3721       }
3722     }
3723   }
3724
3725   // Bring in any functions that this function forward-referenced via
3726   // blockaddresses.
3727   return materializeForwardReferencedFunctions();
3728 }
3729
3730 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3731   const Function *F = dyn_cast<Function>(GV);
3732   if (!F || F->isDeclaration())
3733     return false;
3734
3735   // Dematerializing F would leave dangling references that wouldn't be
3736   // reconnected on re-materialization.
3737   if (BlockAddressesTaken.count(F))
3738     return false;
3739
3740   return DeferredFunctionInfo.count(const_cast<Function*>(F));
3741 }
3742
3743 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3744   Function *F = dyn_cast<Function>(GV);
3745   // If this function isn't dematerializable, this is a noop.
3746   if (!F || !isDematerializable(F))
3747     return;
3748
3749   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3750
3751   // Just forget the function body, we can remat it later.
3752   F->dropAllReferences();
3753   F->setIsMaterializable(true);
3754 }
3755
3756 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3757   assert(M == TheModule &&
3758          "Can only Materialize the Module this BitcodeReader is attached to.");
3759
3760   // Promise to materialize all forward references.
3761   WillMaterializeAllForwardRefs = true;
3762
3763   // Iterate over the module, deserializing any functions that are still on
3764   // disk.
3765   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3766        F != E; ++F) {
3767     if (std::error_code EC = materialize(F))
3768       return EC;
3769   }
3770   // At this point, if there are any function bodies, the current bit is
3771   // pointing to the END_BLOCK record after them. Now make sure the rest
3772   // of the bits in the module have been read.
3773   if (NextUnreadBit)
3774     ParseModule(true);
3775
3776   // Check that all block address forward references got resolved (as we
3777   // promised above).
3778   if (!BasicBlockFwdRefs.empty())
3779     return Error("Never resolved function from blockaddress");
3780
3781   // Upgrade any intrinsic calls that slipped through (should not happen!) and
3782   // delete the old functions to clean up. We can't do this unless the entire
3783   // module is materialized because there could always be another function body
3784   // with calls to the old function.
3785   for (std::vector<std::pair<Function*, Function*> >::iterator I =
3786        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3787     if (I->first != I->second) {
3788       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3789            UI != UE;) {
3790         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3791           UpgradeIntrinsicCall(CI, I->second);
3792       }
3793       if (!I->first->use_empty())
3794         I->first->replaceAllUsesWith(I->second);
3795       I->first->eraseFromParent();
3796     }
3797   }
3798   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3799
3800   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3801     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3802
3803   UpgradeDebugInfo(*M);
3804   return std::error_code();
3805 }
3806
3807 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3808   return IdentifiedStructTypes;
3809 }
3810
3811 std::error_code BitcodeReader::InitStream() {
3812   if (LazyStreamer)
3813     return InitLazyStream();
3814   return InitStreamFromBuffer();
3815 }
3816
3817 std::error_code BitcodeReader::InitStreamFromBuffer() {
3818   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3819   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3820
3821   if (Buffer->getBufferSize() & 3)
3822     return Error("Invalid bitcode signature");
3823
3824   // If we have a wrapper header, parse it and ignore the non-bc file contents.
3825   // The magic number is 0x0B17C0DE stored in little endian.
3826   if (isBitcodeWrapper(BufPtr, BufEnd))
3827     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3828       return Error("Invalid bitcode wrapper header");
3829
3830   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3831   Stream.init(&*StreamFile);
3832
3833   return std::error_code();
3834 }
3835
3836 std::error_code BitcodeReader::InitLazyStream() {
3837   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3838   // see it.
3839   auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3840   StreamingMemoryObject &Bytes = *OwnedBytes;
3841   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3842   Stream.init(&*StreamFile);
3843
3844   unsigned char buf[16];
3845   if (Bytes.readBytes(buf, 16, 0) != 16)
3846     return Error("Invalid bitcode signature");
3847
3848   if (!isBitcode(buf, buf + 16))
3849     return Error("Invalid bitcode signature");
3850
3851   if (isBitcodeWrapper(buf, buf + 4)) {
3852     const unsigned char *bitcodeStart = buf;
3853     const unsigned char *bitcodeEnd = buf + 16;
3854     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3855     Bytes.dropLeadingBytes(bitcodeStart - buf);
3856     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3857   }
3858   return std::error_code();
3859 }
3860
3861 namespace {
3862 class BitcodeErrorCategoryType : public std::error_category {
3863   const char *name() const LLVM_NOEXCEPT override {
3864     return "llvm.bitcode";
3865   }
3866   std::string message(int IE) const override {
3867     BitcodeError E = static_cast<BitcodeError>(IE);
3868     switch (E) {
3869     case BitcodeError::InvalidBitcodeSignature:
3870       return "Invalid bitcode signature";
3871     case BitcodeError::CorruptedBitcode:
3872       return "Corrupted bitcode";
3873     }
3874     llvm_unreachable("Unknown error type!");
3875   }
3876 };
3877 }
3878
3879 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3880
3881 const std::error_category &llvm::BitcodeErrorCategory() {
3882   return *ErrorCategory;
3883 }
3884
3885 //===----------------------------------------------------------------------===//
3886 // External interface
3887 //===----------------------------------------------------------------------===//
3888
3889 /// \brief Get a lazy one-at-time loading module from bitcode.
3890 ///
3891 /// This isn't always used in a lazy context.  In particular, it's also used by
3892 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
3893 /// in forward-referenced functions from block address references.
3894 ///
3895 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3896 /// materialize everything -- in particular, if this isn't truly lazy.
3897 static ErrorOr<Module *>
3898 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3899                          LLVMContext &Context, bool WillMaterializeAll,
3900                          DiagnosticHandlerFunction DiagnosticHandler) {
3901   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3902   BitcodeReader *R =
3903       new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3904   M->setMaterializer(R);
3905
3906   auto cleanupOnError = [&](std::error_code EC) {
3907     R->releaseBuffer(); // Never take ownership on error.
3908     delete M;  // Also deletes R.
3909     return EC;
3910   };
3911
3912   if (std::error_code EC = R->ParseBitcodeInto(M))
3913     return cleanupOnError(EC);
3914
3915   if (!WillMaterializeAll)
3916     // Resolve forward references from blockaddresses.
3917     if (std::error_code EC = R->materializeForwardReferencedFunctions())
3918       return cleanupOnError(EC);
3919
3920   Buffer.release(); // The BitcodeReader owns it now.
3921   return M;
3922 }
3923
3924 ErrorOr<Module *>
3925 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3926                            LLVMContext &Context,
3927                            DiagnosticHandlerFunction DiagnosticHandler) {
3928   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3929                                   DiagnosticHandler);
3930 }
3931
3932 ErrorOr<std::unique_ptr<Module>>
3933 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3934                                LLVMContext &Context,
3935                                DiagnosticHandlerFunction DiagnosticHandler) {
3936   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3937   BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
3938   M->setMaterializer(R);
3939   if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3940     return EC;
3941   return std::move(M);
3942 }
3943
3944 ErrorOr<Module *>
3945 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3946                        DiagnosticHandlerFunction DiagnosticHandler) {
3947   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3948   ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3949       std::move(Buf), Context, true, DiagnosticHandler);
3950   if (!ModuleOrErr)
3951     return ModuleOrErr;
3952   Module *M = ModuleOrErr.get();
3953   // Read in the entire module, and destroy the BitcodeReader.
3954   if (std::error_code EC = M->materializeAllPermanently()) {
3955     delete M;
3956     return EC;
3957   }
3958
3959   // TODO: Restore the use-lists to the in-memory state when the bitcode was
3960   // written.  We must defer until the Module has been fully materialized.
3961
3962   return M;
3963 }
3964
3965 std::string
3966 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3967                              DiagnosticHandlerFunction DiagnosticHandler) {
3968   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3969   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3970                                             DiagnosticHandler);
3971   ErrorOr<std::string> Triple = R->parseTriple();
3972   if (Triple.getError())
3973     return "";
3974   return Triple.get();
3975 }