blob: 9a8ec63e059d825a61fd8970b5c9f9a0dee42f23 [file] [log] [blame]
Chris Lattner1314b992007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner1314b992007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
Chris Lattner1314b992007-04-22 06:23:29 +00009
Chris Lattner6694f602007-04-29 07:54:31 +000010#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattner1314b992007-04-22 06:23:29 +000011#include "BitcodeReader.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000012#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000014#include "llvm/Bitcode/LLVMBitCodes.h"
Chandler Carruth91065212014-03-05 10:34:14 +000015#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Constants.h"
17#include "llvm/IR/DerivedTypes.h"
18#include "llvm/IR/InlineAsm.h"
19#include "llvm/IR/IntrinsicInst.h"
Manman Ren209b17c2013-09-28 00:22:27 +000020#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Module.h"
22#include "llvm/IR/OperandTraits.h"
23#include "llvm/IR/Operator.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000024#include "llvm/Support/DataStream.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000026#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000027#include "llvm/Support/raw_ostream.h"
Chris Bieneman770163e2014-09-19 20:29:02 +000028#include "llvm/Support/ManagedStatic.h"
29
Chris Lattner1314b992007-04-22 06:23:29 +000030using namespace llvm;
31
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000032enum {
33 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34};
35
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000036std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
37 if (WillMaterializeAllForwardRefs)
38 return std::error_code();
39
40 // Prevent recursion.
41 WillMaterializeAllForwardRefs = true;
42
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +000043 while (!BasicBlockFwdRefQueue.empty()) {
44 Function *F = BasicBlockFwdRefQueue.front();
45 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000046 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +000047 if (!BasicBlockFwdRefs.count(F))
48 // Already materialized.
49 continue;
50
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000051 // Check for a function that isn't materializable to prevent an infinite
52 // loop. When parsing a blockaddress stored in a global variable, there
53 // isn't a trivial way to check if a function will have a body without a
54 // linear search through FunctionsWithBodies, so just check it here.
55 if (!F->isMaterializable())
56 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
57
58 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +000059 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000060 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +000061 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +000062 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +000063
64 // Reset state.
65 WillMaterializeAllForwardRefs = false;
66 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +000067}
68
Chris Lattner9eeada92007-05-18 04:02:46 +000069void BitcodeReader::FreeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +000070 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000071 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +000072 ValueList.clear();
Devang Patel05eb6172009-08-04 06:00:18 +000073 MDValueList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +000074 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000075
Bill Wendlinge94d8432012-12-07 23:16:57 +000076 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +000077 std::vector<BasicBlock*>().swap(FunctionBBs);
78 std::vector<Function*>().swap(FunctionsWithBodies);
79 DeferredFunctionInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +000080 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +000081
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +000082 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +000083 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +000084}
85
Chris Lattnerfee5a372007-05-04 03:30:17 +000086//===----------------------------------------------------------------------===//
87// Helper functions to implement forward reference resolution, etc.
88//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +000089
Chris Lattner1314b992007-04-22 06:23:29 +000090/// ConvertToString - Convert a string from a record into an std::string, return
91/// true on failure.
Chris Lattnerccaa4482007-04-23 21:26:05 +000092template<typename StrTy>
Benjamin Kramer9704ed02012-05-28 14:10:31 +000093static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +000094 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +000095 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +000096 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000097
Chris Lattnere14cb882007-05-04 19:11:41 +000098 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
99 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000100 return false;
101}
102
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000103static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000104 switch (Val) {
105 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000106 case 0:
107 return GlobalValue::ExternalLinkage;
108 case 1:
109 return GlobalValue::WeakAnyLinkage;
110 case 2:
111 return GlobalValue::AppendingLinkage;
112 case 3:
113 return GlobalValue::InternalLinkage;
114 case 4:
115 return GlobalValue::LinkOnceAnyLinkage;
116 case 5:
117 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
118 case 6:
119 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
120 case 7:
121 return GlobalValue::ExternalWeakLinkage;
122 case 8:
123 return GlobalValue::CommonLinkage;
124 case 9:
125 return GlobalValue::PrivateLinkage;
126 case 10:
127 return GlobalValue::WeakODRLinkage;
128 case 11:
129 return GlobalValue::LinkOnceODRLinkage;
130 case 12:
131 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000132 case 13:
133 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
134 case 14:
135 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000136 case 15:
137 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Chris Lattner1314b992007-04-22 06:23:29 +0000138 }
139}
140
141static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
142 switch (Val) {
143 default: // Map unknown visibilities to default.
144 case 0: return GlobalValue::DefaultVisibility;
145 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000146 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000147 }
148}
149
Nico Rieck7157bb72014-01-14 15:22:47 +0000150static GlobalValue::DLLStorageClassTypes
151GetDecodedDLLStorageClass(unsigned Val) {
152 switch (Val) {
153 default: // Map unknown values to default.
154 case 0: return GlobalValue::DefaultStorageClass;
155 case 1: return GlobalValue::DLLImportStorageClass;
156 case 2: return GlobalValue::DLLExportStorageClass;
157 }
158}
159
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000160static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
161 switch (Val) {
162 case 0: return GlobalVariable::NotThreadLocal;
163 default: // Map unknown non-zero value to general dynamic.
164 case 1: return GlobalVariable::GeneralDynamicTLSModel;
165 case 2: return GlobalVariable::LocalDynamicTLSModel;
166 case 3: return GlobalVariable::InitialExecTLSModel;
167 case 4: return GlobalVariable::LocalExecTLSModel;
168 }
169}
170
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000171static int GetDecodedCastOpcode(unsigned Val) {
172 switch (Val) {
173 default: return -1;
174 case bitc::CAST_TRUNC : return Instruction::Trunc;
175 case bitc::CAST_ZEXT : return Instruction::ZExt;
176 case bitc::CAST_SEXT : return Instruction::SExt;
177 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
178 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
179 case bitc::CAST_UITOFP : return Instruction::UIToFP;
180 case bitc::CAST_SITOFP : return Instruction::SIToFP;
181 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
182 case bitc::CAST_FPEXT : return Instruction::FPExt;
183 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
184 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
185 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000186 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000187 }
188}
Chris Lattner229907c2011-07-18 04:54:35 +0000189static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000190 switch (Val) {
191 default: return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000192 case bitc::BINOP_ADD:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000193 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000194 case bitc::BINOP_SUB:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000195 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000196 case bitc::BINOP_MUL:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000197 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000198 case bitc::BINOP_UDIV: return Instruction::UDiv;
199 case bitc::BINOP_SDIV:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000200 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000201 case bitc::BINOP_UREM: return Instruction::URem;
202 case bitc::BINOP_SREM:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000203 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000204 case bitc::BINOP_SHL: return Instruction::Shl;
205 case bitc::BINOP_LSHR: return Instruction::LShr;
206 case bitc::BINOP_ASHR: return Instruction::AShr;
207 case bitc::BINOP_AND: return Instruction::And;
208 case bitc::BINOP_OR: return Instruction::Or;
209 case bitc::BINOP_XOR: return Instruction::Xor;
210 }
211}
212
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000213static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
214 switch (Val) {
215 default: return AtomicRMWInst::BAD_BINOP;
216 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
217 case bitc::RMW_ADD: return AtomicRMWInst::Add;
218 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
219 case bitc::RMW_AND: return AtomicRMWInst::And;
220 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
221 case bitc::RMW_OR: return AtomicRMWInst::Or;
222 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
223 case bitc::RMW_MAX: return AtomicRMWInst::Max;
224 case bitc::RMW_MIN: return AtomicRMWInst::Min;
225 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
226 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
227 }
228}
229
Eli Friedmanfee02c62011-07-25 23:16:38 +0000230static AtomicOrdering GetDecodedOrdering(unsigned Val) {
231 switch (Val) {
232 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
233 case bitc::ORDERING_UNORDERED: return Unordered;
234 case bitc::ORDERING_MONOTONIC: return Monotonic;
235 case bitc::ORDERING_ACQUIRE: return Acquire;
236 case bitc::ORDERING_RELEASE: return Release;
237 case bitc::ORDERING_ACQREL: return AcquireRelease;
238 default: // Map unknown orderings to sequentially-consistent.
239 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
240 }
241}
242
243static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
244 switch (Val) {
245 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
246 default: // Map unknown scopes to cross-thread.
247 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
248 }
249}
250
David Majnemerdad0a642014-06-27 18:19:56 +0000251static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
252 switch (Val) {
253 default: // Map unknown selection kinds to any.
254 case bitc::COMDAT_SELECTION_KIND_ANY:
255 return Comdat::Any;
256 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
257 return Comdat::ExactMatch;
258 case bitc::COMDAT_SELECTION_KIND_LARGEST:
259 return Comdat::Largest;
260 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
261 return Comdat::NoDuplicates;
262 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
263 return Comdat::SameSize;
264 }
265}
266
Nico Rieck7157bb72014-01-14 15:22:47 +0000267static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
268 switch (Val) {
269 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
270 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
271 }
272}
273
Gabor Greiff6caff662008-05-10 08:32:32 +0000274namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000275namespace {
276 /// @brief A class for maintaining the slot number definition
277 /// as a placeholder for the actual definition for forward constants defs.
278 class ConstantPlaceHolder : public ConstantExpr {
Craig Toppera60c0f12012-09-15 17:09:36 +0000279 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greife9ecc682008-04-06 20:25:17 +0000280 public:
281 // allocate space for exactly one operand
282 void *operator new(size_t s) {
283 return User::operator new(s, 1);
284 }
Chris Lattner229907c2011-07-18 04:54:35 +0000285 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000286 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000287 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner1663cca2007-04-24 05:48:56 +0000288 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000289
Chris Lattner74429932008-08-21 02:34:16 +0000290 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner74429932008-08-21 02:34:16 +0000291 static bool classof(const Value *V) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000292 return isa<ConstantExpr>(V) &&
Chris Lattner74429932008-08-21 02:34:16 +0000293 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
294 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000295
296
Gabor Greiff6caff662008-05-10 08:32:32 +0000297 /// Provide fast operand accessors
Richard Trieue3d126c2014-11-21 02:42:08 +0000298 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner1663cca2007-04-24 05:48:56 +0000299 };
300}
301
Chris Lattner2d8cd802009-03-31 22:55:09 +0000302// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000303template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000304struct OperandTraits<ConstantPlaceHolder> :
305 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000306};
Richard Trieue3d126c2014-11-21 02:42:08 +0000307DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Gabor Greiff6caff662008-05-10 08:32:32 +0000308}
309
Chris Lattner2d8cd802009-03-31 22:55:09 +0000310
311void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
312 if (Idx == size()) {
313 push_back(V);
314 return;
315 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000316
Chris Lattner2d8cd802009-03-31 22:55:09 +0000317 if (Idx >= size())
318 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000319
Chris Lattner2d8cd802009-03-31 22:55:09 +0000320 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000321 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000322 OldV = V;
323 return;
324 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000325
Chris Lattner2d8cd802009-03-31 22:55:09 +0000326 // Handle constants and non-constants (e.g. instrs) differently for
327 // efficiency.
328 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
329 ResolveConstants.push_back(std::make_pair(PHC, Idx));
330 OldV = V;
331 } else {
332 // If there was a forward reference to this value, replace it.
333 Value *PrevVal = OldV;
334 OldV->replaceAllUsesWith(V);
335 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000336 }
337}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000338
Gabor Greiff6caff662008-05-10 08:32:32 +0000339
Chris Lattner1663cca2007-04-24 05:48:56 +0000340Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000341 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000342 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000343 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000344
Chris Lattner2d8cd802009-03-31 22:55:09 +0000345 if (Value *V = ValuePtrs[Idx]) {
Chris Lattner83930552007-05-01 07:01:57 +0000346 assert(Ty == V->getType() && "Type mismatch in constant table!");
347 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000348 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000349
350 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000351 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000352 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000353 return C;
354}
355
Chris Lattner229907c2011-07-18 04:54:35 +0000356Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000357 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000358 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000359
Chris Lattner2d8cd802009-03-31 22:55:09 +0000360 if (Value *V = ValuePtrs[Idx]) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000361 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
Chris Lattner83930552007-05-01 07:01:57 +0000362 return V;
363 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000364
Chris Lattner1fc27f02007-05-02 05:16:49 +0000365 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000366 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000367
Chris Lattner83930552007-05-01 07:01:57 +0000368 // Create and return a placeholder, which will later be RAUW'd.
369 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000370 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000371 return V;
372}
373
Chris Lattner74429932008-08-21 02:34:16 +0000374/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
375/// resolves any forward references. The idea behind this is that we sometimes
376/// get constants (such as large arrays) which reference *many* forward ref
377/// constants. Replacing each of these causes a lot of thrashing when
378/// building/reuniquing the constant. Instead of doing this, we look at all the
379/// uses and rewrite all the place holders at once for any constant that uses
380/// a placeholder.
381void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000382 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000383 // binary search.
384 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000385
Chris Lattner74429932008-08-21 02:34:16 +0000386 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000387
Chris Lattner74429932008-08-21 02:34:16 +0000388 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000389 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000390 Constant *Placeholder = ResolveConstants.back().first;
391 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000392
Chris Lattner74429932008-08-21 02:34:16 +0000393 // Loop over all users of the placeholder, updating them to reference the
394 // new value. If they reference more than one placeholder, update them all
395 // at once.
396 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000397 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000398 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000399
Chris Lattner74429932008-08-21 02:34:16 +0000400 // If the using object isn't uniqued, just update the operands. This
401 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000402 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000403 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000404 continue;
405 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000406
Chris Lattner74429932008-08-21 02:34:16 +0000407 // Otherwise, we have a constant that uses the placeholder. Replace that
408 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000409 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000410 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
411 I != E; ++I) {
412 Value *NewOp;
413 if (!isa<ConstantPlaceHolder>(*I)) {
414 // Not a placeholder reference.
415 NewOp = *I;
416 } else if (*I == Placeholder) {
417 // Common case is that it just references this one placeholder.
418 NewOp = RealVal;
419 } else {
420 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000421 ResolveConstantsTy::iterator It =
422 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +0000423 std::pair<Constant*, unsigned>(cast<Constant>(*I),
424 0));
425 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000426 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +0000427 }
428
429 NewOps.push_back(cast<Constant>(NewOp));
430 }
431
432 // Make the new constant.
433 Constant *NewC;
434 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +0000435 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000436 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +0000437 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000438 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +0000439 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000440 } else {
441 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +0000442 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000443 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000444
Chris Lattner74429932008-08-21 02:34:16 +0000445 UserC->replaceAllUsesWith(NewC);
446 UserC->destroyConstant();
447 NewOps.clear();
448 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000449
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000450 // Update all ValueHandles, they should be the only users at this point.
451 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000452 delete Placeholder;
453 }
454}
455
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000456void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000457 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000458 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000459 return;
460 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000461
Devang Patel05eb6172009-08-04 06:00:18 +0000462 if (Idx >= size())
463 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000464
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000465 TrackingMDRef &OldMD = MDValuePtrs[Idx];
466 if (!OldMD) {
467 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000468 return;
469 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000470
Devang Patel05eb6172009-08-04 06:00:18 +0000471 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000472 MDNodeFwdDecl *PrevMD = cast<MDNodeFwdDecl>(OldMD.get());
473 PrevMD->replaceAllUsesWith(MD);
474 MDNode::deleteTemporary(PrevMD);
475 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +0000476}
477
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000478Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000479 if (Idx >= size())
480 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000481
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000482 if (Metadata *MD = MDValuePtrs[Idx])
483 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000484
Devang Patel05eb6172009-08-04 06:00:18 +0000485 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000486 AnyFwdRefs = true;
487 ++NumFwdRefs;
488 Metadata *MD = MDNode::getTemporary(Context, None);
489 MDValuePtrs[Idx].reset(MD);
490 return MD;
491}
492
493void BitcodeReaderMDValueList::tryToResolveCycles() {
494 if (!AnyFwdRefs)
495 // Nothing to do.
496 return;
497
498 if (NumFwdRefs)
499 // Still forward references... can't resolve cycles.
500 return;
501
502 // Resolve any cycles.
503 for (auto &MD : MDValuePtrs) {
504 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Unexpected forward reference");
505 if (auto *G = dyn_cast_or_null<GenericMDNode>(MD))
506 G->resolveCycles();
507 }
Devang Patel05eb6172009-08-04 06:00:18 +0000508}
Chris Lattner1314b992007-04-22 06:23:29 +0000509
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000510Type *BitcodeReader::getTypeByID(unsigned ID) {
511 // The type table size is always specified correctly.
512 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +0000513 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +0000514
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000515 if (Type *Ty = TypeList[ID])
516 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000517
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000518 // If we have a forward reference, the only possible case is when it is to a
519 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000520 return TypeList[ID] = createIdentifiedStructType(Context);
521}
522
523StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
524 StringRef Name) {
525 auto *Ret = StructType::create(Context, Name);
526 IdentifiedStructTypes.push_back(Ret);
527 return Ret;
528}
529
530StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
531 auto *Ret = StructType::create(Context);
532 IdentifiedStructTypes.push_back(Ret);
533 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +0000534}
535
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000536
Chris Lattnerfee5a372007-05-04 03:30:17 +0000537//===----------------------------------------------------------------------===//
538// Functions for parsing blocks from the bitcode file
539//===----------------------------------------------------------------------===//
540
Bill Wendling56aeccc2013-02-04 23:32:23 +0000541
542/// \brief This fills an AttrBuilder object with the LLVM attributes that have
543/// been decoded from the given integer. This function must stay in sync with
544/// 'encodeLLVMAttributesForBitcode'.
545static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
546 uint64_t EncodedAttrs) {
547 // FIXME: Remove in 4.0.
548
549 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
550 // the bits above 31 down by 11 bits.
551 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
552 assert((!Alignment || isPowerOf2_32(Alignment)) &&
553 "Alignment must be a power of two.");
554
555 if (Alignment)
556 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +0000557 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +0000558 (EncodedAttrs & 0xffff));
559}
560
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000561std::error_code BitcodeReader::ParseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +0000562 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000563 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000564
Devang Patela05633e2008-09-26 22:53:05 +0000565 if (!MAttributes.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000566 return Error(BitcodeError::InvalidMultipleBlocks);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000567
Chris Lattnerfee5a372007-05-04 03:30:17 +0000568 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000569
Bill Wendling71173cb2013-01-27 00:36:48 +0000570 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000571
Chris Lattnerfee5a372007-05-04 03:30:17 +0000572 // Read all the records.
573 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +0000574 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +0000575
Chris Lattner27d38752013-01-20 02:13:19 +0000576 switch (Entry.Kind) {
577 case BitstreamEntry::SubBlock: // Handled for us already.
578 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000579 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +0000580 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000581 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +0000582 case BitstreamEntry::Record:
583 // The interesting case.
584 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +0000585 }
Joe Abbey97b7a172013-02-06 22:14:06 +0000586
Chris Lattnerfee5a372007-05-04 03:30:17 +0000587 // Read a record.
588 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +0000589 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +0000590 default: // Default behavior: ignore.
591 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +0000592 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
593 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +0000594 if (Record.size() & 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000595 return Error(BitcodeError::InvalidRecord);
Chris Lattnerfee5a372007-05-04 03:30:17 +0000596
Chris Lattnerfee5a372007-05-04 03:30:17 +0000597 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +0000598 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +0000599 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +0000600 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +0000601 }
Devang Patela05633e2008-09-26 22:53:05 +0000602
Bill Wendlinge94d8432012-12-07 23:16:57 +0000603 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +0000604 Attrs.clear();
605 break;
606 }
Bill Wendling0dc08912013-02-12 08:13:50 +0000607 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
608 for (unsigned i = 0, e = Record.size(); i != e; ++i)
609 Attrs.push_back(MAttributeGroups[Record[i]]);
610
611 MAttributes.push_back(AttributeSet::get(Context, Attrs));
612 Attrs.clear();
613 break;
614 }
Duncan Sands04eb67e2007-11-20 14:09:29 +0000615 }
Chris Lattnerfee5a372007-05-04 03:30:17 +0000616 }
617}
618
Reid Klecknere9f36af2013-11-12 01:31:00 +0000619// Returns Attribute::None on unrecognized codes.
620static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
621 switch (Code) {
622 default:
623 return Attribute::None;
624 case bitc::ATTR_KIND_ALIGNMENT:
625 return Attribute::Alignment;
626 case bitc::ATTR_KIND_ALWAYS_INLINE:
627 return Attribute::AlwaysInline;
628 case bitc::ATTR_KIND_BUILTIN:
629 return Attribute::Builtin;
630 case bitc::ATTR_KIND_BY_VAL:
631 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +0000632 case bitc::ATTR_KIND_IN_ALLOCA:
633 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000634 case bitc::ATTR_KIND_COLD:
635 return Attribute::Cold;
636 case bitc::ATTR_KIND_INLINE_HINT:
637 return Attribute::InlineHint;
638 case bitc::ATTR_KIND_IN_REG:
639 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000640 case bitc::ATTR_KIND_JUMP_TABLE:
641 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000642 case bitc::ATTR_KIND_MIN_SIZE:
643 return Attribute::MinSize;
644 case bitc::ATTR_KIND_NAKED:
645 return Attribute::Naked;
646 case bitc::ATTR_KIND_NEST:
647 return Attribute::Nest;
648 case bitc::ATTR_KIND_NO_ALIAS:
649 return Attribute::NoAlias;
650 case bitc::ATTR_KIND_NO_BUILTIN:
651 return Attribute::NoBuiltin;
652 case bitc::ATTR_KIND_NO_CAPTURE:
653 return Attribute::NoCapture;
654 case bitc::ATTR_KIND_NO_DUPLICATE:
655 return Attribute::NoDuplicate;
656 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
657 return Attribute::NoImplicitFloat;
658 case bitc::ATTR_KIND_NO_INLINE:
659 return Attribute::NoInline;
660 case bitc::ATTR_KIND_NON_LAZY_BIND:
661 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000662 case bitc::ATTR_KIND_NON_NULL:
663 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000664 case bitc::ATTR_KIND_DEREFERENCEABLE:
665 return Attribute::Dereferenceable;
Reid Klecknere9f36af2013-11-12 01:31:00 +0000666 case bitc::ATTR_KIND_NO_RED_ZONE:
667 return Attribute::NoRedZone;
668 case bitc::ATTR_KIND_NO_RETURN:
669 return Attribute::NoReturn;
670 case bitc::ATTR_KIND_NO_UNWIND:
671 return Attribute::NoUnwind;
672 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
673 return Attribute::OptimizeForSize;
674 case bitc::ATTR_KIND_OPTIMIZE_NONE:
675 return Attribute::OptimizeNone;
676 case bitc::ATTR_KIND_READ_NONE:
677 return Attribute::ReadNone;
678 case bitc::ATTR_KIND_READ_ONLY:
679 return Attribute::ReadOnly;
680 case bitc::ATTR_KIND_RETURNED:
681 return Attribute::Returned;
682 case bitc::ATTR_KIND_RETURNS_TWICE:
683 return Attribute::ReturnsTwice;
684 case bitc::ATTR_KIND_S_EXT:
685 return Attribute::SExt;
686 case bitc::ATTR_KIND_STACK_ALIGNMENT:
687 return Attribute::StackAlignment;
688 case bitc::ATTR_KIND_STACK_PROTECT:
689 return Attribute::StackProtect;
690 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
691 return Attribute::StackProtectReq;
692 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
693 return Attribute::StackProtectStrong;
694 case bitc::ATTR_KIND_STRUCT_RET:
695 return Attribute::StructRet;
696 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
697 return Attribute::SanitizeAddress;
698 case bitc::ATTR_KIND_SANITIZE_THREAD:
699 return Attribute::SanitizeThread;
700 case bitc::ATTR_KIND_SANITIZE_MEMORY:
701 return Attribute::SanitizeMemory;
702 case bitc::ATTR_KIND_UW_TABLE:
703 return Attribute::UWTable;
704 case bitc::ATTR_KIND_Z_EXT:
705 return Attribute::ZExt;
706 }
707}
708
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000709std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
710 Attribute::AttrKind *Kind) {
Reid Klecknere9f36af2013-11-12 01:31:00 +0000711 *Kind = GetAttrFromCode(Code);
712 if (*Kind == Attribute::None)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000713 return Error(BitcodeError::InvalidValue);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000714 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000715}
716
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000717std::error_code BitcodeReader::ParseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +0000718 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000719 return Error(BitcodeError::InvalidRecord);
Bill Wendlingba629332013-02-10 23:24:25 +0000720
721 if (!MAttributeGroups.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000722 return Error(BitcodeError::InvalidMultipleBlocks);
Bill Wendlingba629332013-02-10 23:24:25 +0000723
724 SmallVector<uint64_t, 64> Record;
725
726 // Read all the records.
727 while (1) {
728 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
729
730 switch (Entry.Kind) {
731 case BitstreamEntry::SubBlock: // Handled for us already.
732 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000733 return Error(BitcodeError::MalformedBlock);
Bill Wendlingba629332013-02-10 23:24:25 +0000734 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000735 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +0000736 case BitstreamEntry::Record:
737 // The interesting case.
738 break;
739 }
740
741 // Read a record.
742 Record.clear();
743 switch (Stream.readRecord(Entry.ID, Record)) {
744 default: // Default behavior: ignore.
745 break;
746 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
747 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000748 return Error(BitcodeError::InvalidRecord);
Bill Wendlingba629332013-02-10 23:24:25 +0000749
Bill Wendlinge46707e2013-02-11 22:32:29 +0000750 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +0000751 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
752
753 AttrBuilder B;
754 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
755 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000756 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000757 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +0000758 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000759
760 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +0000761 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000762 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000763 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +0000764 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000765 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +0000766 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +0000767 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +0000768 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +0000769 else if (Kind == Attribute::Dereferenceable)
770 B.addDereferenceableAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +0000771 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +0000772 assert((Record[i] == 3 || Record[i] == 4) &&
773 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +0000774 bool HasValue = (Record[i++] == 4);
775 SmallString<64> KindStr;
776 SmallString<64> ValStr;
777
778 while (Record[i] != 0 && i != e)
779 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +0000780 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +0000781
782 if (HasValue) {
783 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +0000784 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +0000785 while (Record[i] != 0 && i != e)
786 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +0000787 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +0000788 }
789
790 B.addAttribute(KindStr.str(), ValStr.str());
791 }
792 }
793
Bill Wendlinge46707e2013-02-11 22:32:29 +0000794 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +0000795 break;
796 }
797 }
798 }
799}
800
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000801std::error_code BitcodeReader::ParseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000802 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000803 return Error(BitcodeError::InvalidRecord);
Derek Schuff206dddd2012-02-06 19:03:04 +0000804
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000805 return ParseTypeTableBody();
806}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000807
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000808std::error_code BitcodeReader::ParseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +0000809 if (!TypeList.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000810 return Error(BitcodeError::InvalidMultipleBlocks);
Chris Lattner1314b992007-04-22 06:23:29 +0000811
812 SmallVector<uint64_t, 64> Record;
813 unsigned NumRecords = 0;
814
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000815 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +0000816
Chris Lattner1314b992007-04-22 06:23:29 +0000817 // Read all the records for this type table.
818 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +0000819 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +0000820
Chris Lattner27d38752013-01-20 02:13:19 +0000821 switch (Entry.Kind) {
822 case BitstreamEntry::SubBlock: // Handled for us already.
823 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000824 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +0000825 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +0000826 if (NumRecords != TypeList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000827 return Error(BitcodeError::MalformedBlock);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000828 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +0000829 case BitstreamEntry::Record:
830 // The interesting case.
831 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000832 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000833
Chris Lattner1314b992007-04-22 06:23:29 +0000834 // Read a record.
835 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +0000836 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +0000837 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +0000838 default:
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000839 return Error(BitcodeError::InvalidValue);
Chris Lattner1314b992007-04-22 06:23:29 +0000840 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
841 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
842 // type list. This allows us to reserve space.
843 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000844 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000845 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +0000846 continue;
Chris Lattner1314b992007-04-22 06:23:29 +0000847 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +0000848 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000849 break;
Dan Gohman518cda42011-12-17 00:04:22 +0000850 case bitc::TYPE_CODE_HALF: // HALF
851 ResultTy = Type::getHalfTy(Context);
852 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000853 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +0000854 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000855 break;
856 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +0000857 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000858 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000859 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +0000860 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000861 break;
862 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +0000863 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000864 break;
865 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +0000866 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000867 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000868 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +0000869 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +0000870 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +0000871 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +0000872 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +0000873 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +0000874 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
875 ResultTy = Type::getX86_MMXTy(Context);
876 break;
Chris Lattner1314b992007-04-22 06:23:29 +0000877 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
878 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000879 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000880
Owen Anderson55f1c092009-08-13 21:58:54 +0000881 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +0000882 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000883 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000884 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +0000885 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000886 return Error(BitcodeError::InvalidRecord);
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000887 unsigned AddressSpace = 0;
888 if (Record.size() == 2)
889 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000890 ResultTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000891 if (!ResultTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000892 return Error(BitcodeError::InvalidType);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000893 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +0000894 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000895 }
Nuno Lopes561dae02012-05-23 15:19:39 +0000896 case bitc::TYPE_CODE_FUNCTION_OLD: {
897 // FIXME: attrid is dead, remove it in LLVM 4.0
898 // FUNCTION: [vararg, attrid, retty, paramty x N]
899 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000900 return Error(BitcodeError::InvalidRecord);
Nuno Lopes561dae02012-05-23 15:19:39 +0000901 SmallVector<Type*, 8> ArgTys;
902 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
903 if (Type *T = getTypeByID(Record[i]))
904 ArgTys.push_back(T);
905 else
906 break;
907 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000908
Nuno Lopes561dae02012-05-23 15:19:39 +0000909 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000910 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000911 return Error(BitcodeError::InvalidType);
Nuno Lopes561dae02012-05-23 15:19:39 +0000912
913 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
914 break;
915 }
Chad Rosier95898722011-11-03 00:14:01 +0000916 case bitc::TYPE_CODE_FUNCTION: {
917 // FUNCTION: [vararg, retty, paramty x N]
918 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000919 return Error(BitcodeError::InvalidRecord);
Chris Lattnercc3aaf12012-01-27 03:15:49 +0000920 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +0000921 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
922 if (Type *T = getTypeByID(Record[i]))
923 ArgTys.push_back(T);
924 else
925 break;
926 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000927
Chad Rosier95898722011-11-03 00:14:01 +0000928 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +0000929 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000930 return Error(BitcodeError::InvalidType);
Chad Rosier95898722011-11-03 00:14:01 +0000931
932 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
933 break;
934 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000935 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +0000936 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000937 return Error(BitcodeError::InvalidRecord);
Chris Lattnercc3aaf12012-01-27 03:15:49 +0000938 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000939 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
940 if (Type *T = getTypeByID(Record[i]))
941 EltTys.push_back(T);
942 else
943 break;
944 }
945 if (EltTys.size() != Record.size()-1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000946 return Error(BitcodeError::InvalidType);
Owen Anderson03cb69f2009-08-05 23:16:16 +0000947 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +0000948 break;
949 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000950 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
951 if (ConvertToString(Record, 0, TypeName))
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000952 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000953 continue;
954
955 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
956 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000957 return Error(BitcodeError::InvalidRecord);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000958
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000959 if (NumRecords >= TypeList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000960 return Error(BitcodeError::InvalidTYPETable);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000961
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000962 // Check to see if this was forward referenced, if so fill in the temp.
963 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
964 if (Res) {
965 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +0000966 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000967 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000968 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000969 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000970
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000971 SmallVector<Type*, 8> EltTys;
972 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
973 if (Type *T = getTypeByID(Record[i]))
974 EltTys.push_back(T);
975 else
976 break;
977 }
978 if (EltTys.size() != Record.size()-1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000979 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000980 Res->setBody(EltTys, Record[0]);
981 ResultTy = Res;
982 break;
983 }
984 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
985 if (Record.size() != 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000986 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000987
988 if (NumRecords >= TypeList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +0000989 return Error(BitcodeError::InvalidTYPETable);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000990
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000991 // Check to see if this was forward referenced, if so fill in the temp.
992 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
993 if (Res) {
994 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +0000995 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000996 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000997 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000998 TypeName.clear();
999 ResultTy = Res;
1000 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001001 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001002 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1003 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001004 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001005 if ((ResultTy = getTypeByID(Record[1])))
1006 ResultTy = ArrayType::get(ResultTy, Record[0]);
1007 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001008 return Error(BitcodeError::InvalidType);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001009 break;
1010 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1011 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001012 return Error(BitcodeError::InvalidRecord);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001013 if ((ResultTy = getTypeByID(Record[1])))
1014 ResultTy = VectorType::get(ResultTy, Record[0]);
1015 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001016 return Error(BitcodeError::InvalidType);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001017 break;
1018 }
1019
1020 if (NumRecords >= TypeList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001021 return Error(BitcodeError::InvalidTYPETable);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001022 assert(ResultTy && "Didn't read a type?");
Craig Topper2617dcc2014-04-15 06:32:26 +00001023 assert(!TypeList[NumRecords] && "Already read type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001024 TypeList[NumRecords++] = ResultTy;
1025 }
1026}
1027
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001028std::error_code BitcodeReader::ParseValueSymbolTable() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001029 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001030 return Error(BitcodeError::InvalidRecord);
Chris Lattnerccaa4482007-04-23 21:26:05 +00001031
1032 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001033
Chris Lattnerccaa4482007-04-23 21:26:05 +00001034 // Read all the records for this value table.
1035 SmallString<128> ValueName;
1036 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001037 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001038
Chris Lattner27d38752013-01-20 02:13:19 +00001039 switch (Entry.Kind) {
1040 case BitstreamEntry::SubBlock: // Handled for us already.
1041 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001042 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00001043 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001044 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001045 case BitstreamEntry::Record:
1046 // The interesting case.
1047 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001048 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001049
Chris Lattnerccaa4482007-04-23 21:26:05 +00001050 // Read a record.
1051 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001052 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001053 default: // Default behavior: unknown type.
1054 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001055 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattnerccaa4482007-04-23 21:26:05 +00001056 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001057 return Error(BitcodeError::InvalidRecord);
Chris Lattnerccaa4482007-04-23 21:26:05 +00001058 unsigned ValueID = Record[0];
Karthik Bhat82540e92014-03-27 12:08:23 +00001059 if (ValueID >= ValueList.size() || !ValueList[ValueID])
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001060 return Error(BitcodeError::InvalidRecord);
Chris Lattnerccaa4482007-04-23 21:26:05 +00001061 Value *V = ValueList[ValueID];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001062
Daniel Dunbard786b512009-07-26 00:34:27 +00001063 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnerccaa4482007-04-23 21:26:05 +00001064 ValueName.clear();
1065 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001066 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001067 case bitc::VST_CODE_BBENTRY: {
Chris Lattner6be58c62007-05-03 22:18:21 +00001068 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001069 return Error(BitcodeError::InvalidRecord);
Chris Lattner6be58c62007-05-03 22:18:21 +00001070 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001071 if (!BB)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001072 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001073
Daniel Dunbard786b512009-07-26 00:34:27 +00001074 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001075 ValueName.clear();
1076 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001077 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001078 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001079 }
1080}
1081
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001082std::error_code BitcodeReader::ParseMetadata() {
Devang Patel89923232010-01-11 18:52:33 +00001083 unsigned NextMDValueNo = MDValueList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001084
1085 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001086 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001087
Devang Patel7428d8a2009-07-22 17:43:22 +00001088 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001089
Devang Patel7428d8a2009-07-22 17:43:22 +00001090 // Read all the records.
1091 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001092 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001093
Chris Lattner27d38752013-01-20 02:13:19 +00001094 switch (Entry.Kind) {
1095 case BitstreamEntry::SubBlock: // Handled for us already.
1096 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001097 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00001098 case BitstreamEntry::EndBlock:
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001099 MDValueList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001100 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001101 case BitstreamEntry::Record:
1102 // The interesting case.
1103 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001104 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001105
Devang Patel7428d8a2009-07-22 17:43:22 +00001106 // Read a record.
1107 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001108 unsigned Code = Stream.readRecord(Entry.ID, Record);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001109 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001110 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001111 default: // Default behavior: ignore.
1112 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001113 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001114 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001115 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001116 Record.clear();
1117 Code = Stream.ReadCode();
1118
Chris Lattnerb8778552011-06-17 17:50:30 +00001119 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner27d38752013-01-20 02:13:19 +00001120 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattnerb8778552011-06-17 17:50:30 +00001121 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patel27c87ff2009-07-29 22:34:41 +00001122
1123 // Read named metadata elements.
1124 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001125 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001126 for (unsigned i = 0; i != Size; ++i) {
Karthik Bhat82540e92014-03-27 12:08:23 +00001127 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001128 if (!MD)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001129 return Error(BitcodeError::InvalidRecord);
Dan Gohman2637cc12010-07-21 23:38:33 +00001130 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001131 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001132 break;
1133 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001134 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001135 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001136 // This is a LocalAsMetadata record, the only type of function-local
1137 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001138 if (Record.size() % 2 == 1)
1139 return Error(BitcodeError::InvalidRecord);
1140
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001141 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1142 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001143 auto dropRecord = [&] {
1144 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1145 };
1146 if (Record.size() != 2) {
1147 dropRecord();
1148 break;
1149 }
1150
1151 Type *Ty = getTypeByID(Record[0]);
1152 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1153 dropRecord();
1154 break;
1155 }
1156
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001157 MDValueList.AssignValue(
1158 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1159 NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001160 break;
1161 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001162 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001163 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00001164 if (Record.size() % 2 == 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001165 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001166
Devang Patele059ba6e2009-07-23 01:07:34 +00001167 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001168 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00001169 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001170 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001171 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001172 return Error(BitcodeError::InvalidRecord);
Chris Lattnerfdd87902009-10-05 05:54:46 +00001173 if (Ty->isMetadataTy())
Devang Patel05eb6172009-08-04 06:00:18 +00001174 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001175 else if (!Ty->isVoidTy()) {
1176 auto *MD =
1177 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1178 assert(isa<ConstantAsMetadata>(MD) &&
1179 "Expected non-function-local metadata");
1180 Elts.push_back(MD);
1181 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00001182 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00001183 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001184 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00001185 break;
1186 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001187 case bitc::METADATA_VALUE: {
1188 if (Record.size() != 2)
1189 return Error(BitcodeError::InvalidRecord);
1190
1191 Type *Ty = getTypeByID(Record[0]);
1192 if (Ty->isMetadataTy() || Ty->isVoidTy())
1193 return Error(BitcodeError::InvalidRecord);
1194
1195 MDValueList.AssignValue(
1196 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1197 NextMDValueNo++);
1198 break;
1199 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001200 case bitc::METADATA_DISTINCT_NODE:
1201 IsDistinct = true;
1202 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001203 case bitc::METADATA_NODE: {
1204 SmallVector<Metadata *, 8> Elts;
1205 Elts.reserve(Record.size());
1206 for (unsigned ID : Record)
1207 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001208 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1209 : MDNode::get(Context, Elts),
1210 NextMDValueNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001211 break;
1212 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001213 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00001214 std::string String(Record.begin(), Record.end());
1215 llvm::UpgradeMDStringConstant(String);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001216 Metadata *MD = MDString::get(Context, String);
1217 MDValueList.AssignValue(MD, NextMDValueNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00001218 break;
1219 }
Devang Patelaf206b82009-09-18 19:26:43 +00001220 case bitc::METADATA_KIND: {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001221 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001222 return Error(BitcodeError::InvalidRecord);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001223
Devang Patelb1a44772009-09-28 21:14:55 +00001224 unsigned Kind = Record[0];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001225 SmallString<8> Name(Record.begin()+1, Record.end());
1226
Chris Lattnera0566972009-12-29 09:01:33 +00001227 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman43aa8f02010-07-20 21:42:28 +00001228 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001229 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
Devang Patelaf206b82009-09-18 19:26:43 +00001230 break;
1231 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001232 }
1233 }
1234}
1235
Jan Wen Voungafaced02012-10-11 20:20:40 +00001236/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner08feb1e2007-04-24 04:04:35 +00001237/// the LSB for dense VBR encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001238uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00001239 if ((V & 1) == 0)
1240 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001241 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00001242 return -(V >> 1);
1243 // There is no such thing as -0 with integers. "-0" really means MININT.
1244 return 1ULL << 63;
1245}
1246
Chris Lattner44c17072007-04-26 02:46:40 +00001247/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1248/// values and aliases that we can.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001249std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00001250 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1251 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001252 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001253 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001254
Chris Lattner44c17072007-04-26 02:46:40 +00001255 GlobalInitWorklist.swap(GlobalInits);
1256 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001257 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001258 FunctionPrologueWorklist.swap(FunctionPrologues);
Chris Lattner44c17072007-04-26 02:46:40 +00001259
1260 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00001261 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00001262 if (ValID >= ValueList.size()) {
1263 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00001264 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00001265 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001266 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00001267 GlobalInitWorklist.back().first->setInitializer(C);
1268 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001269 return Error(BitcodeError::ExpectedConstant);
Chris Lattner44c17072007-04-26 02:46:40 +00001270 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001271 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001272 }
1273
1274 while (!AliasInitWorklist.empty()) {
1275 unsigned ValID = AliasInitWorklist.back().second;
1276 if (ValID >= ValueList.size()) {
1277 AliasInits.push_back(AliasInitWorklist.back());
1278 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001279 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Rafael Espindola64c1e182014-06-03 02:41:57 +00001280 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00001281 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001282 return Error(BitcodeError::ExpectedConstant);
Chris Lattner44c17072007-04-26 02:46:40 +00001283 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001284 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00001285 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001286
1287 while (!FunctionPrefixWorklist.empty()) {
1288 unsigned ValID = FunctionPrefixWorklist.back().second;
1289 if (ValID >= ValueList.size()) {
1290 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1291 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00001292 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001293 FunctionPrefixWorklist.back().first->setPrefixData(C);
1294 else
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001295 return Error(BitcodeError::ExpectedConstant);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001296 }
1297 FunctionPrefixWorklist.pop_back();
1298 }
1299
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001300 while (!FunctionPrologueWorklist.empty()) {
1301 unsigned ValID = FunctionPrologueWorklist.back().second;
1302 if (ValID >= ValueList.size()) {
1303 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1304 } else {
1305 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1306 FunctionPrologueWorklist.back().first->setPrologueData(C);
1307 else
1308 return Error(BitcodeError::ExpectedConstant);
1309 }
1310 FunctionPrologueWorklist.pop_back();
1311 }
1312
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001313 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00001314}
1315
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001316static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1317 SmallVector<uint64_t, 8> Words(Vals.size());
1318 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00001319 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001320
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00001321 return APInt(TypeBits, Words);
1322}
1323
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001324std::error_code BitcodeReader::ParseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001325 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001326 return Error(BitcodeError::InvalidRecord);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001327
1328 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001329
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001330 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00001331 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00001332 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001333 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001334 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001335
Chris Lattner27d38752013-01-20 02:13:19 +00001336 switch (Entry.Kind) {
1337 case BitstreamEntry::SubBlock: // Handled for us already.
1338 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001339 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00001340 case BitstreamEntry::EndBlock:
1341 if (NextCstNo != ValueList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001342 return Error(BitcodeError::InvalidConstantReference);
Joe Abbey97b7a172013-02-06 22:14:06 +00001343
Chris Lattner27d38752013-01-20 02:13:19 +00001344 // Once all the constants have been read, go through and resolve forward
1345 // references.
1346 ValueList.ResolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001347 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001348 case BitstreamEntry::Record:
1349 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00001350 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001351 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001352
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001353 // Read a record.
1354 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001355 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001356 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00001357 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001358 default: // Default behavior: unknown constant
1359 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00001360 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001361 break;
1362 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1363 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001364 return Error(BitcodeError::InvalidRecord);
Karthik Bhat82540e92014-03-27 12:08:23 +00001365 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001366 return Error(BitcodeError::InvalidRecord);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001367 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00001368 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001369 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00001370 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001371 break;
1372 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00001373 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001374 return Error(BitcodeError::InvalidRecord);
Jan Wen Voungafaced02012-10-11 20:20:40 +00001375 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00001376 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001377 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00001378 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001379 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001380
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001381 APInt VInt = ReadWideAPInt(Record,
1382 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00001383 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001384
Chris Lattner08feb1e2007-04-24 04:04:35 +00001385 break;
1386 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00001387 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00001388 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001389 return Error(BitcodeError::InvalidRecord);
Dan Gohman518cda42011-12-17 00:04:22 +00001390 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00001391 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1392 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00001393 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00001394 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1395 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001396 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00001397 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1398 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001399 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00001400 // Bits are not stored the same way as a normal i80 APInt, compensate.
1401 uint64_t Rearrange[2];
1402 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1403 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00001404 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1405 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001406 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00001407 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1408 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00001409 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00001410 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1411 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001412 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001413 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001414 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00001415 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001416
Chris Lattnere14cb882007-05-04 19:11:41 +00001417 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1418 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001419 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001420
Chris Lattnere14cb882007-05-04 19:11:41 +00001421 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001422 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001423
Chris Lattner229907c2011-07-18 04:54:35 +00001424 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00001425 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001426 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00001427 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00001428 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00001429 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1430 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00001431 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001432 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00001433 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00001434 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1435 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00001436 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00001437 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00001438 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00001439 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001440 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00001441 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001442 break;
1443 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00001444 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00001445 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1446 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001447 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001448
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001449 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00001450 V = ConstantDataArray::getString(Context, Elts,
1451 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00001452 break;
1453 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00001454 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1455 if (Record.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001456 return Error(BitcodeError::InvalidRecord);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001457
Chris Lattner372dd1e2012-01-30 00:51:16 +00001458 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1459 unsigned Size = Record.size();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001460
Chris Lattner372dd1e2012-01-30 00:51:16 +00001461 if (EltTy->isIntegerTy(8)) {
1462 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1463 if (isa<VectorType>(CurTy))
1464 V = ConstantDataVector::get(Context, Elts);
1465 else
1466 V = ConstantDataArray::get(Context, Elts);
1467 } else if (EltTy->isIntegerTy(16)) {
1468 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1469 if (isa<VectorType>(CurTy))
1470 V = ConstantDataVector::get(Context, Elts);
1471 else
1472 V = ConstantDataArray::get(Context, Elts);
1473 } else if (EltTy->isIntegerTy(32)) {
1474 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1475 if (isa<VectorType>(CurTy))
1476 V = ConstantDataVector::get(Context, Elts);
1477 else
1478 V = ConstantDataArray::get(Context, Elts);
1479 } else if (EltTy->isIntegerTy(64)) {
1480 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1481 if (isa<VectorType>(CurTy))
1482 V = ConstantDataVector::get(Context, Elts);
1483 else
1484 V = ConstantDataArray::get(Context, Elts);
1485 } else if (EltTy->isFloatTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001486 SmallVector<float, 16> Elts(Size);
1487 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001488 if (isa<VectorType>(CurTy))
1489 V = ConstantDataVector::get(Context, Elts);
1490 else
1491 V = ConstantDataArray::get(Context, Elts);
1492 } else if (EltTy->isDoubleTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001493 SmallVector<double, 16> Elts(Size);
1494 std::transform(Record.begin(), Record.end(), Elts.begin(),
1495 BitsToDouble);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001496 if (isa<VectorType>(CurTy))
1497 V = ConstantDataVector::get(Context, Elts);
1498 else
1499 V = ConstantDataArray::get(Context, Elts);
1500 } else {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001501 return Error(BitcodeError::InvalidTypeForValue);
Chris Lattner372dd1e2012-01-30 00:51:16 +00001502 }
1503 break;
1504 }
1505
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001506 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001507 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001508 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001509 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00001510 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001511 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00001512 } else {
1513 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1514 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00001515 unsigned Flags = 0;
1516 if (Record.size() >= 4) {
1517 if (Opc == Instruction::Add ||
1518 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00001519 Opc == Instruction::Mul ||
1520 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00001521 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1522 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1523 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1524 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00001525 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00001526 Opc == Instruction::UDiv ||
1527 Opc == Instruction::LShr ||
1528 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00001529 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00001530 Flags |= SDivOperator::IsExact;
1531 }
1532 }
1533 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00001534 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001535 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001536 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001537 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001538 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001539 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001540 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00001541 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001542 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00001543 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00001544 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001545 if (!OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001546 return Error(BitcodeError::InvalidRecord);
Chris Lattner890683d2007-04-24 18:15:21 +00001547 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001548 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1549 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00001550 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001551 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001552 }
Dan Gohman1639c392009-07-27 21:53:46 +00001553 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001554 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001555 if (Record.size() & 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001556 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001557 SmallVector<Constant*, 16> Elts;
Chris Lattnere14cb882007-05-04 19:11:41 +00001558 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001559 Type *ElTy = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001560 if (!ElTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001561 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001562 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1563 }
Jay Foaded8db7d2011-07-21 14:31:17 +00001564 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad2f5fc8c2011-07-21 15:15:37 +00001565 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1566 BitCode ==
1567 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00001568 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001569 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00001570 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001571 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001572 return Error(BitcodeError::InvalidRecord);
Joe Abbey1a6e7702013-09-12 22:02:31 +00001573
1574 Type *SelectorTy = Type::getInt1Ty(Context);
1575
1576 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1577 // vector. Otherwise, it must be a single bit.
1578 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1579 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1580 VTy->getNumElements());
1581
1582 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1583 SelectorTy),
1584 ValueList.getConstantFwdRef(Record[1],CurTy),
1585 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001586 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00001587 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001588 case bitc::CST_CODE_CE_EXTRACTELT
1589 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001590 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001591 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00001592 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001593 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001594 if (!OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001595 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001596 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001597 Constant *Op1 = nullptr;
1598 if (Record.size() == 4) {
1599 Type *IdxTy = getTypeByID(Record[2]);
1600 if (!IdxTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001601 return Error(BitcodeError::InvalidRecord);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001602 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1603 } else // TODO: Remove with llvm 4.0
1604 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1605 if (!Op1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001606 return Error(BitcodeError::InvalidRecord);
Owen Anderson487375e2009-07-29 18:55:55 +00001607 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001608 break;
1609 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001610 case bitc::CST_CODE_CE_INSERTELT
1611 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00001612 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00001613 if (Record.size() < 3 || !OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001614 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001615 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1616 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1617 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001618 Constant *Op2 = nullptr;
1619 if (Record.size() == 4) {
1620 Type *IdxTy = getTypeByID(Record[2]);
1621 if (!IdxTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001622 return Error(BitcodeError::InvalidRecord);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00001623 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1624 } else // TODO: Remove with llvm 4.0
1625 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1626 if (!Op2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001627 return Error(BitcodeError::InvalidRecord);
Owen Anderson487375e2009-07-29 18:55:55 +00001628 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001629 break;
1630 }
1631 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00001632 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00001633 if (Record.size() < 3 || !OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001634 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001635 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1636 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001637 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00001638 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001639 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00001640 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001641 break;
1642 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00001643 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00001644 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1645 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00001646 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001647 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001648 return Error(BitcodeError::InvalidRecord);
Nate Begeman94aa38d2009-02-12 21:28:33 +00001649 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1650 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00001651 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00001652 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00001653 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00001654 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00001655 break;
1656 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001657 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00001658 if (Record.size() < 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001659 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00001660 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001661 if (!OpTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001662 return Error(BitcodeError::InvalidRecord);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001663 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1664 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1665
Duncan Sands9dff9be2010-02-15 16:12:20 +00001666 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00001667 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00001668 else
Owen Anderson487375e2009-07-29 18:55:55 +00001669 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001670 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00001671 }
Chad Rosierd8c76102012-09-05 19:00:49 +00001672 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00001673 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001674 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001675 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001676 return Error(BitcodeError::InvalidRecord);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001677 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00001678 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00001679 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001680 unsigned AsmStrSize = Record[1];
1681 if (2+AsmStrSize >= Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001682 return Error(BitcodeError::InvalidRecord);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001683 unsigned ConstStrSize = Record[2+AsmStrSize];
1684 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001685 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001686
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001687 for (unsigned i = 0; i != AsmStrSize; ++i)
1688 AsmStr += (char)Record[2+i];
1689 for (unsigned i = 0; i != ConstStrSize; ++i)
1690 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00001691 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001692 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00001693 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00001694 break;
1695 }
Chad Rosierd8c76102012-09-05 19:00:49 +00001696 // This version adds support for the asm dialect keywords (e.g.,
1697 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001698 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001699 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001700 return Error(BitcodeError::InvalidRecord);
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001701 std::string AsmStr, ConstrStr;
1702 bool HasSideEffects = Record[0] & 1;
1703 bool IsAlignStack = (Record[0] >> 1) & 1;
1704 unsigned AsmDialect = Record[0] >> 2;
1705 unsigned AsmStrSize = Record[1];
1706 if (2+AsmStrSize >= Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001707 return Error(BitcodeError::InvalidRecord);
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001708 unsigned ConstStrSize = Record[2+AsmStrSize];
1709 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001710 return Error(BitcodeError::InvalidRecord);
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001711
1712 for (unsigned i = 0; i != AsmStrSize; ++i)
1713 AsmStr += (char)Record[2+i];
1714 for (unsigned i = 0; i != ConstStrSize; ++i)
1715 ConstrStr += (char)Record[3+AsmStrSize+i];
1716 PointerType *PTy = cast<PointerType>(CurTy);
1717 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1718 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00001719 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00001720 break;
1721 }
Chris Lattner5956dc82009-10-28 05:53:48 +00001722 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00001723 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001724 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00001725 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001726 if (!FnTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001727 return Error(BitcodeError::InvalidRecord);
Chris Lattner5956dc82009-10-28 05:53:48 +00001728 Function *Fn =
1729 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00001730 if (!Fn)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001731 return Error(BitcodeError::InvalidRecord);
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001732
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00001733 // Don't let Fn get dematerialized.
1734 BlockAddressesTaken.insert(Fn);
1735
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001736 // If the function is already parsed we can insert the block address right
1737 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001738 BasicBlock *BB;
1739 unsigned BBID = Record[2];
1740 if (!BBID)
1741 // Invalid reference to entry block.
1742 return Error(BitcodeError::InvalidID);
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001743 if (!Fn->empty()) {
1744 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001745 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001746 if (BBI == BBE)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001747 return Error(BitcodeError::InvalidID);
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001748 ++BBI;
1749 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001750 BB = BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001751 } else {
1752 // Otherwise insert a placeholder and remember it so it can be inserted
1753 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00001754 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1755 if (FwdBBs.empty())
1756 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00001757 if (FwdBBs.size() < BBID + 1)
1758 FwdBBs.resize(BBID + 1);
1759 if (!FwdBBs[BBID])
1760 FwdBBs[BBID] = BasicBlock::Create(Context);
1761 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00001762 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00001763 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00001764 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001765 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001766 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001767
Chris Lattner83930552007-05-01 07:01:57 +00001768 ValueList.AssignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00001769 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001770 }
1771}
Chris Lattner1314b992007-04-22 06:23:29 +00001772
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001773std::error_code BitcodeReader::ParseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00001774 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001775 return Error(BitcodeError::InvalidRecord);
Chad Rosierca2567b2011-12-07 21:44:12 +00001776
Chad Rosierca2567b2011-12-07 21:44:12 +00001777 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001778 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00001779 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001780 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001781
Chris Lattner27d38752013-01-20 02:13:19 +00001782 switch (Entry.Kind) {
1783 case BitstreamEntry::SubBlock: // Handled for us already.
1784 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001785 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00001786 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001787 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001788 case BitstreamEntry::Record:
1789 // The interesting case.
1790 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00001791 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001792
Chad Rosierca2567b2011-12-07 21:44:12 +00001793 // Read a use list record.
1794 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001795 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00001796 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00001797 default: // Default behavior: unknown type.
1798 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001799 case bitc::USELIST_CODE_BB:
1800 IsBB = true;
1801 // fallthrough
1802 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00001803 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001804 if (RecordLength < 3)
1805 // Records should have at least an ID and two indexes.
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001806 return Error(BitcodeError::InvalidRecord);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001807 unsigned ID = Record.back();
1808 Record.pop_back();
1809
1810 Value *V;
1811 if (IsBB) {
1812 assert(ID < FunctionBBs.size() && "Basic block not found");
1813 V = FunctionBBs[ID];
1814 } else
1815 V = ValueList[ID];
1816 unsigned NumUses = 0;
1817 SmallDenseMap<const Use *, unsigned, 16> Order;
1818 for (const Use &U : V->uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00001819 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001820 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00001821 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00001822 }
1823 if (Order.size() != Record.size() || NumUses > Record.size())
1824 // Mismatches can happen if the functions are being materialized lazily
1825 // (out-of-order), or a value has been upgraded.
1826 break;
1827
1828 V->sortUseList([&](const Use &L, const Use &R) {
1829 return Order.lookup(&L) < Order.lookup(&R);
1830 });
Chad Rosierca2567b2011-12-07 21:44:12 +00001831 break;
1832 }
1833 }
1834 }
1835}
1836
Chris Lattner85b7b402007-05-01 05:52:21 +00001837/// RememberAndSkipFunctionBody - When we see the block for a function body,
1838/// remember where it is and then skip it. This lets us lazily deserialize the
1839/// functions.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001840std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001841 // Get the function we are talking about.
1842 if (FunctionsWithBodies.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001843 return Error(BitcodeError::InsufficientFunctionProtos);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001844
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001845 Function *Fn = FunctionsWithBodies.back();
1846 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001847
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001848 // Save the current stream state.
1849 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001850 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001851
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001852 // Skip over the function block for now.
1853 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001854 return Error(BitcodeError::InvalidRecord);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001855 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001856}
1857
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001858std::error_code BitcodeReader::GlobalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001859 // Patch the initializers for globals and aliases up.
1860 ResolveGlobalAndAliasInits();
1861 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001862 return Error(BitcodeError::MalformedGlobalInitializerSet);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001863
1864 // Look for intrinsic functions which need to be upgraded at some point
1865 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1866 FI != FE; ++FI) {
1867 Function *NewFn;
1868 if (UpgradeIntrinsicFunction(FI, NewFn))
1869 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1870 }
1871
1872 // Look for global variables which need to be renamed.
1873 for (Module::global_iterator
1874 GI = TheModule->global_begin(), GE = TheModule->global_end();
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001875 GI != GE;) {
1876 GlobalVariable *GV = GI++;
1877 UpgradeGlobalVariable(GV);
1878 }
1879
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001880 // Force deallocation of memory for these vectors to favor the client that
1881 // want lazy deserialization.
1882 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1883 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001884 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001885}
1886
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001887std::error_code BitcodeReader::ParseModule(bool Resume) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001888 if (Resume)
1889 Stream.JumpToBit(NextUnreadBit);
1890 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001891 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00001892
Chris Lattner1314b992007-04-22 06:23:29 +00001893 SmallVector<uint64_t, 64> Record;
1894 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00001895 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00001896
1897 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00001898 while (1) {
1899 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00001900
Chris Lattner27d38752013-01-20 02:13:19 +00001901 switch (Entry.Kind) {
1902 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001903 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00001904 case BitstreamEntry::EndBlock:
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001905 return GlobalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00001906
Chris Lattner27d38752013-01-20 02:13:19 +00001907 case BitstreamEntry::SubBlock:
1908 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00001909 default: // Skip unknown content.
1910 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001911 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00001912 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00001913 case bitc::BLOCKINFO_BLOCK_ID:
1914 if (Stream.ReadBlockInfoBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001915 return Error(BitcodeError::MalformedBlock);
Chris Lattner6eeea5d2007-05-05 18:57:30 +00001916 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001917 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001918 if (std::error_code EC = ParseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001919 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001920 break;
Bill Wendlingba629332013-02-10 23:24:25 +00001921 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001922 if (std::error_code EC = ParseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001923 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00001924 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001925 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001926 if (std::error_code EC = ParseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001927 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00001928 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001929 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001930 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001931 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001932 SeenValueSymbolTable = true;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001933 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001934 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001935 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001936 return EC;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001937 if (std::error_code EC = ResolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001938 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00001939 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001940 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001941 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001942 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00001943 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001944 case bitc::FUNCTION_BLOCK_ID:
1945 // If this is the first function body we've seen, reverse the
1946 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001947 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001948 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001949 if (std::error_code EC = GlobalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001950 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001951 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001952 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001953
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001954 if (std::error_code EC = RememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001955 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001956 // For streaming bitcode, suspend parsing when we reach the function
1957 // bodies. Subsequent materialization calls will resume it when
1958 // necessary. For streaming, the function bodies must be at the end of
1959 // the bitcode. If the bitcode file is old, the symbol table will be
1960 // at the end instead and will not have been seen yet. In this case,
1961 // just finish the parse now.
1962 if (LazyStreamer && SeenValueSymbolTable) {
1963 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001964 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00001965 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00001966 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00001967 case bitc::USELIST_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001968 if (std::error_code EC = ParseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00001969 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00001970 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001971 }
1972 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00001973
Chris Lattner27d38752013-01-20 02:13:19 +00001974 case BitstreamEntry::Record:
1975 // The interesting case.
1976 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001977 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001978
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001979
Chris Lattner1314b992007-04-22 06:23:29 +00001980 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00001981 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1314b992007-04-22 06:23:29 +00001982 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001983 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00001984 if (Record.size() < 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001985 return Error(BitcodeError::InvalidRecord);
Jan Wen Voungafaced02012-10-11 20:20:40 +00001986 // Only version #0 and #1 are supported so far.
1987 unsigned module_version = Record[0];
1988 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001989 default:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00001990 return Error(BitcodeError::InvalidValue);
Jan Wen Voungafaced02012-10-11 20:20:40 +00001991 case 0:
1992 UseRelativeIDs = false;
1993 break;
1994 case 1:
1995 UseRelativeIDs = true;
1996 break;
1997 }
Chris Lattner1314b992007-04-22 06:23:29 +00001998 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00001999 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002000 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002001 std::string S;
2002 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002003 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00002004 TheModule->setTargetTriple(S);
2005 break;
2006 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002007 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002008 std::string S;
2009 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002010 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00002011 TheModule->setDataLayout(S);
2012 break;
2013 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002014 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002015 std::string S;
2016 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002017 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00002018 TheModule->setModuleInlineAsm(S);
2019 break;
2020 }
Bill Wendling706d3d62012-11-28 08:41:48 +00002021 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2022 // FIXME: Remove in 4.0.
2023 std::string S;
2024 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002025 return Error(BitcodeError::InvalidRecord);
Bill Wendling706d3d62012-11-28 08:41:48 +00002026 // Ignore value.
2027 break;
2028 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002029 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002030 std::string S;
2031 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002032 return Error(BitcodeError::InvalidRecord);
Chris Lattner1314b992007-04-22 06:23:29 +00002033 SectionTable.push_back(S);
2034 break;
2035 }
Gordon Henriksend930f912008-08-17 18:44:35 +00002036 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00002037 std::string S;
2038 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002039 return Error(BitcodeError::InvalidRecord);
Gordon Henriksend930f912008-08-17 18:44:35 +00002040 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00002041 break;
2042 }
David Majnemerdad0a642014-06-27 18:19:56 +00002043 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2044 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002045 return Error(BitcodeError::InvalidRecord);
David Majnemerdad0a642014-06-27 18:19:56 +00002046 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2047 unsigned ComdatNameSize = Record[1];
2048 std::string ComdatName;
2049 ComdatName.reserve(ComdatNameSize);
2050 for (unsigned i = 0; i != ComdatNameSize; ++i)
2051 ComdatName += (char)Record[2 + i];
2052 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2053 C->setSelectionKind(SK);
2054 ComdatList.push_back(C);
2055 break;
2056 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002057 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00002058 // linkage, alignment, section, visibility, threadlocal,
Nico Rieck7157bb72014-01-14 15:22:47 +00002059 // unnamed_addr, dllstorageclass]
Chris Lattner1314b992007-04-22 06:23:29 +00002060 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00002061 if (Record.size() < 6)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002062 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002063 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002064 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002065 return Error(BitcodeError::InvalidRecord);
Duncan Sands19d0b472010-02-16 11:11:14 +00002066 if (!Ty->isPointerTy())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002067 return Error(BitcodeError::InvalidTypeForValue);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002068 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattner1314b992007-04-22 06:23:29 +00002069 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002070
Chris Lattner1314b992007-04-22 06:23:29 +00002071 bool isConstant = Record[1];
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +00002072 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Record[3]);
Chris Lattner1314b992007-04-22 06:23:29 +00002073 unsigned Alignment = (1 << Record[4]) >> 1;
2074 std::string Section;
2075 if (Record[5]) {
2076 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002077 return Error(BitcodeError::InvalidID);
Chris Lattner1314b992007-04-22 06:23:29 +00002078 Section = SectionTable[Record[5]-1];
2079 }
Chris Lattner4b00d922007-04-23 16:04:05 +00002080 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002081 // Local linkage must have default visibility.
2082 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2083 // FIXME: Change to an error if non-default in 4.0.
Chris Lattner53862f72007-05-06 19:27:46 +00002084 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002085
2086 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00002087 if (Record.size() > 7)
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002088 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00002089
Rafael Espindola45e6c192011-01-08 16:42:36 +00002090 bool UnnamedAddr = false;
2091 if (Record.size() > 8)
2092 UnnamedAddr = Record[8];
2093
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002094 bool ExternallyInitialized = false;
2095 if (Record.size() > 9)
2096 ExternallyInitialized = Record[9];
2097
Chris Lattner1314b992007-04-22 06:23:29 +00002098 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00002099 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002100 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00002101 NewGV->setAlignment(Alignment);
2102 if (!Section.empty())
2103 NewGV->setSection(Section);
2104 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00002105 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002106
Nico Rieck7157bb72014-01-14 15:22:47 +00002107 if (Record.size() > 10)
2108 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2109 else
2110 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2111
Chris Lattnerccaa4482007-04-23 21:26:05 +00002112 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002113
Chris Lattner47d131b2007-04-24 00:18:21 +00002114 // Remember which value to use for the global initializer.
2115 if (unsigned InitID = Record[2])
2116 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00002117
2118 if (Record.size() > 11)
2119 if (unsigned ComdatID = Record[11]) {
2120 assert(ComdatID <= ComdatList.size());
2121 NewGV->setComdat(ComdatList[ComdatID - 1]);
2122 }
Chris Lattner1314b992007-04-22 06:23:29 +00002123 break;
2124 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002125 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00002126 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002127 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00002128 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002129 if (Record.size() < 8)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002130 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002131 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002132 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002133 return Error(BitcodeError::InvalidRecord);
Duncan Sands19d0b472010-02-16 11:11:14 +00002134 if (!Ty->isPointerTy())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002135 return Error(BitcodeError::InvalidTypeForValue);
Chris Lattner229907c2011-07-18 04:54:35 +00002136 FunctionType *FTy =
Chris Lattner1314b992007-04-22 06:23:29 +00002137 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2138 if (!FTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002139 return Error(BitcodeError::InvalidTypeForValue);
Chris Lattner1314b992007-04-22 06:23:29 +00002140
Gabor Greife9ecc682008-04-06 20:25:17 +00002141 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2142 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00002143
Sandeep Patel68c5f472009-09-02 08:44:58 +00002144 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002145 bool isProto = Record[2];
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +00002146 Func->setLinkage(getDecodedLinkage(Record[3]));
Devang Patel4c758ea2008-09-25 21:00:45 +00002147 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002148
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002149 Func->setAlignment((1 << Record[5]) >> 1);
2150 if (Record[6]) {
2151 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002152 return Error(BitcodeError::InvalidID);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002153 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00002154 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002155 // Local linkage must have default visibility.
2156 if (!Func->hasLocalLinkage())
2157 // FIXME: Change to an error if non-default in 4.0.
2158 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00002159 if (Record.size() > 8 && Record[8]) {
Gordon Henriksend930f912008-08-17 18:44:35 +00002160 if (Record[8]-1 > GCTable.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002161 return Error(BitcodeError::InvalidID);
Gordon Henriksend930f912008-08-17 18:44:35 +00002162 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00002163 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00002164 bool UnnamedAddr = false;
2165 if (Record.size() > 9)
2166 UnnamedAddr = Record[9];
2167 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002168 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002169 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00002170
2171 if (Record.size() > 11)
2172 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2173 else
2174 UpgradeDLLImportExportLinkage(Func, Record[3]);
2175
David Majnemerdad0a642014-06-27 18:19:56 +00002176 if (Record.size() > 12)
2177 if (unsigned ComdatID = Record[12]) {
2178 assert(ComdatID <= ComdatList.size());
2179 Func->setComdat(ComdatList[ComdatID - 1]);
2180 }
2181
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002182 if (Record.size() > 13 && Record[13] != 0)
2183 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2184
Chris Lattnerccaa4482007-04-23 21:26:05 +00002185 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002186
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002187 // If this is a function with a body, remember the prototype we are
2188 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002189 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00002190 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002191 FunctionsWithBodies.push_back(Func);
Rafael Espindola1b47a282014-10-23 15:20:05 +00002192 if (LazyStreamer)
2193 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002194 }
Chris Lattner1314b992007-04-22 06:23:29 +00002195 break;
2196 }
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002197 // ALIAS: [alias type, aliasee val#, linkage]
Nico Rieck7157bb72014-01-14 15:22:47 +00002198 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
Chris Lattner831d4202007-04-26 03:27:58 +00002199 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner44c17072007-04-26 02:46:40 +00002200 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002201 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002202 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002203 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002204 return Error(BitcodeError::InvalidRecord);
Rafael Espindolaa8004452014-05-16 14:22:33 +00002205 auto *PTy = dyn_cast<PointerType>(Ty);
2206 if (!PTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002207 return Error(BitcodeError::InvalidTypeForValue);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002208
Rafael Espindolaa8004452014-05-16 14:22:33 +00002209 auto *NewGA =
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00002210 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +00002211 getDecodedLinkage(Record[2]), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002212 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002213 // Local linkage must have default visibility.
2214 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2215 // FIXME: Change to an error if non-default in 4.0.
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00002216 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Nico Rieck7157bb72014-01-14 15:22:47 +00002217 if (Record.size() > 4)
2218 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2219 else
2220 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
Rafael Espindola59f7eba2014-05-28 18:15:43 +00002221 if (Record.size() > 5)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00002222 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00002223 if (Record.size() > 6)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00002224 NewGA->setUnnamedAddr(Record[6]);
Chris Lattner44c17072007-04-26 02:46:40 +00002225 ValueList.push_back(NewGA);
2226 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2227 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002228 }
Chris Lattner831d4202007-04-26 03:27:58 +00002229 /// MODULE_CODE_PURGEVALS: [numvals]
2230 case bitc::MODULE_CODE_PURGEVALS:
2231 // Trim down the value list to the specified size.
2232 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002233 return Error(BitcodeError::InvalidRecord);
Chris Lattner831d4202007-04-26 03:27:58 +00002234 ValueList.shrinkTo(Record[0]);
2235 break;
2236 }
Chris Lattner1314b992007-04-22 06:23:29 +00002237 Record.clear();
2238 }
Chris Lattner1314b992007-04-22 06:23:29 +00002239}
2240
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002241std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
Craig Topper2617dcc2014-04-15 06:32:26 +00002242 TheModule = nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002243
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002244 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002245 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002246
Chris Lattner1314b992007-04-22 06:23:29 +00002247 // Sniff for the signature.
2248 if (Stream.Read(8) != 'B' ||
2249 Stream.Read(8) != 'C' ||
2250 Stream.Read(4) != 0x0 ||
2251 Stream.Read(4) != 0xC ||
2252 Stream.Read(4) != 0xE ||
2253 Stream.Read(4) != 0xD)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002254 return Error(BitcodeError::InvalidBitcodeSignature);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002255
Chris Lattner1314b992007-04-22 06:23:29 +00002256 // We expect a number of well-defined blocks, though we don't necessarily
2257 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00002258 while (1) {
2259 if (Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002260 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002261
Chris Lattner27d38752013-01-20 02:13:19 +00002262 BitstreamEntry Entry =
2263 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00002264
Chris Lattner27d38752013-01-20 02:13:19 +00002265 switch (Entry.Kind) {
2266 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002267 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002268 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002269 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002270
Chris Lattner27d38752013-01-20 02:13:19 +00002271 case BitstreamEntry::SubBlock:
2272 switch (Entry.ID) {
2273 case bitc::BLOCKINFO_BLOCK_ID:
2274 if (Stream.ReadBlockInfoBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002275 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002276 break;
2277 case bitc::MODULE_BLOCK_ID:
2278 // Reject multiple MODULE_BLOCK's in a single bitstream.
2279 if (TheModule)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002280 return Error(BitcodeError::InvalidMultipleBlocks);
Chris Lattner27d38752013-01-20 02:13:19 +00002281 TheModule = M;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002282 if (std::error_code EC = ParseModule(false))
Rafael Espindola48da4f42013-11-04 16:16:24 +00002283 return EC;
2284 if (LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002285 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002286 break;
2287 default:
2288 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002289 return Error(BitcodeError::InvalidRecord);
Chris Lattner27d38752013-01-20 02:13:19 +00002290 break;
2291 }
2292 continue;
2293 case BitstreamEntry::Record:
2294 // There should be no records in the top-level of blocks.
Joe Abbey97b7a172013-02-06 22:14:06 +00002295
Chris Lattner27d38752013-01-20 02:13:19 +00002296 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosiera15e3aa2011-08-09 22:23:40 +00002297 // to the end of them. If this file size is a multiple of 4 but not 8, we
2298 // have to read and ignore these final 4 bytes :-(
Chris Lattner27d38752013-01-20 02:13:19 +00002299 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolaa97b2382011-05-26 18:59:54 +00002300 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling318f03f2012-07-19 00:15:11 +00002301 Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002302 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002303
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002304 return Error(BitcodeError::InvalidRecord);
Rafael Espindolaa97b2382011-05-26 18:59:54 +00002305 }
Chris Lattner1314b992007-04-22 06:23:29 +00002306 }
Chris Lattner1314b992007-04-22 06:23:29 +00002307}
Chris Lattner6694f602007-04-29 07:54:31 +00002308
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002309ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00002310 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002311 return Error(BitcodeError::InvalidRecord);
Bill Wendling0198ce02010-10-06 01:22:42 +00002312
2313 SmallVector<uint64_t, 64> Record;
2314
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002315 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00002316 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00002317 while (1) {
2318 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002319
Chris Lattner27d38752013-01-20 02:13:19 +00002320 switch (Entry.Kind) {
2321 case BitstreamEntry::SubBlock: // Handled for us already.
2322 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002323 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002324 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00002325 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00002326 case BitstreamEntry::Record:
2327 // The interesting case.
2328 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00002329 }
2330
2331 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002332 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00002333 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00002334 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002335 std::string S;
2336 if (ConvertToString(Record, 0, S))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002337 return Error(BitcodeError::InvalidRecord);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002338 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00002339 break;
2340 }
2341 }
2342 Record.clear();
2343 }
Rafael Espindolae6107792014-07-04 20:05:56 +00002344 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00002345}
2346
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00002347ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002348 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002349 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00002350
2351 // Sniff for the signature.
2352 if (Stream.Read(8) != 'B' ||
2353 Stream.Read(8) != 'C' ||
2354 Stream.Read(4) != 0x0 ||
2355 Stream.Read(4) != 0xC ||
2356 Stream.Read(4) != 0xE ||
2357 Stream.Read(4) != 0xD)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002358 return Error(BitcodeError::InvalidBitcodeSignature);
Bill Wendling0198ce02010-10-06 01:22:42 +00002359
2360 // We expect a number of well-defined blocks, though we don't necessarily
2361 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00002362 while (1) {
2363 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002364
Chris Lattner27d38752013-01-20 02:13:19 +00002365 switch (Entry.Kind) {
2366 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002367 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002368 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002369 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00002370
Chris Lattner27d38752013-01-20 02:13:19 +00002371 case BitstreamEntry::SubBlock:
2372 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00002373 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00002374
Chris Lattner27d38752013-01-20 02:13:19 +00002375 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00002376 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002377 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002378 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002379
Chris Lattner27d38752013-01-20 02:13:19 +00002380 case BitstreamEntry::Record:
2381 Stream.skipRecord(Entry.ID);
2382 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00002383 }
2384 }
Bill Wendling0198ce02010-10-06 01:22:42 +00002385}
2386
Devang Patelaf206b82009-09-18 19:26:43 +00002387/// ParseMetadataAttachment - Parse metadata attachments.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002388std::error_code BitcodeReader::ParseMetadataAttachment() {
Devang Patelaf206b82009-09-18 19:26:43 +00002389 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002390 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002391
Devang Patelaf206b82009-09-18 19:26:43 +00002392 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00002393 while (1) {
2394 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002395
Chris Lattner27d38752013-01-20 02:13:19 +00002396 switch (Entry.Kind) {
2397 case BitstreamEntry::SubBlock: // Handled for us already.
2398 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002399 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002400 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002401 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002402 case BitstreamEntry::Record:
2403 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00002404 break;
2405 }
Chris Lattner27d38752013-01-20 02:13:19 +00002406
Devang Patelaf206b82009-09-18 19:26:43 +00002407 // Read a metadata attachment record.
2408 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00002409 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00002410 default: // Default behavior: ignore.
2411 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00002412 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00002413 unsigned RecordLength = Record.size();
2414 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002415 return Error(BitcodeError::InvalidRecord);
Devang Patelaf206b82009-09-18 19:26:43 +00002416 Instruction *Inst = InstructionList[Record[0]];
2417 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00002418 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00002419 DenseMap<unsigned, unsigned>::iterator I =
2420 MDKindMap.find(Kind);
2421 if (I == MDKindMap.end())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002422 return Error(BitcodeError::InvalidID);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002423 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2424 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00002425 // Drop the attachment. This used to be legal, but there's no
2426 // upgrade path.
2427 break;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002428 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00002429 if (I->second == LLVMContext::MD_tbaa)
2430 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00002431 }
2432 break;
2433 }
2434 }
2435 }
Devang Patelaf206b82009-09-18 19:26:43 +00002436}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002437
Chris Lattner85b7b402007-05-01 05:52:21 +00002438/// ParseFunctionBody - Lazily parse the specified function body block.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002439std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002440 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002441 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002442
Nick Lewyckya72e1af2010-02-25 08:30:17 +00002443 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00002444 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman26d837d2010-08-25 20:22:53 +00002445 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002446
Chris Lattner85b7b402007-05-01 05:52:21 +00002447 // Add all the function arguments to the value table.
2448 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2449 ValueList.push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002450
Chris Lattner83930552007-05-01 07:01:57 +00002451 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00002452 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00002453 unsigned CurBBNo = 0;
2454
Chris Lattner07d09ed2010-04-03 02:17:50 +00002455 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00002456 auto getLastInstruction = [&]() -> Instruction * {
2457 if (CurBB && !CurBB->empty())
2458 return &CurBB->back();
2459 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2460 !FunctionBBs[CurBBNo - 1]->empty())
2461 return &FunctionBBs[CurBBNo - 1]->back();
2462 return nullptr;
2463 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002464
Chris Lattner85b7b402007-05-01 05:52:21 +00002465 // Read all the records.
2466 SmallVector<uint64_t, 64> Record;
2467 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002468 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002469
Chris Lattner27d38752013-01-20 02:13:19 +00002470 switch (Entry.Kind) {
2471 case BitstreamEntry::Error:
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002472 return Error(BitcodeError::MalformedBlock);
Chris Lattner27d38752013-01-20 02:13:19 +00002473 case BitstreamEntry::EndBlock:
2474 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00002475
Chris Lattner27d38752013-01-20 02:13:19 +00002476 case BitstreamEntry::SubBlock:
2477 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00002478 default: // Skip unknown content.
2479 if (Stream.SkipBlock())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002480 return Error(BitcodeError::InvalidRecord);
Chris Lattner85b7b402007-05-01 05:52:21 +00002481 break;
2482 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002483 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002484 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00002485 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00002486 break;
2487 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002488 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002489 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00002490 break;
Devang Patelaf206b82009-09-18 19:26:43 +00002491 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002492 if (std::error_code EC = ParseMetadataAttachment())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002493 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002494 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00002495 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002496 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002497 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00002498 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002499 case bitc::USELIST_BLOCK_ID:
2500 if (std::error_code EC = ParseUseLists())
2501 return EC;
2502 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00002503 }
2504 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002505
Chris Lattner27d38752013-01-20 02:13:19 +00002506 case BitstreamEntry::Record:
2507 // The interesting case.
2508 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00002509 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002510
Chris Lattner85b7b402007-05-01 05:52:21 +00002511 // Read a record.
2512 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002513 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002514 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002515 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00002516 default: // Default behavior: reject
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002517 return Error(BitcodeError::InvalidValue);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002518 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00002519 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002520 return Error(BitcodeError::InvalidRecord);
Chris Lattner85b7b402007-05-01 05:52:21 +00002521 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00002522 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002523
2524 // See if anything took the address of blocks in this function.
2525 auto BBFRI = BasicBlockFwdRefs.find(F);
2526 if (BBFRI == BasicBlockFwdRefs.end()) {
2527 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2528 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2529 } else {
2530 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002531 // Check for invalid basic block references.
2532 if (BBRefs.size() > FunctionBBs.size())
2533 return Error(BitcodeError::InvalidID);
2534 assert(!BBRefs.empty() && "Unexpected empty array");
2535 assert(!BBRefs.front() && "Invalid reference to entry block");
2536 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2537 ++I)
2538 if (I < RE && BBRefs[I]) {
2539 BBRefs[I]->insertInto(F);
2540 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002541 } else {
2542 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2543 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002544
2545 // Erase from the table.
2546 BasicBlockFwdRefs.erase(BBFRI);
2547 }
2548
Chris Lattner83930552007-05-01 07:01:57 +00002549 CurBB = FunctionBBs[0];
2550 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002551 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002552
Chris Lattner07d09ed2010-04-03 02:17:50 +00002553 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2554 // This record indicates that the last instruction is at the same
2555 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00002556 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002557
Craig Topper2617dcc2014-04-15 06:32:26 +00002558 if (!I)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002559 return Error(BitcodeError::InvalidRecord);
Chris Lattner07d09ed2010-04-03 02:17:50 +00002560 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002561 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002562 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002563
Duncan P. N. Exon Smith11fae742015-01-09 02:48:48 +00002564 case bitc::FUNC_CODE_DEBUG_LOC_OLD: { // DEBUG_LOC_OLD: [line,col,scope,ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00002565 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00002566 if (!I || Record.size() < 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002567 return Error(BitcodeError::InvalidRecord);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002568
Chris Lattner07d09ed2010-04-03 02:17:50 +00002569 unsigned Line = Record[0], Col = Record[1];
2570 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002571
Craig Topper2617dcc2014-04-15 06:32:26 +00002572 MDNode *Scope = nullptr, *IA = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002573 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2574 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2575 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2576 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00002577 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002578 continue;
2579 }
2580
Chris Lattnere9759c22007-05-06 00:21:25 +00002581 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2582 unsigned OpNum = 0;
2583 Value *LHS, *RHS;
2584 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002585 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00002586 OpNum+1 > Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002587 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002588
Dan Gohman0ebd6962009-07-20 21:19:07 +00002589 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00002590 if (Opc == -1)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002591 return Error(BitcodeError::InvalidRecord);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00002592 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00002593 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00002594 if (OpNum < Record.size()) {
2595 if (Opc == Instruction::Add ||
2596 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002597 Opc == Instruction::Mul ||
2598 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00002599 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00002600 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00002601 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00002602 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00002603 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002604 Opc == Instruction::UDiv ||
2605 Opc == Instruction::LShr ||
2606 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002607 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002608 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00002609 } else if (isa<FPMathOperator>(I)) {
2610 FastMathFlags FMF;
Michael Ilseman65f14352012-12-09 21:12:04 +00002611 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2612 FMF.setUnsafeAlgebra();
2613 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2614 FMF.setNoNaNs();
2615 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2616 FMF.setNoInfs();
2617 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2618 FMF.setNoSignedZeros();
2619 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2620 FMF.setAllowReciprocal();
Michael Ilseman9978d7e2012-11-27 00:43:38 +00002621 if (FMF.any())
2622 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00002623 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00002624
Dan Gohman1b849082009-09-07 23:54:19 +00002625 }
Chris Lattner85b7b402007-05-01 05:52:21 +00002626 break;
2627 }
Chris Lattnere9759c22007-05-06 00:21:25 +00002628 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2629 unsigned OpNum = 0;
2630 Value *Op;
2631 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2632 OpNum+2 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002633 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002634
Chris Lattner229907c2011-07-18 04:54:35 +00002635 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnere9759c22007-05-06 00:21:25 +00002636 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002637 if (Opc == -1 || !ResTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002638 return Error(BitcodeError::InvalidRecord);
Craig Topper2617dcc2014-04-15 06:32:26 +00002639 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002640 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2641 if (Temp) {
2642 InstructionList.push_back(Temp);
2643 CurBB->getInstList().push_back(Temp);
2644 }
2645 } else {
2646 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2647 }
Devang Patelaf206b82009-09-18 19:26:43 +00002648 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00002649 break;
2650 }
Dan Gohman1639c392009-07-27 21:53:46 +00002651 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattnere14cb882007-05-04 19:11:41 +00002652 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002653 unsigned OpNum = 0;
2654 Value *BasePtr;
2655 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002656 return Error(BitcodeError::InvalidRecord);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002657
Chris Lattner5285b5e2007-05-02 05:46:45 +00002658 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002659 while (OpNum != Record.size()) {
2660 Value *Op;
2661 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002662 return Error(BitcodeError::InvalidRecord);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002663 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002664 }
2665
Jay Foadd1b78492011-07-25 09:48:08 +00002666 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00002667 InstructionList.push_back(I);
Dan Gohman1639c392009-07-27 21:53:46 +00002668 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohman1b849082009-09-07 23:54:19 +00002669 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002670 break;
2671 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002672
Dan Gohman1ecaf452008-05-31 00:58:22 +00002673 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2674 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00002675 unsigned OpNum = 0;
2676 Value *Agg;
2677 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002678 return Error(BitcodeError::InvalidRecord);
Dan Gohman30499842008-05-23 01:55:30 +00002679
Dan Gohman1ecaf452008-05-31 00:58:22 +00002680 SmallVector<unsigned, 4> EXTRACTVALIdx;
2681 for (unsigned RecSize = Record.size();
2682 OpNum != RecSize; ++OpNum) {
2683 uint64_t Index = Record[OpNum];
2684 if ((unsigned)Index != Index)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002685 return Error(BitcodeError::InvalidValue);
Dan Gohman1ecaf452008-05-31 00:58:22 +00002686 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohman30499842008-05-23 01:55:30 +00002687 }
2688
Jay Foad57aa6362011-07-13 10:26:04 +00002689 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00002690 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00002691 break;
2692 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002693
Dan Gohman1ecaf452008-05-31 00:58:22 +00002694 case bitc::FUNC_CODE_INST_INSERTVAL: {
2695 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00002696 unsigned OpNum = 0;
2697 Value *Agg;
2698 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002699 return Error(BitcodeError::InvalidRecord);
Dan Gohman30499842008-05-23 01:55:30 +00002700 Value *Val;
2701 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002702 return Error(BitcodeError::InvalidRecord);
Dan Gohman30499842008-05-23 01:55:30 +00002703
Dan Gohman1ecaf452008-05-31 00:58:22 +00002704 SmallVector<unsigned, 4> INSERTVALIdx;
2705 for (unsigned RecSize = Record.size();
2706 OpNum != RecSize; ++OpNum) {
2707 uint64_t Index = Record[OpNum];
2708 if ((unsigned)Index != Index)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002709 return Error(BitcodeError::InvalidValue);
Dan Gohman1ecaf452008-05-31 00:58:22 +00002710 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohman30499842008-05-23 01:55:30 +00002711 }
2712
Jay Foad57aa6362011-07-13 10:26:04 +00002713 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00002714 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00002715 break;
2716 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002717
Chris Lattnere9759c22007-05-06 00:21:25 +00002718 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00002719 // obsolete form of select
2720 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00002721 unsigned OpNum = 0;
2722 Value *TrueVal, *FalseVal, *Cond;
2723 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002724 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2725 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002726 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002727
Dan Gohmanc5d28922008-09-16 01:01:33 +00002728 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00002729 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00002730 break;
2731 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002732
Dan Gohmanc5d28922008-09-16 01:01:33 +00002733 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2734 // new form of select
2735 // handles select i1 or select [N x i1]
2736 unsigned OpNum = 0;
2737 Value *TrueVal, *FalseVal, *Cond;
2738 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002739 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00002740 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002741 return Error(BitcodeError::InvalidRecord);
Dan Gohmanc579d972008-09-09 01:02:47 +00002742
2743 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00002744 if (VectorType* vector_type =
2745 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00002746 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002747 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002748 return Error(BitcodeError::InvalidTypeForValue);
Dan Gohmanc579d972008-09-09 01:02:47 +00002749 } else {
2750 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002751 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002752 return Error(BitcodeError::InvalidTypeForValue);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002753 }
2754
Gabor Greife9ecc682008-04-06 20:25:17 +00002755 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00002756 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002757 break;
2758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002759
Chris Lattner1fc27f02007-05-02 05:16:49 +00002760 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00002761 unsigned OpNum = 0;
2762 Value *Vec, *Idx;
2763 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002764 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002765 return Error(BitcodeError::InvalidRecord);
Eric Christopherc9742252009-07-25 02:28:41 +00002766 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00002767 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002768 break;
2769 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002770
Chris Lattner1fc27f02007-05-02 05:16:49 +00002771 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00002772 unsigned OpNum = 0;
2773 Value *Vec, *Elt, *Idx;
2774 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002775 popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00002776 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002777 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002778 return Error(BitcodeError::InvalidRecord);
Gabor Greife9ecc682008-04-06 20:25:17 +00002779 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00002780 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002781 break;
2782 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002783
Chris Lattnere9759c22007-05-06 00:21:25 +00002784 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2785 unsigned OpNum = 0;
2786 Value *Vec1, *Vec2, *Mask;
2787 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002788 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002789 return Error(BitcodeError::InvalidRecord);
Chris Lattnere9759c22007-05-06 00:21:25 +00002790
Mon P Wang25f01062008-11-10 04:46:22 +00002791 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002792 return Error(BitcodeError::InvalidRecord);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002793 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00002794 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00002795 break;
2796 }
Mon P Wang25f01062008-11-10 04:46:22 +00002797
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002798 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2799 // Old form of ICmp/FCmp returning bool
2800 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2801 // both legal on vectors but had different behaviour.
2802 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2803 // FCmp/ICmp returning bool or vector of bool
2804
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002805 unsigned OpNum = 0;
2806 Value *LHS, *RHS;
2807 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00002808 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002809 OpNum+1 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002810 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002811
Duncan Sands9dff9be2010-02-15 16:12:20 +00002812 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohmanad1f0a12009-08-25 23:17:54 +00002813 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002814 else
Dan Gohmanad1f0a12009-08-25 23:17:54 +00002815 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00002816 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00002817 break;
2818 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002819
Chris Lattnere53603e2007-05-02 04:27:25 +00002820 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00002821 {
2822 unsigned Size = Record.size();
2823 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002824 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002825 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00002826 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002827 }
Devang Patelbbfd8742008-02-26 01:29:32 +00002828
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002829 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00002830 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00002831 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002832 return Error(BitcodeError::InvalidRecord);
Chris Lattnerf1c87102011-06-17 18:09:11 +00002833 if (OpNum != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002834 return Error(BitcodeError::InvalidRecord);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002835
Chris Lattnerf1c87102011-06-17 18:09:11 +00002836 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002837 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002838 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00002839 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00002840 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00002841 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002842 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002843 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002844 if (!TrueDest)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002845 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002846
Devang Patelaf206b82009-09-18 19:26:43 +00002847 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00002848 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002849 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00002850 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00002851 else {
2852 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002853 Value *Cond = getValue(Record, 2, NextValueNo,
2854 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00002855 if (!FalseDest || !Cond)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002856 return Error(BitcodeError::InvalidRecord);
Gabor Greife9ecc682008-04-06 20:25:17 +00002857 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002858 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002859 }
2860 break;
2861 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00002862 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002863 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002864 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00002865 // "New" SwitchInst format with case ranges. The changes to write this
2866 // format were reverted but we still recognize bitcode that uses it.
2867 // Hopefully someday we will have support for case ranges and can use
2868 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002869
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002870 Type *OpTy = getTypeByID(Record[1]);
2871 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2872
Jan Wen Voungafaced02012-10-11 20:20:40 +00002873 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002874 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002875 if (!OpTy || !Cond || !Default)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002876 return Error(BitcodeError::InvalidRecord);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002877
2878 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002879
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002880 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2881 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002882
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002883 unsigned CurIdx = 5;
2884 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00002885 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002886 unsigned NumItems = Record[CurIdx++];
2887 for (unsigned ci = 0; ci != NumItems; ++ci) {
2888 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002889
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002890 APInt Low;
2891 unsigned ActiveWords = 1;
2892 if (ValueBitWidth > 64)
2893 ActiveWords = Record[CurIdx++];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002894 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2895 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002896 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00002897
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002898 if (!isSingleNumber) {
2899 ActiveWords = 1;
2900 if (ValueBitWidth > 64)
2901 ActiveWords = Record[CurIdx++];
2902 APInt High =
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002903 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2904 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002905 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00002906
2907 // FIXME: It is not clear whether values in the range should be
2908 // compared as signed or unsigned values. The partially
2909 // implemented changes that used this format in the past used
2910 // unsigned comparisons.
2911 for ( ; Low.ule(High); ++Low)
2912 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002913 } else
Bob Wilsone4077362013-09-09 19:14:35 +00002914 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002915 }
2916 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00002917 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2918 cve = CaseVals.end(); cvi != cve; ++cvi)
2919 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002920 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002921 I = SI;
2922 break;
2923 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002924
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002925 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002926
Chris Lattner5285b5e2007-05-02 05:46:45 +00002927 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002928 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002929 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002930 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002931 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002932 if (!OpTy || !Cond || !Default)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002933 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002934 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00002935 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00002936 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002937 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002938 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00002939 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2940 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002941 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00002942 delete SI;
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002943 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00002944 }
2945 SI->addCase(CaseVal, DestBB);
2946 }
2947 I = SI;
2948 break;
2949 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002950 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00002951 if (Record.size() < 2)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002952 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00002953 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002954 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002955 if (!OpTy || !Address)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002956 return Error(BitcodeError::InvalidRecord);
Chris Lattner3ed871f2009-10-27 19:13:16 +00002957 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002958 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00002959 InstructionList.push_back(IBI);
2960 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2961 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2962 IBI->addDestination(DestBB);
2963 } else {
2964 delete IBI;
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002965 return Error(BitcodeError::InvalidRecord);
Chris Lattner3ed871f2009-10-27 19:13:16 +00002966 }
2967 }
2968 I = IBI;
2969 break;
2970 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002971
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00002972 case bitc::FUNC_CODE_INST_INVOKE: {
2973 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002974 if (Record.size() < 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002975 return Error(BitcodeError::InvalidRecord);
Bill Wendlinge94d8432012-12-07 23:16:57 +00002976 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002977 unsigned CCInfo = Record[1];
2978 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2979 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002980
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002981 unsigned OpNum = 4;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002982 Value *Callee;
2983 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002984 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002985
Chris Lattner229907c2011-07-18 04:54:35 +00002986 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00002987 FunctionType *FTy = !CalleeTy ? nullptr :
Chris Lattner5285b5e2007-05-02 05:46:45 +00002988 dyn_cast<FunctionType>(CalleeTy->getElementType());
2989
2990 // Check that the right number of fixed parameters are here.
Craig Topper2617dcc2014-04-15 06:32:26 +00002991 if (!FTy || !NormalBB || !UnwindBB ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002992 Record.size() < OpNum+FTy->getNumParams())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00002993 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002994
Chris Lattner5285b5e2007-05-02 05:46:45 +00002995 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002996 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002997 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2998 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00002999 if (!Ops.back())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003000 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003001 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003002
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003003 if (!FTy->isVarArg()) {
3004 if (Record.size() != OpNum)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003005 return Error(BitcodeError::InvalidRecord);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003006 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003007 // Read type/value pairs for varargs params.
3008 while (OpNum != Record.size()) {
3009 Value *Op;
3010 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003011 return Error(BitcodeError::InvalidRecord);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003012 Ops.push_back(Op);
3013 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003014 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003015
Jay Foad5bd375a2011-07-15 08:37:34 +00003016 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patelaf206b82009-09-18 19:26:43 +00003017 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00003018 cast<InvokeInst>(I)->setCallingConv(
3019 static_cast<CallingConv::ID>(CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00003020 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003021 break;
3022 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00003023 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3024 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003025 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003026 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003027 return Error(BitcodeError::InvalidRecord);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003028 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00003029 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003030 break;
3031 }
Chris Lattnere53603e2007-05-02 04:27:25 +00003032 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00003033 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00003034 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003035 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00003036 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00003037 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003038 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00003039 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003040 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003041 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003042
Jay Foad52131342011-03-30 11:28:46 +00003043 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00003044 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003045
Chris Lattnere14cb882007-05-04 19:11:41 +00003046 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00003047 Value *V;
3048 // With the new function encoding, it is possible that operands have
3049 // negative IDs (for forward references). Use a signed VBR
3050 // representation to keep the encoding small.
3051 if (UseRelativeIDs)
3052 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3053 else
3054 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00003055 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003056 if (!V || !BB)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003057 return Error(BitcodeError::InvalidRecord);
Chris Lattnerc332bba2007-05-03 18:58:09 +00003058 PN->addIncoming(V, BB);
3059 }
3060 I = PN;
3061 break;
3062 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003063
Bill Wendlingfae14752011-08-12 20:24:12 +00003064 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3065 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3066 unsigned Idx = 0;
3067 if (Record.size() < 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003068 return Error(BitcodeError::InvalidRecord);
Bill Wendlingfae14752011-08-12 20:24:12 +00003069 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003070 if (!Ty)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003071 return Error(BitcodeError::InvalidRecord);
Craig Topper2617dcc2014-04-15 06:32:26 +00003072 Value *PersFn = nullptr;
Bill Wendlingfae14752011-08-12 20:24:12 +00003073 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003074 return Error(BitcodeError::InvalidRecord);
Bill Wendlingfae14752011-08-12 20:24:12 +00003075
3076 bool IsCleanup = !!Record[Idx++];
3077 unsigned NumClauses = Record[Idx++];
3078 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3079 LP->setCleanup(IsCleanup);
3080 for (unsigned J = 0; J != NumClauses; ++J) {
3081 LandingPadInst::ClauseType CT =
3082 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3083 Value *Val;
3084
3085 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3086 delete LP;
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003087 return Error(BitcodeError::InvalidRecord);
Bill Wendlingfae14752011-08-12 20:24:12 +00003088 }
3089
3090 assert((CT != LandingPadInst::Catch ||
3091 !isa<ArrayType>(Val->getType())) &&
3092 "Catch clause has a invalid type!");
3093 assert((CT != LandingPadInst::Filter ||
3094 isa<ArrayType>(Val->getType())) &&
3095 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00003096 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00003097 }
3098
3099 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00003100 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00003101 break;
3102 }
3103
Chris Lattnerf1c87102011-06-17 18:09:11 +00003104 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3105 if (Record.size() != 4)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003106 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00003107 PointerType *Ty =
Chris Lattnerc332bba2007-05-03 18:58:09 +00003108 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattner229907c2011-07-18 04:54:35 +00003109 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerf1c87102011-06-17 18:09:11 +00003110 Value *Size = getFnValueByID(Record[2], OpTy);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00003111 unsigned AlignRecord = Record[3];
3112 bool InAlloca = AlignRecord & (1 << 5);
3113 unsigned Align = AlignRecord & ((1 << 5) - 1);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003114 if (!Ty || !Size)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003115 return Error(BitcodeError::InvalidRecord);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00003116 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3117 AI->setUsedWithInAlloca(InAlloca);
3118 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00003119 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00003120 break;
3121 }
Chris Lattner9f600c52007-05-03 22:04:19 +00003122 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003123 unsigned OpNum = 0;
3124 Value *Op;
3125 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3126 OpNum+2 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003127 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003128
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003129 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patelaf206b82009-09-18 19:26:43 +00003130 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00003131 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00003132 }
Eli Friedman59b66882011-08-09 23:02:53 +00003133 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3134 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3135 unsigned OpNum = 0;
3136 Value *Op;
3137 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3138 OpNum+4 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003139 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003140
3141 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3142 if (Ordering == NotAtomic || Ordering == Release ||
3143 Ordering == AcquireRelease)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003144 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003145 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003146 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003147 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3148
3149 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3150 Ordering, SynchScope);
3151 InstructionList.push_back(I);
3152 break;
3153 }
Chris Lattnerc44070802011-06-17 18:17:37 +00003154 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003155 unsigned OpNum = 0;
3156 Value *Val, *Ptr;
3157 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003158 popValue(Record, OpNum, NextValueNo,
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003159 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3160 OpNum+2 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003161 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003162
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003163 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patelaf206b82009-09-18 19:26:43 +00003164 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003165 break;
3166 }
Eli Friedman59b66882011-08-09 23:02:53 +00003167 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3168 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3169 unsigned OpNum = 0;
3170 Value *Val, *Ptr;
3171 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003172 popValue(Record, OpNum, NextValueNo,
Eli Friedman59b66882011-08-09 23:02:53 +00003173 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3174 OpNum+4 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003175 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003176
3177 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00003178 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00003179 Ordering == AcquireRelease)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003180 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003181 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3182 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003183 return Error(BitcodeError::InvalidRecord);
Eli Friedman59b66882011-08-09 23:02:53 +00003184
3185 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3186 Ordering, SynchScope);
3187 InstructionList.push_back(I);
3188 break;
3189 }
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003190 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00003191 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00003192 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003193 unsigned OpNum = 0;
3194 Value *Ptr, *Cmp, *New;
3195 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003196 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003197 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003198 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003199 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
Tim Northover420a2162014-06-13 14:24:07 +00003200 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003201 return Error(BitcodeError::InvalidRecord);
Tim Northovere94a5182014-03-11 10:48:52 +00003202 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3203 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003204 return Error(BitcodeError::InvalidRecord);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003205 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
Tim Northovere94a5182014-03-11 10:48:52 +00003206
3207 AtomicOrdering FailureOrdering;
3208 if (Record.size() < 7)
3209 FailureOrdering =
3210 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3211 else
3212 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3213
3214 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3215 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003216 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00003217
3218 if (Record.size() < 8) {
3219 // Before weak cmpxchgs existed, the instruction simply returned the
3220 // value loaded from memory, so bitcode files from that era will be
3221 // expecting the first component of a modern cmpxchg.
3222 CurBB->getInstList().push_back(I);
3223 I = ExtractValueInst::Create(I, 0);
3224 } else {
3225 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3226 }
3227
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003228 InstructionList.push_back(I);
3229 break;
3230 }
3231 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3232 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3233 unsigned OpNum = 0;
3234 Value *Ptr, *Val;
3235 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003236 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003237 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3238 OpNum+4 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003239 return Error(BitcodeError::InvalidRecord);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003240 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3241 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3242 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003243 return Error(BitcodeError::InvalidRecord);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003244 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman59b66882011-08-09 23:02:53 +00003245 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003246 return Error(BitcodeError::InvalidRecord);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003247 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3248 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3249 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3250 InstructionList.push_back(I);
3251 break;
3252 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00003253 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3254 if (2 != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003255 return Error(BitcodeError::InvalidRecord);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003256 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3257 if (Ordering == NotAtomic || Ordering == Unordered ||
3258 Ordering == Monotonic)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003259 return Error(BitcodeError::InvalidRecord);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003260 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3261 I = new FenceInst(Context, Ordering, SynchScope);
3262 InstructionList.push_back(I);
3263 break;
3264 }
Chris Lattnerc44070802011-06-17 18:17:37 +00003265 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003266 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3267 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003268 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003269
Bill Wendlinge94d8432012-12-07 23:16:57 +00003270 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003271 unsigned CCInfo = Record[1];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003272
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003273 unsigned OpNum = 2;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003274 Value *Callee;
3275 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003276 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003277
Chris Lattner229907c2011-07-18 04:54:35 +00003278 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00003279 FunctionType *FTy = nullptr;
Chris Lattner9f600c52007-05-03 22:04:19 +00003280 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003281 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003282 return Error(BitcodeError::InvalidRecord);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003283
Chris Lattner9f600c52007-05-03 22:04:19 +00003284 SmallVector<Value*, 16> Args;
3285 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003286 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003287 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00003288 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00003289 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00003290 Args.push_back(getValue(Record, OpNum, NextValueNo,
3291 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00003292 if (!Args.back())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003293 return Error(BitcodeError::InvalidRecord);
Chris Lattner9f600c52007-05-03 22:04:19 +00003294 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003295
Chris Lattner9f600c52007-05-03 22:04:19 +00003296 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00003297 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003298 if (OpNum != Record.size())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003299 return Error(BitcodeError::InvalidRecord);
Chris Lattner9f600c52007-05-03 22:04:19 +00003300 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003301 while (OpNum != Record.size()) {
3302 Value *Op;
3303 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003304 return Error(BitcodeError::InvalidRecord);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003305 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00003306 }
3307 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003308
Jay Foad5bd375a2011-07-15 08:37:34 +00003309 I = CallInst::Create(Callee, Args);
Devang Patelaf206b82009-09-18 19:26:43 +00003310 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00003311 cast<CallInst>(I)->setCallingConv(
Reid Kleckner5772b772014-04-24 20:14:34 +00003312 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3313 CallInst::TailCallKind TCK = CallInst::TCK_None;
3314 if (CCInfo & 1)
3315 TCK = CallInst::TCK_Tail;
3316 if (CCInfo & (1 << 14))
3317 TCK = CallInst::TCK_MustTail;
3318 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00003319 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner9f600c52007-05-03 22:04:19 +00003320 break;
3321 }
3322 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3323 if (Record.size() < 3)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003324 return Error(BitcodeError::InvalidRecord);
Chris Lattner229907c2011-07-18 04:54:35 +00003325 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003326 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003327 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00003328 if (!OpTy || !Op || !ResTy)
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003329 return Error(BitcodeError::InvalidRecord);
Chris Lattner9f600c52007-05-03 22:04:19 +00003330 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00003331 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00003332 break;
3333 }
Chris Lattner83930552007-05-01 07:01:57 +00003334 }
3335
3336 // Add instruction to end of current BB. If there is no current BB, reject
3337 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00003338 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00003339 delete I;
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003340 return Error(BitcodeError::InvalidInstructionWithNoBB);
Chris Lattner83930552007-05-01 07:01:57 +00003341 }
3342 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003343
Chris Lattner83930552007-05-01 07:01:57 +00003344 // If this was a terminator instruction, move to the next block.
3345 if (isa<TerminatorInst>(I)) {
3346 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00003347 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00003348 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003349
Chris Lattner83930552007-05-01 07:01:57 +00003350 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003351 if (I && !I->getType()->isVoidTy())
Chris Lattner83930552007-05-01 07:01:57 +00003352 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00003353 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003354
Chris Lattner27d38752013-01-20 02:13:19 +00003355OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00003356
Chris Lattner83930552007-05-01 07:01:57 +00003357 // Check the function list for unresolved values.
3358 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003359 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00003360 // We found at least one unresolved value. Nuke them all to avoid leaks.
3361 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00003362 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003363 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00003364 delete A;
3365 }
3366 }
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003367 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
Chris Lattner83930552007-05-01 07:01:57 +00003368 }
Chris Lattner83930552007-05-01 07:01:57 +00003369 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003370
Dan Gohman9b9ff462010-08-25 20:23:38 +00003371 // FIXME: Check for unresolved forward-declared metadata references
3372 // and clean up leaks.
3373
Chris Lattner85b7b402007-05-01 05:52:21 +00003374 // Trim the value list down to the size it was before we parsed this function.
3375 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman26d837d2010-08-25 20:22:53 +00003376 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00003377 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003378 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003379}
3380
Rafael Espindola7d712032013-11-05 17:16:08 +00003381/// Find the function body in the bitcode stream
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003382std::error_code BitcodeReader::FindFunctionInStream(
3383 Function *F,
3384 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003385 while (DeferredFunctionInfoIterator->second == 0) {
3386 if (Stream.AtEndOfStream())
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003387 return Error(BitcodeError::CouldNotFindFunctionInStream);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003388 // ParseModule will parse the next body in the stream and set its
3389 // position in the DeferredFunctionInfo map.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003390 if (std::error_code EC = ParseModule(true))
Rafael Espindola7d712032013-11-05 17:16:08 +00003391 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003392 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003393 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003394}
3395
Chris Lattner9eeada92007-05-18 04:02:46 +00003396//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003397// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00003398//===----------------------------------------------------------------------===//
3399
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00003400void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00003401
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00003402std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003403 Function *F = dyn_cast<Function>(GV);
3404 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003405 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003406 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003407
3408 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00003409 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003410 // If its position is recorded as 0, its body is somewhere in the stream
3411 // but we haven't seen it yet.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003412 if (DFII->second == 0 && LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003413 if (std::error_code EC = FindFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003414 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003415
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003416 // Move the bit stream to the saved position of the deferred function body.
3417 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003418
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003419 if (std::error_code EC = ParseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003420 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003421 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00003422
3423 // Upgrade any old intrinsic calls in the function.
3424 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3425 E = UpgradedIntrinsics.end(); I != E; ++I) {
3426 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003427 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3428 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00003429 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3430 UpgradeIntrinsicCall(CI, I->second);
3431 }
3432 }
3433 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003434
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003435 // Bring in any functions that this function forward-referenced via
3436 // blockaddresses.
3437 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00003438}
3439
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003440bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3441 const Function *F = dyn_cast<Function>(GV);
3442 if (!F || F->isDeclaration())
3443 return false;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003444
3445 // Dematerializing F would leave dangling references that wouldn't be
3446 // reconnected on re-materialization.
3447 if (BlockAddressesTaken.count(F))
3448 return false;
3449
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003450 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3451}
3452
3453void BitcodeReader::Dematerialize(GlobalValue *GV) {
3454 Function *F = dyn_cast<Function>(GV);
3455 // If this function isn't dematerializable, this is a noop.
3456 if (!F || !isDematerializable(F))
Chris Lattner9eeada92007-05-18 04:02:46 +00003457 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003458
Chris Lattner9eeada92007-05-18 04:02:46 +00003459 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003460
Chris Lattner9eeada92007-05-18 04:02:46 +00003461 // Just forget the function body, we can remat it later.
Petar Jovanovic7480e4d2014-09-23 12:54:19 +00003462 F->dropAllReferences();
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003463 F->setIsMaterializable(true);
Chris Lattner9eeada92007-05-18 04:02:46 +00003464}
3465
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003466std::error_code BitcodeReader::MaterializeModule(Module *M) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003467 assert(M == TheModule &&
3468 "Can only Materialize the Module this BitcodeReader is attached to.");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003469
3470 // Promise to materialize all forward references.
3471 WillMaterializeAllForwardRefs = true;
3472
Chris Lattner06310bf2009-06-16 05:15:21 +00003473 // Iterate over the module, deserializing any functions that are still on
3474 // disk.
3475 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003476 F != E; ++F) {
Rafael Espindola246c4fb2014-11-01 16:46:18 +00003477 if (std::error_code EC = materialize(F))
3478 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00003479 }
Derek Schuff92ef9752012-02-29 00:07:09 +00003480 // At this point, if there are any function bodies, the current bit is
3481 // pointing to the END_BLOCK record after them. Now make sure the rest
3482 // of the bits in the module have been read.
3483 if (NextUnreadBit)
3484 ParseModule(true);
3485
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003486 // Check that all block address forward references got resolved (as we
3487 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003488 if (!BasicBlockFwdRefs.empty())
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003489 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3490
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003491 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3492 // delete the old functions to clean up. We can't do this unless the entire
3493 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00003494 // with calls to the old function.
3495 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3496 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3497 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003498 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3499 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00003500 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3501 UpgradeIntrinsicCall(CI, I->second);
3502 }
Chris Lattner647cffb2009-04-01 01:43:03 +00003503 if (!I->first->use_empty())
3504 I->first->replaceAllUsesWith(I->second);
Chandler Carruth7132e002007-08-04 01:51:18 +00003505 I->first->eraseFromParent();
3506 }
3507 }
3508 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patel80ae3492009-08-28 23:24:31 +00003509
Manman Ren209b17c2013-09-28 00:22:27 +00003510 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3511 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3512
Manman Ren8b4306c2013-12-02 21:29:56 +00003513 UpgradeDebugInfo(*M);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003514 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00003515}
3516
Rafael Espindola2fa1e432014-12-03 07:18:23 +00003517std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3518 return IdentifiedStructTypes;
3519}
3520
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003521std::error_code BitcodeReader::InitStream() {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003522 if (LazyStreamer)
3523 return InitLazyStream();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003524 return InitStreamFromBuffer();
3525}
3526
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003527std::error_code BitcodeReader::InitStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00003528 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003529 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3530
Rafael Espindola27435252014-07-29 21:01:24 +00003531 if (Buffer->getBufferSize() & 3)
3532 return Error(BitcodeError::InvalidBitcodeSignature);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003533
3534 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3535 // The magic number is 0x0B17C0DE stored in little endian.
3536 if (isBitcodeWrapper(BufPtr, BufEnd))
3537 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003538 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003539
3540 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00003541 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003542
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003543 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003544}
3545
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003546std::error_code BitcodeReader::InitLazyStream() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003547 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3548 // see it.
Yaron Keren06d69302014-12-18 10:03:35 +00003549 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
Rafael Espindola7d727b52014-12-18 05:08:43 +00003550 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00003551 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00003552 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003553
3554 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00003555 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindola27435252014-07-29 21:01:24 +00003556 return Error(BitcodeError::InvalidBitcodeSignature);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003557
3558 if (!isBitcode(buf, buf + 16))
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003559 return Error(BitcodeError::InvalidBitcodeSignature);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003560
3561 if (isBitcodeWrapper(buf, buf + 4)) {
3562 const unsigned char *bitcodeStart = buf;
3563 const unsigned char *bitcodeEnd = buf + 16;
3564 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00003565 Bytes.dropLeadingBytes(bitcodeStart - buf);
3566 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003567 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003568 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00003569}
3570
3571namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00003572class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00003573 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003574 return "llvm.bitcode";
3575 }
Craig Topper73156022014-03-02 09:09:27 +00003576 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003577 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003578 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003579 case BitcodeError::ConflictingMETADATA_KINDRecords:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003580 return "Conflicting METADATA_KIND records";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003581 case BitcodeError::CouldNotFindFunctionInStream:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003582 return "Could not find function in stream";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003583 case BitcodeError::ExpectedConstant:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003584 return "Expected a constant";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003585 case BitcodeError::InsufficientFunctionProtos:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003586 return "Insufficient function protos";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003587 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003588 return "Invalid bitcode signature";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003589 case BitcodeError::InvalidBitcodeWrapperHeader:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003590 return "Invalid bitcode wrapper header";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003591 case BitcodeError::InvalidConstantReference:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003592 return "Invalid ronstant reference";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003593 case BitcodeError::InvalidID:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003594 return "Invalid ID";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003595 case BitcodeError::InvalidInstructionWithNoBB:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003596 return "Invalid instruction with no BB";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003597 case BitcodeError::InvalidRecord:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003598 return "Invalid record";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003599 case BitcodeError::InvalidTypeForValue:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003600 return "Invalid type for value";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003601 case BitcodeError::InvalidTYPETable:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003602 return "Invalid TYPE table";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003603 case BitcodeError::InvalidType:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003604 return "Invalid type";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003605 case BitcodeError::MalformedBlock:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003606 return "Malformed block";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003607 case BitcodeError::MalformedGlobalInitializerSet:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003608 return "Malformed global initializer set";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003609 case BitcodeError::InvalidMultipleBlocks:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003610 return "Invalid multiple blocks";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003611 case BitcodeError::NeverResolvedValueFoundInFunction:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003612 return "Never resolved value found in function";
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003613 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3614 return "Never resolved function from blockaddress";
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003615 case BitcodeError::InvalidValue:
Rafael Espindola48da4f42013-11-04 16:16:24 +00003616 return "Invalid value";
3617 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00003618 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00003619 }
3620};
3621}
3622
Chris Bieneman770163e2014-09-19 20:29:02 +00003623static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3624
Rafael Espindolac3f2e732014-07-29 20:22:46 +00003625const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00003626 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003627}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003628
Chris Lattner6694f602007-04-29 07:54:31 +00003629//===----------------------------------------------------------------------===//
3630// External interface
3631//===----------------------------------------------------------------------===//
3632
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003633/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00003634///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003635/// This isn't always used in a lazy context. In particular, it's also used by
3636/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3637/// in forward-referenced functions from block address references.
3638///
3639/// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3640/// materialize everything -- in particular, if this isn't truly lazy.
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003641static ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00003642getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003643 LLVMContext &Context, bool WillMaterializeAll) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003644 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003645 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003646 M->setMaterializer(R);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003647
3648 auto cleanupOnError = [&](std::error_code EC) {
Rafael Espindola8fb31112014-06-18 20:07:35 +00003649 R->releaseBuffer(); // Never take ownership on error.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003650 delete M; // Also deletes R.
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00003651 return EC;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003652 };
Rafael Espindolab7993462012-01-02 07:49:53 +00003653
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00003654 if (std::error_code EC = R->ParseBitcodeInto(M))
3655 return cleanupOnError(EC);
3656
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003657 if (!WillMaterializeAll)
3658 // Resolve forward references from blockaddresses.
3659 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3660 return cleanupOnError(EC);
Rafael Espindolab7993462012-01-02 07:49:53 +00003661
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003662 Buffer.release(); // The BitcodeReader owns it now.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003663 return M;
Chris Lattner6694f602007-04-29 07:54:31 +00003664}
3665
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003666ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00003667llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolae2c1d772014-08-26 22:00:09 +00003668 LLVMContext &Context) {
Rafael Espindola68812152014-09-03 17:31:46 +00003669 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00003670}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003671
Rafael Espindola7d727b52014-12-18 05:08:43 +00003672ErrorOr<std::unique_ptr<Module>>
3673llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3674 LLVMContext &Context) {
3675 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3676 BitcodeReader *R = new BitcodeReader(Streamer, Context);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003677 M->setMaterializer(R);
Rafael Espindola7d727b52014-12-18 05:08:43 +00003678 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3679 return EC;
3680 return std::move(M);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003681}
3682
Rafael Espindolad96d5532014-08-26 21:49:01 +00003683ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
Rafael Espindola8f31e212014-01-15 01:08:23 +00003684 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00003685 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola68812152014-09-03 17:31:46 +00003686 ErrorOr<Module *> ModuleOrErr =
3687 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Rafael Espindola8f31e212014-01-15 01:08:23 +00003688 if (!ModuleOrErr)
3689 return ModuleOrErr;
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00003690 Module *M = ModuleOrErr.get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003691 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolad96d5532014-08-26 21:49:01 +00003692 if (std::error_code EC = M->materializeAllPermanently()) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003693 delete M;
Rafael Espindola8f31e212014-01-15 01:08:23 +00003694 return EC;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003695 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003696
Chad Rosierca2567b2011-12-07 21:44:12 +00003697 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3698 // written. We must defer until the Module has been fully materialized.
3699
Chris Lattner6694f602007-04-29 07:54:31 +00003700 return M;
3701}
Bill Wendling0198ce02010-10-06 01:22:42 +00003702
Rafael Espindolad96d5532014-08-26 21:49:01 +00003703std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003704 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00003705 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolacdb871d2014-08-27 21:11:13 +00003706 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003707 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00003708 if (Triple.getError())
3709 return "";
3710 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00003711}