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