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