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