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