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