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