blob: 59cda22503db0beed1e5d4b7d883776eedcfb93a [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Lattnercaee0dc2007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/AutoUpgrade.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/InlineAsm.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/OperandTraits.h"
25#include "llvm/IR/Operator.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000026#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000027#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000028#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000029using namespace llvm;
30
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000031enum {
32 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
33};
34
Rafael Espindola47f79bb2012-01-02 07:49:53 +000035void BitcodeReader::materializeForwardReferencedFunctions() {
36 while (!BlockAddrFwdRefs.empty()) {
37 Function *F = BlockAddrFwdRefs.begin()->first;
38 F->Materialize();
39 }
40}
41
Chris Lattnerb348bb82007-05-18 04:02:46 +000042void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000043 if (BufferOwned)
44 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000045 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000046 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000048 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000049
Bill Wendling99faa3b2012-12-07 23:16:57 +000050 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000051 std::vector<BasicBlock*>().swap(FunctionBBs);
52 std::vector<Function*>().swap(FunctionsWithBodies);
53 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000054 MDKindMap.clear();
Benjamin Kramer122f5e52012-09-21 14:34:31 +000055
56 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
Chris Lattnerc453f762007-04-29 07:54:31 +000057}
58
Chris Lattner48c85b82007-05-04 03:30:17 +000059//===----------------------------------------------------------------------===//
60// Helper functions to implement forward reference resolution, etc.
61//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000062
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063/// ConvertToString - Convert a string from a record into an std::string, return
64/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000065template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000066static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000067 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000068 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000069 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000070
Chris Lattner15e6d172007-05-04 19:11:41 +000071 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
72 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000073 return false;
74}
75
76static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
77 switch (Val) {
78 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000079 case 0: return GlobalValue::ExternalLinkage;
80 case 1: return GlobalValue::WeakAnyLinkage;
81 case 2: return GlobalValue::AppendingLinkage;
82 case 3: return GlobalValue::InternalLinkage;
83 case 4: return GlobalValue::LinkOnceAnyLinkage;
84 case 5: return GlobalValue::DLLImportLinkage;
85 case 6: return GlobalValue::DLLExportLinkage;
86 case 7: return GlobalValue::ExternalWeakLinkage;
87 case 8: return GlobalValue::CommonLinkage;
88 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000089 case 10: return GlobalValue::WeakODRLinkage;
90 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000091 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000092 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000093 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000094 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000095 }
96}
97
98static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
99 switch (Val) {
100 default: // Map unknown visibilities to default.
101 case 0: return GlobalValue::DefaultVisibility;
102 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000103 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000104 }
105}
106
Hans Wennborgce718ff2012-06-23 11:37:03 +0000107static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
108 switch (Val) {
109 case 0: return GlobalVariable::NotThreadLocal;
110 default: // Map unknown non-zero value to general dynamic.
111 case 1: return GlobalVariable::GeneralDynamicTLSModel;
112 case 2: return GlobalVariable::LocalDynamicTLSModel;
113 case 3: return GlobalVariable::InitialExecTLSModel;
114 case 4: return GlobalVariable::LocalExecTLSModel;
115 }
116}
117
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000118static int GetDecodedCastOpcode(unsigned Val) {
119 switch (Val) {
120 default: return -1;
121 case bitc::CAST_TRUNC : return Instruction::Trunc;
122 case bitc::CAST_ZEXT : return Instruction::ZExt;
123 case bitc::CAST_SEXT : return Instruction::SExt;
124 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
125 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
126 case bitc::CAST_UITOFP : return Instruction::UIToFP;
127 case bitc::CAST_SITOFP : return Instruction::SIToFP;
128 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
129 case bitc::CAST_FPEXT : return Instruction::FPExt;
130 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
131 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
132 case bitc::CAST_BITCAST : return Instruction::BitCast;
133 }
134}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000135static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000136 switch (Val) {
137 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000138 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000139 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000140 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000141 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000142 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000143 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000144 case bitc::BINOP_UDIV: return Instruction::UDiv;
145 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000146 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000147 case bitc::BINOP_UREM: return Instruction::URem;
148 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000149 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000150 case bitc::BINOP_SHL: return Instruction::Shl;
151 case bitc::BINOP_LSHR: return Instruction::LShr;
152 case bitc::BINOP_ASHR: return Instruction::AShr;
153 case bitc::BINOP_AND: return Instruction::And;
154 case bitc::BINOP_OR: return Instruction::Or;
155 case bitc::BINOP_XOR: return Instruction::Xor;
156 }
157}
158
Eli Friedmanff030482011-07-28 21:48:00 +0000159static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
160 switch (Val) {
161 default: return AtomicRMWInst::BAD_BINOP;
162 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
163 case bitc::RMW_ADD: return AtomicRMWInst::Add;
164 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
165 case bitc::RMW_AND: return AtomicRMWInst::And;
166 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
167 case bitc::RMW_OR: return AtomicRMWInst::Or;
168 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
169 case bitc::RMW_MAX: return AtomicRMWInst::Max;
170 case bitc::RMW_MIN: return AtomicRMWInst::Min;
171 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
172 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
173 }
174}
175
Eli Friedman47f35132011-07-25 23:16:38 +0000176static AtomicOrdering GetDecodedOrdering(unsigned Val) {
177 switch (Val) {
178 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
179 case bitc::ORDERING_UNORDERED: return Unordered;
180 case bitc::ORDERING_MONOTONIC: return Monotonic;
181 case bitc::ORDERING_ACQUIRE: return Acquire;
182 case bitc::ORDERING_RELEASE: return Release;
183 case bitc::ORDERING_ACQREL: return AcquireRelease;
184 default: // Map unknown orderings to sequentially-consistent.
185 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
186 }
187}
188
189static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
190 switch (Val) {
191 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
192 default: // Map unknown scopes to cross-thread.
193 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
194 }
195}
196
Gabor Greifefe65362008-05-10 08:32:32 +0000197namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000198namespace {
199 /// @brief A class for maintaining the slot number definition
200 /// as a placeholder for the actual definition for forward constants defs.
201 class ConstantPlaceHolder : public ConstantExpr {
Craig Topper86a1c322012-09-15 17:09:36 +0000202 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greif051a9502008-04-06 20:25:17 +0000203 public:
204 // allocate space for exactly one operand
205 void *operator new(size_t s) {
206 return User::operator new(s, 1);
207 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000208 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000209 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000210 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000211 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000212
Chris Lattnerea693df2008-08-21 02:34:16 +0000213 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattnerea693df2008-08-21 02:34:16 +0000214 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000215 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000216 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
217 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000218
219
Gabor Greifefe65362008-05-10 08:32:32 +0000220 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000221 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000222 };
223}
224
Chris Lattner46e77402009-03-31 22:55:09 +0000225// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000226template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000227struct OperandTraits<ConstantPlaceHolder> :
228 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000229};
Gabor Greifefe65362008-05-10 08:32:32 +0000230}
231
Chris Lattner46e77402009-03-31 22:55:09 +0000232
233void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
234 if (Idx == size()) {
235 push_back(V);
236 return;
237 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000238
Chris Lattner46e77402009-03-31 22:55:09 +0000239 if (Idx >= size())
240 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000241
Chris Lattner46e77402009-03-31 22:55:09 +0000242 WeakVH &OldV = ValuePtrs[Idx];
243 if (OldV == 0) {
244 OldV = V;
245 return;
246 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000247
Chris Lattner46e77402009-03-31 22:55:09 +0000248 // Handle constants and non-constants (e.g. instrs) differently for
249 // efficiency.
250 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
251 ResolveConstants.push_back(std::make_pair(PHC, Idx));
252 OldV = V;
253 } else {
254 // If there was a forward reference to this value, replace it.
255 Value *PrevVal = OldV;
256 OldV->replaceAllUsesWith(V);
257 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000258 }
259}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000260
Gabor Greifefe65362008-05-10 08:32:32 +0000261
Chris Lattner522b7b12007-04-24 05:48:56 +0000262Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000263 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000264 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000265 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000266
Chris Lattner46e77402009-03-31 22:55:09 +0000267 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000268 assert(Ty == V->getType() && "Type mismatch in constant table!");
269 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000270 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000271
272 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000273 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000274 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000275 return C;
276}
277
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000278Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000279 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000280 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000281
Chris Lattner46e77402009-03-31 22:55:09 +0000282 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000283 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
284 return V;
285 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000286
Chris Lattner01ff65f2007-05-02 05:16:49 +0000287 // No type specified, must be invalid reference.
288 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000289
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000290 // Create and return a placeholder, which will later be RAUW'd.
291 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000292 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000293 return V;
294}
295
Chris Lattnerea693df2008-08-21 02:34:16 +0000296/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
297/// resolves any forward references. The idea behind this is that we sometimes
298/// get constants (such as large arrays) which reference *many* forward ref
299/// constants. Replacing each of these causes a lot of thrashing when
300/// building/reuniquing the constant. Instead of doing this, we look at all the
301/// uses and rewrite all the place holders at once for any constant that uses
302/// a placeholder.
303void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000304 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000305 // binary search.
306 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000307
Chris Lattnerea693df2008-08-21 02:34:16 +0000308 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000309
Chris Lattnerea693df2008-08-21 02:34:16 +0000310 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000311 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000312 Constant *Placeholder = ResolveConstants.back().first;
313 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000314
Chris Lattnerea693df2008-08-21 02:34:16 +0000315 // Loop over all users of the placeholder, updating them to reference the
316 // new value. If they reference more than one placeholder, update them all
317 // at once.
318 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000319 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000320 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000321
Chris Lattnerea693df2008-08-21 02:34:16 +0000322 // If the using object isn't uniqued, just update the operands. This
323 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000324 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000325 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000326 continue;
327 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000328
Chris Lattnerea693df2008-08-21 02:34:16 +0000329 // Otherwise, we have a constant that uses the placeholder. Replace that
330 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000331 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000332 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
333 I != E; ++I) {
334 Value *NewOp;
335 if (!isa<ConstantPlaceHolder>(*I)) {
336 // Not a placeholder reference.
337 NewOp = *I;
338 } else if (*I == Placeholder) {
339 // Common case is that it just references this one placeholder.
340 NewOp = RealVal;
341 } else {
342 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000343 ResolveConstantsTy::iterator It =
344 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000345 std::pair<Constant*, unsigned>(cast<Constant>(*I),
346 0));
347 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000348 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000349 }
350
351 NewOps.push_back(cast<Constant>(NewOp));
352 }
353
354 // Make the new constant.
355 Constant *NewC;
356 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000357 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000358 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000359 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000360 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000361 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000362 } else {
363 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000364 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000365 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000366
Chris Lattnerea693df2008-08-21 02:34:16 +0000367 UserC->replaceAllUsesWith(NewC);
368 UserC->destroyConstant();
369 NewOps.clear();
370 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000371
Nick Lewyckycb337992009-05-10 20:57:05 +0000372 // Update all ValueHandles, they should be the only users at this point.
373 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000374 delete Placeholder;
375 }
376}
377
Devang Pateld5ac4042009-08-04 06:00:18 +0000378void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
379 if (Idx == size()) {
380 push_back(V);
381 return;
382 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000383
Devang Pateld5ac4042009-08-04 06:00:18 +0000384 if (Idx >= size())
385 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000386
Devang Pateld5ac4042009-08-04 06:00:18 +0000387 WeakVH &OldV = MDValuePtrs[Idx];
388 if (OldV == 0) {
389 OldV = V;
390 return;
391 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000392
Devang Pateld5ac4042009-08-04 06:00:18 +0000393 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000394 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000395 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000396 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000397 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
398 // value for Idx.
399 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000400}
401
402Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
403 if (Idx >= size())
404 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000405
Devang Pateld5ac4042009-08-04 06:00:18 +0000406 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000407 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000408 return V;
409 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000410
Devang Pateld5ac4042009-08-04 06:00:18 +0000411 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000412 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000413 MDValuePtrs[Idx] = V;
414 return V;
415}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000416
Chris Lattner1afcace2011-07-09 17:41:24 +0000417Type *BitcodeReader::getTypeByID(unsigned ID) {
418 // The type table size is always specified correctly.
419 if (ID >= TypeList.size())
420 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000421
Chris Lattner1afcace2011-07-09 17:41:24 +0000422 if (Type *Ty = TypeList[ID])
423 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000424
Chris Lattner1afcace2011-07-09 17:41:24 +0000425 // If we have a forward reference, the only possible case is when it is to a
426 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000427 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000428}
429
Chris Lattner1afcace2011-07-09 17:41:24 +0000430
Chris Lattner48c85b82007-05-04 03:30:17 +0000431//===----------------------------------------------------------------------===//
432// Functions for parsing blocks from the bitcode file
433//===----------------------------------------------------------------------===//
434
Devang Patel05988662008-09-25 21:00:45 +0000435bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000436 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000437 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000438
Devang Patel19c87462008-09-26 22:53:05 +0000439 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000440 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000441
Chris Lattner48c85b82007-05-04 03:30:17 +0000442 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000443
Devang Patel05988662008-09-25 21:00:45 +0000444 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000445
Chris Lattner48c85b82007-05-04 03:30:17 +0000446 // Read all the records.
447 while (1) {
448 unsigned Code = Stream.ReadCode();
449 if (Code == bitc::END_BLOCK) {
450 if (Stream.ReadBlockEnd())
451 return Error("Error at end of PARAMATTR block");
452 return false;
453 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000454
Chris Lattner48c85b82007-05-04 03:30:17 +0000455 if (Code == bitc::ENTER_SUBBLOCK) {
456 // No known subblocks, always skip them.
457 Stream.ReadSubBlockID();
458 if (Stream.SkipBlock())
459 return Error("Malformed block record");
460 continue;
461 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000462
Chris Lattner48c85b82007-05-04 03:30:17 +0000463 if (Code == bitc::DEFINE_ABBREV) {
464 Stream.ReadAbbrevRecord();
465 continue;
466 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000467
Chris Lattner48c85b82007-05-04 03:30:17 +0000468 // Read a record.
469 Record.clear();
470 switch (Stream.ReadRecord(Code, Record)) {
471 default: // Default behavior: ignore.
472 break;
473 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
474 if (Record.size() & 1)
475 return Error("Invalid ENTRY record");
476
Chris Lattner48c85b82007-05-04 03:30:17 +0000477 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling034b94b2012-12-19 07:18:57 +0000478 Attribute ReconstitutedAttr =
479 Attribute::decodeLLVMAttributesForBitcode(Context, Record[i+1]);
Bill Wendlingc966e082012-12-30 01:05:42 +0000480 Record[i+1] = ReconstitutedAttr.getBitMask();
Chris Lattner48c85b82007-05-04 03:30:17 +0000481 }
Chris Lattner461edd92008-03-12 02:25:52 +0000482
Devang Patel19c87462008-09-26 22:53:05 +0000483 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling702cc912012-10-15 20:35:56 +0000484 AttrBuilder B(Record[i+1]);
Bill Wendlingcb3de0b2012-10-15 04:46:55 +0000485 if (B.hasAttributes())
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000486 Attrs.push_back(AttributeWithIndex::get(Record[i],
Bill Wendling034b94b2012-12-19 07:18:57 +0000487 Attribute::get(Context, B)));
Devang Patel19c87462008-09-26 22:53:05 +0000488 }
Devang Patel19c87462008-09-26 22:53:05 +0000489
Bill Wendling99faa3b2012-12-07 23:16:57 +0000490 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000491 Attrs.clear();
492 break;
493 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000494 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000495 }
496}
497
Chris Lattner86697142007-05-01 05:01:34 +0000498bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000499 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000500 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000501
Chris Lattner1afcace2011-07-09 17:41:24 +0000502 return ParseTypeTableBody();
503}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000504
Chris Lattner1afcace2011-07-09 17:41:24 +0000505bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000506 if (!TypeList.empty())
507 return Error("Multiple TYPE_BLOCKs found!");
508
509 SmallVector<uint64_t, 64> Record;
510 unsigned NumRecords = 0;
511
Chris Lattner1afcace2011-07-09 17:41:24 +0000512 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000513
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000514 // Read all the records for this type table.
515 while (1) {
516 unsigned Code = Stream.ReadCode();
517 if (Code == bitc::END_BLOCK) {
518 if (NumRecords != TypeList.size())
519 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000520 if (Stream.ReadBlockEnd())
521 return Error("Error at end of type table block");
522 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000523 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000524
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000525 if (Code == bitc::ENTER_SUBBLOCK) {
526 // No known subblocks, always skip them.
527 Stream.ReadSubBlockID();
528 if (Stream.SkipBlock())
529 return Error("Malformed block record");
530 continue;
531 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000532
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000533 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000534 Stream.ReadAbbrevRecord();
535 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000536 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000537
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000538 // Read a record.
539 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000540 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000541 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000542 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000543 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
544 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
545 // type list. This allows us to reserve space.
546 if (Record.size() < 1)
547 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000548 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000549 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000550 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000551 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000552 break;
Dan Gohmance163392011-12-17 00:04:22 +0000553 case bitc::TYPE_CODE_HALF: // HALF
554 ResultTy = Type::getHalfTy(Context);
555 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000556 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000557 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000558 break;
559 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000561 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000562 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000563 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000564 break;
565 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000566 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000567 break;
568 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000569 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000570 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000571 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000572 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000573 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000574 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000575 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000576 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000577 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
578 ResultTy = Type::getX86_MMXTy(Context);
579 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000580 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
581 if (Record.size() < 1)
582 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000583
Owen Anderson1d0be152009-08-13 21:58:54 +0000584 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000585 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000586 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000587 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000588 if (Record.size() < 1)
589 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000590 unsigned AddressSpace = 0;
591 if (Record.size() == 2)
592 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000593 ResultTy = getTypeByID(Record[0]);
594 if (ResultTy == 0) return Error("invalid element type in pointer type");
595 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000596 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000597 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000598 case bitc::TYPE_CODE_FUNCTION_OLD: {
599 // FIXME: attrid is dead, remove it in LLVM 4.0
600 // FUNCTION: [vararg, attrid, retty, paramty x N]
601 if (Record.size() < 3)
602 return Error("Invalid FUNCTION type record");
603 SmallVector<Type*, 8> ArgTys;
604 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
605 if (Type *T = getTypeByID(Record[i]))
606 ArgTys.push_back(T);
607 else
608 break;
609 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000610
Nuno Lopesee8100d2012-05-23 15:19:39 +0000611 ResultTy = getTypeByID(Record[2]);
612 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
613 return Error("invalid type in function type");
614
615 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
616 break;
617 }
Chad Rosiercde54642011-11-03 00:14:01 +0000618 case bitc::TYPE_CODE_FUNCTION: {
619 // FUNCTION: [vararg, retty, paramty x N]
620 if (Record.size() < 2)
621 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000622 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000623 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
624 if (Type *T = getTypeByID(Record[i]))
625 ArgTys.push_back(T);
626 else
627 break;
628 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000629
Chad Rosiercde54642011-11-03 00:14:01 +0000630 ResultTy = getTypeByID(Record[1]);
631 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
632 return Error("invalid type in function type");
633
634 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
635 break;
636 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000637 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000638 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000639 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000640 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000641 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
642 if (Type *T = getTypeByID(Record[i]))
643 EltTys.push_back(T);
644 else
645 break;
646 }
647 if (EltTys.size() != Record.size()-1)
648 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000649 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000650 break;
651 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000652 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
653 if (ConvertToString(Record, 0, TypeName))
654 return Error("Invalid STRUCT_NAME record");
655 continue;
656
657 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
658 if (Record.size() < 1)
659 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000660
Chris Lattner1afcace2011-07-09 17:41:24 +0000661 if (NumRecords >= TypeList.size())
662 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000663
Chris Lattner1afcace2011-07-09 17:41:24 +0000664 // Check to see if this was forward referenced, if so fill in the temp.
665 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
666 if (Res) {
667 Res->setName(TypeName);
668 TypeList[NumRecords] = 0;
669 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000670 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000671 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000672
Chris Lattner1afcace2011-07-09 17:41:24 +0000673 SmallVector<Type*, 8> EltTys;
674 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
675 if (Type *T = getTypeByID(Record[i]))
676 EltTys.push_back(T);
677 else
678 break;
679 }
680 if (EltTys.size() != Record.size()-1)
681 return Error("invalid STRUCT type record");
682 Res->setBody(EltTys, Record[0]);
683 ResultTy = Res;
684 break;
685 }
686 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
687 if (Record.size() != 1)
688 return Error("Invalid OPAQUE type record");
689
690 if (NumRecords >= TypeList.size())
691 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000692
Chris Lattner1afcace2011-07-09 17:41:24 +0000693 // Check to see if this was forward referenced, if so fill in the temp.
694 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
695 if (Res) {
696 Res->setName(TypeName);
697 TypeList[NumRecords] = 0;
698 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000699 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000700 TypeName.clear();
701 ResultTy = Res;
702 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000703 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000704 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
705 if (Record.size() < 2)
706 return Error("Invalid ARRAY type record");
707 if ((ResultTy = getTypeByID(Record[1])))
708 ResultTy = ArrayType::get(ResultTy, Record[0]);
709 else
710 return Error("Invalid ARRAY type element");
711 break;
712 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
713 if (Record.size() < 2)
714 return Error("Invalid VECTOR type record");
715 if ((ResultTy = getTypeByID(Record[1])))
716 ResultTy = VectorType::get(ResultTy, Record[0]);
717 else
718 return Error("Invalid ARRAY type element");
719 break;
720 }
721
722 if (NumRecords >= TypeList.size())
723 return Error("invalid TYPE table");
724 assert(ResultTy && "Didn't read a type?");
725 assert(TypeList[NumRecords] == 0 && "Already read type?");
726 TypeList[NumRecords++] = ResultTy;
727 }
728}
729
Chris Lattner86697142007-05-01 05:01:34 +0000730bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000731 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000732 return Error("Malformed block record");
733
734 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000735
Chris Lattner0b2482a2007-04-23 21:26:05 +0000736 // Read all the records for this value table.
737 SmallString<128> ValueName;
738 while (1) {
739 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000740 if (Code == bitc::END_BLOCK) {
741 if (Stream.ReadBlockEnd())
742 return Error("Error at end of value symbol table block");
743 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000745 if (Code == bitc::ENTER_SUBBLOCK) {
746 // No known subblocks, always skip them.
747 Stream.ReadSubBlockID();
748 if (Stream.SkipBlock())
749 return Error("Malformed block record");
750 continue;
751 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000752
Chris Lattner0b2482a2007-04-23 21:26:05 +0000753 if (Code == bitc::DEFINE_ABBREV) {
754 Stream.ReadAbbrevRecord();
755 continue;
756 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattner0b2482a2007-04-23 21:26:05 +0000758 // Read a record.
759 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000760 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000761 default: // Default behavior: unknown type.
762 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000763 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000764 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000765 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000766 unsigned ValueID = Record[0];
767 if (ValueID >= ValueList.size())
768 return Error("Invalid Value ID in VST_ENTRY record");
769 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000770
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000771 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000772 ValueName.clear();
773 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000774 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000775 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000776 if (ConvertToString(Record, 1, ValueName))
777 return Error("Invalid VST_BBENTRY record");
778 BasicBlock *BB = getBasicBlock(Record[0]);
779 if (BB == 0)
780 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000782 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000783 ValueName.clear();
784 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000785 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000786 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000787 }
788}
789
Devang Patele54abc92009-07-22 17:43:22 +0000790bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000791 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000792
793 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
794 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000795
Devang Patele54abc92009-07-22 17:43:22 +0000796 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000797
Devang Patele54abc92009-07-22 17:43:22 +0000798 // Read all the records.
799 while (1) {
800 unsigned Code = Stream.ReadCode();
801 if (Code == bitc::END_BLOCK) {
802 if (Stream.ReadBlockEnd())
803 return Error("Error at end of PARAMATTR block");
804 return false;
805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000806
Devang Patele54abc92009-07-22 17:43:22 +0000807 if (Code == bitc::ENTER_SUBBLOCK) {
808 // No known subblocks, always skip them.
809 Stream.ReadSubBlockID();
810 if (Stream.SkipBlock())
811 return Error("Malformed block record");
812 continue;
813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000814
Devang Patele54abc92009-07-22 17:43:22 +0000815 if (Code == bitc::DEFINE_ABBREV) {
816 Stream.ReadAbbrevRecord();
817 continue;
818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000819
Victor Hernandez24e64df2010-01-10 07:14:18 +0000820 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000821 // Read a record.
822 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000823 Code = Stream.ReadRecord(Code, Record);
824 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000825 default: // Default behavior: ignore.
826 break;
Devang Patelaa993142009-07-29 22:34:41 +0000827 case bitc::METADATA_NAME: {
828 // Read named of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000829 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000830 Record.clear();
831 Code = Stream.ReadCode();
832
Chris Lattner9d61dd92011-06-17 17:50:30 +0000833 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000834 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000835 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000836
837 // Read named metadata elements.
838 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000839 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000840 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000841 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
842 if (MD == 0)
843 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000844 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000845 }
Devang Patelaa993142009-07-29 22:34:41 +0000846 break;
847 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000848 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000849 IsFunctionLocal = true;
850 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000851 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000852 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000853 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000854
Devang Patel104cf9e2009-07-23 01:07:34 +0000855 unsigned Size = Record.size();
856 SmallVector<Value*, 8> Elts;
857 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000858 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000859 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000860 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000861 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000862 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000863 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
864 else
865 Elts.push_back(NULL);
866 }
Jay Foadec9186b2011-04-21 19:59:31 +0000867 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000868 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000869 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000870 break;
871 }
Devang Patele54abc92009-07-22 17:43:22 +0000872 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000873 SmallString<8> String(Record.begin(), Record.end());
874 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000875 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000876 break;
877 }
Devang Patele8e02132009-09-18 19:26:43 +0000878 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000879 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000880 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000881
Devang Patela2148402009-09-28 21:14:55 +0000882 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000883 SmallString<8> Name(Record.begin()+1, Record.end());
884
Chris Lattner08113472009-12-29 09:01:33 +0000885 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000886 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
887 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000888 break;
889 }
Devang Patele54abc92009-07-22 17:43:22 +0000890 }
891 }
892}
893
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000894/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +0000895/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000896uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +0000897 if ((V & 1) == 0)
898 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000899 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000900 return -(V >> 1);
901 // There is no such thing as -0 with integers. "-0" really means MININT.
902 return 1ULL << 63;
903}
904
Chris Lattner07d98b42007-04-26 02:46:40 +0000905/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
906/// values and aliases that we can.
907bool BitcodeReader::ResolveGlobalAndAliasInits() {
908 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
909 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000910
Chris Lattner07d98b42007-04-26 02:46:40 +0000911 GlobalInitWorklist.swap(GlobalInits);
912 AliasInitWorklist.swap(AliasInits);
913
914 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000915 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000916 if (ValID >= ValueList.size()) {
917 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000918 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000919 } else {
920 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
921 GlobalInitWorklist.back().first->setInitializer(C);
922 else
923 return Error("Global variable initializer is not a constant!");
924 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000926 }
927
928 while (!AliasInitWorklist.empty()) {
929 unsigned ValID = AliasInitWorklist.back().second;
930 if (ValID >= ValueList.size()) {
931 AliasInits.push_back(AliasInitWorklist.back());
932 } else {
933 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000934 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000935 else
936 return Error("Alias initializer is not a constant!");
937 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000938 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000939 }
940 return false;
941}
942
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000943static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
944 SmallVector<uint64_t, 8> Words(Vals.size());
945 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000946 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000947
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000948 return APInt(TypeBits, Words);
949}
950
Chris Lattner86697142007-05-01 05:01:34 +0000951bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000952 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000953 return Error("Malformed block record");
954
955 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000956
Chris Lattnere16504e2007-04-24 03:30:34 +0000957 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000958 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000959 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000960 while (1) {
961 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000962 if (Code == bitc::END_BLOCK)
963 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000964
Chris Lattnere16504e2007-04-24 03:30:34 +0000965 if (Code == bitc::ENTER_SUBBLOCK) {
966 // No known subblocks, always skip them.
967 Stream.ReadSubBlockID();
968 if (Stream.SkipBlock())
969 return Error("Malformed block record");
970 continue;
971 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000972
Chris Lattnere16504e2007-04-24 03:30:34 +0000973 if (Code == bitc::DEFINE_ABBREV) {
974 Stream.ReadAbbrevRecord();
975 continue;
976 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000977
Chris Lattnere16504e2007-04-24 03:30:34 +0000978 // Read a record.
979 Record.clear();
980 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000981 unsigned BitCode = Stream.ReadRecord(Code, Record);
982 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000983 default: // Default behavior: unknown constant
984 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000985 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000986 break;
987 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
988 if (Record.empty())
989 return Error("Malformed CST_SETTYPE record");
990 if (Record[0] >= TypeList.size())
991 return Error("Invalid Type ID in CST_SETTYPE record");
992 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000993 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000994 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000995 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000996 break;
997 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000998 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000999 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001000 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001001 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001002 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001003 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001004 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001005
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001006 APInt VInt = ReadWideAPInt(Record,
1007 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001008 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +00001009
Chris Lattner0eef0802007-04-24 04:04:35 +00001010 break;
1011 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001012 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001013 if (Record.empty())
1014 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001015 if (CurTy->isHalfTy())
1016 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1017 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001018 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001019 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001020 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001021 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001022 // Bits are not stored the same way as a normal i80 APInt, compensate.
1023 uint64_t Rearrange[2];
1024 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1025 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001026 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001027 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001028 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001029 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001030 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001031 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001032 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001033 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001034 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001035
Chris Lattner15e6d172007-05-04 19:11:41 +00001036 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1037 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001038 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001039
Chris Lattner15e6d172007-05-04 19:11:41 +00001040 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001041 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001042
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001043 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001044 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001045 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001046 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001047 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001048 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1049 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001050 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001051 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001052 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001053 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1054 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001055 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001056 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001057 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001058 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001059 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001060 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001061 break;
1062 }
Chris Lattner2237f842012-02-05 02:41:35 +00001063 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001064 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1065 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001066 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001067
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001068 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001069 V = ConstantDataArray::getString(Context, Elts,
1070 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001071 break;
1072 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001073 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1074 if (Record.empty())
1075 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001076
Chris Lattnerd408f062012-01-30 00:51:16 +00001077 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1078 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001079
Chris Lattnerd408f062012-01-30 00:51:16 +00001080 if (EltTy->isIntegerTy(8)) {
1081 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1082 if (isa<VectorType>(CurTy))
1083 V = ConstantDataVector::get(Context, Elts);
1084 else
1085 V = ConstantDataArray::get(Context, Elts);
1086 } else if (EltTy->isIntegerTy(16)) {
1087 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1088 if (isa<VectorType>(CurTy))
1089 V = ConstantDataVector::get(Context, Elts);
1090 else
1091 V = ConstantDataArray::get(Context, Elts);
1092 } else if (EltTy->isIntegerTy(32)) {
1093 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1094 if (isa<VectorType>(CurTy))
1095 V = ConstantDataVector::get(Context, Elts);
1096 else
1097 V = ConstantDataArray::get(Context, Elts);
1098 } else if (EltTy->isIntegerTy(64)) {
1099 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1100 if (isa<VectorType>(CurTy))
1101 V = ConstantDataVector::get(Context, Elts);
1102 else
1103 V = ConstantDataArray::get(Context, Elts);
1104 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001105 SmallVector<float, 16> Elts(Size);
1106 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001107 if (isa<VectorType>(CurTy))
1108 V = ConstantDataVector::get(Context, Elts);
1109 else
1110 V = ConstantDataArray::get(Context, Elts);
1111 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001112 SmallVector<double, 16> Elts(Size);
1113 std::transform(Record.begin(), Record.end(), Elts.begin(),
1114 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001115 if (isa<VectorType>(CurTy))
1116 V = ConstantDataVector::get(Context, Elts);
1117 else
1118 V = ConstantDataArray::get(Context, Elts);
1119 } else {
1120 return Error("Unknown element type in CE_DATA");
1121 }
1122 break;
1123 }
1124
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001125 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1126 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1127 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001128 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001129 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001130 } else {
1131 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1132 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001133 unsigned Flags = 0;
1134 if (Record.size() >= 4) {
1135 if (Opc == Instruction::Add ||
1136 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001137 Opc == Instruction::Mul ||
1138 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001139 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1140 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1141 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1142 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001143 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001144 Opc == Instruction::UDiv ||
1145 Opc == Instruction::LShr ||
1146 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001147 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001148 Flags |= SDivOperator::IsExact;
1149 }
1150 }
1151 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001152 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001153 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001154 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001155 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1156 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1157 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001158 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001159 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001160 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001161 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001162 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001163 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001164 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001165 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001166 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001167 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001168 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001169 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001170 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001171 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001172 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001173 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001174 if (!ElTy) return Error("Invalid CE_GEP record");
1175 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1176 }
Jay Foaddab3d292011-07-21 14:31:17 +00001177 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001178 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1179 BitCode ==
1180 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001181 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001182 }
1183 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1184 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbeye46b14a2012-11-19 19:22:55 +00001185 V = ConstantExpr::getSelect(
1186 ValueList.getConstantFwdRef(Record[0],
1187 Type::getInt1Ty(Context)),
1188 ValueList.getConstantFwdRef(Record[1],CurTy),
1189 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001190 break;
1191 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1192 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001193 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001194 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1195 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1196 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001197 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001198 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001199 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001200 break;
1201 }
1202 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001203 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001204 if (Record.size() < 3 || OpTy == 0)
1205 return Error("Invalid CE_INSERTELT record");
1206 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1207 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1208 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001209 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001210 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001211 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001212 break;
1213 }
1214 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001215 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001216 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001217 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001218 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1219 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001220 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001221 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001222 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001223 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001224 break;
1225 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001226 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001227 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1228 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001229 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001230 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1231 return Error("Invalid CE_SHUFVEC_EX record");
1232 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1233 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001234 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001235 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001236 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001237 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001238 break;
1239 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001240 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1241 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001242 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001243 if (OpTy == 0) return Error("Invalid CE_CMP record");
1244 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1245 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1246
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001247 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001248 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001249 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001250 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001251 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001252 }
Chad Rosier581600b2012-09-05 19:00:49 +00001253 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001254 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001255 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001256 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1257 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001258 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001259 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001260 unsigned AsmStrSize = Record[1];
1261 if (2+AsmStrSize >= Record.size())
1262 return Error("Invalid INLINEASM record");
1263 unsigned ConstStrSize = Record[2+AsmStrSize];
1264 if (3+AsmStrSize+ConstStrSize > Record.size())
1265 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001266
Chris Lattner2bce93a2007-05-06 01:58:20 +00001267 for (unsigned i = 0; i != AsmStrSize; ++i)
1268 AsmStr += (char)Record[2+i];
1269 for (unsigned i = 0; i != ConstStrSize; ++i)
1270 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001271 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001272 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001273 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001274 break;
1275 }
Chad Rosier581600b2012-09-05 19:00:49 +00001276 // This version adds support for the asm dialect keywords (e.g.,
1277 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001278 case bitc::CST_CODE_INLINEASM: {
1279 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1280 std::string AsmStr, ConstrStr;
1281 bool HasSideEffects = Record[0] & 1;
1282 bool IsAlignStack = (Record[0] >> 1) & 1;
1283 unsigned AsmDialect = Record[0] >> 2;
1284 unsigned AsmStrSize = Record[1];
1285 if (2+AsmStrSize >= Record.size())
1286 return Error("Invalid INLINEASM record");
1287 unsigned ConstStrSize = Record[2+AsmStrSize];
1288 if (3+AsmStrSize+ConstStrSize > Record.size())
1289 return Error("Invalid INLINEASM record");
1290
1291 for (unsigned i = 0; i != AsmStrSize; ++i)
1292 AsmStr += (char)Record[2+i];
1293 for (unsigned i = 0; i != ConstStrSize; ++i)
1294 ConstrStr += (char)Record[3+AsmStrSize+i];
1295 PointerType *PTy = cast<PointerType>(CurTy);
1296 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1297 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001298 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001299 break;
1300 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001301 case bitc::CST_CODE_BLOCKADDRESS:{
1302 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001303 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001304 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1305 Function *Fn =
1306 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1307 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001308
1309 // If the function is already parsed we can insert the block address right
1310 // away.
1311 if (!Fn->empty()) {
1312 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1313 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1314 if (BBI == BBE)
1315 return Error("Invalid blockaddress block #");
1316 ++BBI;
1317 }
1318 V = BlockAddress::get(Fn, BBI);
1319 } else {
1320 // Otherwise insert a placeholder and remember it so it can be inserted
1321 // when the function is parsed.
1322 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1323 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001324 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001325 0, "");
1326 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1327 V = FwdRef;
1328 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001329 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001330 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001331 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001332
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001333 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001334 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001335 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001336
Chris Lattnerea693df2008-08-21 02:34:16 +00001337 if (NextCstNo != ValueList.size())
1338 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001339
Chris Lattnerea693df2008-08-21 02:34:16 +00001340 if (Stream.ReadBlockEnd())
1341 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001342
Chris Lattnerea693df2008-08-21 02:34:16 +00001343 // Once all the constants have been read, go through and resolve forward
1344 // references.
1345 ValueList.ResolveConstantForwardRefs();
1346 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001347}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001348
Chad Rosiercbbb0962011-12-07 21:44:12 +00001349bool BitcodeReader::ParseUseLists() {
1350 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1351 return Error("Malformed block record");
1352
1353 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001354
Chad Rosiercbbb0962011-12-07 21:44:12 +00001355 // Read all the records.
1356 while (1) {
1357 unsigned Code = Stream.ReadCode();
1358 if (Code == bitc::END_BLOCK) {
1359 if (Stream.ReadBlockEnd())
1360 return Error("Error at end of use-list table block");
1361 return false;
1362 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001363
Chad Rosiercbbb0962011-12-07 21:44:12 +00001364 if (Code == bitc::ENTER_SUBBLOCK) {
1365 // No known subblocks, always skip them.
1366 Stream.ReadSubBlockID();
1367 if (Stream.SkipBlock())
1368 return Error("Malformed block record");
1369 continue;
1370 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001371
Chad Rosiercbbb0962011-12-07 21:44:12 +00001372 if (Code == bitc::DEFINE_ABBREV) {
1373 Stream.ReadAbbrevRecord();
1374 continue;
1375 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001376
Chad Rosiercbbb0962011-12-07 21:44:12 +00001377 // Read a use list record.
1378 Record.clear();
1379 switch (Stream.ReadRecord(Code, Record)) {
1380 default: // Default behavior: unknown type.
1381 break;
1382 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1383 unsigned RecordLength = Record.size();
1384 if (RecordLength < 1)
1385 return Error ("Invalid UseList reader!");
1386 UseListRecords.push_back(Record);
1387 break;
1388 }
1389 }
1390 }
1391}
1392
Chris Lattner980e5aa2007-05-01 05:52:21 +00001393/// RememberAndSkipFunctionBody - When we see the block for a function body,
1394/// remember where it is and then skip it. This lets us lazily deserialize the
1395/// functions.
1396bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001397 // Get the function we are talking about.
1398 if (FunctionsWithBodies.empty())
1399 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001400
Chris Lattner48f84872007-05-01 04:59:48 +00001401 Function *Fn = FunctionsWithBodies.back();
1402 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001403
Chris Lattner48f84872007-05-01 04:59:48 +00001404 // Save the current stream state.
1405 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001406 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001407
Chris Lattner48f84872007-05-01 04:59:48 +00001408 // Skip over the function block for now.
1409 if (Stream.SkipBlock())
1410 return Error("Malformed block record");
1411 return false;
1412}
1413
Derek Schuff2ea93872012-02-06 22:30:29 +00001414bool BitcodeReader::GlobalCleanup() {
1415 // Patch the initializers for globals and aliases up.
1416 ResolveGlobalAndAliasInits();
1417 if (!GlobalInits.empty() || !AliasInits.empty())
1418 return Error("Malformed global initializer set");
1419
1420 // Look for intrinsic functions which need to be upgraded at some point
1421 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1422 FI != FE; ++FI) {
1423 Function *NewFn;
1424 if (UpgradeIntrinsicFunction(FI, NewFn))
1425 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1426 }
1427
1428 // Look for global variables which need to be renamed.
1429 for (Module::global_iterator
1430 GI = TheModule->global_begin(), GE = TheModule->global_end();
1431 GI != GE; ++GI)
1432 UpgradeGlobalVariable(GI);
1433 // Force deallocation of memory for these vectors to favor the client that
1434 // want lazy deserialization.
1435 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1436 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1437 return false;
1438}
1439
1440bool BitcodeReader::ParseModule(bool Resume) {
1441 if (Resume)
1442 Stream.JumpToBit(NextUnreadBit);
1443 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001444 return Error("Malformed block record");
1445
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001446 SmallVector<uint64_t, 64> Record;
1447 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001448 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001449
1450 // Read all the records for this module.
1451 while (!Stream.AtEndOfStream()) {
1452 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001453 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001454 if (Stream.ReadBlockEnd())
1455 return Error("Error at end of module block");
1456
Derek Schuff2ea93872012-02-06 22:30:29 +00001457 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001458 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001459
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001460 if (Code == bitc::ENTER_SUBBLOCK) {
1461 switch (Stream.ReadSubBlockID()) {
1462 default: // Skip unknown content.
1463 if (Stream.SkipBlock())
1464 return Error("Malformed block record");
1465 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001466 case bitc::BLOCKINFO_BLOCK_ID:
1467 if (Stream.ReadBlockInfoBlock())
1468 return Error("Malformed BlockInfoBlock");
1469 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001470 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001471 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001472 return true;
1473 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001474 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001475 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001476 return true;
1477 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001478 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001479 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001480 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001481 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001482 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001483 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001484 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001485 return true;
1486 break;
Devang Patele54abc92009-07-22 17:43:22 +00001487 case bitc::METADATA_BLOCK_ID:
1488 if (ParseMetadata())
1489 return true;
1490 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001491 case bitc::FUNCTION_BLOCK_ID:
1492 // If this is the first function body we've seen, reverse the
1493 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001494 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001495 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001496 if (GlobalCleanup())
1497 return true;
1498 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001499 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001500
Chris Lattner980e5aa2007-05-01 05:52:21 +00001501 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001502 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001503 // For streaming bitcode, suspend parsing when we reach the function
1504 // bodies. Subsequent materialization calls will resume it when
1505 // necessary. For streaming, the function bodies must be at the end of
1506 // the bitcode. If the bitcode file is old, the symbol table will be
1507 // at the end instead and will not have been seen yet. In this case,
1508 // just finish the parse now.
1509 if (LazyStreamer && SeenValueSymbolTable) {
1510 NextUnreadBit = Stream.GetCurrentBitNo();
1511 return false;
1512 }
Chris Lattner48f84872007-05-01 04:59:48 +00001513 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001514 case bitc::USELIST_BLOCK_ID:
1515 if (ParseUseLists())
1516 return true;
1517 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001518 }
1519 continue;
1520 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001521
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001522 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001523 Stream.ReadAbbrevRecord();
1524 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001525 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001526
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001527 // Read a record.
1528 switch (Stream.ReadRecord(Code, Record)) {
1529 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001530 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001531 if (Record.size() < 1)
1532 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001533 // Only version #0 and #1 are supported so far.
1534 unsigned module_version = Record[0];
1535 switch (module_version) {
1536 default: return Error("Unknown bitstream version!");
1537 case 0:
1538 UseRelativeIDs = false;
1539 break;
1540 case 1:
1541 UseRelativeIDs = true;
1542 break;
1543 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001544 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001545 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001546 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001547 std::string S;
1548 if (ConvertToString(Record, 0, S))
1549 return Error("Invalid MODULE_CODE_TRIPLE record");
1550 TheModule->setTargetTriple(S);
1551 break;
1552 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001553 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001554 std::string S;
1555 if (ConvertToString(Record, 0, S))
1556 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1557 TheModule->setDataLayout(S);
1558 break;
1559 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001560 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001561 std::string S;
1562 if (ConvertToString(Record, 0, S))
1563 return Error("Invalid MODULE_CODE_ASM record");
1564 TheModule->setModuleInlineAsm(S);
1565 break;
1566 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001567 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1568 // FIXME: Remove in 4.0.
1569 std::string S;
1570 if (ConvertToString(Record, 0, S))
1571 return Error("Invalid MODULE_CODE_DEPLIB record");
1572 // Ignore value.
1573 break;
1574 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001575 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001576 std::string S;
1577 if (ConvertToString(Record, 0, S))
1578 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1579 SectionTable.push_back(S);
1580 break;
1581 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001582 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001583 std::string S;
1584 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001585 return Error("Invalid MODULE_CODE_GCNAME record");
1586 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001587 break;
1588 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001589 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001590 // linkage, alignment, section, visibility, threadlocal,
1591 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001592 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001593 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001595 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001596 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001597 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001598 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001599 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001600 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001601
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001602 bool isConstant = Record[1];
1603 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1604 unsigned Alignment = (1 << Record[4]) >> 1;
1605 std::string Section;
1606 if (Record[5]) {
1607 if (Record[5]-1 >= SectionTable.size())
1608 return Error("Invalid section ID");
1609 Section = SectionTable[Record[5]-1];
1610 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001611 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001612 if (Record.size() > 6)
1613 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001614
1615 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001616 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001617 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001618
Rafael Espindolabea46262011-01-08 16:42:36 +00001619 bool UnnamedAddr = false;
1620 if (Record.size() > 8)
1621 UnnamedAddr = Record[8];
1622
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001623 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001624 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001625 TLM, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001626 NewGV->setAlignment(Alignment);
1627 if (!Section.empty())
1628 NewGV->setSection(Section);
1629 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001630 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001631
Chris Lattner0b2482a2007-04-23 21:26:05 +00001632 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001634 // Remember which value to use for the global initializer.
1635 if (unsigned InitID = Record[2])
1636 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001637 break;
1638 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001639 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001640 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001641 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001642 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001643 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001644 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001645 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001646 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001647 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001648 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001649 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1650 if (!FTy)
1651 return Error("Function not a pointer to function type!");
1652
Gabor Greif051a9502008-04-06 20:25:17 +00001653 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1654 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001655
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001656 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001657 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001658 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001659 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001660
Chris Lattnera9bb7132007-05-08 05:38:01 +00001661 Func->setAlignment((1 << Record[5]) >> 1);
1662 if (Record[6]) {
1663 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001664 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001665 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001666 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001667 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001668 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001669 if (Record[8]-1 > GCTable.size())
1670 return Error("Invalid GC ID");
1671 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001672 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001673 bool UnnamedAddr = false;
1674 if (Record.size() > 9)
1675 UnnamedAddr = Record[9];
1676 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001677 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001678
Chris Lattner48f84872007-05-01 04:59:48 +00001679 // If this is a function with a body, remember the prototype we are
1680 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001681 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001682 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001683 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1684 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001685 break;
1686 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001687 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001688 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001689 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001690 if (Record.size() < 3)
1691 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001692 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001693 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001694 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001695 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001696
Chris Lattner07d98b42007-04-26 02:46:40 +00001697 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1698 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001699 // Old bitcode files didn't have visibility field.
1700 if (Record.size() > 3)
1701 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001702 ValueList.push_back(NewGA);
1703 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1704 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001705 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001706 /// MODULE_CODE_PURGEVALS: [numvals]
1707 case bitc::MODULE_CODE_PURGEVALS:
1708 // Trim down the value list to the specified size.
1709 if (Record.size() < 1 || Record[0] > ValueList.size())
1710 return Error("Invalid MODULE_PURGEVALS record");
1711 ValueList.shrinkTo(Record[0]);
1712 break;
1713 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001714 Record.clear();
1715 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001716
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001717 return Error("Premature end of bitstream");
1718}
1719
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001720bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001721 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001722
Derek Schuff2ea93872012-02-06 22:30:29 +00001723 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001724
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001725 // Sniff for the signature.
1726 if (Stream.Read(8) != 'B' ||
1727 Stream.Read(8) != 'C' ||
1728 Stream.Read(4) != 0x0 ||
1729 Stream.Read(4) != 0xC ||
1730 Stream.Read(4) != 0xE ||
1731 Stream.Read(4) != 0xD)
1732 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001733
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001734 // We expect a number of well-defined blocks, though we don't necessarily
1735 // need to understand them all.
1736 while (!Stream.AtEndOfStream()) {
1737 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001738
Rafael Espindolac9687b32011-05-26 18:59:54 +00001739 if (Code != bitc::ENTER_SUBBLOCK) {
1740
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001741 // The ranlib in xcode 4 will align archive members by appending newlines
1742 // to the end of them. If this file size is a multiple of 4 but not 8, we
1743 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001744 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1745 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001746 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001747 return false;
1748
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001749 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001750 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001751
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001752 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001753
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001754 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001755 switch (BlockID) {
1756 case bitc::BLOCKINFO_BLOCK_ID:
1757 if (Stream.ReadBlockInfoBlock())
1758 return Error("Malformed BlockInfoBlock");
1759 break;
1760 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001761 // Reject multiple MODULE_BLOCK's in a single bitstream.
1762 if (TheModule)
1763 return Error("Multiple MODULE_BLOCKs in same stream");
1764 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001765 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001766 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001767 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001768 break;
1769 default:
1770 if (Stream.SkipBlock())
1771 return Error("Malformed block record");
1772 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001773 }
1774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001775
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001776 return false;
1777}
Chris Lattnerc453f762007-04-29 07:54:31 +00001778
Bill Wendling34711742010-10-06 01:22:42 +00001779bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1780 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1781 return Error("Malformed block record");
1782
1783 SmallVector<uint64_t, 64> Record;
1784
1785 // Read all the records for this module.
1786 while (!Stream.AtEndOfStream()) {
1787 unsigned Code = Stream.ReadCode();
1788 if (Code == bitc::END_BLOCK) {
1789 if (Stream.ReadBlockEnd())
1790 return Error("Error at end of module block");
1791
1792 return false;
1793 }
1794
1795 if (Code == bitc::ENTER_SUBBLOCK) {
1796 switch (Stream.ReadSubBlockID()) {
1797 default: // Skip unknown content.
1798 if (Stream.SkipBlock())
1799 return Error("Malformed block record");
1800 break;
1801 }
1802 continue;
1803 }
1804
1805 if (Code == bitc::DEFINE_ABBREV) {
1806 Stream.ReadAbbrevRecord();
1807 continue;
1808 }
1809
1810 // Read a record.
1811 switch (Stream.ReadRecord(Code, Record)) {
1812 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00001813 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1814 std::string S;
1815 if (ConvertToString(Record, 0, S))
1816 return Error("Invalid MODULE_CODE_TRIPLE record");
1817 Triple = S;
1818 break;
1819 }
1820 }
1821 Record.clear();
1822 }
1823
1824 return Error("Premature end of bitstream");
1825}
1826
1827bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001828 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001829
1830 // Sniff for the signature.
1831 if (Stream.Read(8) != 'B' ||
1832 Stream.Read(8) != 'C' ||
1833 Stream.Read(4) != 0x0 ||
1834 Stream.Read(4) != 0xC ||
1835 Stream.Read(4) != 0xE ||
1836 Stream.Read(4) != 0xD)
1837 return Error("Invalid bitcode signature");
1838
1839 // We expect a number of well-defined blocks, though we don't necessarily
1840 // need to understand them all.
1841 while (!Stream.AtEndOfStream()) {
1842 unsigned Code = Stream.ReadCode();
1843
1844 if (Code != bitc::ENTER_SUBBLOCK)
1845 return Error("Invalid record at top-level");
1846
1847 unsigned BlockID = Stream.ReadSubBlockID();
1848
1849 // We only know the MODULE subblock ID.
1850 switch (BlockID) {
1851 case bitc::MODULE_BLOCK_ID:
1852 if (ParseModuleTriple(Triple))
1853 return true;
1854 break;
1855 default:
1856 if (Stream.SkipBlock())
1857 return Error("Malformed block record");
1858 break;
1859 }
1860 }
1861
1862 return false;
1863}
1864
Devang Patele8e02132009-09-18 19:26:43 +00001865/// ParseMetadataAttachment - Parse metadata attachments.
1866bool BitcodeReader::ParseMetadataAttachment() {
1867 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1868 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001869
Devang Patele8e02132009-09-18 19:26:43 +00001870 SmallVector<uint64_t, 64> Record;
1871 while(1) {
1872 unsigned Code = Stream.ReadCode();
1873 if (Code == bitc::END_BLOCK) {
1874 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001875 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001876 break;
1877 }
1878 if (Code == bitc::DEFINE_ABBREV) {
1879 Stream.ReadAbbrevRecord();
1880 continue;
1881 }
1882 // Read a metadata attachment record.
1883 Record.clear();
1884 switch (Stream.ReadRecord(Code, Record)) {
1885 default: // Default behavior: ignore.
1886 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001887 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001888 unsigned RecordLength = Record.size();
1889 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001890 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001891 Instruction *Inst = InstructionList[Record[0]];
1892 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001893 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001894 DenseMap<unsigned, unsigned>::iterator I =
1895 MDKindMap.find(Kind);
1896 if (I == MDKindMap.end())
1897 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001898 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001899 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001900 }
1901 break;
1902 }
1903 }
1904 }
1905 return false;
1906}
Chris Lattner48f84872007-05-01 04:59:48 +00001907
Chris Lattner980e5aa2007-05-01 05:52:21 +00001908/// ParseFunctionBody - Lazily parse the specified function body block.
1909bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001910 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001911 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912
Nick Lewycky9a49f152010-02-25 08:30:17 +00001913 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001914 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001915 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Chris Lattner980e5aa2007-05-01 05:52:21 +00001917 // Add all the function arguments to the value table.
1918 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1919 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001920
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001921 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001922 BasicBlock *CurBB = 0;
1923 unsigned CurBBNo = 0;
1924
Chris Lattnera6245242010-04-03 02:17:50 +00001925 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00001926
Chris Lattner980e5aa2007-05-01 05:52:21 +00001927 // Read all the records.
1928 SmallVector<uint64_t, 64> Record;
1929 while (1) {
1930 unsigned Code = Stream.ReadCode();
1931 if (Code == bitc::END_BLOCK) {
1932 if (Stream.ReadBlockEnd())
1933 return Error("Error at end of function block");
1934 break;
1935 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001936
Chris Lattner980e5aa2007-05-01 05:52:21 +00001937 if (Code == bitc::ENTER_SUBBLOCK) {
1938 switch (Stream.ReadSubBlockID()) {
1939 default: // Skip unknown content.
1940 if (Stream.SkipBlock())
1941 return Error("Malformed block record");
1942 break;
1943 case bitc::CONSTANTS_BLOCK_ID:
1944 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001945 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001946 break;
1947 case bitc::VALUE_SYMTAB_BLOCK_ID:
1948 if (ParseValueSymbolTable()) return true;
1949 break;
Devang Patele8e02132009-09-18 19:26:43 +00001950 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001951 if (ParseMetadataAttachment()) return true;
1952 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001953 case bitc::METADATA_BLOCK_ID:
1954 if (ParseMetadata()) return true;
1955 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001956 }
1957 continue;
1958 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001959
Chris Lattner980e5aa2007-05-01 05:52:21 +00001960 if (Code == bitc::DEFINE_ABBREV) {
1961 Stream.ReadAbbrevRecord();
1962 continue;
1963 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001964
Chris Lattner980e5aa2007-05-01 05:52:21 +00001965 // Read a record.
1966 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001967 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001968 unsigned BitCode = Stream.ReadRecord(Code, Record);
1969 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001970 default: // Default behavior: reject
1971 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001972 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001973 if (Record.size() < 1 || Record[0] == 0)
1974 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001975 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001976 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001977 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001978 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001979 CurBB = FunctionBBs[0];
1980 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001981
Chris Lattnera6245242010-04-03 02:17:50 +00001982 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1983 // This record indicates that the last instruction is at the same
1984 // location as the previous instruction with a location.
1985 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00001986
Chris Lattnera6245242010-04-03 02:17:50 +00001987 // Get the last instruction emitted.
1988 if (CurBB && !CurBB->empty())
1989 I = &CurBB->back();
1990 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1991 !FunctionBBs[CurBBNo-1]->empty())
1992 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00001993
Chris Lattnera6245242010-04-03 02:17:50 +00001994 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1995 I->setDebugLoc(LastLoc);
1996 I = 0;
1997 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001998
Chris Lattner4f6bab92011-06-17 18:17:37 +00001999 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002000 I = 0; // Get the last instruction emitted.
2001 if (CurBB && !CurBB->empty())
2002 I = &CurBB->back();
2003 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2004 !FunctionBBs[CurBBNo-1]->empty())
2005 I = &FunctionBBs[CurBBNo-1]->back();
2006 if (I == 0 || Record.size() < 4)
2007 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002008
Chris Lattnera6245242010-04-03 02:17:50 +00002009 unsigned Line = Record[0], Col = Record[1];
2010 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00002011
Chris Lattnera6245242010-04-03 02:17:50 +00002012 MDNode *Scope = 0, *IA = 0;
2013 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2014 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2015 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2016 I->setDebugLoc(LastLoc);
2017 I = 0;
2018 continue;
2019 }
2020
Chris Lattnerabfbf852007-05-06 00:21:25 +00002021 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2022 unsigned OpNum = 0;
2023 Value *LHS, *RHS;
2024 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002025 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002026 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002027 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002028
Dan Gohman1224c382009-07-20 21:19:07 +00002029 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002030 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002031 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002032 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002033 if (OpNum < Record.size()) {
2034 if (Opc == Instruction::Add ||
2035 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002036 Opc == Instruction::Mul ||
2037 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002038 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002039 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002040 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002041 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002042 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002043 Opc == Instruction::UDiv ||
2044 Opc == Instruction::LShr ||
2045 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002046 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002047 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002048 } else if (isa<FPMathOperator>(I)) {
2049 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002050 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2051 FMF.setUnsafeAlgebra();
2052 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2053 FMF.setNoNaNs();
2054 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2055 FMF.setNoInfs();
2056 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2057 FMF.setNoSignedZeros();
2058 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2059 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002060 if (FMF.any())
2061 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002062 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002063
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002064 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002065 break;
2066 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002067 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2068 unsigned OpNum = 0;
2069 Value *Op;
2070 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2071 OpNum+2 != Record.size())
2072 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002073
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002074 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002075 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2076 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002077 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002078 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002079 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002080 break;
2081 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002082 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002083 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002084 unsigned OpNum = 0;
2085 Value *BasePtr;
2086 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002087 return Error("Invalid GEP record");
2088
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002089 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002090 while (OpNum != Record.size()) {
2091 Value *Op;
2092 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002093 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002094 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002095 }
2096
Jay Foada9203102011-07-25 09:48:08 +00002097 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002098 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002099 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002100 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002101 break;
2102 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002103
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002104 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2105 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002106 unsigned OpNum = 0;
2107 Value *Agg;
2108 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2109 return Error("Invalid EXTRACTVAL record");
2110
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002111 SmallVector<unsigned, 4> EXTRACTVALIdx;
2112 for (unsigned RecSize = Record.size();
2113 OpNum != RecSize; ++OpNum) {
2114 uint64_t Index = Record[OpNum];
2115 if ((unsigned)Index != Index)
2116 return Error("Invalid EXTRACTVAL index");
2117 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002118 }
2119
Jay Foadfc6d3a42011-07-13 10:26:04 +00002120 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002121 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002122 break;
2123 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002124
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002125 case bitc::FUNC_CODE_INST_INSERTVAL: {
2126 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002127 unsigned OpNum = 0;
2128 Value *Agg;
2129 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2130 return Error("Invalid INSERTVAL record");
2131 Value *Val;
2132 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2133 return Error("Invalid INSERTVAL record");
2134
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002135 SmallVector<unsigned, 4> INSERTVALIdx;
2136 for (unsigned RecSize = Record.size();
2137 OpNum != RecSize; ++OpNum) {
2138 uint64_t Index = Record[OpNum];
2139 if ((unsigned)Index != Index)
2140 return Error("Invalid INSERTVAL index");
2141 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002142 }
2143
Jay Foadfc6d3a42011-07-13 10:26:04 +00002144 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002145 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002146 break;
2147 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002148
Chris Lattnerabfbf852007-05-06 00:21:25 +00002149 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002150 // obsolete form of select
2151 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002152 unsigned OpNum = 0;
2153 Value *TrueVal, *FalseVal, *Cond;
2154 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002155 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2156 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002157 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002158
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002159 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002160 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002161 break;
2162 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002164 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2165 // new form of select
2166 // handles select i1 or select [N x i1]
2167 unsigned OpNum = 0;
2168 Value *TrueVal, *FalseVal, *Cond;
2169 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002170 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002171 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2172 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002173
2174 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002175 if (VectorType* vector_type =
2176 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002177 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002178 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002179 return Error("Invalid SELECT condition type");
2180 } else {
2181 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002182 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002183 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002184 }
2185
Gabor Greif051a9502008-04-06 20:25:17 +00002186 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002187 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002188 break;
2189 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002190
Chris Lattner01ff65f2007-05-02 05:16:49 +00002191 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002192 unsigned OpNum = 0;
2193 Value *Vec, *Idx;
2194 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002195 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002196 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002197 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002198 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002199 break;
2200 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002201
Chris Lattner01ff65f2007-05-02 05:16:49 +00002202 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002203 unsigned OpNum = 0;
2204 Value *Vec, *Elt, *Idx;
2205 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002206 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002207 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002208 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002209 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002210 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002211 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002212 break;
2213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002214
Chris Lattnerabfbf852007-05-06 00:21:25 +00002215 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2216 unsigned OpNum = 0;
2217 Value *Vec1, *Vec2, *Mask;
2218 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002219 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002220 return Error("Invalid SHUFFLEVEC record");
2221
Mon P Wangaeb06d22008-11-10 04:46:22 +00002222 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002223 return Error("Invalid SHUFFLEVEC record");
2224 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002225 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002226 break;
2227 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002228
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002229 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2230 // Old form of ICmp/FCmp returning bool
2231 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2232 // both legal on vectors but had different behaviour.
2233 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2234 // FCmp/ICmp returning bool or vector of bool
2235
Chris Lattner7337ab92007-05-06 00:00:00 +00002236 unsigned OpNum = 0;
2237 Value *LHS, *RHS;
2238 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002239 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002240 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002241 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002242
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002243 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002244 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002245 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002246 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002247 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002248 break;
2249 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002250
Chris Lattner231cbcb2007-05-02 04:27:25 +00002251 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002252 {
2253 unsigned Size = Record.size();
2254 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002255 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002256 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002257 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002258 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002259
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002260 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002261 Value *Op = NULL;
2262 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2263 return Error("Invalid RET record");
2264 if (OpNum != Record.size())
2265 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002266
Chris Lattner96a74c52011-06-17 18:09:11 +00002267 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002268 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002269 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002270 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002271 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002272 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002273 return Error("Invalid BR record");
2274 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2275 if (TrueDest == 0)
2276 return Error("Invalid BR record");
2277
Devang Patele8e02132009-09-18 19:26:43 +00002278 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002279 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002280 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002281 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002282 else {
2283 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002284 Value *Cond = getValue(Record, 2, NextValueNo,
2285 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002286 if (FalseDest == 0 || Cond == 0)
2287 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002288 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002289 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002290 }
2291 break;
2292 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002293 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002294 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002295 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2296 // New SwitchInst format with case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002297
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002298 Type *OpTy = getTypeByID(Record[1]);
2299 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2300
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002301 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002302 BasicBlock *Default = getBasicBlock(Record[3]);
2303 if (OpTy == 0 || Cond == 0 || Default == 0)
2304 return Error("Invalid SWITCH record");
2305
2306 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002307
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002308 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2309 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002310
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002311 unsigned CurIdx = 5;
2312 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002313 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002314 unsigned NumItems = Record[CurIdx++];
2315 for (unsigned ci = 0; ci != NumItems; ++ci) {
2316 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002317
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002318 APInt Low;
2319 unsigned ActiveWords = 1;
2320 if (ValueBitWidth > 64)
2321 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002322 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2323 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002324 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002325
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002326 if (!isSingleNumber) {
2327 ActiveWords = 1;
2328 if (ValueBitWidth > 64)
2329 ActiveWords = Record[CurIdx++];
2330 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002331 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2332 ValueBitWidth);
Michael Ilseman407a6162012-11-15 22:34:00 +00002333
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002334 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2335 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002336 CurIdx += ActiveWords;
2337 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002338 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002339 }
2340 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Michael Ilseman407a6162012-11-15 22:34:00 +00002341 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002342 SI->addCase(Case, DestBB);
2343 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002344 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002345 if (Hash != (Record[0] & 0xFFFF))
2346 return Error("Invalid SWITCH record");
2347 I = SI;
2348 break;
2349 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002350
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002351 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002352
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002353 if (Record.size() < 3 || (Record.size() & 1) == 0)
2354 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002355 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002356 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002357 BasicBlock *Default = getBasicBlock(Record[2]);
2358 if (OpTy == 0 || Cond == 0 || Default == 0)
2359 return Error("Invalid SWITCH record");
2360 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002361 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002362 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002363 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002364 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002365 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2366 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2367 if (CaseVal == 0 || DestBB == 0) {
2368 delete SI;
2369 return Error("Invalid SWITCH record!");
2370 }
2371 SI->addCase(CaseVal, DestBB);
2372 }
2373 I = SI;
2374 break;
2375 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002376 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002377 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002378 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002379 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002380 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002381 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002382 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002383 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002384 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002385 InstructionList.push_back(IBI);
2386 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2387 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2388 IBI->addDestination(DestBB);
2389 } else {
2390 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002391 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002392 }
2393 }
2394 I = IBI;
2395 break;
2396 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002397
Duncan Sandsdc024672007-11-27 13:23:08 +00002398 case bitc::FUNC_CODE_INST_INVOKE: {
2399 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002400 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002401 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002402 unsigned CCInfo = Record[1];
2403 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2404 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002405
Chris Lattnera9bb7132007-05-08 05:38:01 +00002406 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002407 Value *Callee;
2408 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002409 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002410
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002411 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2412 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002413 dyn_cast<FunctionType>(CalleeTy->getElementType());
2414
2415 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002416 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2417 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002418 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002419
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002420 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002421 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002422 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2423 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002424 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002425 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002426
Chris Lattner7337ab92007-05-06 00:00:00 +00002427 if (!FTy->isVarArg()) {
2428 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002429 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002430 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002431 // Read type/value pairs for varargs params.
2432 while (OpNum != Record.size()) {
2433 Value *Op;
2434 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2435 return Error("Invalid INVOKE record");
2436 Ops.push_back(Op);
2437 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002438 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002439
Jay Foada3efbb12011-07-15 08:37:34 +00002440 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002441 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002442 cast<InvokeInst>(I)->setCallingConv(
2443 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002444 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002445 break;
2446 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002447 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2448 unsigned Idx = 0;
2449 Value *Val = 0;
2450 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2451 return Error("Invalid RESUME record");
2452 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002453 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002454 break;
2455 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002456 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002457 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002458 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002459 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002460 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002461 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002462 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002463 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002464 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002465
Jay Foad3ecfc862011-03-30 11:28:46 +00002466 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002467 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002468
Chris Lattner15e6d172007-05-04 19:11:41 +00002469 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002470 Value *V;
2471 // With the new function encoding, it is possible that operands have
2472 // negative IDs (for forward references). Use a signed VBR
2473 // representation to keep the encoding small.
2474 if (UseRelativeIDs)
2475 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2476 else
2477 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002478 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002479 if (!V || !BB) return Error("Invalid PHI record");
2480 PN->addIncoming(V, BB);
2481 }
2482 I = PN;
2483 break;
2484 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002485
Bill Wendlinge6e88262011-08-12 20:24:12 +00002486 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2487 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2488 unsigned Idx = 0;
2489 if (Record.size() < 4)
2490 return Error("Invalid LANDINGPAD record");
2491 Type *Ty = getTypeByID(Record[Idx++]);
2492 if (!Ty) return Error("Invalid LANDINGPAD record");
2493 Value *PersFn = 0;
2494 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2495 return Error("Invalid LANDINGPAD record");
2496
2497 bool IsCleanup = !!Record[Idx++];
2498 unsigned NumClauses = Record[Idx++];
2499 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2500 LP->setCleanup(IsCleanup);
2501 for (unsigned J = 0; J != NumClauses; ++J) {
2502 LandingPadInst::ClauseType CT =
2503 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2504 Value *Val;
2505
2506 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2507 delete LP;
2508 return Error("Invalid LANDINGPAD record");
2509 }
2510
2511 assert((CT != LandingPadInst::Catch ||
2512 !isa<ArrayType>(Val->getType())) &&
2513 "Catch clause has a invalid type!");
2514 assert((CT != LandingPadInst::Filter ||
2515 isa<ArrayType>(Val->getType())) &&
2516 "Filter clause has invalid type!");
2517 LP->addClause(Val);
2518 }
2519
2520 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002521 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002522 break;
2523 }
2524
Chris Lattner96a74c52011-06-17 18:09:11 +00002525 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2526 if (Record.size() != 4)
2527 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002528 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002529 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002530 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002531 Value *Size = getFnValueByID(Record[2], OpTy);
2532 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002533 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002534 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002535 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002536 break;
2537 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002538 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002539 unsigned OpNum = 0;
2540 Value *Op;
2541 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2542 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002543 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002544
Chris Lattner7337ab92007-05-06 00:00:00 +00002545 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002546 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002547 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002548 }
Eli Friedman21006d42011-08-09 23:02:53 +00002549 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2550 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2551 unsigned OpNum = 0;
2552 Value *Op;
2553 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2554 OpNum+4 != Record.size())
2555 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002556
Eli Friedman21006d42011-08-09 23:02:53 +00002557
2558 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2559 if (Ordering == NotAtomic || Ordering == Release ||
2560 Ordering == AcquireRelease)
2561 return Error("Invalid LOADATOMIC record");
2562 if (Ordering != NotAtomic && Record[OpNum] == 0)
2563 return Error("Invalid LOADATOMIC record");
2564 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2565
2566 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2567 Ordering, SynchScope);
2568 InstructionList.push_back(I);
2569 break;
2570 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002571 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002572 unsigned OpNum = 0;
2573 Value *Val, *Ptr;
2574 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002575 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002576 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2577 OpNum+2 != Record.size())
2578 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002579
Christopher Lambfe63fb92007-12-11 08:59:05 +00002580 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002581 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002582 break;
2583 }
Eli Friedman21006d42011-08-09 23:02:53 +00002584 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2585 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2586 unsigned OpNum = 0;
2587 Value *Val, *Ptr;
2588 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002589 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002590 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2591 OpNum+4 != Record.size())
2592 return Error("Invalid STOREATOMIC record");
2593
2594 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002595 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002596 Ordering == AcquireRelease)
2597 return Error("Invalid STOREATOMIC record");
2598 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2599 if (Ordering != NotAtomic && Record[OpNum] == 0)
2600 return Error("Invalid STOREATOMIC record");
2601
2602 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2603 Ordering, SynchScope);
2604 InstructionList.push_back(I);
2605 break;
2606 }
Eli Friedmanff030482011-07-28 21:48:00 +00002607 case bitc::FUNC_CODE_INST_CMPXCHG: {
2608 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2609 unsigned OpNum = 0;
2610 Value *Ptr, *Cmp, *New;
2611 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002612 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002613 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002614 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002615 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2616 OpNum+3 != Record.size())
2617 return Error("Invalid CMPXCHG record");
2618 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002619 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002620 return Error("Invalid CMPXCHG record");
2621 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2622 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2623 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2624 InstructionList.push_back(I);
2625 break;
2626 }
2627 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2628 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2629 unsigned OpNum = 0;
2630 Value *Ptr, *Val;
2631 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002632 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002633 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2634 OpNum+4 != Record.size())
2635 return Error("Invalid ATOMICRMW record");
2636 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2637 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2638 Operation > AtomicRMWInst::LAST_BINOP)
2639 return Error("Invalid ATOMICRMW record");
2640 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002641 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002642 return Error("Invalid ATOMICRMW record");
2643 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2644 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2645 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2646 InstructionList.push_back(I);
2647 break;
2648 }
Eli Friedman47f35132011-07-25 23:16:38 +00002649 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2650 if (2 != Record.size())
2651 return Error("Invalid FENCE record");
2652 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2653 if (Ordering == NotAtomic || Ordering == Unordered ||
2654 Ordering == Monotonic)
2655 return Error("Invalid FENCE record");
2656 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2657 I = new FenceInst(Context, Ordering, SynchScope);
2658 InstructionList.push_back(I);
2659 break;
2660 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002661 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002662 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2663 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002664 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002665
Bill Wendling99faa3b2012-12-07 23:16:57 +00002666 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002667 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002668
Chris Lattnera9bb7132007-05-08 05:38:01 +00002669 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002670 Value *Callee;
2671 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2672 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002673
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002674 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2675 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002676 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002677 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002678 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002679
Chris Lattner0579f7f2007-05-03 22:04:19 +00002680 SmallVector<Value*, 16> Args;
2681 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002682 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002683 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002684 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002685 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002686 Args.push_back(getValue(Record, OpNum, NextValueNo,
2687 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002688 if (Args.back() == 0) return Error("Invalid CALL record");
2689 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002690
Chris Lattner0579f7f2007-05-03 22:04:19 +00002691 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002692 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002693 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002694 return Error("Invalid CALL record");
2695 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002696 while (OpNum != Record.size()) {
2697 Value *Op;
2698 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2699 return Error("Invalid CALL record");
2700 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002701 }
2702 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002703
Jay Foada3efbb12011-07-15 08:37:34 +00002704 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002705 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002706 cast<CallInst>(I)->setCallingConv(
2707 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002708 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002709 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002710 break;
2711 }
2712 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2713 if (Record.size() < 3)
2714 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002715 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002716 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002717 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002718 if (!OpTy || !Op || !ResTy)
2719 return Error("Invalid VAARG record");
2720 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002721 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002722 break;
2723 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002724 }
2725
2726 // Add instruction to end of current BB. If there is no current BB, reject
2727 // this file.
2728 if (CurBB == 0) {
2729 delete I;
2730 return Error("Invalid instruction with no BB");
2731 }
2732 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002733
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002734 // If this was a terminator instruction, move to the next block.
2735 if (isa<TerminatorInst>(I)) {
2736 ++CurBBNo;
2737 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2738 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002739
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002740 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002741 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002742 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002743 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002744
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002745 // Check the function list for unresolved values.
2746 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2747 if (A->getParent() == 0) {
2748 // We found at least one unresolved value. Nuke them all to avoid leaks.
2749 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002750 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002751 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002752 delete A;
2753 }
2754 }
Chris Lattner35a04702007-05-04 03:50:29 +00002755 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002756 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002757 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002758
Dan Gohman064ff3e2010-08-25 20:23:38 +00002759 // FIXME: Check for unresolved forward-declared metadata references
2760 // and clean up leaks.
2761
Chris Lattner50b136d2009-10-28 05:53:48 +00002762 // See if anything took the address of blocks in this function. If so,
2763 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002764 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2765 BlockAddrFwdRefs.find(F);
2766 if (BAFRI != BlockAddrFwdRefs.end()) {
2767 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2768 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2769 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002770 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002771 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00002772
Chris Lattner50b136d2009-10-28 05:53:48 +00002773 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002774 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002775 FwdRef->eraseFromParent();
2776 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002777
Chris Lattner50b136d2009-10-28 05:53:48 +00002778 BlockAddrFwdRefs.erase(BAFRI);
2779 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002780
Chris Lattner980e5aa2007-05-01 05:52:21 +00002781 // Trim the value list down to the size it was before we parsed this function.
2782 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002783 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002784 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002785 return false;
2786}
2787
Derek Schuff2ea93872012-02-06 22:30:29 +00002788/// FindFunctionInStream - Find the function body in the bitcode stream
2789bool BitcodeReader::FindFunctionInStream(Function *F,
2790 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2791 while (DeferredFunctionInfoIterator->second == 0) {
2792 if (Stream.AtEndOfStream())
2793 return Error("Could not find Function in stream");
2794 // ParseModule will parse the next body in the stream and set its
2795 // position in the DeferredFunctionInfo map.
2796 if (ParseModule(true)) return true;
2797 }
2798 return false;
2799}
2800
Chris Lattnerb348bb82007-05-18 04:02:46 +00002801//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002802// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002803//===----------------------------------------------------------------------===//
2804
2805
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002806bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2807 if (const Function *F = dyn_cast<Function>(GV)) {
2808 return F->isDeclaration() &&
2809 DeferredFunctionInfo.count(const_cast<Function*>(F));
2810 }
2811 return false;
2812}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002813
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002814bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2815 Function *F = dyn_cast<Function>(GV);
2816 // If it's not a function or is already material, ignore the request.
2817 if (!F || !F->isMaterializable()) return false;
2818
2819 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002820 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002821 // If its position is recorded as 0, its body is somewhere in the stream
2822 // but we haven't seen it yet.
2823 if (DFII->second == 0)
2824 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002825
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002826 // Move the bit stream to the saved position of the deferred function body.
2827 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002828
Chris Lattnerb348bb82007-05-18 04:02:46 +00002829 if (ParseFunctionBody(F)) {
2830 if (ErrInfo) *ErrInfo = ErrorString;
2831 return true;
2832 }
Chandler Carruth69940402007-08-04 01:51:18 +00002833
2834 // Upgrade any old intrinsic calls in the function.
2835 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2836 E = UpgradedIntrinsics.end(); I != E; ++I) {
2837 if (I->first != I->second) {
2838 for (Value::use_iterator UI = I->first->use_begin(),
2839 UE = I->first->use_end(); UI != UE; ) {
2840 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2841 UpgradeIntrinsicCall(CI, I->second);
2842 }
2843 }
2844 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002845
Chris Lattnerb348bb82007-05-18 04:02:46 +00002846 return false;
2847}
2848
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002849bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2850 const Function *F = dyn_cast<Function>(GV);
2851 if (!F || F->isDeclaration())
2852 return false;
2853 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2854}
2855
2856void BitcodeReader::Dematerialize(GlobalValue *GV) {
2857 Function *F = dyn_cast<Function>(GV);
2858 // If this function isn't dematerializable, this is a noop.
2859 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002860 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002861
Chris Lattnerb348bb82007-05-18 04:02:46 +00002862 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002863
Chris Lattnerb348bb82007-05-18 04:02:46 +00002864 // Just forget the function body, we can remat it later.
2865 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002866}
2867
2868
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002869bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2870 assert(M == TheModule &&
2871 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002872 // Iterate over the module, deserializing any functions that are still on
2873 // disk.
2874 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2875 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002876 if (F->isMaterializable() &&
2877 Materialize(F, ErrInfo))
2878 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002879
Derek Schuff0ffe6982012-02-29 00:07:09 +00002880 // At this point, if there are any function bodies, the current bit is
2881 // pointing to the END_BLOCK record after them. Now make sure the rest
2882 // of the bits in the module have been read.
2883 if (NextUnreadBit)
2884 ParseModule(true);
2885
Daniel Dunbara279bc32009-09-20 02:20:51 +00002886 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2887 // delete the old functions to clean up. We can't do this unless the entire
2888 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002889 // with calls to the old function.
2890 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2891 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2892 if (I->first != I->second) {
2893 for (Value::use_iterator UI = I->first->use_begin(),
2894 UE = I->first->use_end(); UI != UE; ) {
2895 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2896 UpgradeIntrinsicCall(CI, I->second);
2897 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002898 if (!I->first->use_empty())
2899 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002900 I->first->eraseFromParent();
2901 }
2902 }
2903 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002904
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002905 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002906}
2907
Derek Schuff2ea93872012-02-06 22:30:29 +00002908bool BitcodeReader::InitStream() {
2909 if (LazyStreamer) return InitLazyStream();
2910 return InitStreamFromBuffer();
2911}
2912
2913bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00002914 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00002915 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2916
2917 if (Buffer->getBufferSize() & 3) {
2918 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2919 return Error("Invalid bitcode signature");
2920 else
2921 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2922 }
2923
2924 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2925 // The magic number is 0x0B17C0DE stored in little endian.
2926 if (isBitcodeWrapper(BufPtr, BufEnd))
2927 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2928 return Error("Invalid bitcode wrapper header");
2929
2930 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2931 Stream.init(*StreamFile);
2932
2933 return false;
2934}
2935
2936bool BitcodeReader::InitLazyStream() {
2937 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2938 // see it.
2939 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2940 StreamFile.reset(new BitstreamReader(Bytes));
2941 Stream.init(*StreamFile);
2942
2943 unsigned char buf[16];
2944 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2945 return Error("Bitcode stream must be at least 16 bytes in length");
2946
2947 if (!isBitcode(buf, buf + 16))
2948 return Error("Invalid bitcode signature");
2949
2950 if (isBitcodeWrapper(buf, buf + 4)) {
2951 const unsigned char *bitcodeStart = buf;
2952 const unsigned char *bitcodeEnd = buf + 16;
2953 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2954 Bytes->dropLeadingBytes(bitcodeStart - buf);
2955 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2956 }
2957 return false;
2958}
Chris Lattner48f84872007-05-01 04:59:48 +00002959
Chris Lattnerc453f762007-04-29 07:54:31 +00002960//===----------------------------------------------------------------------===//
2961// External interface
2962//===----------------------------------------------------------------------===//
2963
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002964/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002965///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002966Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2967 LLVMContext& Context,
2968 std::string *ErrMsg) {
2969 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002970 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002971 M->setMaterializer(R);
2972 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002973 if (ErrMsg)
2974 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002975
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002976 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002977 return 0;
2978 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002979 // Have the BitcodeReader dtor delete 'Buffer'.
2980 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002981
2982 R->materializeForwardReferencedFunctions();
2983
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002984 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002985}
2986
Derek Schuff2ea93872012-02-06 22:30:29 +00002987
2988Module *llvm::getStreamedBitcodeModule(const std::string &name,
2989 DataStreamer *streamer,
2990 LLVMContext &Context,
2991 std::string *ErrMsg) {
2992 Module *M = new Module(name, Context);
2993 BitcodeReader *R = new BitcodeReader(streamer, Context);
2994 M->setMaterializer(R);
2995 if (R->ParseBitcodeInto(M)) {
2996 if (ErrMsg)
2997 *ErrMsg = R->getErrorString();
2998 delete M; // Also deletes R.
2999 return 0;
3000 }
3001 R->setBufferOwned(false); // no buffer to delete
3002 return M;
3003}
3004
Chris Lattnerc453f762007-04-29 07:54:31 +00003005/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3006/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003007Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00003008 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003009 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3010 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003011
3012 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3013 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003014 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003015
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003016 // Read in the entire module, and destroy the BitcodeReader.
3017 if (M->MaterializeAllPermanently(ErrMsg)) {
3018 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003019 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003020 }
Bill Wendling34711742010-10-06 01:22:42 +00003021
Chad Rosiercbbb0962011-12-07 21:44:12 +00003022 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3023 // written. We must defer until the Module has been fully materialized.
3024
Chris Lattnerc453f762007-04-29 07:54:31 +00003025 return M;
3026}
Bill Wendling34711742010-10-06 01:22:42 +00003027
3028std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3029 LLVMContext& Context,
3030 std::string *ErrMsg) {
3031 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3032 // Don't let the BitcodeReader dtor delete 'Buffer'.
3033 R->setBufferOwned(false);
3034
3035 std::string Triple("");
3036 if (R->ParseTriple(Triple))
3037 if (ErrMsg)
3038 *ErrMsg = R->getErrorString();
3039
3040 delete R;
3041 return Triple;
3042}