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