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