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