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