blob: 2b98f01e583c2ebb31fa5e29601cdde77eb27495 [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 Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000031enum {
32 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
33};
34
Rafael Espindola47f79bb2012-01-02 07:49:53 +000035void BitcodeReader::materializeForwardReferencedFunctions() {
36 while (!BlockAddrFwdRefs.empty()) {
37 Function *F = BlockAddrFwdRefs.begin()->first;
38 F->Materialize();
39 }
40}
41
Chris Lattnerb348bb82007-05-18 04:02:46 +000042void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000043 if (BufferOwned)
44 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000045 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000046 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000048 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000049
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>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000064static bool ConvertToString(ArrayRef<uint64_t> 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 Lattner48c85b82007-05-04 03:30:17 +0000465 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000466 // FIXME: remove in LLVM 3.0
467 // The alignment is stored as a 16-bit raw value from bits 31--16.
468 // We shift the bits above 31 down by 11 bits.
469
470 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
471 if (Alignment && !isPowerOf2_32(Alignment))
472 return Error("Alignment is not a power of two.");
473
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000474 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000475 if (Alignment)
476 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000477 ReconstitutedAttr |=
478 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000479
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000480 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000481 }
Chris Lattner461edd92008-03-12 02:25:52 +0000482
Devang Patel19c87462008-09-26 22:53:05 +0000483 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nuno Lopes006c7b92012-05-08 17:07:35 +0000484 if (Attributes(Record[i+1]) != Attribute::None)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000485 Attrs.push_back(AttributeWithIndex::get(Record[i],
486 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000487 }
Devang Patel19c87462008-09-26 22:53:05 +0000488
Chris Lattnerd509d0b2012-05-28 01:47:44 +0000489 MAttributes.push_back(AttrListPtr::get(Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000490 Attrs.clear();
491 break;
492 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000493 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000494 }
495}
496
Chris Lattner86697142007-05-01 05:01:34 +0000497bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000498 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000499 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000500
Chris Lattner1afcace2011-07-09 17:41:24 +0000501 return ParseTypeTableBody();
502}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000503
Chris Lattner1afcace2011-07-09 17:41:24 +0000504bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000505 if (!TypeList.empty())
506 return Error("Multiple TYPE_BLOCKs found!");
507
508 SmallVector<uint64_t, 64> Record;
509 unsigned NumRecords = 0;
510
Chris Lattner1afcace2011-07-09 17:41:24 +0000511 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000512
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000513 // Read all the records for this type table.
514 while (1) {
515 unsigned Code = Stream.ReadCode();
516 if (Code == bitc::END_BLOCK) {
517 if (NumRecords != TypeList.size())
518 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000519 if (Stream.ReadBlockEnd())
520 return Error("Error at end of type table block");
521 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000522 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000523
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000524 if (Code == bitc::ENTER_SUBBLOCK) {
525 // No known subblocks, always skip them.
526 Stream.ReadSubBlockID();
527 if (Stream.SkipBlock())
528 return Error("Malformed block record");
529 continue;
530 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000531
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000532 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000533 Stream.ReadAbbrevRecord();
534 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000535 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000536
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000537 // Read a record.
538 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000539 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000540 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000541 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000542 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
543 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
544 // type list. This allows us to reserve space.
545 if (Record.size() < 1)
546 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000547 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000548 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000549 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000550 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000551 break;
Dan Gohmance163392011-12-17 00:04:22 +0000552 case bitc::TYPE_CODE_HALF: // HALF
553 ResultTy = Type::getHalfTy(Context);
554 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000555 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000556 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000557 break;
558 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000559 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000560 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000561 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000562 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000563 break;
564 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000565 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000566 break;
567 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000568 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000569 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000570 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000571 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000572 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000573 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000574 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000575 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000576 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
577 ResultTy = Type::getX86_MMXTy(Context);
578 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000579 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
580 if (Record.size() < 1)
581 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000582
Owen Anderson1d0be152009-08-13 21:58:54 +0000583 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000584 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000585 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000586 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000587 if (Record.size() < 1)
588 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000589 unsigned AddressSpace = 0;
590 if (Record.size() == 2)
591 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000592 ResultTy = getTypeByID(Record[0]);
593 if (ResultTy == 0) return Error("invalid element type in pointer type");
594 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000595 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000596 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000597 case bitc::TYPE_CODE_FUNCTION_OLD: {
598 // FIXME: attrid is dead, remove it in LLVM 4.0
599 // FUNCTION: [vararg, attrid, retty, paramty x N]
600 if (Record.size() < 3)
601 return Error("Invalid FUNCTION type record");
602 SmallVector<Type*, 8> ArgTys;
603 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
604 if (Type *T = getTypeByID(Record[i]))
605 ArgTys.push_back(T);
606 else
607 break;
608 }
609
610 ResultTy = getTypeByID(Record[2]);
611 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
612 return Error("invalid type in function type");
613
614 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
615 break;
616 }
Chad Rosiercde54642011-11-03 00:14:01 +0000617 case bitc::TYPE_CODE_FUNCTION: {
618 // FUNCTION: [vararg, retty, paramty x N]
619 if (Record.size() < 2)
620 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000621 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000622 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
623 if (Type *T = getTypeByID(Record[i]))
624 ArgTys.push_back(T);
625 else
626 break;
627 }
628
629 ResultTy = getTypeByID(Record[1]);
630 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
631 return Error("invalid type in function type");
632
633 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
634 break;
635 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000636 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000637 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000638 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000639 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000640 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
641 if (Type *T = getTypeByID(Record[i]))
642 EltTys.push_back(T);
643 else
644 break;
645 }
646 if (EltTys.size() != Record.size()-1)
647 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000648 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000649 break;
650 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000651 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
652 if (ConvertToString(Record, 0, TypeName))
653 return Error("Invalid STRUCT_NAME record");
654 continue;
655
656 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
657 if (Record.size() < 1)
658 return Error("Invalid STRUCT type record");
659
660 if (NumRecords >= TypeList.size())
661 return Error("invalid TYPE table");
662
663 // Check to see if this was forward referenced, if so fill in the temp.
664 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
665 if (Res) {
666 Res->setName(TypeName);
667 TypeList[NumRecords] = 0;
668 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000669 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000670 TypeName.clear();
671
672 SmallVector<Type*, 8> EltTys;
673 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
674 if (Type *T = getTypeByID(Record[i]))
675 EltTys.push_back(T);
676 else
677 break;
678 }
679 if (EltTys.size() != Record.size()-1)
680 return Error("invalid STRUCT type record");
681 Res->setBody(EltTys, Record[0]);
682 ResultTy = Res;
683 break;
684 }
685 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
686 if (Record.size() != 1)
687 return Error("Invalid OPAQUE type record");
688
689 if (NumRecords >= TypeList.size())
690 return Error("invalid TYPE table");
691
692 // Check to see if this was forward referenced, if so fill in the temp.
693 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
694 if (Res) {
695 Res->setName(TypeName);
696 TypeList[NumRecords] = 0;
697 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000698 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000699 TypeName.clear();
700 ResultTy = Res;
701 break;
702 }
703 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
704 if (Record.size() < 2)
705 return Error("Invalid ARRAY type record");
706 if ((ResultTy = getTypeByID(Record[1])))
707 ResultTy = ArrayType::get(ResultTy, Record[0]);
708 else
709 return Error("Invalid ARRAY type element");
710 break;
711 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
712 if (Record.size() < 2)
713 return Error("Invalid VECTOR type record");
714 if ((ResultTy = getTypeByID(Record[1])))
715 ResultTy = VectorType::get(ResultTy, Record[0]);
716 else
717 return Error("Invalid ARRAY type element");
718 break;
719 }
720
721 if (NumRecords >= TypeList.size())
722 return Error("invalid TYPE table");
723 assert(ResultTy && "Didn't read a type?");
724 assert(TypeList[NumRecords] == 0 && "Already read type?");
725 TypeList[NumRecords++] = ResultTy;
726 }
727}
728
Chris Lattner86697142007-05-01 05:01:34 +0000729bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000730 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000731 return Error("Malformed block record");
732
733 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000734
Chris Lattner0b2482a2007-04-23 21:26:05 +0000735 // Read all the records for this value table.
736 SmallString<128> ValueName;
737 while (1) {
738 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000739 if (Code == bitc::END_BLOCK) {
740 if (Stream.ReadBlockEnd())
741 return Error("Error at end of value symbol table block");
742 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000743 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000744 if (Code == bitc::ENTER_SUBBLOCK) {
745 // No known subblocks, always skip them.
746 Stream.ReadSubBlockID();
747 if (Stream.SkipBlock())
748 return Error("Malformed block record");
749 continue;
750 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000751
Chris Lattner0b2482a2007-04-23 21:26:05 +0000752 if (Code == bitc::DEFINE_ABBREV) {
753 Stream.ReadAbbrevRecord();
754 continue;
755 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000756
Chris Lattner0b2482a2007-04-23 21:26:05 +0000757 // Read a record.
758 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000759 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000760 default: // Default behavior: unknown type.
761 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000762 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000763 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000764 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000765 unsigned ValueID = Record[0];
766 if (ValueID >= ValueList.size())
767 return Error("Invalid Value ID in VST_ENTRY record");
768 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000769
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000770 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000771 ValueName.clear();
772 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000773 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000774 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000775 if (ConvertToString(Record, 1, ValueName))
776 return Error("Invalid VST_BBENTRY record");
777 BasicBlock *BB = getBasicBlock(Record[0]);
778 if (BB == 0)
779 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000780
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000781 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000782 ValueName.clear();
783 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000784 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000785 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000786 }
787}
788
Devang Patele54abc92009-07-22 17:43:22 +0000789bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000790 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000791
792 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
793 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Devang Patele54abc92009-07-22 17:43:22 +0000795 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000796
Devang Patele54abc92009-07-22 17:43:22 +0000797 // Read all the records.
798 while (1) {
799 unsigned Code = Stream.ReadCode();
800 if (Code == bitc::END_BLOCK) {
801 if (Stream.ReadBlockEnd())
802 return Error("Error at end of PARAMATTR block");
803 return false;
804 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000805
Devang Patele54abc92009-07-22 17:43:22 +0000806 if (Code == bitc::ENTER_SUBBLOCK) {
807 // No known subblocks, always skip them.
808 Stream.ReadSubBlockID();
809 if (Stream.SkipBlock())
810 return Error("Malformed block record");
811 continue;
812 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000813
Devang Patele54abc92009-07-22 17:43:22 +0000814 if (Code == bitc::DEFINE_ABBREV) {
815 Stream.ReadAbbrevRecord();
816 continue;
817 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000818
Victor Hernandez24e64df2010-01-10 07:14:18 +0000819 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000820 // Read a record.
821 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000822 Code = Stream.ReadRecord(Code, Record);
823 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000824 default: // Default behavior: ignore.
825 break;
Devang Patelaa993142009-07-29 22:34:41 +0000826 case bitc::METADATA_NAME: {
827 // Read named of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000828 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000829 Record.clear();
830 Code = Stream.ReadCode();
831
Chris Lattner9d61dd92011-06-17 17:50:30 +0000832 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000833 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000834 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000835
836 // Read named metadata elements.
837 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000838 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000839 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000840 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
841 if (MD == 0)
842 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000843 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000844 }
Devang Patelaa993142009-07-29 22:34:41 +0000845 break;
846 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000847 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000848 IsFunctionLocal = true;
849 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000850 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000851 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000852 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000853
Devang Patel104cf9e2009-07-23 01:07:34 +0000854 unsigned Size = Record.size();
855 SmallVector<Value*, 8> Elts;
856 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000857 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000858 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000859 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000860 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000861 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000862 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
863 else
864 Elts.push_back(NULL);
865 }
Jay Foadec9186b2011-04-21 19:59:31 +0000866 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000867 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000868 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000869 break;
870 }
Devang Patele54abc92009-07-22 17:43:22 +0000871 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000872 SmallString<8> String(Record.begin(), Record.end());
873 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000874 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000875 break;
876 }
Devang Patele8e02132009-09-18 19:26:43 +0000877 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000878 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000879 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000880
Devang Patela2148402009-09-28 21:14:55 +0000881 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000882 SmallString<8> Name(Record.begin()+1, Record.end());
883
Chris Lattner08113472009-12-29 09:01:33 +0000884 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000885 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
886 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000887 break;
888 }
Devang Patele54abc92009-07-22 17:43:22 +0000889 }
890 }
891}
892
Chris Lattner0eef0802007-04-24 04:04:35 +0000893/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
894/// the LSB for dense VBR encoding.
895static uint64_t DecodeSignRotatedValue(uint64_t V) {
896 if ((V & 1) == 0)
897 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000898 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000899 return -(V >> 1);
900 // There is no such thing as -0 with integers. "-0" really means MININT.
901 return 1ULL << 63;
902}
903
Chris Lattner07d98b42007-04-26 02:46:40 +0000904/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
905/// values and aliases that we can.
906bool BitcodeReader::ResolveGlobalAndAliasInits() {
907 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
908 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000909
Chris Lattner07d98b42007-04-26 02:46:40 +0000910 GlobalInitWorklist.swap(GlobalInits);
911 AliasInitWorklist.swap(AliasInits);
912
913 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000914 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000915 if (ValID >= ValueList.size()) {
916 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000917 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000918 } else {
919 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
920 GlobalInitWorklist.back().first->setInitializer(C);
921 else
922 return Error("Global variable initializer is not a constant!");
923 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000924 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000925 }
926
927 while (!AliasInitWorklist.empty()) {
928 unsigned ValID = AliasInitWorklist.back().second;
929 if (ValID >= ValueList.size()) {
930 AliasInits.push_back(AliasInitWorklist.back());
931 } else {
932 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000933 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000934 else
935 return Error("Alias initializer is not a constant!");
936 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000937 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000938 }
939 return false;
940}
941
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000942static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
943 SmallVector<uint64_t, 8> Words(Vals.size());
944 std::transform(Vals.begin(), Vals.end(), Words.begin(),
945 DecodeSignRotatedValue);
946
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000947 return APInt(TypeBits, Words);
948}
949
Chris Lattner86697142007-05-01 05:01:34 +0000950bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000951 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000952 return Error("Malformed block record");
953
954 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000955
Chris Lattnere16504e2007-04-24 03:30:34 +0000956 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000957 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000958 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000959 while (1) {
960 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000961 if (Code == bitc::END_BLOCK)
962 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000963
Chris Lattnere16504e2007-04-24 03:30:34 +0000964 if (Code == bitc::ENTER_SUBBLOCK) {
965 // No known subblocks, always skip them.
966 Stream.ReadSubBlockID();
967 if (Stream.SkipBlock())
968 return Error("Malformed block record");
969 continue;
970 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000971
Chris Lattnere16504e2007-04-24 03:30:34 +0000972 if (Code == bitc::DEFINE_ABBREV) {
973 Stream.ReadAbbrevRecord();
974 continue;
975 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000976
Chris Lattnere16504e2007-04-24 03:30:34 +0000977 // Read a record.
978 Record.clear();
979 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000980 unsigned BitCode = Stream.ReadRecord(Code, Record);
981 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000982 default: // Default behavior: unknown constant
983 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000984 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000985 break;
986 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
987 if (Record.empty())
988 return Error("Malformed CST_SETTYPE record");
989 if (Record[0] >= TypeList.size())
990 return Error("Invalid Type ID in CST_SETTYPE record");
991 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000992 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000993 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000994 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000995 break;
996 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000997 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000998 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +0000999 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001000 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001001 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001002 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001003 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001004
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001005 APInt VInt = ReadWideAPInt(Record,
1006 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001007 V = ConstantInt::get(Context, VInt);
1008
Chris Lattner0eef0802007-04-24 04:04:35 +00001009 break;
1010 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001011 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001012 if (Record.empty())
1013 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001014 if (CurTy->isHalfTy())
1015 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1016 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001017 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001018 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001019 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001020 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001021 // Bits are not stored the same way as a normal i80 APInt, compensate.
1022 uint64_t Rearrange[2];
1023 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1024 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001025 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001026 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001027 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001028 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001029 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001030 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001031 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001032 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001033 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001034
Chris Lattner15e6d172007-05-04 19:11:41 +00001035 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1036 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001037 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001038
Chris Lattner15e6d172007-05-04 19:11:41 +00001039 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001040 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001041
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001042 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001043 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001044 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001045 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001046 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001047 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1048 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001049 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001050 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001051 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001052 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1053 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001054 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001055 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001056 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001057 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001058 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001059 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001060 break;
1061 }
Chris Lattner2237f842012-02-05 02:41:35 +00001062 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001063 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1064 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001065 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001066
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001067 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001068 V = ConstantDataArray::getString(Context, Elts,
1069 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001070 break;
1071 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001072 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1073 if (Record.empty())
1074 return Error("Invalid CST_DATA record");
1075
1076 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1077 unsigned Size = Record.size();
1078
1079 if (EltTy->isIntegerTy(8)) {
1080 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1081 if (isa<VectorType>(CurTy))
1082 V = ConstantDataVector::get(Context, Elts);
1083 else
1084 V = ConstantDataArray::get(Context, Elts);
1085 } else if (EltTy->isIntegerTy(16)) {
1086 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1087 if (isa<VectorType>(CurTy))
1088 V = ConstantDataVector::get(Context, Elts);
1089 else
1090 V = ConstantDataArray::get(Context, Elts);
1091 } else if (EltTy->isIntegerTy(32)) {
1092 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1093 if (isa<VectorType>(CurTy))
1094 V = ConstantDataVector::get(Context, Elts);
1095 else
1096 V = ConstantDataArray::get(Context, Elts);
1097 } else if (EltTy->isIntegerTy(64)) {
1098 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1099 if (isa<VectorType>(CurTy))
1100 V = ConstantDataVector::get(Context, Elts);
1101 else
1102 V = ConstantDataArray::get(Context, Elts);
1103 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001104 SmallVector<float, 16> Elts(Size);
1105 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001106 if (isa<VectorType>(CurTy))
1107 V = ConstantDataVector::get(Context, Elts);
1108 else
1109 V = ConstantDataArray::get(Context, Elts);
1110 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001111 SmallVector<double, 16> Elts(Size);
1112 std::transform(Record.begin(), Record.end(), Elts.begin(),
1113 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001114 if (isa<VectorType>(CurTy))
1115 V = ConstantDataVector::get(Context, Elts);
1116 else
1117 V = ConstantDataArray::get(Context, Elts);
1118 } else {
1119 return Error("Unknown element type in CE_DATA");
1120 }
1121 break;
1122 }
1123
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001124 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1125 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1126 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001127 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001128 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001129 } else {
1130 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1131 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001132 unsigned Flags = 0;
1133 if (Record.size() >= 4) {
1134 if (Opc == Instruction::Add ||
1135 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001136 Opc == Instruction::Mul ||
1137 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001138 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1139 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1140 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1141 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001142 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001143 Opc == Instruction::UDiv ||
1144 Opc == Instruction::LShr ||
1145 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001146 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001147 Flags |= SDivOperator::IsExact;
1148 }
1149 }
1150 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001151 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001152 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001153 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001154 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1155 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1156 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001157 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001158 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001159 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001160 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001161 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001162 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001163 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001164 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001165 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001166 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001167 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001168 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001169 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001170 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001171 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001172 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001173 if (!ElTy) return Error("Invalid CE_GEP record");
1174 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1175 }
Jay Foaddab3d292011-07-21 14:31:17 +00001176 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001177 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1178 BitCode ==
1179 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001180 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001181 }
1182 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1183 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001184 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001185 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001186 ValueList.getConstantFwdRef(Record[1],CurTy),
1187 ValueList.getConstantFwdRef(Record[2],CurTy));
1188 break;
1189 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1190 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001191 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001192 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1193 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1194 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001195 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001196 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001197 break;
1198 }
1199 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001200 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001201 if (Record.size() < 3 || OpTy == 0)
1202 return Error("Invalid CE_INSERTELT record");
1203 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1204 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1205 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001206 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001207 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001208 break;
1209 }
1210 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001211 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001212 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001213 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001214 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1215 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001216 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001217 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001218 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001219 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001220 break;
1221 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001222 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001223 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1224 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001225 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001226 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1227 return Error("Invalid CE_SHUFVEC_EX record");
1228 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1229 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001230 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001231 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001232 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001233 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001234 break;
1235 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001236 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1237 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001238 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001239 if (OpTy == 0) return Error("Invalid CE_CMP record");
1240 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1241 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1242
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001243 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001244 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001245 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001246 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001247 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001248 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001249 case bitc::CST_CODE_INLINEASM: {
1250 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1251 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001252 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001253 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001254 unsigned AsmStrSize = Record[1];
1255 if (2+AsmStrSize >= Record.size())
1256 return Error("Invalid INLINEASM record");
1257 unsigned ConstStrSize = Record[2+AsmStrSize];
1258 if (3+AsmStrSize+ConstStrSize > Record.size())
1259 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001260
Chris Lattner2bce93a2007-05-06 01:58:20 +00001261 for (unsigned i = 0; i != AsmStrSize; ++i)
1262 AsmStr += (char)Record[2+i];
1263 for (unsigned i = 0; i != ConstStrSize; ++i)
1264 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001265 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001266 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001267 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001268 break;
1269 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001270 case bitc::CST_CODE_BLOCKADDRESS:{
1271 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001272 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001273 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1274 Function *Fn =
1275 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1276 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1277
1278 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1279 Type::getInt8Ty(Context),
1280 false, GlobalValue::InternalLinkage,
1281 0, "");
1282 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1283 V = FwdRef;
1284 break;
1285 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001286 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001287
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001288 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001289 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001290 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001291
Chris Lattnerea693df2008-08-21 02:34:16 +00001292 if (NextCstNo != ValueList.size())
1293 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001294
Chris Lattnerea693df2008-08-21 02:34:16 +00001295 if (Stream.ReadBlockEnd())
1296 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001297
Chris Lattnerea693df2008-08-21 02:34:16 +00001298 // Once all the constants have been read, go through and resolve forward
1299 // references.
1300 ValueList.ResolveConstantForwardRefs();
1301 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001302}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001303
Chad Rosiercbbb0962011-12-07 21:44:12 +00001304bool BitcodeReader::ParseUseLists() {
1305 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1306 return Error("Malformed block record");
1307
1308 SmallVector<uint64_t, 64> Record;
1309
1310 // Read all the records.
1311 while (1) {
1312 unsigned Code = Stream.ReadCode();
1313 if (Code == bitc::END_BLOCK) {
1314 if (Stream.ReadBlockEnd())
1315 return Error("Error at end of use-list table block");
1316 return false;
1317 }
1318
1319 if (Code == bitc::ENTER_SUBBLOCK) {
1320 // No known subblocks, always skip them.
1321 Stream.ReadSubBlockID();
1322 if (Stream.SkipBlock())
1323 return Error("Malformed block record");
1324 continue;
1325 }
1326
1327 if (Code == bitc::DEFINE_ABBREV) {
1328 Stream.ReadAbbrevRecord();
1329 continue;
1330 }
1331
1332 // Read a use list record.
1333 Record.clear();
1334 switch (Stream.ReadRecord(Code, Record)) {
1335 default: // Default behavior: unknown type.
1336 break;
1337 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1338 unsigned RecordLength = Record.size();
1339 if (RecordLength < 1)
1340 return Error ("Invalid UseList reader!");
1341 UseListRecords.push_back(Record);
1342 break;
1343 }
1344 }
1345 }
1346}
1347
Chris Lattner980e5aa2007-05-01 05:52:21 +00001348/// RememberAndSkipFunctionBody - When we see the block for a function body,
1349/// remember where it is and then skip it. This lets us lazily deserialize the
1350/// functions.
1351bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001352 // Get the function we are talking about.
1353 if (FunctionsWithBodies.empty())
1354 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001355
Chris Lattner48f84872007-05-01 04:59:48 +00001356 Function *Fn = FunctionsWithBodies.back();
1357 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001358
Chris Lattner48f84872007-05-01 04:59:48 +00001359 // Save the current stream state.
1360 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001361 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001362
Chris Lattner48f84872007-05-01 04:59:48 +00001363 // Skip over the function block for now.
1364 if (Stream.SkipBlock())
1365 return Error("Malformed block record");
1366 return false;
1367}
1368
Derek Schuff2ea93872012-02-06 22:30:29 +00001369bool BitcodeReader::GlobalCleanup() {
1370 // Patch the initializers for globals and aliases up.
1371 ResolveGlobalAndAliasInits();
1372 if (!GlobalInits.empty() || !AliasInits.empty())
1373 return Error("Malformed global initializer set");
1374
1375 // Look for intrinsic functions which need to be upgraded at some point
1376 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1377 FI != FE; ++FI) {
1378 Function *NewFn;
1379 if (UpgradeIntrinsicFunction(FI, NewFn))
1380 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1381 }
1382
1383 // Look for global variables which need to be renamed.
1384 for (Module::global_iterator
1385 GI = TheModule->global_begin(), GE = TheModule->global_end();
1386 GI != GE; ++GI)
1387 UpgradeGlobalVariable(GI);
1388 // Force deallocation of memory for these vectors to favor the client that
1389 // want lazy deserialization.
1390 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1391 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1392 return false;
1393}
1394
1395bool BitcodeReader::ParseModule(bool Resume) {
1396 if (Resume)
1397 Stream.JumpToBit(NextUnreadBit);
1398 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001399 return Error("Malformed block record");
1400
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001401 SmallVector<uint64_t, 64> Record;
1402 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001403 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001404
1405 // Read all the records for this module.
1406 while (!Stream.AtEndOfStream()) {
1407 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001408 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001409 if (Stream.ReadBlockEnd())
1410 return Error("Error at end of module block");
1411
Derek Schuff2ea93872012-02-06 22:30:29 +00001412 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001413 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001414
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001415 if (Code == bitc::ENTER_SUBBLOCK) {
1416 switch (Stream.ReadSubBlockID()) {
1417 default: // Skip unknown content.
1418 if (Stream.SkipBlock())
1419 return Error("Malformed block record");
1420 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001421 case bitc::BLOCKINFO_BLOCK_ID:
1422 if (Stream.ReadBlockInfoBlock())
1423 return Error("Malformed BlockInfoBlock");
1424 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001425 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001426 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001427 return true;
1428 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001429 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001430 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001431 return true;
1432 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001433 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001434 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001435 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001436 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001437 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001438 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001439 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001440 return true;
1441 break;
Devang Patele54abc92009-07-22 17:43:22 +00001442 case bitc::METADATA_BLOCK_ID:
1443 if (ParseMetadata())
1444 return true;
1445 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001446 case bitc::FUNCTION_BLOCK_ID:
1447 // If this is the first function body we've seen, reverse the
1448 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001449 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001450 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001451 if (GlobalCleanup())
1452 return true;
1453 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001455
Chris Lattner980e5aa2007-05-01 05:52:21 +00001456 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001457 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001458 // For streaming bitcode, suspend parsing when we reach the function
1459 // bodies. Subsequent materialization calls will resume it when
1460 // necessary. For streaming, the function bodies must be at the end of
1461 // the bitcode. If the bitcode file is old, the symbol table will be
1462 // at the end instead and will not have been seen yet. In this case,
1463 // just finish the parse now.
1464 if (LazyStreamer && SeenValueSymbolTable) {
1465 NextUnreadBit = Stream.GetCurrentBitNo();
1466 return false;
1467 }
Chris Lattner48f84872007-05-01 04:59:48 +00001468 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001469 case bitc::USELIST_BLOCK_ID:
1470 if (ParseUseLists())
1471 return true;
1472 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001473 }
1474 continue;
1475 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001476
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001477 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001478 Stream.ReadAbbrevRecord();
1479 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001480 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001481
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001482 // Read a record.
1483 switch (Stream.ReadRecord(Code, Record)) {
1484 default: break; // Default behavior, ignore unknown content.
1485 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1486 if (Record.size() < 1)
1487 return Error("Malformed MODULE_CODE_VERSION");
1488 // Only version #0 is supported so far.
1489 if (Record[0] != 0)
1490 return Error("Unknown bitstream version!");
1491 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001492 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001493 std::string S;
1494 if (ConvertToString(Record, 0, S))
1495 return Error("Invalid MODULE_CODE_TRIPLE record");
1496 TheModule->setTargetTriple(S);
1497 break;
1498 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001499 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001500 std::string S;
1501 if (ConvertToString(Record, 0, S))
1502 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1503 TheModule->setDataLayout(S);
1504 break;
1505 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001506 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001507 std::string S;
1508 if (ConvertToString(Record, 0, S))
1509 return Error("Invalid MODULE_CODE_ASM record");
1510 TheModule->setModuleInlineAsm(S);
1511 break;
1512 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001513 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001514 std::string S;
1515 if (ConvertToString(Record, 0, S))
1516 return Error("Invalid MODULE_CODE_DEPLIB record");
1517 TheModule->addLibrary(S);
1518 break;
1519 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001520 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001521 std::string S;
1522 if (ConvertToString(Record, 0, S))
1523 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1524 SectionTable.push_back(S);
1525 break;
1526 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001527 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001528 std::string S;
1529 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001530 return Error("Invalid MODULE_CODE_GCNAME record");
1531 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001532 break;
1533 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001534 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001535 // linkage, alignment, section, visibility, threadlocal,
1536 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001537 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001538 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001539 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001540 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001541 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001542 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001543 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001544 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001545 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001546
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001547 bool isConstant = Record[1];
1548 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1549 unsigned Alignment = (1 << Record[4]) >> 1;
1550 std::string Section;
1551 if (Record[5]) {
1552 if (Record[5]-1 >= SectionTable.size())
1553 return Error("Invalid section ID");
1554 Section = SectionTable[Record[5]-1];
1555 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001556 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001557 if (Record.size() > 6)
1558 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001559 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001560 if (Record.size() > 7)
1561 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001562
Rafael Espindolabea46262011-01-08 16:42:36 +00001563 bool UnnamedAddr = false;
1564 if (Record.size() > 8)
1565 UnnamedAddr = Record[8];
1566
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001567 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001568 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001569 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001570 NewGV->setAlignment(Alignment);
1571 if (!Section.empty())
1572 NewGV->setSection(Section);
1573 NewGV->setVisibility(Visibility);
1574 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001575 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001576
Chris Lattner0b2482a2007-04-23 21:26:05 +00001577 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001578
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001579 // Remember which value to use for the global initializer.
1580 if (unsigned InitID = Record[2])
1581 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001582 break;
1583 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001584 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001585 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001586 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001587 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001588 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001589 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001590 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001591 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001592 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001593 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1595 if (!FTy)
1596 return Error("Function not a pointer to function type!");
1597
Gabor Greif051a9502008-04-06 20:25:17 +00001598 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1599 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001600
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001601 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001602 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001603 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001604 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001605
Chris Lattnera9bb7132007-05-08 05:38:01 +00001606 Func->setAlignment((1 << Record[5]) >> 1);
1607 if (Record[6]) {
1608 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001609 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001610 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001611 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001612 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001613 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001614 if (Record[8]-1 > GCTable.size())
1615 return Error("Invalid GC ID");
1616 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001617 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001618 bool UnnamedAddr = false;
1619 if (Record.size() > 9)
1620 UnnamedAddr = Record[9];
1621 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001622 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001623
Chris Lattner48f84872007-05-01 04:59:48 +00001624 // If this is a function with a body, remember the prototype we are
1625 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001626 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001627 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001628 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1629 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001630 break;
1631 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001632 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001633 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001634 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001635 if (Record.size() < 3)
1636 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001637 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001638 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001639 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001640 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001641
Chris Lattner07d98b42007-04-26 02:46:40 +00001642 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1643 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001644 // Old bitcode files didn't have visibility field.
1645 if (Record.size() > 3)
1646 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001647 ValueList.push_back(NewGA);
1648 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1649 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001650 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001651 /// MODULE_CODE_PURGEVALS: [numvals]
1652 case bitc::MODULE_CODE_PURGEVALS:
1653 // Trim down the value list to the specified size.
1654 if (Record.size() < 1 || Record[0] > ValueList.size())
1655 return Error("Invalid MODULE_PURGEVALS record");
1656 ValueList.shrinkTo(Record[0]);
1657 break;
1658 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001659 Record.clear();
1660 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001661
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001662 return Error("Premature end of bitstream");
1663}
1664
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001665bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001666 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001667
Derek Schuff2ea93872012-02-06 22:30:29 +00001668 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001669
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001670 // Sniff for the signature.
1671 if (Stream.Read(8) != 'B' ||
1672 Stream.Read(8) != 'C' ||
1673 Stream.Read(4) != 0x0 ||
1674 Stream.Read(4) != 0xC ||
1675 Stream.Read(4) != 0xE ||
1676 Stream.Read(4) != 0xD)
1677 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001678
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001679 // We expect a number of well-defined blocks, though we don't necessarily
1680 // need to understand them all.
1681 while (!Stream.AtEndOfStream()) {
1682 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001683
Rafael Espindolac9687b32011-05-26 18:59:54 +00001684 if (Code != bitc::ENTER_SUBBLOCK) {
1685
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001686 // The ranlib in xcode 4 will align archive members by appending newlines
1687 // to the end of them. If this file size is a multiple of 4 but not 8, we
1688 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001689 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1690 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1691 Stream.AtEndOfStream())
1692 return false;
1693
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001694 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001695 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001696
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001697 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001698
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001699 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001700 switch (BlockID) {
1701 case bitc::BLOCKINFO_BLOCK_ID:
1702 if (Stream.ReadBlockInfoBlock())
1703 return Error("Malformed BlockInfoBlock");
1704 break;
1705 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001706 // Reject multiple MODULE_BLOCK's in a single bitstream.
1707 if (TheModule)
1708 return Error("Multiple MODULE_BLOCKs in same stream");
1709 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001710 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001711 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001712 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001713 break;
1714 default:
1715 if (Stream.SkipBlock())
1716 return Error("Malformed block record");
1717 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001718 }
1719 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001721 return false;
1722}
Chris Lattnerc453f762007-04-29 07:54:31 +00001723
Bill Wendling34711742010-10-06 01:22:42 +00001724bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1725 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1726 return Error("Malformed block record");
1727
1728 SmallVector<uint64_t, 64> Record;
1729
1730 // Read all the records for this module.
1731 while (!Stream.AtEndOfStream()) {
1732 unsigned Code = Stream.ReadCode();
1733 if (Code == bitc::END_BLOCK) {
1734 if (Stream.ReadBlockEnd())
1735 return Error("Error at end of module block");
1736
1737 return false;
1738 }
1739
1740 if (Code == bitc::ENTER_SUBBLOCK) {
1741 switch (Stream.ReadSubBlockID()) {
1742 default: // Skip unknown content.
1743 if (Stream.SkipBlock())
1744 return Error("Malformed block record");
1745 break;
1746 }
1747 continue;
1748 }
1749
1750 if (Code == bitc::DEFINE_ABBREV) {
1751 Stream.ReadAbbrevRecord();
1752 continue;
1753 }
1754
1755 // Read a record.
1756 switch (Stream.ReadRecord(Code, Record)) {
1757 default: break; // Default behavior, ignore unknown content.
1758 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1759 if (Record.size() < 1)
1760 return Error("Malformed MODULE_CODE_VERSION");
1761 // Only version #0 is supported so far.
1762 if (Record[0] != 0)
1763 return Error("Unknown bitstream version!");
1764 break;
1765 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1766 std::string S;
1767 if (ConvertToString(Record, 0, S))
1768 return Error("Invalid MODULE_CODE_TRIPLE record");
1769 Triple = S;
1770 break;
1771 }
1772 }
1773 Record.clear();
1774 }
1775
1776 return Error("Premature end of bitstream");
1777}
1778
1779bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001780 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001781
1782 // Sniff for the signature.
1783 if (Stream.Read(8) != 'B' ||
1784 Stream.Read(8) != 'C' ||
1785 Stream.Read(4) != 0x0 ||
1786 Stream.Read(4) != 0xC ||
1787 Stream.Read(4) != 0xE ||
1788 Stream.Read(4) != 0xD)
1789 return Error("Invalid bitcode signature");
1790
1791 // We expect a number of well-defined blocks, though we don't necessarily
1792 // need to understand them all.
1793 while (!Stream.AtEndOfStream()) {
1794 unsigned Code = Stream.ReadCode();
1795
1796 if (Code != bitc::ENTER_SUBBLOCK)
1797 return Error("Invalid record at top-level");
1798
1799 unsigned BlockID = Stream.ReadSubBlockID();
1800
1801 // We only know the MODULE subblock ID.
1802 switch (BlockID) {
1803 case bitc::MODULE_BLOCK_ID:
1804 if (ParseModuleTriple(Triple))
1805 return true;
1806 break;
1807 default:
1808 if (Stream.SkipBlock())
1809 return Error("Malformed block record");
1810 break;
1811 }
1812 }
1813
1814 return false;
1815}
1816
Devang Patele8e02132009-09-18 19:26:43 +00001817/// ParseMetadataAttachment - Parse metadata attachments.
1818bool BitcodeReader::ParseMetadataAttachment() {
1819 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1820 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001821
Devang Patele8e02132009-09-18 19:26:43 +00001822 SmallVector<uint64_t, 64> Record;
1823 while(1) {
1824 unsigned Code = Stream.ReadCode();
1825 if (Code == bitc::END_BLOCK) {
1826 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001827 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001828 break;
1829 }
1830 if (Code == bitc::DEFINE_ABBREV) {
1831 Stream.ReadAbbrevRecord();
1832 continue;
1833 }
1834 // Read a metadata attachment record.
1835 Record.clear();
1836 switch (Stream.ReadRecord(Code, Record)) {
1837 default: // Default behavior: ignore.
1838 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001839 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001840 unsigned RecordLength = Record.size();
1841 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001842 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001843 Instruction *Inst = InstructionList[Record[0]];
1844 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001845 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001846 DenseMap<unsigned, unsigned>::iterator I =
1847 MDKindMap.find(Kind);
1848 if (I == MDKindMap.end())
1849 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001850 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001851 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001852 }
1853 break;
1854 }
1855 }
1856 }
1857 return false;
1858}
Chris Lattner48f84872007-05-01 04:59:48 +00001859
Chris Lattner980e5aa2007-05-01 05:52:21 +00001860/// ParseFunctionBody - Lazily parse the specified function body block.
1861bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001862 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001863 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001864
Nick Lewycky9a49f152010-02-25 08:30:17 +00001865 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001866 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001867 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001868
Chris Lattner980e5aa2007-05-01 05:52:21 +00001869 // Add all the function arguments to the value table.
1870 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1871 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001872
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001873 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001874 BasicBlock *CurBB = 0;
1875 unsigned CurBBNo = 0;
1876
Chris Lattnera6245242010-04-03 02:17:50 +00001877 DebugLoc LastLoc;
1878
Chris Lattner980e5aa2007-05-01 05:52:21 +00001879 // Read all the records.
1880 SmallVector<uint64_t, 64> Record;
1881 while (1) {
1882 unsigned Code = Stream.ReadCode();
1883 if (Code == bitc::END_BLOCK) {
1884 if (Stream.ReadBlockEnd())
1885 return Error("Error at end of function block");
1886 break;
1887 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001888
Chris Lattner980e5aa2007-05-01 05:52:21 +00001889 if (Code == bitc::ENTER_SUBBLOCK) {
1890 switch (Stream.ReadSubBlockID()) {
1891 default: // Skip unknown content.
1892 if (Stream.SkipBlock())
1893 return Error("Malformed block record");
1894 break;
1895 case bitc::CONSTANTS_BLOCK_ID:
1896 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001897 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001898 break;
1899 case bitc::VALUE_SYMTAB_BLOCK_ID:
1900 if (ParseValueSymbolTable()) return true;
1901 break;
Devang Patele8e02132009-09-18 19:26:43 +00001902 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001903 if (ParseMetadataAttachment()) return true;
1904 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001905 case bitc::METADATA_BLOCK_ID:
1906 if (ParseMetadata()) return true;
1907 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001908 }
1909 continue;
1910 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001911
Chris Lattner980e5aa2007-05-01 05:52:21 +00001912 if (Code == bitc::DEFINE_ABBREV) {
1913 Stream.ReadAbbrevRecord();
1914 continue;
1915 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Chris Lattner980e5aa2007-05-01 05:52:21 +00001917 // Read a record.
1918 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001919 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001920 unsigned BitCode = Stream.ReadRecord(Code, Record);
1921 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001922 default: // Default behavior: reject
1923 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001924 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001925 if (Record.size() < 1 || Record[0] == 0)
1926 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001927 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001928 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001929 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001930 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001931 CurBB = FunctionBBs[0];
1932 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001933
1934 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1935 // This record indicates that the last instruction is at the same
1936 // location as the previous instruction with a location.
1937 I = 0;
1938
1939 // Get the last instruction emitted.
1940 if (CurBB && !CurBB->empty())
1941 I = &CurBB->back();
1942 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1943 !FunctionBBs[CurBBNo-1]->empty())
1944 I = &FunctionBBs[CurBBNo-1]->back();
1945
1946 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1947 I->setDebugLoc(LastLoc);
1948 I = 0;
1949 continue;
1950
Chris Lattner4f6bab92011-06-17 18:17:37 +00001951 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001952 I = 0; // Get the last instruction emitted.
1953 if (CurBB && !CurBB->empty())
1954 I = &CurBB->back();
1955 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1956 !FunctionBBs[CurBBNo-1]->empty())
1957 I = &FunctionBBs[CurBBNo-1]->back();
1958 if (I == 0 || Record.size() < 4)
1959 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1960
1961 unsigned Line = Record[0], Col = Record[1];
1962 unsigned ScopeID = Record[2], IAID = Record[3];
1963
1964 MDNode *Scope = 0, *IA = 0;
1965 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1966 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1967 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1968 I->setDebugLoc(LastLoc);
1969 I = 0;
1970 continue;
1971 }
1972
Chris Lattnerabfbf852007-05-06 00:21:25 +00001973 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1974 unsigned OpNum = 0;
1975 Value *LHS, *RHS;
1976 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1977 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001978 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001979 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001980
Dan Gohman1224c382009-07-20 21:19:07 +00001981 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001982 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001983 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001984 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001985 if (OpNum < Record.size()) {
1986 if (Opc == Instruction::Add ||
1987 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001988 Opc == Instruction::Mul ||
1989 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00001990 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001991 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00001992 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001993 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00001994 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001995 Opc == Instruction::UDiv ||
1996 Opc == Instruction::LShr ||
1997 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001998 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001999 cast<BinaryOperator>(I)->setIsExact(true);
2000 }
2001 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002002 break;
2003 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002004 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2005 unsigned OpNum = 0;
2006 Value *Op;
2007 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2008 OpNum+2 != Record.size())
2009 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002010
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002011 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002012 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2013 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002014 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002015 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002016 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002017 break;
2018 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002019 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002020 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002021 unsigned OpNum = 0;
2022 Value *BasePtr;
2023 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002024 return Error("Invalid GEP record");
2025
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002026 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002027 while (OpNum != Record.size()) {
2028 Value *Op;
2029 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002030 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002031 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002032 }
2033
Jay Foada9203102011-07-25 09:48:08 +00002034 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002035 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002036 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002037 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002038 break;
2039 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002040
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002041 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2042 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002043 unsigned OpNum = 0;
2044 Value *Agg;
2045 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2046 return Error("Invalid EXTRACTVAL record");
2047
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002048 SmallVector<unsigned, 4> EXTRACTVALIdx;
2049 for (unsigned RecSize = Record.size();
2050 OpNum != RecSize; ++OpNum) {
2051 uint64_t Index = Record[OpNum];
2052 if ((unsigned)Index != Index)
2053 return Error("Invalid EXTRACTVAL index");
2054 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002055 }
2056
Jay Foadfc6d3a42011-07-13 10:26:04 +00002057 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002058 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002059 break;
2060 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002061
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002062 case bitc::FUNC_CODE_INST_INSERTVAL: {
2063 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002064 unsigned OpNum = 0;
2065 Value *Agg;
2066 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2067 return Error("Invalid INSERTVAL record");
2068 Value *Val;
2069 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2070 return Error("Invalid INSERTVAL record");
2071
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002072 SmallVector<unsigned, 4> INSERTVALIdx;
2073 for (unsigned RecSize = Record.size();
2074 OpNum != RecSize; ++OpNum) {
2075 uint64_t Index = Record[OpNum];
2076 if ((unsigned)Index != Index)
2077 return Error("Invalid INSERTVAL index");
2078 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002079 }
2080
Jay Foadfc6d3a42011-07-13 10:26:04 +00002081 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002082 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002083 break;
2084 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002085
Chris Lattnerabfbf852007-05-06 00:21:25 +00002086 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002087 // obsolete form of select
2088 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002089 unsigned OpNum = 0;
2090 Value *TrueVal, *FalseVal, *Cond;
2091 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2092 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002093 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002094 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002095
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002096 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002097 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002098 break;
2099 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002100
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002101 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2102 // new form of select
2103 // handles select i1 or select [N x i1]
2104 unsigned OpNum = 0;
2105 Value *TrueVal, *FalseVal, *Cond;
2106 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2107 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2108 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2109 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002110
2111 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002112 if (VectorType* vector_type =
2113 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002114 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002115 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002116 return Error("Invalid SELECT condition type");
2117 } else {
2118 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002119 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002120 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002121 }
2122
Gabor Greif051a9502008-04-06 20:25:17 +00002123 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002124 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002125 break;
2126 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002127
Chris Lattner01ff65f2007-05-02 05:16:49 +00002128 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002129 unsigned OpNum = 0;
2130 Value *Vec, *Idx;
2131 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002132 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002133 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002134 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002135 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002136 break;
2137 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002138
Chris Lattner01ff65f2007-05-02 05:16:49 +00002139 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002140 unsigned OpNum = 0;
2141 Value *Vec, *Elt, *Idx;
2142 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002143 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002144 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002145 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002146 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002147 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002148 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002149 break;
2150 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002151
Chris Lattnerabfbf852007-05-06 00:21:25 +00002152 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2153 unsigned OpNum = 0;
2154 Value *Vec1, *Vec2, *Mask;
2155 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2156 getValue(Record, OpNum, Vec1->getType(), Vec2))
2157 return Error("Invalid SHUFFLEVEC record");
2158
Mon P Wangaeb06d22008-11-10 04:46:22 +00002159 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002160 return Error("Invalid SHUFFLEVEC record");
2161 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002162 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002163 break;
2164 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002165
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002166 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2167 // Old form of ICmp/FCmp returning bool
2168 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2169 // both legal on vectors but had different behaviour.
2170 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2171 // FCmp/ICmp returning bool or vector of bool
2172
Chris Lattner7337ab92007-05-06 00:00:00 +00002173 unsigned OpNum = 0;
2174 Value *LHS, *RHS;
2175 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2176 getValue(Record, OpNum, LHS->getType(), RHS) ||
2177 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002178 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002179
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002180 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002181 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002182 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002183 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002184 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002185 break;
2186 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002187
Chris Lattner231cbcb2007-05-02 04:27:25 +00002188 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002189 {
2190 unsigned Size = Record.size();
2191 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002192 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002193 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002194 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002195 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002196
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002197 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002198 Value *Op = NULL;
2199 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2200 return Error("Invalid RET record");
2201 if (OpNum != Record.size())
2202 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002203
Chris Lattner96a74c52011-06-17 18:09:11 +00002204 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002205 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002206 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002207 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002208 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002209 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002210 return Error("Invalid BR record");
2211 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2212 if (TrueDest == 0)
2213 return Error("Invalid BR record");
2214
Devang Patele8e02132009-09-18 19:26:43 +00002215 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002216 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002217 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002218 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002219 else {
2220 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002221 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002222 if (FalseDest == 0 || Cond == 0)
2223 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002224 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002225 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002226 }
2227 break;
2228 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002229 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002230 // Check magic
2231 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2232 // New SwitchInst format with case ranges.
2233
2234 Type *OpTy = getTypeByID(Record[1]);
2235 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2236
2237 Value *Cond = getFnValueByID(Record[2], OpTy);
2238 BasicBlock *Default = getBasicBlock(Record[3]);
2239 if (OpTy == 0 || Cond == 0 || Default == 0)
2240 return Error("Invalid SWITCH record");
2241
2242 unsigned NumCases = Record[4];
2243
2244 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2245 InstructionList.push_back(SI);
2246
2247 unsigned CurIdx = 5;
2248 for (unsigned i = 0; i != NumCases; ++i) {
2249 CRSBuilder CaseBuilder;
2250 unsigned NumItems = Record[CurIdx++];
2251 for (unsigned ci = 0; ci != NumItems; ++ci) {
2252 bool isSingleNumber = Record[CurIdx++];
2253
2254 APInt Low;
2255 unsigned ActiveWords = 1;
2256 if (ValueBitWidth > 64)
2257 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002258 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2259 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002260 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002261
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002262 if (!isSingleNumber) {
2263 ActiveWords = 1;
2264 if (ValueBitWidth > 64)
2265 ActiveWords = Record[CurIdx++];
2266 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002267 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2268 ValueBitWidth);
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002269 IntItemConstantIntImpl HighImpl =
2270 cast<ConstantInt>(ConstantInt::get(OpTy, High));
2271
2272 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2273 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002274 CurIdx += ActiveWords;
2275 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002276 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002277 }
2278 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2279 ConstantRangesSet Case = CaseBuilder.getCase();
2280 SI->addCase(Case, DestBB);
2281 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002282 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002283 if (Hash != (Record[0] & 0xFFFF))
2284 return Error("Invalid SWITCH record");
2285 I = SI;
2286 break;
2287 }
2288
2289 // Old SwitchInst format without case ranges.
2290
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002291 if (Record.size() < 3 || (Record.size() & 1) == 0)
2292 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002293 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002294 Value *Cond = getFnValueByID(Record[1], OpTy);
2295 BasicBlock *Default = getBasicBlock(Record[2]);
2296 if (OpTy == 0 || Cond == 0 || Default == 0)
2297 return Error("Invalid SWITCH record");
2298 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002299 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002300 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002301 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002302 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002303 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2304 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2305 if (CaseVal == 0 || DestBB == 0) {
2306 delete SI;
2307 return Error("Invalid SWITCH record!");
2308 }
2309 SI->addCase(CaseVal, DestBB);
2310 }
2311 I = SI;
2312 break;
2313 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002314 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002315 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002316 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002317 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002318 Value *Address = getFnValueByID(Record[1], OpTy);
2319 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002320 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002321 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002322 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002323 InstructionList.push_back(IBI);
2324 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2325 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2326 IBI->addDestination(DestBB);
2327 } else {
2328 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002329 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002330 }
2331 }
2332 I = IBI;
2333 break;
2334 }
2335
Duncan Sandsdc024672007-11-27 13:23:08 +00002336 case bitc::FUNC_CODE_INST_INVOKE: {
2337 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002338 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002339 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002340 unsigned CCInfo = Record[1];
2341 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2342 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002343
Chris Lattnera9bb7132007-05-08 05:38:01 +00002344 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002345 Value *Callee;
2346 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002347 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002348
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002349 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2350 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002351 dyn_cast<FunctionType>(CalleeTy->getElementType());
2352
2353 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002354 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2355 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002356 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002357
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002358 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002359 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2360 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2361 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002362 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002363
Chris Lattner7337ab92007-05-06 00:00:00 +00002364 if (!FTy->isVarArg()) {
2365 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002366 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002367 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002368 // Read type/value pairs for varargs params.
2369 while (OpNum != Record.size()) {
2370 Value *Op;
2371 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2372 return Error("Invalid INVOKE record");
2373 Ops.push_back(Op);
2374 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002375 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002376
Jay Foada3efbb12011-07-15 08:37:34 +00002377 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002378 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002379 cast<InvokeInst>(I)->setCallingConv(
2380 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002381 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002382 break;
2383 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002384 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2385 unsigned Idx = 0;
2386 Value *Val = 0;
2387 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2388 return Error("Invalid RESUME record");
2389 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002390 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002391 break;
2392 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002393 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002394 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002395 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002396 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002397 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002398 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002399 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002400 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002401 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002402
Jay Foad3ecfc862011-03-30 11:28:46 +00002403 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002404 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002405
Chris Lattner15e6d172007-05-04 19:11:41 +00002406 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2407 Value *V = getFnValueByID(Record[1+i], Ty);
2408 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002409 if (!V || !BB) return Error("Invalid PHI record");
2410 PN->addIncoming(V, BB);
2411 }
2412 I = PN;
2413 break;
2414 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002415
Bill Wendlinge6e88262011-08-12 20:24:12 +00002416 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2417 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2418 unsigned Idx = 0;
2419 if (Record.size() < 4)
2420 return Error("Invalid LANDINGPAD record");
2421 Type *Ty = getTypeByID(Record[Idx++]);
2422 if (!Ty) return Error("Invalid LANDINGPAD record");
2423 Value *PersFn = 0;
2424 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2425 return Error("Invalid LANDINGPAD record");
2426
2427 bool IsCleanup = !!Record[Idx++];
2428 unsigned NumClauses = Record[Idx++];
2429 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2430 LP->setCleanup(IsCleanup);
2431 for (unsigned J = 0; J != NumClauses; ++J) {
2432 LandingPadInst::ClauseType CT =
2433 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2434 Value *Val;
2435
2436 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2437 delete LP;
2438 return Error("Invalid LANDINGPAD record");
2439 }
2440
2441 assert((CT != LandingPadInst::Catch ||
2442 !isa<ArrayType>(Val->getType())) &&
2443 "Catch clause has a invalid type!");
2444 assert((CT != LandingPadInst::Filter ||
2445 isa<ArrayType>(Val->getType())) &&
2446 "Filter clause has invalid type!");
2447 LP->addClause(Val);
2448 }
2449
2450 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002451 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002452 break;
2453 }
2454
Chris Lattner96a74c52011-06-17 18:09:11 +00002455 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2456 if (Record.size() != 4)
2457 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002458 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002459 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002460 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002461 Value *Size = getFnValueByID(Record[2], OpTy);
2462 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002463 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002464 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002465 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002466 break;
2467 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002468 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002469 unsigned OpNum = 0;
2470 Value *Op;
2471 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2472 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002473 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002474
Chris Lattner7337ab92007-05-06 00:00:00 +00002475 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002476 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002477 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002478 }
Eli Friedman21006d42011-08-09 23:02:53 +00002479 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2480 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2481 unsigned OpNum = 0;
2482 Value *Op;
2483 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2484 OpNum+4 != Record.size())
2485 return Error("Invalid LOADATOMIC record");
2486
2487
2488 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2489 if (Ordering == NotAtomic || Ordering == Release ||
2490 Ordering == AcquireRelease)
2491 return Error("Invalid LOADATOMIC record");
2492 if (Ordering != NotAtomic && Record[OpNum] == 0)
2493 return Error("Invalid LOADATOMIC record");
2494 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2495
2496 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2497 Ordering, SynchScope);
2498 InstructionList.push_back(I);
2499 break;
2500 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002501 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002502 unsigned OpNum = 0;
2503 Value *Val, *Ptr;
2504 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002505 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002506 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2507 OpNum+2 != Record.size())
2508 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002509
Christopher Lambfe63fb92007-12-11 08:59:05 +00002510 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002511 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002512 break;
2513 }
Eli Friedman21006d42011-08-09 23:02:53 +00002514 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2515 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2516 unsigned OpNum = 0;
2517 Value *Val, *Ptr;
2518 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2519 getValue(Record, OpNum,
2520 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2521 OpNum+4 != Record.size())
2522 return Error("Invalid STOREATOMIC record");
2523
2524 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002525 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002526 Ordering == AcquireRelease)
2527 return Error("Invalid STOREATOMIC record");
2528 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2529 if (Ordering != NotAtomic && Record[OpNum] == 0)
2530 return Error("Invalid STOREATOMIC record");
2531
2532 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2533 Ordering, SynchScope);
2534 InstructionList.push_back(I);
2535 break;
2536 }
Eli Friedmanff030482011-07-28 21:48:00 +00002537 case bitc::FUNC_CODE_INST_CMPXCHG: {
2538 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2539 unsigned OpNum = 0;
2540 Value *Ptr, *Cmp, *New;
2541 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2542 getValue(Record, OpNum,
2543 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2544 getValue(Record, OpNum,
2545 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2546 OpNum+3 != Record.size())
2547 return Error("Invalid CMPXCHG record");
2548 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002549 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002550 return Error("Invalid CMPXCHG record");
2551 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2552 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2553 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2554 InstructionList.push_back(I);
2555 break;
2556 }
2557 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2558 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2559 unsigned OpNum = 0;
2560 Value *Ptr, *Val;
2561 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2562 getValue(Record, OpNum,
2563 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2564 OpNum+4 != Record.size())
2565 return Error("Invalid ATOMICRMW record");
2566 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2567 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2568 Operation > AtomicRMWInst::LAST_BINOP)
2569 return Error("Invalid ATOMICRMW record");
2570 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002571 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002572 return Error("Invalid ATOMICRMW record");
2573 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2574 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2575 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2576 InstructionList.push_back(I);
2577 break;
2578 }
Eli Friedman47f35132011-07-25 23:16:38 +00002579 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2580 if (2 != Record.size())
2581 return Error("Invalid FENCE record");
2582 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2583 if (Ordering == NotAtomic || Ordering == Unordered ||
2584 Ordering == Monotonic)
2585 return Error("Invalid FENCE record");
2586 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2587 I = new FenceInst(Context, Ordering, SynchScope);
2588 InstructionList.push_back(I);
2589 break;
2590 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002591 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002592 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2593 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002594 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002595
Devang Patel05988662008-09-25 21:00:45 +00002596 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002597 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002598
Chris Lattnera9bb7132007-05-08 05:38:01 +00002599 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002600 Value *Callee;
2601 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2602 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002603
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002604 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2605 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002606 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002607 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002608 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002609
Chris Lattner0579f7f2007-05-03 22:04:19 +00002610 SmallVector<Value*, 16> Args;
2611 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002612 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002613 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002614 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002615 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002616 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002617 if (Args.back() == 0) return Error("Invalid CALL record");
2618 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002619
Chris Lattner0579f7f2007-05-03 22:04:19 +00002620 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002621 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002622 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002623 return Error("Invalid CALL record");
2624 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002625 while (OpNum != Record.size()) {
2626 Value *Op;
2627 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2628 return Error("Invalid CALL record");
2629 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002630 }
2631 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Jay Foada3efbb12011-07-15 08:37:34 +00002633 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002634 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002635 cast<CallInst>(I)->setCallingConv(
2636 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002637 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002638 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002639 break;
2640 }
2641 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2642 if (Record.size() < 3)
2643 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002644 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002645 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002646 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002647 if (!OpTy || !Op || !ResTy)
2648 return Error("Invalid VAARG record");
2649 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002650 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002651 break;
2652 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002653 }
2654
2655 // Add instruction to end of current BB. If there is no current BB, reject
2656 // this file.
2657 if (CurBB == 0) {
2658 delete I;
2659 return Error("Invalid instruction with no BB");
2660 }
2661 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002662
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002663 // If this was a terminator instruction, move to the next block.
2664 if (isa<TerminatorInst>(I)) {
2665 ++CurBBNo;
2666 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2667 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002668
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002669 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002670 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002671 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002672 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002673
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002674 // Check the function list for unresolved values.
2675 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2676 if (A->getParent() == 0) {
2677 // We found at least one unresolved value. Nuke them all to avoid leaks.
2678 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002679 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002680 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002681 delete A;
2682 }
2683 }
Chris Lattner35a04702007-05-04 03:50:29 +00002684 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002685 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002686 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002687
Dan Gohman064ff3e2010-08-25 20:23:38 +00002688 // FIXME: Check for unresolved forward-declared metadata references
2689 // and clean up leaks.
2690
Chris Lattner50b136d2009-10-28 05:53:48 +00002691 // See if anything took the address of blocks in this function. If so,
2692 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002693 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2694 BlockAddrFwdRefs.find(F);
2695 if (BAFRI != BlockAddrFwdRefs.end()) {
2696 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2697 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2698 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002699 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002700 return Error("Invalid blockaddress block #");
2701
2702 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002703 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002704 FwdRef->eraseFromParent();
2705 }
2706
2707 BlockAddrFwdRefs.erase(BAFRI);
2708 }
2709
Chris Lattner980e5aa2007-05-01 05:52:21 +00002710 // Trim the value list down to the size it was before we parsed this function.
2711 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002712 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002713 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002714 return false;
2715}
2716
Derek Schuff2ea93872012-02-06 22:30:29 +00002717/// FindFunctionInStream - Find the function body in the bitcode stream
2718bool BitcodeReader::FindFunctionInStream(Function *F,
2719 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2720 while (DeferredFunctionInfoIterator->second == 0) {
2721 if (Stream.AtEndOfStream())
2722 return Error("Could not find Function in stream");
2723 // ParseModule will parse the next body in the stream and set its
2724 // position in the DeferredFunctionInfo map.
2725 if (ParseModule(true)) return true;
2726 }
2727 return false;
2728}
2729
Chris Lattnerb348bb82007-05-18 04:02:46 +00002730//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002731// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002732//===----------------------------------------------------------------------===//
2733
2734
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002735bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2736 if (const Function *F = dyn_cast<Function>(GV)) {
2737 return F->isDeclaration() &&
2738 DeferredFunctionInfo.count(const_cast<Function*>(F));
2739 }
2740 return false;
2741}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002742
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002743bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2744 Function *F = dyn_cast<Function>(GV);
2745 // If it's not a function or is already material, ignore the request.
2746 if (!F || !F->isMaterializable()) return false;
2747
2748 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002749 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002750 // If its position is recorded as 0, its body is somewhere in the stream
2751 // but we haven't seen it yet.
2752 if (DFII->second == 0)
2753 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002754
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002755 // Move the bit stream to the saved position of the deferred function body.
2756 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002757
Chris Lattnerb348bb82007-05-18 04:02:46 +00002758 if (ParseFunctionBody(F)) {
2759 if (ErrInfo) *ErrInfo = ErrorString;
2760 return true;
2761 }
Chandler Carruth69940402007-08-04 01:51:18 +00002762
2763 // Upgrade any old intrinsic calls in the function.
2764 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2765 E = UpgradedIntrinsics.end(); I != E; ++I) {
2766 if (I->first != I->second) {
2767 for (Value::use_iterator UI = I->first->use_begin(),
2768 UE = I->first->use_end(); UI != UE; ) {
2769 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2770 UpgradeIntrinsicCall(CI, I->second);
2771 }
2772 }
2773 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002774
Chris Lattnerb348bb82007-05-18 04:02:46 +00002775 return false;
2776}
2777
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002778bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2779 const Function *F = dyn_cast<Function>(GV);
2780 if (!F || F->isDeclaration())
2781 return false;
2782 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2783}
2784
2785void BitcodeReader::Dematerialize(GlobalValue *GV) {
2786 Function *F = dyn_cast<Function>(GV);
2787 // If this function isn't dematerializable, this is a noop.
2788 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002789 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002790
Chris Lattnerb348bb82007-05-18 04:02:46 +00002791 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002792
Chris Lattnerb348bb82007-05-18 04:02:46 +00002793 // Just forget the function body, we can remat it later.
2794 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002795}
2796
2797
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002798bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2799 assert(M == TheModule &&
2800 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002801 // Iterate over the module, deserializing any functions that are still on
2802 // disk.
2803 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2804 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002805 if (F->isMaterializable() &&
2806 Materialize(F, ErrInfo))
2807 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002808
Derek Schuff0ffe6982012-02-29 00:07:09 +00002809 // At this point, if there are any function bodies, the current bit is
2810 // pointing to the END_BLOCK record after them. Now make sure the rest
2811 // of the bits in the module have been read.
2812 if (NextUnreadBit)
2813 ParseModule(true);
2814
Daniel Dunbara279bc32009-09-20 02:20:51 +00002815 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2816 // delete the old functions to clean up. We can't do this unless the entire
2817 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002818 // with calls to the old function.
2819 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2820 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2821 if (I->first != I->second) {
2822 for (Value::use_iterator UI = I->first->use_begin(),
2823 UE = I->first->use_end(); UI != UE; ) {
2824 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2825 UpgradeIntrinsicCall(CI, I->second);
2826 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002827 if (!I->first->use_empty())
2828 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002829 I->first->eraseFromParent();
2830 }
2831 }
2832 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002833
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002834 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002835}
2836
Derek Schuff2ea93872012-02-06 22:30:29 +00002837bool BitcodeReader::InitStream() {
2838 if (LazyStreamer) return InitLazyStream();
2839 return InitStreamFromBuffer();
2840}
2841
2842bool BitcodeReader::InitStreamFromBuffer() {
2843 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2844 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2845
2846 if (Buffer->getBufferSize() & 3) {
2847 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2848 return Error("Invalid bitcode signature");
2849 else
2850 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2851 }
2852
2853 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2854 // The magic number is 0x0B17C0DE stored in little endian.
2855 if (isBitcodeWrapper(BufPtr, BufEnd))
2856 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2857 return Error("Invalid bitcode wrapper header");
2858
2859 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2860 Stream.init(*StreamFile);
2861
2862 return false;
2863}
2864
2865bool BitcodeReader::InitLazyStream() {
2866 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2867 // see it.
2868 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2869 StreamFile.reset(new BitstreamReader(Bytes));
2870 Stream.init(*StreamFile);
2871
2872 unsigned char buf[16];
2873 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2874 return Error("Bitcode stream must be at least 16 bytes in length");
2875
2876 if (!isBitcode(buf, buf + 16))
2877 return Error("Invalid bitcode signature");
2878
2879 if (isBitcodeWrapper(buf, buf + 4)) {
2880 const unsigned char *bitcodeStart = buf;
2881 const unsigned char *bitcodeEnd = buf + 16;
2882 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2883 Bytes->dropLeadingBytes(bitcodeStart - buf);
2884 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2885 }
2886 return false;
2887}
Chris Lattner48f84872007-05-01 04:59:48 +00002888
Chris Lattnerc453f762007-04-29 07:54:31 +00002889//===----------------------------------------------------------------------===//
2890// External interface
2891//===----------------------------------------------------------------------===//
2892
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002893/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002894///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002895Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2896 LLVMContext& Context,
2897 std::string *ErrMsg) {
2898 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002899 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002900 M->setMaterializer(R);
2901 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002902 if (ErrMsg)
2903 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002904
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002905 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002906 return 0;
2907 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002908 // Have the BitcodeReader dtor delete 'Buffer'.
2909 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002910
2911 R->materializeForwardReferencedFunctions();
2912
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002913 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002914}
2915
Derek Schuff2ea93872012-02-06 22:30:29 +00002916
2917Module *llvm::getStreamedBitcodeModule(const std::string &name,
2918 DataStreamer *streamer,
2919 LLVMContext &Context,
2920 std::string *ErrMsg) {
2921 Module *M = new Module(name, Context);
2922 BitcodeReader *R = new BitcodeReader(streamer, Context);
2923 M->setMaterializer(R);
2924 if (R->ParseBitcodeInto(M)) {
2925 if (ErrMsg)
2926 *ErrMsg = R->getErrorString();
2927 delete M; // Also deletes R.
2928 return 0;
2929 }
2930 R->setBufferOwned(false); // no buffer to delete
2931 return M;
2932}
2933
Chris Lattnerc453f762007-04-29 07:54:31 +00002934/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2935/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002936Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002937 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002938 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2939 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002940
2941 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2942 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002943 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002944
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002945 // Read in the entire module, and destroy the BitcodeReader.
2946 if (M->MaterializeAllPermanently(ErrMsg)) {
2947 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002948 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002949 }
Bill Wendling34711742010-10-06 01:22:42 +00002950
Chad Rosiercbbb0962011-12-07 21:44:12 +00002951 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2952 // written. We must defer until the Module has been fully materialized.
2953
Chris Lattnerc453f762007-04-29 07:54:31 +00002954 return M;
2955}
Bill Wendling34711742010-10-06 01:22:42 +00002956
2957std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2958 LLVMContext& Context,
2959 std::string *ErrMsg) {
2960 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2961 // Don't let the BitcodeReader dtor delete 'Buffer'.
2962 R->setBufferOwned(false);
2963
2964 std::string Triple("");
2965 if (R->ParseTriple(Triple))
2966 if (ErrMsg)
2967 *ErrMsg = R->getErrorString();
2968
2969 delete R;
2970 return Triple;
2971}