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