blob: a06a6f00f8b629683f4515dcf9f0e5fd92fddb43 [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"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Devang Patele4b27562009-08-28 23:24:31 +000019#include "llvm/IntrinsicInst.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000021#include "llvm/Operator.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000024#include "llvm/ADT/SmallVector.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000025#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000026#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000027#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000028#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000029using namespace llvm;
30
Stepan Dyatkovskiy85a44062012-05-08 06:36:08 +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
Devang Patel19c87462008-09-26 22:53:05 +000050 std::vector<AttrListPtr>().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();
Chris Lattnerc453f762007-04-29 07:54:31 +000055}
56
Chris Lattner48c85b82007-05-04 03:30:17 +000057//===----------------------------------------------------------------------===//
58// Helper functions to implement forward reference resolution, etc.
59//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000060
Chris Lattnercaee0dc2007-04-22 06:23:29 +000061/// ConvertToString - Convert a string from a record into an std::string, return
62/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000063template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000064static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000065 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000066 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000067 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000068
Chris Lattner15e6d172007-05-04 19:11:41 +000069 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
70 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000071 return false;
72}
73
74static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
75 switch (Val) {
76 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000077 case 0: return GlobalValue::ExternalLinkage;
78 case 1: return GlobalValue::WeakAnyLinkage;
79 case 2: return GlobalValue::AppendingLinkage;
80 case 3: return GlobalValue::InternalLinkage;
81 case 4: return GlobalValue::LinkOnceAnyLinkage;
82 case 5: return GlobalValue::DLLImportLinkage;
83 case 6: return GlobalValue::DLLExportLinkage;
84 case 7: return GlobalValue::ExternalWeakLinkage;
85 case 8: return GlobalValue::CommonLinkage;
86 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000087 case 10: return GlobalValue::WeakODRLinkage;
88 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000089 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000090 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000091 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling55ae5152010-08-20 22:05:50 +000092 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000093 }
94}
95
96static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
97 switch (Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000101 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000102 }
103}
104
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000105static int GetDecodedCastOpcode(unsigned Val) {
106 switch (Val) {
107 default: return -1;
108 case bitc::CAST_TRUNC : return Instruction::Trunc;
109 case bitc::CAST_ZEXT : return Instruction::ZExt;
110 case bitc::CAST_SEXT : return Instruction::SExt;
111 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
112 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
113 case bitc::CAST_UITOFP : return Instruction::UIToFP;
114 case bitc::CAST_SITOFP : return Instruction::SIToFP;
115 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
116 case bitc::CAST_FPEXT : return Instruction::FPExt;
117 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
118 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
119 case bitc::CAST_BITCAST : return Instruction::BitCast;
120 }
121}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000122static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000123 switch (Val) {
124 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000125 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000126 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000127 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000128 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000129 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000130 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000131 case bitc::BINOP_UDIV: return Instruction::UDiv;
132 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000133 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000134 case bitc::BINOP_UREM: return Instruction::URem;
135 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000136 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000137 case bitc::BINOP_SHL: return Instruction::Shl;
138 case bitc::BINOP_LSHR: return Instruction::LShr;
139 case bitc::BINOP_ASHR: return Instruction::AShr;
140 case bitc::BINOP_AND: return Instruction::And;
141 case bitc::BINOP_OR: return Instruction::Or;
142 case bitc::BINOP_XOR: return Instruction::Xor;
143 }
144}
145
Eli Friedmanff030482011-07-28 21:48:00 +0000146static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
147 switch (Val) {
148 default: return AtomicRMWInst::BAD_BINOP;
149 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
150 case bitc::RMW_ADD: return AtomicRMWInst::Add;
151 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
152 case bitc::RMW_AND: return AtomicRMWInst::And;
153 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
154 case bitc::RMW_OR: return AtomicRMWInst::Or;
155 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
156 case bitc::RMW_MAX: return AtomicRMWInst::Max;
157 case bitc::RMW_MIN: return AtomicRMWInst::Min;
158 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
159 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
160 }
161}
162
Eli Friedman47f35132011-07-25 23:16:38 +0000163static AtomicOrdering GetDecodedOrdering(unsigned Val) {
164 switch (Val) {
165 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
166 case bitc::ORDERING_UNORDERED: return Unordered;
167 case bitc::ORDERING_MONOTONIC: return Monotonic;
168 case bitc::ORDERING_ACQUIRE: return Acquire;
169 case bitc::ORDERING_RELEASE: return Release;
170 case bitc::ORDERING_ACQREL: return AcquireRelease;
171 default: // Map unknown orderings to sequentially-consistent.
172 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
173 }
174}
175
176static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
177 switch (Val) {
178 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
179 default: // Map unknown scopes to cross-thread.
180 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
181 }
182}
183
Gabor Greifefe65362008-05-10 08:32:32 +0000184namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000185namespace {
186 /// @brief A class for maintaining the slot number definition
187 /// as a placeholder for the actual definition for forward constants defs.
188 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000189 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000190 public:
191 // allocate space for exactly one operand
192 void *operator new(size_t s) {
193 return User::operator new(s, 1);
194 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000195 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000196 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000197 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000198 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000199
Chris Lattnerea693df2008-08-21 02:34:16 +0000200 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000201 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000202 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000203 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000204 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
205 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000206
207
Gabor Greifefe65362008-05-10 08:32:32 +0000208 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000209 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000210 };
211}
212
Chris Lattner46e77402009-03-31 22:55:09 +0000213// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000214template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000215struct OperandTraits<ConstantPlaceHolder> :
216 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000217};
Gabor Greifefe65362008-05-10 08:32:32 +0000218}
219
Chris Lattner46e77402009-03-31 22:55:09 +0000220
221void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
222 if (Idx == size()) {
223 push_back(V);
224 return;
225 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000226
Chris Lattner46e77402009-03-31 22:55:09 +0000227 if (Idx >= size())
228 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000229
Chris Lattner46e77402009-03-31 22:55:09 +0000230 WeakVH &OldV = ValuePtrs[Idx];
231 if (OldV == 0) {
232 OldV = V;
233 return;
234 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000235
Chris Lattner46e77402009-03-31 22:55:09 +0000236 // Handle constants and non-constants (e.g. instrs) differently for
237 // efficiency.
238 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
239 ResolveConstants.push_back(std::make_pair(PHC, Idx));
240 OldV = V;
241 } else {
242 // If there was a forward reference to this value, replace it.
243 Value *PrevVal = OldV;
244 OldV->replaceAllUsesWith(V);
245 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000246 }
247}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000248
Gabor Greifefe65362008-05-10 08:32:32 +0000249
Chris Lattner522b7b12007-04-24 05:48:56 +0000250Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000251 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000252 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000253 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000254
Chris Lattner46e77402009-03-31 22:55:09 +0000255 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000256 assert(Ty == V->getType() && "Type mismatch in constant table!");
257 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000258 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000259
260 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000261 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000262 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000263 return C;
264}
265
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000266Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000267 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000268 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000269
Chris Lattner46e77402009-03-31 22:55:09 +0000270 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000271 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
272 return V;
273 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000274
Chris Lattner01ff65f2007-05-02 05:16:49 +0000275 // No type specified, must be invalid reference.
276 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000277
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000278 // Create and return a placeholder, which will later be RAUW'd.
279 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000280 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000281 return V;
282}
283
Chris Lattnerea693df2008-08-21 02:34:16 +0000284/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
285/// resolves any forward references. The idea behind this is that we sometimes
286/// get constants (such as large arrays) which reference *many* forward ref
287/// constants. Replacing each of these causes a lot of thrashing when
288/// building/reuniquing the constant. Instead of doing this, we look at all the
289/// uses and rewrite all the place holders at once for any constant that uses
290/// a placeholder.
291void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000292 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000293 // binary search.
294 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000295
Chris Lattnerea693df2008-08-21 02:34:16 +0000296 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattnerea693df2008-08-21 02:34:16 +0000298 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000299 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000300 Constant *Placeholder = ResolveConstants.back().first;
301 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000302
Chris Lattnerea693df2008-08-21 02:34:16 +0000303 // Loop over all users of the placeholder, updating them to reference the
304 // new value. If they reference more than one placeholder, update them all
305 // at once.
306 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000307 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000308 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000309
Chris Lattnerea693df2008-08-21 02:34:16 +0000310 // If the using object isn't uniqued, just update the operands. This
311 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000312 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000313 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000314 continue;
315 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000316
Chris Lattnerea693df2008-08-21 02:34:16 +0000317 // Otherwise, we have a constant that uses the placeholder. Replace that
318 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000319 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000320 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
321 I != E; ++I) {
322 Value *NewOp;
323 if (!isa<ConstantPlaceHolder>(*I)) {
324 // Not a placeholder reference.
325 NewOp = *I;
326 } else if (*I == Placeholder) {
327 // Common case is that it just references this one placeholder.
328 NewOp = RealVal;
329 } else {
330 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331 ResolveConstantsTy::iterator It =
332 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000333 std::pair<Constant*, unsigned>(cast<Constant>(*I),
334 0));
335 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000336 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000337 }
338
339 NewOps.push_back(cast<Constant>(NewOp));
340 }
341
342 // Make the new constant.
343 Constant *NewC;
344 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000345 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000346 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000347 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000348 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000349 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000350 } else {
351 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000352 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000353 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000354
Chris Lattnerea693df2008-08-21 02:34:16 +0000355 UserC->replaceAllUsesWith(NewC);
356 UserC->destroyConstant();
357 NewOps.clear();
358 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000359
Nick Lewyckycb337992009-05-10 20:57:05 +0000360 // Update all ValueHandles, they should be the only users at this point.
361 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000362 delete Placeholder;
363 }
364}
365
Devang Pateld5ac4042009-08-04 06:00:18 +0000366void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
367 if (Idx == size()) {
368 push_back(V);
369 return;
370 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000371
Devang Pateld5ac4042009-08-04 06:00:18 +0000372 if (Idx >= size())
373 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000374
Devang Pateld5ac4042009-08-04 06:00:18 +0000375 WeakVH &OldV = MDValuePtrs[Idx];
376 if (OldV == 0) {
377 OldV = V;
378 return;
379 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000380
Devang Pateld5ac4042009-08-04 06:00:18 +0000381 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000382 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000383 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000384 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000385 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
386 // value for Idx.
387 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000388}
389
390Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
391 if (Idx >= size())
392 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000393
Devang Pateld5ac4042009-08-04 06:00:18 +0000394 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000395 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000396 return V;
397 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000398
Devang Pateld5ac4042009-08-04 06:00:18 +0000399 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000400 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000401 MDValuePtrs[Idx] = V;
402 return V;
403}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000404
Chris Lattner1afcace2011-07-09 17:41:24 +0000405Type *BitcodeReader::getTypeByID(unsigned ID) {
406 // The type table size is always specified correctly.
407 if (ID >= TypeList.size())
408 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000409
Chris Lattner1afcace2011-07-09 17:41:24 +0000410 if (Type *Ty = TypeList[ID])
411 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413 // If we have a forward reference, the only possible case is when it is to a
414 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000415 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000416}
417
Chris Lattner1afcace2011-07-09 17:41:24 +0000418
Chris Lattner48c85b82007-05-04 03:30:17 +0000419//===----------------------------------------------------------------------===//
420// Functions for parsing blocks from the bitcode file
421//===----------------------------------------------------------------------===//
422
Devang Patel05988662008-09-25 21:00:45 +0000423bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000424 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000425 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000426
Devang Patel19c87462008-09-26 22:53:05 +0000427 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000428 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000429
Chris Lattner48c85b82007-05-04 03:30:17 +0000430 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000431
Devang Patel05988662008-09-25 21:00:45 +0000432 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000433
Chris Lattner48c85b82007-05-04 03:30:17 +0000434 // Read all the records.
435 while (1) {
436 unsigned Code = Stream.ReadCode();
437 if (Code == bitc::END_BLOCK) {
438 if (Stream.ReadBlockEnd())
439 return Error("Error at end of PARAMATTR block");
440 return false;
441 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000442
Chris Lattner48c85b82007-05-04 03:30:17 +0000443 if (Code == bitc::ENTER_SUBBLOCK) {
444 // No known subblocks, always skip them.
445 Stream.ReadSubBlockID();
446 if (Stream.SkipBlock())
447 return Error("Malformed block record");
448 continue;
449 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000450
Chris Lattner48c85b82007-05-04 03:30:17 +0000451 if (Code == bitc::DEFINE_ABBREV) {
452 Stream.ReadAbbrevRecord();
453 continue;
454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000455
Chris Lattner48c85b82007-05-04 03:30:17 +0000456 // Read a record.
457 Record.clear();
458 switch (Stream.ReadRecord(Code, Record)) {
459 default: // Default behavior: ignore.
460 break;
461 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
462 if (Record.size() & 1)
463 return Error("Invalid ENTRY record");
464
Chris Lattner9a6cb152008-10-05 18:22:09 +0000465 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000466 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000467 // to index ~0. Index 0 is used for return value attributes but used to be
468 // used for function attributes.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000469 Attributes RetAttribute;
470 Attributes FnAttribute;
Chris Lattner48c85b82007-05-04 03:30:17 +0000471 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000472 // FIXME: remove in LLVM 3.0
473 // The alignment is stored as a 16-bit raw value from bits 31--16.
474 // We shift the bits above 31 down by 11 bits.
475
476 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
477 if (Alignment && !isPowerOf2_32(Alignment))
478 return Error("Alignment is not a power of two.");
479
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000480 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000481 if (Alignment)
482 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000483 ReconstitutedAttr |=
484 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000485
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000486 Record[i+1] = ReconstitutedAttr.Raw();
Devang Patel19c87462008-09-26 22:53:05 +0000487 if (Record[i] == 0)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000488 RetAttribute = ReconstitutedAttr;
Devang Patel19c87462008-09-26 22:53:05 +0000489 else if (Record[i] == ~0U)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000490 FnAttribute = ReconstitutedAttr;
Devang Patel19c87462008-09-26 22:53:05 +0000491 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000492
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000493 Attributes OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
Chris Lattner9a6cb152008-10-05 18:22:09 +0000494 Attribute::ReadOnly|Attribute::ReadNone);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000495
Chris Lattner9a6cb152008-10-05 18:22:09 +0000496 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000497 (RetAttribute & OldRetAttrs)) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000498 if (FnAttribute == Attribute::None) { // add a slot so they get added.
499 Record.push_back(~0U);
500 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000501 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000502
Chris Lattner9a6cb152008-10-05 18:22:09 +0000503 FnAttribute |= RetAttribute & OldRetAttrs;
504 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000505 }
Chris Lattner461edd92008-03-12 02:25:52 +0000506
Devang Patel19c87462008-09-26 22:53:05 +0000507 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000508 if (Record[i] == 0) {
509 if (RetAttribute != Attribute::None)
510 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
511 } else if (Record[i] == ~0U) {
512 if (FnAttribute != Attribute::None)
513 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000514 } else if (Attributes(Record[i+1]) != Attribute::None)
515 Attrs.push_back(AttributeWithIndex::get(Record[i],
516 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000517 }
Devang Patel19c87462008-09-26 22:53:05 +0000518
519 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000520 Attrs.clear();
521 break;
522 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000523 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000524 }
525}
526
Chris Lattner86697142007-05-01 05:01:34 +0000527bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000528 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000529 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000530
Chris Lattner1afcace2011-07-09 17:41:24 +0000531 return ParseTypeTableBody();
532}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000533
Chris Lattner1afcace2011-07-09 17:41:24 +0000534bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000535 if (!TypeList.empty())
536 return Error("Multiple TYPE_BLOCKs found!");
537
538 SmallVector<uint64_t, 64> Record;
539 unsigned NumRecords = 0;
540
Chris Lattner1afcace2011-07-09 17:41:24 +0000541 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000542
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000543 // Read all the records for this type table.
544 while (1) {
545 unsigned Code = Stream.ReadCode();
546 if (Code == bitc::END_BLOCK) {
547 if (NumRecords != TypeList.size())
548 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000549 if (Stream.ReadBlockEnd())
550 return Error("Error at end of type table block");
551 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000552 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000553
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000554 if (Code == bitc::ENTER_SUBBLOCK) {
555 // No known subblocks, always skip them.
556 Stream.ReadSubBlockID();
557 if (Stream.SkipBlock())
558 return Error("Malformed block record");
559 continue;
560 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000561
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000562 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000563 Stream.ReadAbbrevRecord();
564 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000565 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000566
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000567 // Read a record.
568 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000569 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000570 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000571 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000572 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
573 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
574 // type list. This allows us to reserve space.
575 if (Record.size() < 1)
576 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000577 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000578 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000579 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000580 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000581 break;
Dan Gohmance163392011-12-17 00:04:22 +0000582 case bitc::TYPE_CODE_HALF: // HALF
583 ResultTy = Type::getHalfTy(Context);
584 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000585 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000586 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000587 break;
588 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000589 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000590 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000591 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000592 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000593 break;
594 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000595 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000596 break;
597 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000598 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000599 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000600 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000601 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000602 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000603 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000604 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000605 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000606 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
607 ResultTy = Type::getX86_MMXTy(Context);
608 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000609 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
610 if (Record.size() < 1)
611 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000612
Owen Anderson1d0be152009-08-13 21:58:54 +0000613 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000614 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000615 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000616 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000617 if (Record.size() < 1)
618 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000619 unsigned AddressSpace = 0;
620 if (Record.size() == 2)
621 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000622 ResultTy = getTypeByID(Record[0]);
623 if (ResultTy == 0) return Error("invalid element type in pointer type");
624 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000625 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000626 }
Chad Rosiercde54642011-11-03 00:14:01 +0000627 case bitc::TYPE_CODE_FUNCTION_OLD: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000628 // FIXME: attrid is dead, remove it in LLVM 3.0
629 // FUNCTION: [vararg, attrid, retty, paramty x N]
630 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000631 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000632 SmallVector<Type*, 8> ArgTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000633 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
634 if (Type *T = getTypeByID(Record[i]))
635 ArgTys.push_back(T);
636 else
637 break;
638 }
639
640 ResultTy = getTypeByID(Record[2]);
641 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
642 return Error("invalid type in function type");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000643
Chris Lattner1afcace2011-07-09 17:41:24 +0000644 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000645 break;
646 }
Chad Rosiercde54642011-11-03 00:14:01 +0000647 case bitc::TYPE_CODE_FUNCTION: {
648 // FUNCTION: [vararg, retty, paramty x N]
649 if (Record.size() < 2)
650 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000651 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000652 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
653 if (Type *T = getTypeByID(Record[i]))
654 ArgTys.push_back(T);
655 else
656 break;
657 }
658
659 ResultTy = getTypeByID(Record[1]);
660 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
661 return Error("invalid type in function type");
662
663 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
664 break;
665 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000666 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000667 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000668 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000669 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000670 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
671 if (Type *T = getTypeByID(Record[i]))
672 EltTys.push_back(T);
673 else
674 break;
675 }
676 if (EltTys.size() != Record.size()-1)
677 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000678 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000679 break;
680 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000681 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
682 if (ConvertToString(Record, 0, TypeName))
683 return Error("Invalid STRUCT_NAME record");
684 continue;
685
686 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
687 if (Record.size() < 1)
688 return Error("Invalid STRUCT type record");
689
690 if (NumRecords >= TypeList.size())
691 return Error("invalid TYPE table");
692
693 // 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.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000699 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000700 TypeName.clear();
701
702 SmallVector<Type*, 8> EltTys;
703 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
704 if (Type *T = getTypeByID(Record[i]))
705 EltTys.push_back(T);
706 else
707 break;
708 }
709 if (EltTys.size() != Record.size()-1)
710 return Error("invalid STRUCT type record");
711 Res->setBody(EltTys, Record[0]);
712 ResultTy = Res;
713 break;
714 }
715 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
716 if (Record.size() != 1)
717 return Error("Invalid OPAQUE type record");
718
719 if (NumRecords >= TypeList.size())
720 return Error("invalid TYPE table");
721
722 // Check to see if this was forward referenced, if so fill in the temp.
723 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
724 if (Res) {
725 Res->setName(TypeName);
726 TypeList[NumRecords] = 0;
727 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000728 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000729 TypeName.clear();
730 ResultTy = Res;
731 break;
732 }
733 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
734 if (Record.size() < 2)
735 return Error("Invalid ARRAY type record");
736 if ((ResultTy = getTypeByID(Record[1])))
737 ResultTy = ArrayType::get(ResultTy, Record[0]);
738 else
739 return Error("Invalid ARRAY type element");
740 break;
741 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
742 if (Record.size() < 2)
743 return Error("Invalid VECTOR type record");
744 if ((ResultTy = getTypeByID(Record[1])))
745 ResultTy = VectorType::get(ResultTy, Record[0]);
746 else
747 return Error("Invalid ARRAY type element");
748 break;
749 }
750
751 if (NumRecords >= TypeList.size())
752 return Error("invalid TYPE table");
753 assert(ResultTy && "Didn't read a type?");
754 assert(TypeList[NumRecords] == 0 && "Already read type?");
755 TypeList[NumRecords++] = ResultTy;
756 }
757}
758
Chris Lattner86697142007-05-01 05:01:34 +0000759bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000760 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000761 return Error("Malformed block record");
762
763 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000764
Chris Lattner0b2482a2007-04-23 21:26:05 +0000765 // Read all the records for this value table.
766 SmallString<128> ValueName;
767 while (1) {
768 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000769 if (Code == bitc::END_BLOCK) {
770 if (Stream.ReadBlockEnd())
771 return Error("Error at end of value symbol table block");
772 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000773 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000774 if (Code == bitc::ENTER_SUBBLOCK) {
775 // No known subblocks, always skip them.
776 Stream.ReadSubBlockID();
777 if (Stream.SkipBlock())
778 return Error("Malformed block record");
779 continue;
780 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Chris Lattner0b2482a2007-04-23 21:26:05 +0000782 if (Code == bitc::DEFINE_ABBREV) {
783 Stream.ReadAbbrevRecord();
784 continue;
785 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000786
Chris Lattner0b2482a2007-04-23 21:26:05 +0000787 // Read a record.
788 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000789 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000790 default: // Default behavior: unknown type.
791 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000792 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000793 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000794 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000795 unsigned ValueID = Record[0];
796 if (ValueID >= ValueList.size())
797 return Error("Invalid Value ID in VST_ENTRY record");
798 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000799
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000800 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000801 ValueName.clear();
802 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000803 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000804 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000805 if (ConvertToString(Record, 1, ValueName))
806 return Error("Invalid VST_BBENTRY record");
807 BasicBlock *BB = getBasicBlock(Record[0]);
808 if (BB == 0)
809 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000810
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000811 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000812 ValueName.clear();
813 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000814 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000815 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000816 }
817}
818
Devang Patele54abc92009-07-22 17:43:22 +0000819bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000820 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000821
822 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
823 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000824
Devang Patele54abc92009-07-22 17:43:22 +0000825 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000826
Devang Patele54abc92009-07-22 17:43:22 +0000827 // Read all the records.
828 while (1) {
829 unsigned Code = Stream.ReadCode();
830 if (Code == bitc::END_BLOCK) {
831 if (Stream.ReadBlockEnd())
832 return Error("Error at end of PARAMATTR block");
833 return false;
834 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000835
Devang Patele54abc92009-07-22 17:43:22 +0000836 if (Code == bitc::ENTER_SUBBLOCK) {
837 // No known subblocks, always skip them.
838 Stream.ReadSubBlockID();
839 if (Stream.SkipBlock())
840 return Error("Malformed block record");
841 continue;
842 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000843
Devang Patele54abc92009-07-22 17:43:22 +0000844 if (Code == bitc::DEFINE_ABBREV) {
845 Stream.ReadAbbrevRecord();
846 continue;
847 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000848
Victor Hernandez24e64df2010-01-10 07:14:18 +0000849 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000850 // Read a record.
851 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000852 Code = Stream.ReadRecord(Code, Record);
853 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000854 default: // Default behavior: ignore.
855 break;
Devang Patelaa993142009-07-29 22:34:41 +0000856 case bitc::METADATA_NAME: {
857 // Read named of the named metadata.
858 unsigned NameLength = Record.size();
859 SmallString<8> Name;
860 Name.resize(NameLength);
861 for (unsigned i = 0; i != NameLength; ++i)
862 Name[i] = Record[i];
863 Record.clear();
864 Code = Stream.ReadCode();
865
Chris Lattner9d61dd92011-06-17 17:50:30 +0000866 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000867 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000868 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000869
870 // Read named metadata elements.
871 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000872 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000873 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000874 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
875 if (MD == 0)
876 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000877 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000878 }
Devang Patelaa993142009-07-29 22:34:41 +0000879 break;
880 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000881 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000882 IsFunctionLocal = true;
883 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000884 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000885 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000886 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000887
Devang Patel104cf9e2009-07-23 01:07:34 +0000888 unsigned Size = Record.size();
889 SmallVector<Value*, 8> Elts;
890 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000891 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000892 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000893 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000894 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000895 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000896 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
897 else
898 Elts.push_back(NULL);
899 }
Jay Foadec9186b2011-04-21 19:59:31 +0000900 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000901 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000902 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000903 break;
904 }
Devang Patele54abc92009-07-22 17:43:22 +0000905 case bitc::METADATA_STRING: {
906 unsigned MDStringLength = Record.size();
907 SmallString<8> String;
908 String.resize(MDStringLength);
909 for (unsigned i = 0; i != MDStringLength; ++i)
910 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000911 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +0000912 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +0000913 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000914 break;
915 }
Devang Patele8e02132009-09-18 19:26:43 +0000916 case bitc::METADATA_KIND: {
917 unsigned RecordLength = Record.size();
918 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000919 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +0000920 SmallString<8> Name;
921 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +0000922 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +0000923 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000924 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +0000925
Chris Lattner08113472009-12-29 09:01:33 +0000926 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000927 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
928 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000929 break;
930 }
Devang Patele54abc92009-07-22 17:43:22 +0000931 }
932 }
933}
934
Chris Lattner0eef0802007-04-24 04:04:35 +0000935/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
936/// the LSB for dense VBR encoding.
937static uint64_t DecodeSignRotatedValue(uint64_t V) {
938 if ((V & 1) == 0)
939 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000940 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000941 return -(V >> 1);
942 // There is no such thing as -0 with integers. "-0" really means MININT.
943 return 1ULL << 63;
944}
945
Chris Lattner07d98b42007-04-26 02:46:40 +0000946/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
947/// values and aliases that we can.
948bool BitcodeReader::ResolveGlobalAndAliasInits() {
949 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
950 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000951
Chris Lattner07d98b42007-04-26 02:46:40 +0000952 GlobalInitWorklist.swap(GlobalInits);
953 AliasInitWorklist.swap(AliasInits);
954
955 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000956 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000957 if (ValID >= ValueList.size()) {
958 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000959 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000960 } else {
961 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
962 GlobalInitWorklist.back().first->setInitializer(C);
963 else
964 return Error("Global variable initializer is not a constant!");
965 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000966 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000967 }
968
969 while (!AliasInitWorklist.empty()) {
970 unsigned ValID = AliasInitWorklist.back().second;
971 if (ValID >= ValueList.size()) {
972 AliasInits.push_back(AliasInitWorklist.back());
973 } else {
974 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000975 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000976 else
977 return Error("Alias initializer is not a constant!");
978 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000979 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000980 }
981 return false;
982}
983
Stepan Dyatkovskiy85a44062012-05-08 06:36:08 +0000984template <typename intty>
985APInt ReadWideAPInt(const intty *Vals, unsigned ActiveWords,
986 unsigned TypeBits) {
987 SmallVector<uint64_t, 8> Words;
988 Words.resize(ActiveWords);
989 for (unsigned i = 0; i != ActiveWords; ++i)
990 Words[i] = DecodeSignRotatedValue(Vals[i]);
991
992 return APInt(TypeBits, Words);
993}
994
Chris Lattner86697142007-05-01 05:01:34 +0000995bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000996 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000997 return Error("Malformed block record");
998
999 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001000
Chris Lattnere16504e2007-04-24 03:30:34 +00001001 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001002 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +00001003 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +00001004 while (1) {
1005 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +00001006 if (Code == bitc::END_BLOCK)
1007 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001008
Chris Lattnere16504e2007-04-24 03:30:34 +00001009 if (Code == bitc::ENTER_SUBBLOCK) {
1010 // No known subblocks, always skip them.
1011 Stream.ReadSubBlockID();
1012 if (Stream.SkipBlock())
1013 return Error("Malformed block record");
1014 continue;
1015 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001016
Chris Lattnere16504e2007-04-24 03:30:34 +00001017 if (Code == bitc::DEFINE_ABBREV) {
1018 Stream.ReadAbbrevRecord();
1019 continue;
1020 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001021
Chris Lattnere16504e2007-04-24 03:30:34 +00001022 // Read a record.
1023 Record.clear();
1024 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001025 unsigned BitCode = Stream.ReadRecord(Code, Record);
1026 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001027 default: // Default behavior: unknown constant
1028 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001029 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001030 break;
1031 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1032 if (Record.empty())
1033 return Error("Malformed CST_SETTYPE record");
1034 if (Record[0] >= TypeList.size())
1035 return Error("Invalid Type ID in CST_SETTYPE record");
1036 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001037 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001038 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001039 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001040 break;
1041 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001042 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001043 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +00001044 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001045 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001046 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001047 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001048 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001049
Chris Lattner15e6d172007-05-04 19:11:41 +00001050 unsigned NumWords = Record.size();
Stepan Dyatkovskiy85a44062012-05-08 06:36:08 +00001051
1052 APInt VInt = ReadWideAPInt(&Record[0], NumWords,
1053 cast<IntegerType>(CurTy)->getBitWidth());
1054 V = ConstantInt::get(Context, VInt);
1055
Chris Lattner0eef0802007-04-24 04:04:35 +00001056 break;
1057 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001058 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001059 if (Record.empty())
1060 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001061 if (CurTy->isHalfTy())
1062 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1063 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001064 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001065 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001066 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001067 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001068 // Bits are not stored the same way as a normal i80 APInt, compensate.
1069 uint64_t Rearrange[2];
1070 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1071 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001072 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001073 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001074 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001075 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001076 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001077 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001078 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001079 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001080 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001081
Chris Lattner15e6d172007-05-04 19:11:41 +00001082 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1083 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001084 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001085
Chris Lattner15e6d172007-05-04 19:11:41 +00001086 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001087 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001088
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001089 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001090 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001091 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001092 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001093 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001094 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1095 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001096 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001097 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001098 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001099 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1100 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001101 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001102 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001103 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001104 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001105 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001106 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001107 break;
1108 }
Chris Lattner2237f842012-02-05 02:41:35 +00001109 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001110 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1111 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001112 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001113
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001114 unsigned Size = Record.size();
Chris Lattner2237f842012-02-05 02:41:35 +00001115 SmallString<16> Elts;
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001116 for (unsigned i = 0; i != Size; ++i)
Chris Lattner2237f842012-02-05 02:41:35 +00001117 Elts.push_back(Record[i]);
1118 V = ConstantDataArray::getString(Context, Elts,
1119 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001120 break;
1121 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001122 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1123 if (Record.empty())
1124 return Error("Invalid CST_DATA record");
1125
1126 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1127 unsigned Size = Record.size();
1128
1129 if (EltTy->isIntegerTy(8)) {
1130 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1131 if (isa<VectorType>(CurTy))
1132 V = ConstantDataVector::get(Context, Elts);
1133 else
1134 V = ConstantDataArray::get(Context, Elts);
1135 } else if (EltTy->isIntegerTy(16)) {
1136 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1137 if (isa<VectorType>(CurTy))
1138 V = ConstantDataVector::get(Context, Elts);
1139 else
1140 V = ConstantDataArray::get(Context, Elts);
1141 } else if (EltTy->isIntegerTy(32)) {
1142 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1143 if (isa<VectorType>(CurTy))
1144 V = ConstantDataVector::get(Context, Elts);
1145 else
1146 V = ConstantDataArray::get(Context, Elts);
1147 } else if (EltTy->isIntegerTy(64)) {
1148 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1149 if (isa<VectorType>(CurTy))
1150 V = ConstantDataVector::get(Context, Elts);
1151 else
1152 V = ConstantDataArray::get(Context, Elts);
1153 } else if (EltTy->isFloatTy()) {
1154 SmallVector<float, 16> Elts;
1155 for (unsigned i = 0; i != Size; ++i) {
1156 union { uint32_t I; float F; };
1157 I = Record[i];
1158 Elts.push_back(F);
1159 }
1160 if (isa<VectorType>(CurTy))
1161 V = ConstantDataVector::get(Context, Elts);
1162 else
1163 V = ConstantDataArray::get(Context, Elts);
1164 } else if (EltTy->isDoubleTy()) {
1165 SmallVector<double, 16> Elts;
1166 for (unsigned i = 0; i != Size; ++i) {
1167 union { uint64_t I; double F; };
1168 I = Record[i];
1169 Elts.push_back(F);
1170 }
1171 if (isa<VectorType>(CurTy))
1172 V = ConstantDataVector::get(Context, Elts);
1173 else
1174 V = ConstantDataArray::get(Context, Elts);
1175 } else {
1176 return Error("Unknown element type in CE_DATA");
1177 }
1178 break;
1179 }
1180
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001181 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1182 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1183 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001184 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001185 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001186 } else {
1187 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1188 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001189 unsigned Flags = 0;
1190 if (Record.size() >= 4) {
1191 if (Opc == Instruction::Add ||
1192 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001193 Opc == Instruction::Mul ||
1194 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001195 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1196 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1197 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1198 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001199 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001200 Opc == Instruction::UDiv ||
1201 Opc == Instruction::LShr ||
1202 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001203 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001204 Flags |= SDivOperator::IsExact;
1205 }
1206 }
1207 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001208 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001209 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001210 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001211 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1212 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1213 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001214 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001215 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001216 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001217 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001218 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001219 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001220 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001221 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001222 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001223 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001224 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001225 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001226 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001227 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001228 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001229 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001230 if (!ElTy) return Error("Invalid CE_GEP record");
1231 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1232 }
Jay Foaddab3d292011-07-21 14:31:17 +00001233 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001234 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1235 BitCode ==
1236 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001237 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001238 }
1239 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1240 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001241 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001242 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001243 ValueList.getConstantFwdRef(Record[1],CurTy),
1244 ValueList.getConstantFwdRef(Record[2],CurTy));
1245 break;
1246 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1247 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001248 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001249 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1250 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1251 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001252 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001253 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001254 break;
1255 }
1256 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001257 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001258 if (Record.size() < 3 || OpTy == 0)
1259 return Error("Invalid CE_INSERTELT record");
1260 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1261 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1262 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001263 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001264 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001265 break;
1266 }
1267 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001268 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001269 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001270 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001271 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1272 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001273 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001274 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001275 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001276 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001277 break;
1278 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001279 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001280 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1281 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001282 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001283 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1284 return Error("Invalid CE_SHUFVEC_EX record");
1285 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1286 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001287 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001288 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001289 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001290 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001291 break;
1292 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001293 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1294 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001295 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001296 if (OpTy == 0) return Error("Invalid CE_CMP record");
1297 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1298 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1299
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001300 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001301 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001302 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001303 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001304 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001305 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001306 case bitc::CST_CODE_INLINEASM: {
1307 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1308 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001309 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001310 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001311 unsigned AsmStrSize = Record[1];
1312 if (2+AsmStrSize >= Record.size())
1313 return Error("Invalid INLINEASM record");
1314 unsigned ConstStrSize = Record[2+AsmStrSize];
1315 if (3+AsmStrSize+ConstStrSize > Record.size())
1316 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001317
Chris Lattner2bce93a2007-05-06 01:58:20 +00001318 for (unsigned i = 0; i != AsmStrSize; ++i)
1319 AsmStr += (char)Record[2+i];
1320 for (unsigned i = 0; i != ConstStrSize; ++i)
1321 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001322 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001323 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001324 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001325 break;
1326 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001327 case bitc::CST_CODE_BLOCKADDRESS:{
1328 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001329 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001330 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1331 Function *Fn =
1332 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1333 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1334
1335 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1336 Type::getInt8Ty(Context),
1337 false, GlobalValue::InternalLinkage,
1338 0, "");
1339 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1340 V = FwdRef;
1341 break;
1342 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001343 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001344
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001345 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001346 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001347 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001348
Chris Lattnerea693df2008-08-21 02:34:16 +00001349 if (NextCstNo != ValueList.size())
1350 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001351
Chris Lattnerea693df2008-08-21 02:34:16 +00001352 if (Stream.ReadBlockEnd())
1353 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001354
Chris Lattnerea693df2008-08-21 02:34:16 +00001355 // Once all the constants have been read, go through and resolve forward
1356 // references.
1357 ValueList.ResolveConstantForwardRefs();
1358 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001359}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001360
Chad Rosiercbbb0962011-12-07 21:44:12 +00001361bool BitcodeReader::ParseUseLists() {
1362 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1363 return Error("Malformed block record");
1364
1365 SmallVector<uint64_t, 64> Record;
1366
1367 // Read all the records.
1368 while (1) {
1369 unsigned Code = Stream.ReadCode();
1370 if (Code == bitc::END_BLOCK) {
1371 if (Stream.ReadBlockEnd())
1372 return Error("Error at end of use-list table block");
1373 return false;
1374 }
1375
1376 if (Code == bitc::ENTER_SUBBLOCK) {
1377 // No known subblocks, always skip them.
1378 Stream.ReadSubBlockID();
1379 if (Stream.SkipBlock())
1380 return Error("Malformed block record");
1381 continue;
1382 }
1383
1384 if (Code == bitc::DEFINE_ABBREV) {
1385 Stream.ReadAbbrevRecord();
1386 continue;
1387 }
1388
1389 // Read a use list record.
1390 Record.clear();
1391 switch (Stream.ReadRecord(Code, Record)) {
1392 default: // Default behavior: unknown type.
1393 break;
1394 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1395 unsigned RecordLength = Record.size();
1396 if (RecordLength < 1)
1397 return Error ("Invalid UseList reader!");
1398 UseListRecords.push_back(Record);
1399 break;
1400 }
1401 }
1402 }
1403}
1404
Chris Lattner980e5aa2007-05-01 05:52:21 +00001405/// RememberAndSkipFunctionBody - When we see the block for a function body,
1406/// remember where it is and then skip it. This lets us lazily deserialize the
1407/// functions.
1408bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001409 // Get the function we are talking about.
1410 if (FunctionsWithBodies.empty())
1411 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001412
Chris Lattner48f84872007-05-01 04:59:48 +00001413 Function *Fn = FunctionsWithBodies.back();
1414 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001415
Chris Lattner48f84872007-05-01 04:59:48 +00001416 // Save the current stream state.
1417 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001418 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001419
Chris Lattner48f84872007-05-01 04:59:48 +00001420 // Skip over the function block for now.
1421 if (Stream.SkipBlock())
1422 return Error("Malformed block record");
1423 return false;
1424}
1425
Derek Schuff2ea93872012-02-06 22:30:29 +00001426bool BitcodeReader::GlobalCleanup() {
1427 // Patch the initializers for globals and aliases up.
1428 ResolveGlobalAndAliasInits();
1429 if (!GlobalInits.empty() || !AliasInits.empty())
1430 return Error("Malformed global initializer set");
1431
1432 // Look for intrinsic functions which need to be upgraded at some point
1433 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1434 FI != FE; ++FI) {
1435 Function *NewFn;
1436 if (UpgradeIntrinsicFunction(FI, NewFn))
1437 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1438 }
1439
1440 // Look for global variables which need to be renamed.
1441 for (Module::global_iterator
1442 GI = TheModule->global_begin(), GE = TheModule->global_end();
1443 GI != GE; ++GI)
1444 UpgradeGlobalVariable(GI);
1445 // Force deallocation of memory for these vectors to favor the client that
1446 // want lazy deserialization.
1447 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1448 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1449 return false;
1450}
1451
1452bool BitcodeReader::ParseModule(bool Resume) {
1453 if (Resume)
1454 Stream.JumpToBit(NextUnreadBit);
1455 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001456 return Error("Malformed block record");
1457
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001458 SmallVector<uint64_t, 64> Record;
1459 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001460 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001461
1462 // Read all the records for this module.
1463 while (!Stream.AtEndOfStream()) {
1464 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001465 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001466 if (Stream.ReadBlockEnd())
1467 return Error("Error at end of module block");
1468
Derek Schuff2ea93872012-02-06 22:30:29 +00001469 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001470 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001471
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001472 if (Code == bitc::ENTER_SUBBLOCK) {
1473 switch (Stream.ReadSubBlockID()) {
1474 default: // Skip unknown content.
1475 if (Stream.SkipBlock())
1476 return Error("Malformed block record");
1477 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001478 case bitc::BLOCKINFO_BLOCK_ID:
1479 if (Stream.ReadBlockInfoBlock())
1480 return Error("Malformed BlockInfoBlock");
1481 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001482 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001483 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001484 return true;
1485 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001486 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001487 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001488 return true;
1489 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001490 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001491 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001492 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001493 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001494 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001495 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001496 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001497 return true;
1498 break;
Devang Patele54abc92009-07-22 17:43:22 +00001499 case bitc::METADATA_BLOCK_ID:
1500 if (ParseMetadata())
1501 return true;
1502 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001503 case bitc::FUNCTION_BLOCK_ID:
1504 // If this is the first function body we've seen, reverse the
1505 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001506 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001507 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001508 if (GlobalCleanup())
1509 return true;
1510 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001511 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001512
Chris Lattner980e5aa2007-05-01 05:52:21 +00001513 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001514 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001515 // For streaming bitcode, suspend parsing when we reach the function
1516 // bodies. Subsequent materialization calls will resume it when
1517 // necessary. For streaming, the function bodies must be at the end of
1518 // the bitcode. If the bitcode file is old, the symbol table will be
1519 // at the end instead and will not have been seen yet. In this case,
1520 // just finish the parse now.
1521 if (LazyStreamer && SeenValueSymbolTable) {
1522 NextUnreadBit = Stream.GetCurrentBitNo();
1523 return false;
1524 }
Chris Lattner48f84872007-05-01 04:59:48 +00001525 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001526 case bitc::USELIST_BLOCK_ID:
1527 if (ParseUseLists())
1528 return true;
1529 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001530 }
1531 continue;
1532 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001533
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001534 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001535 Stream.ReadAbbrevRecord();
1536 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001537 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001538
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001539 // Read a record.
1540 switch (Stream.ReadRecord(Code, Record)) {
1541 default: break; // Default behavior, ignore unknown content.
1542 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1543 if (Record.size() < 1)
1544 return Error("Malformed MODULE_CODE_VERSION");
1545 // Only version #0 is supported so far.
1546 if (Record[0] != 0)
1547 return Error("Unknown bitstream version!");
1548 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001549 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001550 std::string S;
1551 if (ConvertToString(Record, 0, S))
1552 return Error("Invalid MODULE_CODE_TRIPLE record");
1553 TheModule->setTargetTriple(S);
1554 break;
1555 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001556 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001557 std::string S;
1558 if (ConvertToString(Record, 0, S))
1559 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1560 TheModule->setDataLayout(S);
1561 break;
1562 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001563 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001564 std::string S;
1565 if (ConvertToString(Record, 0, S))
1566 return Error("Invalid MODULE_CODE_ASM record");
1567 TheModule->setModuleInlineAsm(S);
1568 break;
1569 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001570 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001571 std::string S;
1572 if (ConvertToString(Record, 0, S))
1573 return Error("Invalid MODULE_CODE_DEPLIB record");
1574 TheModule->addLibrary(S);
1575 break;
1576 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001577 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001578 std::string S;
1579 if (ConvertToString(Record, 0, S))
1580 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1581 SectionTable.push_back(S);
1582 break;
1583 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001584 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001585 std::string S;
1586 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001587 return Error("Invalid MODULE_CODE_GCNAME record");
1588 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001589 break;
1590 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001591 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001592 // linkage, alignment, section, visibility, threadlocal,
1593 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001595 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001596 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001597 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001598 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001599 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001600 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001601 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001602 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001603
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001604 bool isConstant = Record[1];
1605 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1606 unsigned Alignment = (1 << Record[4]) >> 1;
1607 std::string Section;
1608 if (Record[5]) {
1609 if (Record[5]-1 >= SectionTable.size())
1610 return Error("Invalid section ID");
1611 Section = SectionTable[Record[5]-1];
1612 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001613 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001614 if (Record.size() > 6)
1615 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001616 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001617 if (Record.size() > 7)
1618 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001619
Rafael Espindolabea46262011-01-08 16:42:36 +00001620 bool UnnamedAddr = false;
1621 if (Record.size() > 8)
1622 UnnamedAddr = Record[8];
1623
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001624 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001625 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001626 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001627 NewGV->setAlignment(Alignment);
1628 if (!Section.empty())
1629 NewGV->setSection(Section);
1630 NewGV->setVisibility(Visibility);
1631 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001632 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001633
Chris Lattner0b2482a2007-04-23 21:26:05 +00001634 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001635
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001636 // Remember which value to use for the global initializer.
1637 if (unsigned InitID = Record[2])
1638 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001639 break;
1640 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001641 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001642 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001643 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001644 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001645 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001646 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001647 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001648 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001649 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001650 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001651 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1652 if (!FTy)
1653 return Error("Function not a pointer to function type!");
1654
Gabor Greif051a9502008-04-06 20:25:17 +00001655 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1656 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001657
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001658 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001659 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001660 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001661 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001662
Chris Lattnera9bb7132007-05-08 05:38:01 +00001663 Func->setAlignment((1 << Record[5]) >> 1);
1664 if (Record[6]) {
1665 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001666 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001667 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001668 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001669 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001670 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001671 if (Record[8]-1 > GCTable.size())
1672 return Error("Invalid GC ID");
1673 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001674 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001675 bool UnnamedAddr = false;
1676 if (Record.size() > 9)
1677 UnnamedAddr = Record[9];
1678 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001679 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001680
Chris Lattner48f84872007-05-01 04:59:48 +00001681 // If this is a function with a body, remember the prototype we are
1682 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001683 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001684 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001685 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1686 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001687 break;
1688 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001689 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001690 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001691 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001692 if (Record.size() < 3)
1693 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001694 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001695 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001696 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001697 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001698
Chris Lattner07d98b42007-04-26 02:46:40 +00001699 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1700 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001701 // Old bitcode files didn't have visibility field.
1702 if (Record.size() > 3)
1703 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001704 ValueList.push_back(NewGA);
1705 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1706 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001707 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001708 /// MODULE_CODE_PURGEVALS: [numvals]
1709 case bitc::MODULE_CODE_PURGEVALS:
1710 // Trim down the value list to the specified size.
1711 if (Record.size() < 1 || Record[0] > ValueList.size())
1712 return Error("Invalid MODULE_PURGEVALS record");
1713 ValueList.shrinkTo(Record[0]);
1714 break;
1715 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001716 Record.clear();
1717 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001718
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001719 return Error("Premature end of bitstream");
1720}
1721
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001722bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001723 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001724
Derek Schuff2ea93872012-02-06 22:30:29 +00001725 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001726
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001727 // Sniff for the signature.
1728 if (Stream.Read(8) != 'B' ||
1729 Stream.Read(8) != 'C' ||
1730 Stream.Read(4) != 0x0 ||
1731 Stream.Read(4) != 0xC ||
1732 Stream.Read(4) != 0xE ||
1733 Stream.Read(4) != 0xD)
1734 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001735
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001736 // We expect a number of well-defined blocks, though we don't necessarily
1737 // need to understand them all.
1738 while (!Stream.AtEndOfStream()) {
1739 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001740
Rafael Espindolac9687b32011-05-26 18:59:54 +00001741 if (Code != bitc::ENTER_SUBBLOCK) {
1742
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001743 // The ranlib in xcode 4 will align archive members by appending newlines
1744 // to the end of them. If this file size is a multiple of 4 but not 8, we
1745 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001746 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1747 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1748 Stream.AtEndOfStream())
1749 return false;
1750
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001751 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001752 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001753
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001754 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001755
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001756 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001757 switch (BlockID) {
1758 case bitc::BLOCKINFO_BLOCK_ID:
1759 if (Stream.ReadBlockInfoBlock())
1760 return Error("Malformed BlockInfoBlock");
1761 break;
1762 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001763 // Reject multiple MODULE_BLOCK's in a single bitstream.
1764 if (TheModule)
1765 return Error("Multiple MODULE_BLOCKs in same stream");
1766 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001767 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001768 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001769 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001770 break;
1771 default:
1772 if (Stream.SkipBlock())
1773 return Error("Malformed block record");
1774 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001775 }
1776 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001777
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001778 return false;
1779}
Chris Lattnerc453f762007-04-29 07:54:31 +00001780
Bill Wendling34711742010-10-06 01:22:42 +00001781bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1782 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1783 return Error("Malformed block record");
1784
1785 SmallVector<uint64_t, 64> Record;
1786
1787 // Read all the records for this module.
1788 while (!Stream.AtEndOfStream()) {
1789 unsigned Code = Stream.ReadCode();
1790 if (Code == bitc::END_BLOCK) {
1791 if (Stream.ReadBlockEnd())
1792 return Error("Error at end of module block");
1793
1794 return false;
1795 }
1796
1797 if (Code == bitc::ENTER_SUBBLOCK) {
1798 switch (Stream.ReadSubBlockID()) {
1799 default: // Skip unknown content.
1800 if (Stream.SkipBlock())
1801 return Error("Malformed block record");
1802 break;
1803 }
1804 continue;
1805 }
1806
1807 if (Code == bitc::DEFINE_ABBREV) {
1808 Stream.ReadAbbrevRecord();
1809 continue;
1810 }
1811
1812 // Read a record.
1813 switch (Stream.ReadRecord(Code, Record)) {
1814 default: break; // Default behavior, ignore unknown content.
1815 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1816 if (Record.size() < 1)
1817 return Error("Malformed MODULE_CODE_VERSION");
1818 // Only version #0 is supported so far.
1819 if (Record[0] != 0)
1820 return Error("Unknown bitstream version!");
1821 break;
1822 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1823 std::string S;
1824 if (ConvertToString(Record, 0, S))
1825 return Error("Invalid MODULE_CODE_TRIPLE record");
1826 Triple = S;
1827 break;
1828 }
1829 }
1830 Record.clear();
1831 }
1832
1833 return Error("Premature end of bitstream");
1834}
1835
1836bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001837 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001838
1839 // Sniff for the signature.
1840 if (Stream.Read(8) != 'B' ||
1841 Stream.Read(8) != 'C' ||
1842 Stream.Read(4) != 0x0 ||
1843 Stream.Read(4) != 0xC ||
1844 Stream.Read(4) != 0xE ||
1845 Stream.Read(4) != 0xD)
1846 return Error("Invalid bitcode signature");
1847
1848 // We expect a number of well-defined blocks, though we don't necessarily
1849 // need to understand them all.
1850 while (!Stream.AtEndOfStream()) {
1851 unsigned Code = Stream.ReadCode();
1852
1853 if (Code != bitc::ENTER_SUBBLOCK)
1854 return Error("Invalid record at top-level");
1855
1856 unsigned BlockID = Stream.ReadSubBlockID();
1857
1858 // We only know the MODULE subblock ID.
1859 switch (BlockID) {
1860 case bitc::MODULE_BLOCK_ID:
1861 if (ParseModuleTriple(Triple))
1862 return true;
1863 break;
1864 default:
1865 if (Stream.SkipBlock())
1866 return Error("Malformed block record");
1867 break;
1868 }
1869 }
1870
1871 return false;
1872}
1873
Devang Patele8e02132009-09-18 19:26:43 +00001874/// ParseMetadataAttachment - Parse metadata attachments.
1875bool BitcodeReader::ParseMetadataAttachment() {
1876 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1877 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001878
Devang Patele8e02132009-09-18 19:26:43 +00001879 SmallVector<uint64_t, 64> Record;
1880 while(1) {
1881 unsigned Code = Stream.ReadCode();
1882 if (Code == bitc::END_BLOCK) {
1883 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001884 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001885 break;
1886 }
1887 if (Code == bitc::DEFINE_ABBREV) {
1888 Stream.ReadAbbrevRecord();
1889 continue;
1890 }
1891 // Read a metadata attachment record.
1892 Record.clear();
1893 switch (Stream.ReadRecord(Code, Record)) {
1894 default: // Default behavior: ignore.
1895 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001896 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001897 unsigned RecordLength = Record.size();
1898 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001899 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001900 Instruction *Inst = InstructionList[Record[0]];
1901 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001902 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001903 DenseMap<unsigned, unsigned>::iterator I =
1904 MDKindMap.find(Kind);
1905 if (I == MDKindMap.end())
1906 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001907 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001908 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001909 }
1910 break;
1911 }
1912 }
1913 }
1914 return false;
1915}
Chris Lattner48f84872007-05-01 04:59:48 +00001916
Chris Lattner980e5aa2007-05-01 05:52:21 +00001917/// ParseFunctionBody - Lazily parse the specified function body block.
1918bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001919 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001920 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001921
Nick Lewycky9a49f152010-02-25 08:30:17 +00001922 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001923 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001924 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001925
Chris Lattner980e5aa2007-05-01 05:52:21 +00001926 // Add all the function arguments to the value table.
1927 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1928 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001929
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001930 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001931 BasicBlock *CurBB = 0;
1932 unsigned CurBBNo = 0;
1933
Chris Lattnera6245242010-04-03 02:17:50 +00001934 DebugLoc LastLoc;
1935
Chris Lattner980e5aa2007-05-01 05:52:21 +00001936 // Read all the records.
1937 SmallVector<uint64_t, 64> Record;
1938 while (1) {
1939 unsigned Code = Stream.ReadCode();
1940 if (Code == bitc::END_BLOCK) {
1941 if (Stream.ReadBlockEnd())
1942 return Error("Error at end of function block");
1943 break;
1944 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001945
Chris Lattner980e5aa2007-05-01 05:52:21 +00001946 if (Code == bitc::ENTER_SUBBLOCK) {
1947 switch (Stream.ReadSubBlockID()) {
1948 default: // Skip unknown content.
1949 if (Stream.SkipBlock())
1950 return Error("Malformed block record");
1951 break;
1952 case bitc::CONSTANTS_BLOCK_ID:
1953 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001954 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001955 break;
1956 case bitc::VALUE_SYMTAB_BLOCK_ID:
1957 if (ParseValueSymbolTable()) return true;
1958 break;
Devang Patele8e02132009-09-18 19:26:43 +00001959 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001960 if (ParseMetadataAttachment()) return true;
1961 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001962 case bitc::METADATA_BLOCK_ID:
1963 if (ParseMetadata()) return true;
1964 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001965 }
1966 continue;
1967 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001968
Chris Lattner980e5aa2007-05-01 05:52:21 +00001969 if (Code == bitc::DEFINE_ABBREV) {
1970 Stream.ReadAbbrevRecord();
1971 continue;
1972 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001973
Chris Lattner980e5aa2007-05-01 05:52:21 +00001974 // Read a record.
1975 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001976 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001977 unsigned BitCode = Stream.ReadRecord(Code, Record);
1978 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001979 default: // Default behavior: reject
1980 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001981 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001982 if (Record.size() < 1 || Record[0] == 0)
1983 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001984 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001985 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001986 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001987 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001988 CurBB = FunctionBBs[0];
1989 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001990
1991 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1992 // This record indicates that the last instruction is at the same
1993 // location as the previous instruction with a location.
1994 I = 0;
1995
1996 // Get the last instruction emitted.
1997 if (CurBB && !CurBB->empty())
1998 I = &CurBB->back();
1999 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2000 !FunctionBBs[CurBBNo-1]->empty())
2001 I = &FunctionBBs[CurBBNo-1]->back();
2002
2003 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2004 I->setDebugLoc(LastLoc);
2005 I = 0;
2006 continue;
2007
Chris Lattner4f6bab92011-06-17 18:17:37 +00002008 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002009 I = 0; // Get the last instruction emitted.
2010 if (CurBB && !CurBB->empty())
2011 I = &CurBB->back();
2012 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2013 !FunctionBBs[CurBBNo-1]->empty())
2014 I = &FunctionBBs[CurBBNo-1]->back();
2015 if (I == 0 || Record.size() < 4)
2016 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2017
2018 unsigned Line = Record[0], Col = Record[1];
2019 unsigned ScopeID = Record[2], IAID = Record[3];
2020
2021 MDNode *Scope = 0, *IA = 0;
2022 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2023 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2024 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2025 I->setDebugLoc(LastLoc);
2026 I = 0;
2027 continue;
2028 }
2029
Chris Lattnerabfbf852007-05-06 00:21:25 +00002030 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2031 unsigned OpNum = 0;
2032 Value *LHS, *RHS;
2033 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2034 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002035 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002036 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002037
Dan Gohman1224c382009-07-20 21:19:07 +00002038 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002039 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002041 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002042 if (OpNum < Record.size()) {
2043 if (Opc == Instruction::Add ||
2044 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002045 Opc == Instruction::Mul ||
2046 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002047 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002048 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002049 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002050 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002051 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002052 Opc == Instruction::UDiv ||
2053 Opc == Instruction::LShr ||
2054 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002055 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002056 cast<BinaryOperator>(I)->setIsExact(true);
2057 }
2058 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002059 break;
2060 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002061 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2062 unsigned OpNum = 0;
2063 Value *Op;
2064 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2065 OpNum+2 != Record.size())
2066 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002067
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002068 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002069 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2070 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002071 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002072 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002073 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002074 break;
2075 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002076 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002077 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002078 unsigned OpNum = 0;
2079 Value *BasePtr;
2080 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002081 return Error("Invalid GEP record");
2082
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002083 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002084 while (OpNum != Record.size()) {
2085 Value *Op;
2086 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002087 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002088 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002089 }
2090
Jay Foada9203102011-07-25 09:48:08 +00002091 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002092 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002093 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002094 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002095 break;
2096 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002097
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002098 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2099 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002100 unsigned OpNum = 0;
2101 Value *Agg;
2102 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2103 return Error("Invalid EXTRACTVAL record");
2104
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002105 SmallVector<unsigned, 4> EXTRACTVALIdx;
2106 for (unsigned RecSize = Record.size();
2107 OpNum != RecSize; ++OpNum) {
2108 uint64_t Index = Record[OpNum];
2109 if ((unsigned)Index != Index)
2110 return Error("Invalid EXTRACTVAL index");
2111 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002112 }
2113
Jay Foadfc6d3a42011-07-13 10:26:04 +00002114 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002115 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002116 break;
2117 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002118
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002119 case bitc::FUNC_CODE_INST_INSERTVAL: {
2120 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002121 unsigned OpNum = 0;
2122 Value *Agg;
2123 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2124 return Error("Invalid INSERTVAL record");
2125 Value *Val;
2126 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2127 return Error("Invalid INSERTVAL record");
2128
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002129 SmallVector<unsigned, 4> INSERTVALIdx;
2130 for (unsigned RecSize = Record.size();
2131 OpNum != RecSize; ++OpNum) {
2132 uint64_t Index = Record[OpNum];
2133 if ((unsigned)Index != Index)
2134 return Error("Invalid INSERTVAL index");
2135 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002136 }
2137
Jay Foadfc6d3a42011-07-13 10:26:04 +00002138 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002139 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002140 break;
2141 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002142
Chris Lattnerabfbf852007-05-06 00:21:25 +00002143 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002144 // obsolete form of select
2145 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002146 unsigned OpNum = 0;
2147 Value *TrueVal, *FalseVal, *Cond;
2148 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2149 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002150 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002151 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002152
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002153 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002154 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002155 break;
2156 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002157
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002158 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2159 // new form of select
2160 // handles select i1 or select [N x i1]
2161 unsigned OpNum = 0;
2162 Value *TrueVal, *FalseVal, *Cond;
2163 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2164 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2165 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2166 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002167
2168 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002169 if (VectorType* vector_type =
2170 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002171 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002172 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002173 return Error("Invalid SELECT condition type");
2174 } else {
2175 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002176 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002177 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002178 }
2179
Gabor Greif051a9502008-04-06 20:25:17 +00002180 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002181 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002182 break;
2183 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002184
Chris Lattner01ff65f2007-05-02 05:16:49 +00002185 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002186 unsigned OpNum = 0;
2187 Value *Vec, *Idx;
2188 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002189 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002190 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002191 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002192 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002193 break;
2194 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002195
Chris Lattner01ff65f2007-05-02 05:16:49 +00002196 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002197 unsigned OpNum = 0;
2198 Value *Vec, *Elt, *Idx;
2199 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002200 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002201 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002202 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002203 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002204 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002205 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002206 break;
2207 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002208
Chris Lattnerabfbf852007-05-06 00:21:25 +00002209 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2210 unsigned OpNum = 0;
2211 Value *Vec1, *Vec2, *Mask;
2212 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2213 getValue(Record, OpNum, Vec1->getType(), Vec2))
2214 return Error("Invalid SHUFFLEVEC record");
2215
Mon P Wangaeb06d22008-11-10 04:46:22 +00002216 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002217 return Error("Invalid SHUFFLEVEC record");
2218 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002219 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002220 break;
2221 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002222
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002223 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2224 // Old form of ICmp/FCmp returning bool
2225 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2226 // both legal on vectors but had different behaviour.
2227 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2228 // FCmp/ICmp returning bool or vector of bool
2229
Chris Lattner7337ab92007-05-06 00:00:00 +00002230 unsigned OpNum = 0;
2231 Value *LHS, *RHS;
2232 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2233 getValue(Record, OpNum, LHS->getType(), RHS) ||
2234 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002235 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002236
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002237 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002238 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002239 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002240 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002241 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002242 break;
2243 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002244
Chris Lattner231cbcb2007-05-02 04:27:25 +00002245 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002246 {
2247 unsigned Size = Record.size();
2248 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002249 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002250 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002251 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002252 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002253
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002254 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002255 Value *Op = NULL;
2256 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2257 return Error("Invalid RET record");
2258 if (OpNum != Record.size())
2259 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002260
Chris Lattner96a74c52011-06-17 18:09:11 +00002261 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002262 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002263 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002264 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002265 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002266 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002267 return Error("Invalid BR record");
2268 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2269 if (TrueDest == 0)
2270 return Error("Invalid BR record");
2271
Devang Patele8e02132009-09-18 19:26:43 +00002272 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002273 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002274 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002275 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002276 else {
2277 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002278 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002279 if (FalseDest == 0 || Cond == 0)
2280 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002281 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002282 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002283 }
2284 break;
2285 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002286 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Stepan Dyatkovskiy85a44062012-05-08 06:36:08 +00002287 // Check magic
2288 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2289 // New SwitchInst format with case ranges.
2290
2291 Type *OpTy = getTypeByID(Record[1]);
2292 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2293
2294 Value *Cond = getFnValueByID(Record[2], OpTy);
2295 BasicBlock *Default = getBasicBlock(Record[3]);
2296 if (OpTy == 0 || Cond == 0 || Default == 0)
2297 return Error("Invalid SWITCH record");
2298
2299 unsigned NumCases = Record[4];
2300
2301 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2302
2303 unsigned CurIdx = 5;
2304 for (unsigned i = 0; i != NumCases; ++i) {
2305 CRSBuilder CaseBuilder;
2306 unsigned NumItems = Record[CurIdx++];
2307 for (unsigned ci = 0; ci != NumItems; ++ci) {
2308 bool isSingleNumber = Record[CurIdx++];
2309
2310 APInt Low;
2311 unsigned ActiveWords = 1;
2312 if (ValueBitWidth > 64)
2313 ActiveWords = Record[CurIdx++];
2314 Low = ReadWideAPInt(&Record[CurIdx], ActiveWords, ValueBitWidth);
2315 CurIdx += ActiveWords;
2316
2317 if (!isSingleNumber) {
2318 ActiveWords = 1;
2319 if (ValueBitWidth > 64)
2320 ActiveWords = Record[CurIdx++];
2321 APInt High =
2322 ReadWideAPInt(&Record[CurIdx], ActiveWords, ValueBitWidth);
2323 CaseBuilder.add(cast<ConstantInt>(ConstantInt::get(OpTy, Low)),
2324 cast<ConstantInt>(ConstantInt::get(OpTy, High)));
2325 CurIdx += ActiveWords;
2326 } else
2327 CaseBuilder.add(cast<ConstantInt>(ConstantInt::get(OpTy, Low)));
2328 }
2329 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2330 ConstantRangesSet Case = CaseBuilder.getCase();
2331 SI->addCase(Case, DestBB);
2332 }
2333 uint16_t Hash = SI->Hash();
2334 if (Hash != (Record[0] & 0xFFFF))
2335 return Error("Invalid SWITCH record");
2336 I = SI;
2337 break;
2338 }
2339
2340 // Old SwitchInst format without case ranges.
2341
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002342 if (Record.size() < 3 || (Record.size() & 1) == 0)
2343 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002344 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002345 Value *Cond = getFnValueByID(Record[1], OpTy);
2346 BasicBlock *Default = getBasicBlock(Record[2]);
2347 if (OpTy == 0 || Cond == 0 || Default == 0)
2348 return Error("Invalid SWITCH record");
2349 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002350 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002351 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002352 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002353 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002354 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2355 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2356 if (CaseVal == 0 || DestBB == 0) {
2357 delete SI;
2358 return Error("Invalid SWITCH record!");
2359 }
2360 SI->addCase(CaseVal, DestBB);
2361 }
2362 I = SI;
2363 break;
2364 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002365 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002366 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002367 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002368 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002369 Value *Address = getFnValueByID(Record[1], OpTy);
2370 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002371 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002372 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002373 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002374 InstructionList.push_back(IBI);
2375 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2376 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2377 IBI->addDestination(DestBB);
2378 } else {
2379 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002380 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002381 }
2382 }
2383 I = IBI;
2384 break;
2385 }
2386
Duncan Sandsdc024672007-11-27 13:23:08 +00002387 case bitc::FUNC_CODE_INST_INVOKE: {
2388 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002389 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002390 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002391 unsigned CCInfo = Record[1];
2392 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2393 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002394
Chris Lattnera9bb7132007-05-08 05:38:01 +00002395 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002396 Value *Callee;
2397 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002398 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002399
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002400 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2401 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002402 dyn_cast<FunctionType>(CalleeTy->getElementType());
2403
2404 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002405 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2406 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002407 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002408
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002409 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002410 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2411 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2412 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002413 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002414
Chris Lattner7337ab92007-05-06 00:00:00 +00002415 if (!FTy->isVarArg()) {
2416 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002417 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002418 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002419 // Read type/value pairs for varargs params.
2420 while (OpNum != Record.size()) {
2421 Value *Op;
2422 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2423 return Error("Invalid INVOKE record");
2424 Ops.push_back(Op);
2425 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002426 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002427
Jay Foada3efbb12011-07-15 08:37:34 +00002428 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002429 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002430 cast<InvokeInst>(I)->setCallingConv(
2431 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002432 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002433 break;
2434 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002435 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2436 unsigned Idx = 0;
2437 Value *Val = 0;
2438 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2439 return Error("Invalid RESUME record");
2440 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002441 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002442 break;
2443 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002444 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002445 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002446 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002447 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002448 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002449 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002450 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002451 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002452 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002453
Jay Foad3ecfc862011-03-30 11:28:46 +00002454 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002455 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002456
Chris Lattner15e6d172007-05-04 19:11:41 +00002457 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2458 Value *V = getFnValueByID(Record[1+i], Ty);
2459 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002460 if (!V || !BB) return Error("Invalid PHI record");
2461 PN->addIncoming(V, BB);
2462 }
2463 I = PN;
2464 break;
2465 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002466
Bill Wendlinge6e88262011-08-12 20:24:12 +00002467 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2468 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2469 unsigned Idx = 0;
2470 if (Record.size() < 4)
2471 return Error("Invalid LANDINGPAD record");
2472 Type *Ty = getTypeByID(Record[Idx++]);
2473 if (!Ty) return Error("Invalid LANDINGPAD record");
2474 Value *PersFn = 0;
2475 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2476 return Error("Invalid LANDINGPAD record");
2477
2478 bool IsCleanup = !!Record[Idx++];
2479 unsigned NumClauses = Record[Idx++];
2480 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2481 LP->setCleanup(IsCleanup);
2482 for (unsigned J = 0; J != NumClauses; ++J) {
2483 LandingPadInst::ClauseType CT =
2484 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2485 Value *Val;
2486
2487 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2488 delete LP;
2489 return Error("Invalid LANDINGPAD record");
2490 }
2491
2492 assert((CT != LandingPadInst::Catch ||
2493 !isa<ArrayType>(Val->getType())) &&
2494 "Catch clause has a invalid type!");
2495 assert((CT != LandingPadInst::Filter ||
2496 isa<ArrayType>(Val->getType())) &&
2497 "Filter clause has invalid type!");
2498 LP->addClause(Val);
2499 }
2500
2501 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002502 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002503 break;
2504 }
2505
Chris Lattner96a74c52011-06-17 18:09:11 +00002506 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2507 if (Record.size() != 4)
2508 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002509 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002510 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002511 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002512 Value *Size = getFnValueByID(Record[2], OpTy);
2513 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002514 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002515 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002516 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002517 break;
2518 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002519 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002520 unsigned OpNum = 0;
2521 Value *Op;
2522 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2523 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002524 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002525
Chris Lattner7337ab92007-05-06 00:00:00 +00002526 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002527 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002528 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002529 }
Eli Friedman21006d42011-08-09 23:02:53 +00002530 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2531 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2532 unsigned OpNum = 0;
2533 Value *Op;
2534 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2535 OpNum+4 != Record.size())
2536 return Error("Invalid LOADATOMIC record");
2537
2538
2539 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2540 if (Ordering == NotAtomic || Ordering == Release ||
2541 Ordering == AcquireRelease)
2542 return Error("Invalid LOADATOMIC record");
2543 if (Ordering != NotAtomic && Record[OpNum] == 0)
2544 return Error("Invalid LOADATOMIC record");
2545 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2546
2547 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2548 Ordering, SynchScope);
2549 InstructionList.push_back(I);
2550 break;
2551 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002552 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002553 unsigned OpNum = 0;
2554 Value *Val, *Ptr;
2555 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002556 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002557 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2558 OpNum+2 != Record.size())
2559 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002560
Christopher Lambfe63fb92007-12-11 08:59:05 +00002561 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002562 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002563 break;
2564 }
Eli Friedman21006d42011-08-09 23:02:53 +00002565 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2566 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2567 unsigned OpNum = 0;
2568 Value *Val, *Ptr;
2569 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2570 getValue(Record, OpNum,
2571 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2572 OpNum+4 != Record.size())
2573 return Error("Invalid STOREATOMIC record");
2574
2575 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002576 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002577 Ordering == AcquireRelease)
2578 return Error("Invalid STOREATOMIC record");
2579 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2580 if (Ordering != NotAtomic && Record[OpNum] == 0)
2581 return Error("Invalid STOREATOMIC record");
2582
2583 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2584 Ordering, SynchScope);
2585 InstructionList.push_back(I);
2586 break;
2587 }
Eli Friedmanff030482011-07-28 21:48:00 +00002588 case bitc::FUNC_CODE_INST_CMPXCHG: {
2589 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2590 unsigned OpNum = 0;
2591 Value *Ptr, *Cmp, *New;
2592 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2593 getValue(Record, OpNum,
2594 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2595 getValue(Record, OpNum,
2596 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2597 OpNum+3 != Record.size())
2598 return Error("Invalid CMPXCHG record");
2599 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002600 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002601 return Error("Invalid CMPXCHG record");
2602 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2603 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2604 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2605 InstructionList.push_back(I);
2606 break;
2607 }
2608 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2609 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2610 unsigned OpNum = 0;
2611 Value *Ptr, *Val;
2612 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2613 getValue(Record, OpNum,
2614 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2615 OpNum+4 != Record.size())
2616 return Error("Invalid ATOMICRMW record");
2617 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2618 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2619 Operation > AtomicRMWInst::LAST_BINOP)
2620 return Error("Invalid ATOMICRMW record");
2621 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002622 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002623 return Error("Invalid ATOMICRMW record");
2624 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2625 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2626 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2627 InstructionList.push_back(I);
2628 break;
2629 }
Eli Friedman47f35132011-07-25 23:16:38 +00002630 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2631 if (2 != Record.size())
2632 return Error("Invalid FENCE record");
2633 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2634 if (Ordering == NotAtomic || Ordering == Unordered ||
2635 Ordering == Monotonic)
2636 return Error("Invalid FENCE record");
2637 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2638 I = new FenceInst(Context, Ordering, SynchScope);
2639 InstructionList.push_back(I);
2640 break;
2641 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002642 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002643 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2644 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002645 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002646
Devang Patel05988662008-09-25 21:00:45 +00002647 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002648 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002649
Chris Lattnera9bb7132007-05-08 05:38:01 +00002650 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002651 Value *Callee;
2652 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2653 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002654
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002655 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2656 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002657 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002658 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002659 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002660
Chris Lattner0579f7f2007-05-03 22:04:19 +00002661 SmallVector<Value*, 16> Args;
2662 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002663 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002664 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002665 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002666 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002667 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002668 if (Args.back() == 0) return Error("Invalid CALL record");
2669 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002670
Chris Lattner0579f7f2007-05-03 22:04:19 +00002671 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002672 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002673 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002674 return Error("Invalid CALL record");
2675 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002676 while (OpNum != Record.size()) {
2677 Value *Op;
2678 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2679 return Error("Invalid CALL record");
2680 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002681 }
2682 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002683
Jay Foada3efbb12011-07-15 08:37:34 +00002684 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002685 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002686 cast<CallInst>(I)->setCallingConv(
2687 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002688 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002689 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002690 break;
2691 }
2692 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2693 if (Record.size() < 3)
2694 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002695 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002696 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002697 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002698 if (!OpTy || !Op || !ResTy)
2699 return Error("Invalid VAARG record");
2700 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002701 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002702 break;
2703 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002704 }
2705
2706 // Add instruction to end of current BB. If there is no current BB, reject
2707 // this file.
2708 if (CurBB == 0) {
2709 delete I;
2710 return Error("Invalid instruction with no BB");
2711 }
2712 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002713
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002714 // If this was a terminator instruction, move to the next block.
2715 if (isa<TerminatorInst>(I)) {
2716 ++CurBBNo;
2717 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2718 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002719
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002720 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002721 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002722 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002723 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002724
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002725 // Check the function list for unresolved values.
2726 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2727 if (A->getParent() == 0) {
2728 // We found at least one unresolved value. Nuke them all to avoid leaks.
2729 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002730 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002731 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002732 delete A;
2733 }
2734 }
Chris Lattner35a04702007-05-04 03:50:29 +00002735 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002736 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002737 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002738
Dan Gohman064ff3e2010-08-25 20:23:38 +00002739 // FIXME: Check for unresolved forward-declared metadata references
2740 // and clean up leaks.
2741
Chris Lattner50b136d2009-10-28 05:53:48 +00002742 // See if anything took the address of blocks in this function. If so,
2743 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002744 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2745 BlockAddrFwdRefs.find(F);
2746 if (BAFRI != BlockAddrFwdRefs.end()) {
2747 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2748 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2749 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002750 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002751 return Error("Invalid blockaddress block #");
2752
2753 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002754 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002755 FwdRef->eraseFromParent();
2756 }
2757
2758 BlockAddrFwdRefs.erase(BAFRI);
2759 }
2760
Chris Lattner980e5aa2007-05-01 05:52:21 +00002761 // Trim the value list down to the size it was before we parsed this function.
2762 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002763 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002764 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002765 return false;
2766}
2767
Derek Schuff2ea93872012-02-06 22:30:29 +00002768/// FindFunctionInStream - Find the function body in the bitcode stream
2769bool BitcodeReader::FindFunctionInStream(Function *F,
2770 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2771 while (DeferredFunctionInfoIterator->second == 0) {
2772 if (Stream.AtEndOfStream())
2773 return Error("Could not find Function in stream");
2774 // ParseModule will parse the next body in the stream and set its
2775 // position in the DeferredFunctionInfo map.
2776 if (ParseModule(true)) return true;
2777 }
2778 return false;
2779}
2780
Chris Lattnerb348bb82007-05-18 04:02:46 +00002781//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002782// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002783//===----------------------------------------------------------------------===//
2784
2785
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002786bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2787 if (const Function *F = dyn_cast<Function>(GV)) {
2788 return F->isDeclaration() &&
2789 DeferredFunctionInfo.count(const_cast<Function*>(F));
2790 }
2791 return false;
2792}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002793
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002794bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2795 Function *F = dyn_cast<Function>(GV);
2796 // If it's not a function or is already material, ignore the request.
2797 if (!F || !F->isMaterializable()) return false;
2798
2799 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002800 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002801 // If its position is recorded as 0, its body is somewhere in the stream
2802 // but we haven't seen it yet.
2803 if (DFII->second == 0)
2804 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002805
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002806 // Move the bit stream to the saved position of the deferred function body.
2807 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002808
Chris Lattnerb348bb82007-05-18 04:02:46 +00002809 if (ParseFunctionBody(F)) {
2810 if (ErrInfo) *ErrInfo = ErrorString;
2811 return true;
2812 }
Chandler Carruth69940402007-08-04 01:51:18 +00002813
2814 // Upgrade any old intrinsic calls in the function.
2815 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2816 E = UpgradedIntrinsics.end(); I != E; ++I) {
2817 if (I->first != I->second) {
2818 for (Value::use_iterator UI = I->first->use_begin(),
2819 UE = I->first->use_end(); UI != UE; ) {
2820 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2821 UpgradeIntrinsicCall(CI, I->second);
2822 }
2823 }
2824 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002825
Chris Lattnerb348bb82007-05-18 04:02:46 +00002826 return false;
2827}
2828
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002829bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2830 const Function *F = dyn_cast<Function>(GV);
2831 if (!F || F->isDeclaration())
2832 return false;
2833 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2834}
2835
2836void BitcodeReader::Dematerialize(GlobalValue *GV) {
2837 Function *F = dyn_cast<Function>(GV);
2838 // If this function isn't dematerializable, this is a noop.
2839 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002840 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002841
Chris Lattnerb348bb82007-05-18 04:02:46 +00002842 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002843
Chris Lattnerb348bb82007-05-18 04:02:46 +00002844 // Just forget the function body, we can remat it later.
2845 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002846}
2847
2848
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002849bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2850 assert(M == TheModule &&
2851 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002852 // Iterate over the module, deserializing any functions that are still on
2853 // disk.
2854 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2855 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002856 if (F->isMaterializable() &&
2857 Materialize(F, ErrInfo))
2858 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002859
Derek Schuff0ffe6982012-02-29 00:07:09 +00002860 // At this point, if there are any function bodies, the current bit is
2861 // pointing to the END_BLOCK record after them. Now make sure the rest
2862 // of the bits in the module have been read.
2863 if (NextUnreadBit)
2864 ParseModule(true);
2865
Daniel Dunbara279bc32009-09-20 02:20:51 +00002866 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2867 // delete the old functions to clean up. We can't do this unless the entire
2868 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002869 // with calls to the old function.
2870 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2871 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2872 if (I->first != I->second) {
2873 for (Value::use_iterator UI = I->first->use_begin(),
2874 UE = I->first->use_end(); UI != UE; ) {
2875 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2876 UpgradeIntrinsicCall(CI, I->second);
2877 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002878 if (!I->first->use_empty())
2879 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002880 I->first->eraseFromParent();
2881 }
2882 }
2883 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002884
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002885 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002886}
2887
Derek Schuff2ea93872012-02-06 22:30:29 +00002888bool BitcodeReader::InitStream() {
2889 if (LazyStreamer) return InitLazyStream();
2890 return InitStreamFromBuffer();
2891}
2892
2893bool BitcodeReader::InitStreamFromBuffer() {
2894 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2895 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2896
2897 if (Buffer->getBufferSize() & 3) {
2898 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2899 return Error("Invalid bitcode signature");
2900 else
2901 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2902 }
2903
2904 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2905 // The magic number is 0x0B17C0DE stored in little endian.
2906 if (isBitcodeWrapper(BufPtr, BufEnd))
2907 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2908 return Error("Invalid bitcode wrapper header");
2909
2910 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2911 Stream.init(*StreamFile);
2912
2913 return false;
2914}
2915
2916bool BitcodeReader::InitLazyStream() {
2917 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2918 // see it.
2919 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2920 StreamFile.reset(new BitstreamReader(Bytes));
2921 Stream.init(*StreamFile);
2922
2923 unsigned char buf[16];
2924 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2925 return Error("Bitcode stream must be at least 16 bytes in length");
2926
2927 if (!isBitcode(buf, buf + 16))
2928 return Error("Invalid bitcode signature");
2929
2930 if (isBitcodeWrapper(buf, buf + 4)) {
2931 const unsigned char *bitcodeStart = buf;
2932 const unsigned char *bitcodeEnd = buf + 16;
2933 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2934 Bytes->dropLeadingBytes(bitcodeStart - buf);
2935 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2936 }
2937 return false;
2938}
Chris Lattner48f84872007-05-01 04:59:48 +00002939
Chris Lattnerc453f762007-04-29 07:54:31 +00002940//===----------------------------------------------------------------------===//
2941// External interface
2942//===----------------------------------------------------------------------===//
2943
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002944/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002945///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002946Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2947 LLVMContext& Context,
2948 std::string *ErrMsg) {
2949 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002950 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002951 M->setMaterializer(R);
2952 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002953 if (ErrMsg)
2954 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002955
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002956 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002957 return 0;
2958 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002959 // Have the BitcodeReader dtor delete 'Buffer'.
2960 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002961
2962 R->materializeForwardReferencedFunctions();
2963
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002964 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002965}
2966
Derek Schuff2ea93872012-02-06 22:30:29 +00002967
2968Module *llvm::getStreamedBitcodeModule(const std::string &name,
2969 DataStreamer *streamer,
2970 LLVMContext &Context,
2971 std::string *ErrMsg) {
2972 Module *M = new Module(name, Context);
2973 BitcodeReader *R = new BitcodeReader(streamer, Context);
2974 M->setMaterializer(R);
2975 if (R->ParseBitcodeInto(M)) {
2976 if (ErrMsg)
2977 *ErrMsg = R->getErrorString();
2978 delete M; // Also deletes R.
2979 return 0;
2980 }
2981 R->setBufferOwned(false); // no buffer to delete
2982 return M;
2983}
2984
Chris Lattnerc453f762007-04-29 07:54:31 +00002985/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2986/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002987Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002988 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002989 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2990 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002991
2992 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2993 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002994 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002995
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002996 // Read in the entire module, and destroy the BitcodeReader.
2997 if (M->MaterializeAllPermanently(ErrMsg)) {
2998 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002999 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003000 }
Bill Wendling34711742010-10-06 01:22:42 +00003001
Chad Rosiercbbb0962011-12-07 21:44:12 +00003002 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3003 // written. We must defer until the Module has been fully materialized.
3004
Chris Lattnerc453f762007-04-29 07:54:31 +00003005 return M;
3006}
Bill Wendling34711742010-10-06 01:22:42 +00003007
3008std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3009 LLVMContext& Context,
3010 std::string *ErrMsg) {
3011 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3012 // Don't let the BitcodeReader dtor delete 'Buffer'.
3013 R->setBufferOwned(false);
3014
3015 std::string Triple("");
3016 if (R->ParseTriple(Triple))
3017 if (ErrMsg)
3018 *ErrMsg = R->getErrorString();
3019
3020 delete R;
3021 return Triple;
3022}