blob: 83756daa7ae88fece98663f7d6114a08c4dee652 [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) {
Meador Ingee99f8be2012-05-28 15:45:43 +0000466 Attributes ReconstitutedAttr =
467 Attribute::decodeLLVMAttributesForBitcode(Record[i+1]);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000468 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000469 }
Chris Lattner461edd92008-03-12 02:25:52 +0000470
Devang Patel19c87462008-09-26 22:53:05 +0000471 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nuno Lopes006c7b92012-05-08 17:07:35 +0000472 if (Attributes(Record[i+1]) != Attribute::None)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000473 Attrs.push_back(AttributeWithIndex::get(Record[i],
474 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000475 }
Devang Patel19c87462008-09-26 22:53:05 +0000476
Chris Lattnerd509d0b2012-05-28 01:47:44 +0000477 MAttributes.push_back(AttrListPtr::get(Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000478 Attrs.clear();
479 break;
480 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000481 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000482 }
483}
484
Chris Lattner86697142007-05-01 05:01:34 +0000485bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000486 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000487 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000488
Chris Lattner1afcace2011-07-09 17:41:24 +0000489 return ParseTypeTableBody();
490}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000491
Chris Lattner1afcace2011-07-09 17:41:24 +0000492bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000493 if (!TypeList.empty())
494 return Error("Multiple TYPE_BLOCKs found!");
495
496 SmallVector<uint64_t, 64> Record;
497 unsigned NumRecords = 0;
498
Chris Lattner1afcace2011-07-09 17:41:24 +0000499 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000500
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000501 // Read all the records for this type table.
502 while (1) {
503 unsigned Code = Stream.ReadCode();
504 if (Code == bitc::END_BLOCK) {
505 if (NumRecords != TypeList.size())
506 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000507 if (Stream.ReadBlockEnd())
508 return Error("Error at end of type table block");
509 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000510 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000511
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000512 if (Code == bitc::ENTER_SUBBLOCK) {
513 // No known subblocks, always skip them.
514 Stream.ReadSubBlockID();
515 if (Stream.SkipBlock())
516 return Error("Malformed block record");
517 continue;
518 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000519
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000520 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000521 Stream.ReadAbbrevRecord();
522 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000523 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000524
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000525 // Read a record.
526 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000527 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000528 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000529 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000530 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
531 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
532 // type list. This allows us to reserve space.
533 if (Record.size() < 1)
534 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000535 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000536 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000537 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000538 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000539 break;
Dan Gohmance163392011-12-17 00:04:22 +0000540 case bitc::TYPE_CODE_HALF: // HALF
541 ResultTy = Type::getHalfTy(Context);
542 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000543 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000544 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000545 break;
546 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000547 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000548 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000549 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000550 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000551 break;
552 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000553 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000554 break;
555 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000556 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000557 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000558 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000559 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000560 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000561 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000562 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000563 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000564 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
565 ResultTy = Type::getX86_MMXTy(Context);
566 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000567 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
568 if (Record.size() < 1)
569 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000570
Owen Anderson1d0be152009-08-13 21:58:54 +0000571 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000572 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000573 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000574 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000575 if (Record.size() < 1)
576 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000577 unsigned AddressSpace = 0;
578 if (Record.size() == 2)
579 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000580 ResultTy = getTypeByID(Record[0]);
581 if (ResultTy == 0) return Error("invalid element type in pointer type");
582 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000584 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000585 case bitc::TYPE_CODE_FUNCTION_OLD: {
586 // FIXME: attrid is dead, remove it in LLVM 4.0
587 // FUNCTION: [vararg, attrid, retty, paramty x N]
588 if (Record.size() < 3)
589 return Error("Invalid FUNCTION type record");
590 SmallVector<Type*, 8> ArgTys;
591 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
592 if (Type *T = getTypeByID(Record[i]))
593 ArgTys.push_back(T);
594 else
595 break;
596 }
597
598 ResultTy = getTypeByID(Record[2]);
599 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
600 return Error("invalid type in function type");
601
602 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
603 break;
604 }
Chad Rosiercde54642011-11-03 00:14:01 +0000605 case bitc::TYPE_CODE_FUNCTION: {
606 // FUNCTION: [vararg, retty, paramty x N]
607 if (Record.size() < 2)
608 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000609 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000610 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
611 if (Type *T = getTypeByID(Record[i]))
612 ArgTys.push_back(T);
613 else
614 break;
615 }
616
617 ResultTy = getTypeByID(Record[1]);
618 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
619 return Error("invalid type in function type");
620
621 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
622 break;
623 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000624 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000625 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000626 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000627 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000628 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
629 if (Type *T = getTypeByID(Record[i]))
630 EltTys.push_back(T);
631 else
632 break;
633 }
634 if (EltTys.size() != Record.size()-1)
635 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000636 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000637 break;
638 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000639 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
640 if (ConvertToString(Record, 0, TypeName))
641 return Error("Invalid STRUCT_NAME record");
642 continue;
643
644 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
645 if (Record.size() < 1)
646 return Error("Invalid STRUCT type record");
647
648 if (NumRecords >= TypeList.size())
649 return Error("invalid TYPE table");
650
651 // Check to see if this was forward referenced, if so fill in the temp.
652 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
653 if (Res) {
654 Res->setName(TypeName);
655 TypeList[NumRecords] = 0;
656 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000657 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000658 TypeName.clear();
659
660 SmallVector<Type*, 8> EltTys;
661 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
662 if (Type *T = getTypeByID(Record[i]))
663 EltTys.push_back(T);
664 else
665 break;
666 }
667 if (EltTys.size() != Record.size()-1)
668 return Error("invalid STRUCT type record");
669 Res->setBody(EltTys, Record[0]);
670 ResultTy = Res;
671 break;
672 }
673 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
674 if (Record.size() != 1)
675 return Error("Invalid OPAQUE type record");
676
677 if (NumRecords >= TypeList.size())
678 return Error("invalid TYPE table");
679
680 // Check to see if this was forward referenced, if so fill in the temp.
681 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
682 if (Res) {
683 Res->setName(TypeName);
684 TypeList[NumRecords] = 0;
685 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000686 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000687 TypeName.clear();
688 ResultTy = Res;
689 break;
690 }
691 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
692 if (Record.size() < 2)
693 return Error("Invalid ARRAY type record");
694 if ((ResultTy = getTypeByID(Record[1])))
695 ResultTy = ArrayType::get(ResultTy, Record[0]);
696 else
697 return Error("Invalid ARRAY type element");
698 break;
699 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
700 if (Record.size() < 2)
701 return Error("Invalid VECTOR type record");
702 if ((ResultTy = getTypeByID(Record[1])))
703 ResultTy = VectorType::get(ResultTy, Record[0]);
704 else
705 return Error("Invalid ARRAY type element");
706 break;
707 }
708
709 if (NumRecords >= TypeList.size())
710 return Error("invalid TYPE table");
711 assert(ResultTy && "Didn't read a type?");
712 assert(TypeList[NumRecords] == 0 && "Already read type?");
713 TypeList[NumRecords++] = ResultTy;
714 }
715}
716
Chris Lattner86697142007-05-01 05:01:34 +0000717bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000718 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000719 return Error("Malformed block record");
720
721 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000722
Chris Lattner0b2482a2007-04-23 21:26:05 +0000723 // Read all the records for this value table.
724 SmallString<128> ValueName;
725 while (1) {
726 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000727 if (Code == bitc::END_BLOCK) {
728 if (Stream.ReadBlockEnd())
729 return Error("Error at end of value symbol table block");
730 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000731 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000732 if (Code == bitc::ENTER_SUBBLOCK) {
733 // No known subblocks, always skip them.
734 Stream.ReadSubBlockID();
735 if (Stream.SkipBlock())
736 return Error("Malformed block record");
737 continue;
738 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000739
Chris Lattner0b2482a2007-04-23 21:26:05 +0000740 if (Code == bitc::DEFINE_ABBREV) {
741 Stream.ReadAbbrevRecord();
742 continue;
743 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744
Chris Lattner0b2482a2007-04-23 21:26:05 +0000745 // Read a record.
746 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000747 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000748 default: // Default behavior: unknown type.
749 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000750 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000751 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000752 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000753 unsigned ValueID = Record[0];
754 if (ValueID >= ValueList.size())
755 return Error("Invalid Value ID in VST_ENTRY record");
756 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000758 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000759 ValueName.clear();
760 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000761 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000762 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000763 if (ConvertToString(Record, 1, ValueName))
764 return Error("Invalid VST_BBENTRY record");
765 BasicBlock *BB = getBasicBlock(Record[0]);
766 if (BB == 0)
767 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000768
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000769 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000770 ValueName.clear();
771 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000772 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000773 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000774 }
775}
776
Devang Patele54abc92009-07-22 17:43:22 +0000777bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000778 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000779
780 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
781 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000782
Devang Patele54abc92009-07-22 17:43:22 +0000783 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000784
Devang Patele54abc92009-07-22 17:43:22 +0000785 // Read all the records.
786 while (1) {
787 unsigned Code = Stream.ReadCode();
788 if (Code == bitc::END_BLOCK) {
789 if (Stream.ReadBlockEnd())
790 return Error("Error at end of PARAMATTR block");
791 return false;
792 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000793
Devang Patele54abc92009-07-22 17:43:22 +0000794 if (Code == bitc::ENTER_SUBBLOCK) {
795 // No known subblocks, always skip them.
796 Stream.ReadSubBlockID();
797 if (Stream.SkipBlock())
798 return Error("Malformed block record");
799 continue;
800 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000801
Devang Patele54abc92009-07-22 17:43:22 +0000802 if (Code == bitc::DEFINE_ABBREV) {
803 Stream.ReadAbbrevRecord();
804 continue;
805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000806
Victor Hernandez24e64df2010-01-10 07:14:18 +0000807 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000808 // Read a record.
809 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000810 Code = Stream.ReadRecord(Code, Record);
811 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000812 default: // Default behavior: ignore.
813 break;
Devang Patelaa993142009-07-29 22:34:41 +0000814 case bitc::METADATA_NAME: {
815 // Read named of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000816 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000817 Record.clear();
818 Code = Stream.ReadCode();
819
Chris Lattner9d61dd92011-06-17 17:50:30 +0000820 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000821 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000822 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000823
824 // Read named metadata elements.
825 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000826 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000827 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000828 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
829 if (MD == 0)
830 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000831 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000832 }
Devang Patelaa993142009-07-29 22:34:41 +0000833 break;
834 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000835 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000836 IsFunctionLocal = true;
837 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000838 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000839 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000840 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000841
Devang Patel104cf9e2009-07-23 01:07:34 +0000842 unsigned Size = Record.size();
843 SmallVector<Value*, 8> Elts;
844 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000845 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000846 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000847 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000848 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000849 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000850 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
851 else
852 Elts.push_back(NULL);
853 }
Jay Foadec9186b2011-04-21 19:59:31 +0000854 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000855 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000856 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000857 break;
858 }
Devang Patele54abc92009-07-22 17:43:22 +0000859 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000860 SmallString<8> String(Record.begin(), Record.end());
861 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000862 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000863 break;
864 }
Devang Patele8e02132009-09-18 19:26:43 +0000865 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000866 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000867 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000868
Devang Patela2148402009-09-28 21:14:55 +0000869 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000870 SmallString<8> Name(Record.begin()+1, Record.end());
871
Chris Lattner08113472009-12-29 09:01:33 +0000872 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000873 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
874 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000875 break;
876 }
Devang Patele54abc92009-07-22 17:43:22 +0000877 }
878 }
879}
880
Chris Lattner0eef0802007-04-24 04:04:35 +0000881/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
882/// the LSB for dense VBR encoding.
883static uint64_t DecodeSignRotatedValue(uint64_t V) {
884 if ((V & 1) == 0)
885 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000886 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000887 return -(V >> 1);
888 // There is no such thing as -0 with integers. "-0" really means MININT.
889 return 1ULL << 63;
890}
891
Chris Lattner07d98b42007-04-26 02:46:40 +0000892/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
893/// values and aliases that we can.
894bool BitcodeReader::ResolveGlobalAndAliasInits() {
895 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
896 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000897
Chris Lattner07d98b42007-04-26 02:46:40 +0000898 GlobalInitWorklist.swap(GlobalInits);
899 AliasInitWorklist.swap(AliasInits);
900
901 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000902 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000903 if (ValID >= ValueList.size()) {
904 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000905 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000906 } else {
907 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
908 GlobalInitWorklist.back().first->setInitializer(C);
909 else
910 return Error("Global variable initializer is not a constant!");
911 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000912 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000913 }
914
915 while (!AliasInitWorklist.empty()) {
916 unsigned ValID = AliasInitWorklist.back().second;
917 if (ValID >= ValueList.size()) {
918 AliasInits.push_back(AliasInitWorklist.back());
919 } else {
920 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000921 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000922 else
923 return Error("Alias initializer is not a constant!");
924 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000926 }
927 return false;
928}
929
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000930static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
931 SmallVector<uint64_t, 8> Words(Vals.size());
932 std::transform(Vals.begin(), Vals.end(), Words.begin(),
933 DecodeSignRotatedValue);
934
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000935 return APInt(TypeBits, Words);
936}
937
Chris Lattner86697142007-05-01 05:01:34 +0000938bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000939 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000940 return Error("Malformed block record");
941
942 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000943
Chris Lattnere16504e2007-04-24 03:30:34 +0000944 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000945 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000946 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000947 while (1) {
948 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000949 if (Code == bitc::END_BLOCK)
950 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000951
Chris Lattnere16504e2007-04-24 03:30:34 +0000952 if (Code == bitc::ENTER_SUBBLOCK) {
953 // No known subblocks, always skip them.
954 Stream.ReadSubBlockID();
955 if (Stream.SkipBlock())
956 return Error("Malformed block record");
957 continue;
958 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000959
Chris Lattnere16504e2007-04-24 03:30:34 +0000960 if (Code == bitc::DEFINE_ABBREV) {
961 Stream.ReadAbbrevRecord();
962 continue;
963 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000964
Chris Lattnere16504e2007-04-24 03:30:34 +0000965 // Read a record.
966 Record.clear();
967 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000968 unsigned BitCode = Stream.ReadRecord(Code, Record);
969 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000970 default: // Default behavior: unknown constant
971 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000972 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000973 break;
974 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
975 if (Record.empty())
976 return Error("Malformed CST_SETTYPE record");
977 if (Record[0] >= TypeList.size())
978 return Error("Invalid Type ID in CST_SETTYPE record");
979 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000980 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000981 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000982 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000983 break;
984 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000985 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000986 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +0000987 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000988 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000989 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000990 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000991 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000992
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000993 APInt VInt = ReadWideAPInt(Record,
994 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000995 V = ConstantInt::get(Context, VInt);
996
Chris Lattner0eef0802007-04-24 04:04:35 +0000997 break;
998 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000999 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001000 if (Record.empty())
1001 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001002 if (CurTy->isHalfTy())
1003 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1004 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001005 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001006 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001007 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001008 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001009 // Bits are not stored the same way as a normal i80 APInt, compensate.
1010 uint64_t Rearrange[2];
1011 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1012 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001013 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001014 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001015 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001016 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001017 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001018 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001019 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001020 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001021 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001022
Chris Lattner15e6d172007-05-04 19:11:41 +00001023 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1024 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001025 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001026
Chris Lattner15e6d172007-05-04 19:11:41 +00001027 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001028 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001029
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001030 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001031 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001032 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001033 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001034 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001035 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1036 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001037 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001038 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001039 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001040 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1041 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001042 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001043 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001044 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001045 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001046 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001047 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001048 break;
1049 }
Chris Lattner2237f842012-02-05 02:41:35 +00001050 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001051 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1052 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001053 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001054
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001055 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001056 V = ConstantDataArray::getString(Context, Elts,
1057 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001058 break;
1059 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001060 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1061 if (Record.empty())
1062 return Error("Invalid CST_DATA record");
1063
1064 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1065 unsigned Size = Record.size();
1066
1067 if (EltTy->isIntegerTy(8)) {
1068 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1069 if (isa<VectorType>(CurTy))
1070 V = ConstantDataVector::get(Context, Elts);
1071 else
1072 V = ConstantDataArray::get(Context, Elts);
1073 } else if (EltTy->isIntegerTy(16)) {
1074 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1075 if (isa<VectorType>(CurTy))
1076 V = ConstantDataVector::get(Context, Elts);
1077 else
1078 V = ConstantDataArray::get(Context, Elts);
1079 } else if (EltTy->isIntegerTy(32)) {
1080 SmallVector<uint32_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(64)) {
1086 SmallVector<uint64_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->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001092 SmallVector<float, 16> Elts(Size);
1093 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001094 if (isa<VectorType>(CurTy))
1095 V = ConstantDataVector::get(Context, Elts);
1096 else
1097 V = ConstantDataArray::get(Context, Elts);
1098 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001099 SmallVector<double, 16> Elts(Size);
1100 std::transform(Record.begin(), Record.end(), Elts.begin(),
1101 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001102 if (isa<VectorType>(CurTy))
1103 V = ConstantDataVector::get(Context, Elts);
1104 else
1105 V = ConstantDataArray::get(Context, Elts);
1106 } else {
1107 return Error("Unknown element type in CE_DATA");
1108 }
1109 break;
1110 }
1111
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001112 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1113 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1114 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001115 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001116 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001117 } else {
1118 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1119 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001120 unsigned Flags = 0;
1121 if (Record.size() >= 4) {
1122 if (Opc == Instruction::Add ||
1123 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001124 Opc == Instruction::Mul ||
1125 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001126 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1127 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1128 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1129 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001130 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001131 Opc == Instruction::UDiv ||
1132 Opc == Instruction::LShr ||
1133 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001134 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001135 Flags |= SDivOperator::IsExact;
1136 }
1137 }
1138 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001139 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001140 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001141 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001142 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1143 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1144 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001145 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001146 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001147 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001148 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001149 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001150 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001151 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001152 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001153 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001154 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001155 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001156 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001157 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001158 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001159 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001160 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001161 if (!ElTy) return Error("Invalid CE_GEP record");
1162 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1163 }
Jay Foaddab3d292011-07-21 14:31:17 +00001164 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001165 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1166 BitCode ==
1167 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001168 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001169 }
1170 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1171 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001172 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001173 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001174 ValueList.getConstantFwdRef(Record[1],CurTy),
1175 ValueList.getConstantFwdRef(Record[2],CurTy));
1176 break;
1177 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1178 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001179 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001180 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1181 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1182 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001183 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001184 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001185 break;
1186 }
1187 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001188 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001189 if (Record.size() < 3 || OpTy == 0)
1190 return Error("Invalid CE_INSERTELT record");
1191 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1192 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1193 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001194 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001195 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001196 break;
1197 }
1198 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001199 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001200 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001201 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001202 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1203 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001204 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001205 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001206 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001207 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001208 break;
1209 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001210 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001211 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1212 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001213 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001214 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1215 return Error("Invalid CE_SHUFVEC_EX record");
1216 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1217 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001218 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001219 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001220 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001221 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001222 break;
1223 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001224 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1225 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001226 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001227 if (OpTy == 0) return Error("Invalid CE_CMP record");
1228 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1229 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1230
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001231 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001232 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001233 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001234 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001235 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001236 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001237 case bitc::CST_CODE_INLINEASM: {
1238 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1239 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001240 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001241 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001242 unsigned AsmStrSize = Record[1];
1243 if (2+AsmStrSize >= Record.size())
1244 return Error("Invalid INLINEASM record");
1245 unsigned ConstStrSize = Record[2+AsmStrSize];
1246 if (3+AsmStrSize+ConstStrSize > Record.size())
1247 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001248
Chris Lattner2bce93a2007-05-06 01:58:20 +00001249 for (unsigned i = 0; i != AsmStrSize; ++i)
1250 AsmStr += (char)Record[2+i];
1251 for (unsigned i = 0; i != ConstStrSize; ++i)
1252 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001253 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001254 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001255 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001256 break;
1257 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001258 case bitc::CST_CODE_BLOCKADDRESS:{
1259 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001260 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001261 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1262 Function *Fn =
1263 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1264 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1265
1266 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1267 Type::getInt8Ty(Context),
1268 false, GlobalValue::InternalLinkage,
1269 0, "");
1270 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1271 V = FwdRef;
1272 break;
1273 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001274 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001275
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001276 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001277 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001278 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001279
Chris Lattnerea693df2008-08-21 02:34:16 +00001280 if (NextCstNo != ValueList.size())
1281 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001282
Chris Lattnerea693df2008-08-21 02:34:16 +00001283 if (Stream.ReadBlockEnd())
1284 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001285
Chris Lattnerea693df2008-08-21 02:34:16 +00001286 // Once all the constants have been read, go through and resolve forward
1287 // references.
1288 ValueList.ResolveConstantForwardRefs();
1289 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001290}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001291
Chad Rosiercbbb0962011-12-07 21:44:12 +00001292bool BitcodeReader::ParseUseLists() {
1293 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1294 return Error("Malformed block record");
1295
1296 SmallVector<uint64_t, 64> Record;
1297
1298 // Read all the records.
1299 while (1) {
1300 unsigned Code = Stream.ReadCode();
1301 if (Code == bitc::END_BLOCK) {
1302 if (Stream.ReadBlockEnd())
1303 return Error("Error at end of use-list table block");
1304 return false;
1305 }
1306
1307 if (Code == bitc::ENTER_SUBBLOCK) {
1308 // No known subblocks, always skip them.
1309 Stream.ReadSubBlockID();
1310 if (Stream.SkipBlock())
1311 return Error("Malformed block record");
1312 continue;
1313 }
1314
1315 if (Code == bitc::DEFINE_ABBREV) {
1316 Stream.ReadAbbrevRecord();
1317 continue;
1318 }
1319
1320 // Read a use list record.
1321 Record.clear();
1322 switch (Stream.ReadRecord(Code, Record)) {
1323 default: // Default behavior: unknown type.
1324 break;
1325 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1326 unsigned RecordLength = Record.size();
1327 if (RecordLength < 1)
1328 return Error ("Invalid UseList reader!");
1329 UseListRecords.push_back(Record);
1330 break;
1331 }
1332 }
1333 }
1334}
1335
Chris Lattner980e5aa2007-05-01 05:52:21 +00001336/// RememberAndSkipFunctionBody - When we see the block for a function body,
1337/// remember where it is and then skip it. This lets us lazily deserialize the
1338/// functions.
1339bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001340 // Get the function we are talking about.
1341 if (FunctionsWithBodies.empty())
1342 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001343
Chris Lattner48f84872007-05-01 04:59:48 +00001344 Function *Fn = FunctionsWithBodies.back();
1345 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001346
Chris Lattner48f84872007-05-01 04:59:48 +00001347 // Save the current stream state.
1348 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001349 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001350
Chris Lattner48f84872007-05-01 04:59:48 +00001351 // Skip over the function block for now.
1352 if (Stream.SkipBlock())
1353 return Error("Malformed block record");
1354 return false;
1355}
1356
Derek Schuff2ea93872012-02-06 22:30:29 +00001357bool BitcodeReader::GlobalCleanup() {
1358 // Patch the initializers for globals and aliases up.
1359 ResolveGlobalAndAliasInits();
1360 if (!GlobalInits.empty() || !AliasInits.empty())
1361 return Error("Malformed global initializer set");
1362
1363 // Look for intrinsic functions which need to be upgraded at some point
1364 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1365 FI != FE; ++FI) {
1366 Function *NewFn;
1367 if (UpgradeIntrinsicFunction(FI, NewFn))
1368 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1369 }
1370
1371 // Look for global variables which need to be renamed.
1372 for (Module::global_iterator
1373 GI = TheModule->global_begin(), GE = TheModule->global_end();
1374 GI != GE; ++GI)
1375 UpgradeGlobalVariable(GI);
1376 // Force deallocation of memory for these vectors to favor the client that
1377 // want lazy deserialization.
1378 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1379 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1380 return false;
1381}
1382
1383bool BitcodeReader::ParseModule(bool Resume) {
1384 if (Resume)
1385 Stream.JumpToBit(NextUnreadBit);
1386 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001387 return Error("Malformed block record");
1388
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001389 SmallVector<uint64_t, 64> Record;
1390 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001391 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001392
1393 // Read all the records for this module.
1394 while (!Stream.AtEndOfStream()) {
1395 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001396 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001397 if (Stream.ReadBlockEnd())
1398 return Error("Error at end of module block");
1399
Derek Schuff2ea93872012-02-06 22:30:29 +00001400 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001401 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001402
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001403 if (Code == bitc::ENTER_SUBBLOCK) {
1404 switch (Stream.ReadSubBlockID()) {
1405 default: // Skip unknown content.
1406 if (Stream.SkipBlock())
1407 return Error("Malformed block record");
1408 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001409 case bitc::BLOCKINFO_BLOCK_ID:
1410 if (Stream.ReadBlockInfoBlock())
1411 return Error("Malformed BlockInfoBlock");
1412 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001413 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001414 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001415 return true;
1416 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001417 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001418 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001419 return true;
1420 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001421 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001422 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001423 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001424 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001425 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001426 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001427 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001428 return true;
1429 break;
Devang Patele54abc92009-07-22 17:43:22 +00001430 case bitc::METADATA_BLOCK_ID:
1431 if (ParseMetadata())
1432 return true;
1433 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001434 case bitc::FUNCTION_BLOCK_ID:
1435 // If this is the first function body we've seen, reverse the
1436 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001437 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001438 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001439 if (GlobalCleanup())
1440 return true;
1441 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001442 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001443
Chris Lattner980e5aa2007-05-01 05:52:21 +00001444 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001445 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001446 // For streaming bitcode, suspend parsing when we reach the function
1447 // bodies. Subsequent materialization calls will resume it when
1448 // necessary. For streaming, the function bodies must be at the end of
1449 // the bitcode. If the bitcode file is old, the symbol table will be
1450 // at the end instead and will not have been seen yet. In this case,
1451 // just finish the parse now.
1452 if (LazyStreamer && SeenValueSymbolTable) {
1453 NextUnreadBit = Stream.GetCurrentBitNo();
1454 return false;
1455 }
Chris Lattner48f84872007-05-01 04:59:48 +00001456 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001457 case bitc::USELIST_BLOCK_ID:
1458 if (ParseUseLists())
1459 return true;
1460 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001461 }
1462 continue;
1463 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001464
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001465 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001466 Stream.ReadAbbrevRecord();
1467 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001468 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001469
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001470 // Read a record.
1471 switch (Stream.ReadRecord(Code, Record)) {
1472 default: break; // Default behavior, ignore unknown content.
1473 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1474 if (Record.size() < 1)
1475 return Error("Malformed MODULE_CODE_VERSION");
1476 // Only version #0 is supported so far.
1477 if (Record[0] != 0)
1478 return Error("Unknown bitstream version!");
1479 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001480 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001481 std::string S;
1482 if (ConvertToString(Record, 0, S))
1483 return Error("Invalid MODULE_CODE_TRIPLE record");
1484 TheModule->setTargetTriple(S);
1485 break;
1486 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001487 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001488 std::string S;
1489 if (ConvertToString(Record, 0, S))
1490 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1491 TheModule->setDataLayout(S);
1492 break;
1493 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001494 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001495 std::string S;
1496 if (ConvertToString(Record, 0, S))
1497 return Error("Invalid MODULE_CODE_ASM record");
1498 TheModule->setModuleInlineAsm(S);
1499 break;
1500 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001501 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001502 std::string S;
1503 if (ConvertToString(Record, 0, S))
1504 return Error("Invalid MODULE_CODE_DEPLIB record");
1505 TheModule->addLibrary(S);
1506 break;
1507 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001508 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001509 std::string S;
1510 if (ConvertToString(Record, 0, S))
1511 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1512 SectionTable.push_back(S);
1513 break;
1514 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001515 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001516 std::string S;
1517 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001518 return Error("Invalid MODULE_CODE_GCNAME record");
1519 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001520 break;
1521 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001522 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001523 // linkage, alignment, section, visibility, threadlocal,
1524 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001525 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001526 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001527 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001528 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001529 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001530 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001531 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001532 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001533 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001534
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001535 bool isConstant = Record[1];
1536 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1537 unsigned Alignment = (1 << Record[4]) >> 1;
1538 std::string Section;
1539 if (Record[5]) {
1540 if (Record[5]-1 >= SectionTable.size())
1541 return Error("Invalid section ID");
1542 Section = SectionTable[Record[5]-1];
1543 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001544 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001545 if (Record.size() > 6)
1546 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001547 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001548 if (Record.size() > 7)
1549 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001550
Rafael Espindolabea46262011-01-08 16:42:36 +00001551 bool UnnamedAddr = false;
1552 if (Record.size() > 8)
1553 UnnamedAddr = Record[8];
1554
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001555 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001556 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001557 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001558 NewGV->setAlignment(Alignment);
1559 if (!Section.empty())
1560 NewGV->setSection(Section);
1561 NewGV->setVisibility(Visibility);
1562 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001563 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001564
Chris Lattner0b2482a2007-04-23 21:26:05 +00001565 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001566
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001567 // Remember which value to use for the global initializer.
1568 if (unsigned InitID = Record[2])
1569 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001570 break;
1571 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001572 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001573 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001574 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001575 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001576 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001577 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001578 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001579 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001580 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001581 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001582 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1583 if (!FTy)
1584 return Error("Function not a pointer to function type!");
1585
Gabor Greif051a9502008-04-06 20:25:17 +00001586 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1587 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001588
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001589 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001590 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001591 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001592 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001593
Chris Lattnera9bb7132007-05-08 05:38:01 +00001594 Func->setAlignment((1 << Record[5]) >> 1);
1595 if (Record[6]) {
1596 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001597 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001598 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001599 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001600 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001601 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001602 if (Record[8]-1 > GCTable.size())
1603 return Error("Invalid GC ID");
1604 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001605 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001606 bool UnnamedAddr = false;
1607 if (Record.size() > 9)
1608 UnnamedAddr = Record[9];
1609 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001610 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001611
Chris Lattner48f84872007-05-01 04:59:48 +00001612 // If this is a function with a body, remember the prototype we are
1613 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001614 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001615 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001616 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1617 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001618 break;
1619 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001620 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001621 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001622 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001623 if (Record.size() < 3)
1624 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001625 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001626 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001627 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001628 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Chris Lattner07d98b42007-04-26 02:46:40 +00001630 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1631 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001632 // Old bitcode files didn't have visibility field.
1633 if (Record.size() > 3)
1634 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001635 ValueList.push_back(NewGA);
1636 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1637 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001638 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001639 /// MODULE_CODE_PURGEVALS: [numvals]
1640 case bitc::MODULE_CODE_PURGEVALS:
1641 // Trim down the value list to the specified size.
1642 if (Record.size() < 1 || Record[0] > ValueList.size())
1643 return Error("Invalid MODULE_PURGEVALS record");
1644 ValueList.shrinkTo(Record[0]);
1645 break;
1646 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001647 Record.clear();
1648 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001650 return Error("Premature end of bitstream");
1651}
1652
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001653bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001654 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001655
Derek Schuff2ea93872012-02-06 22:30:29 +00001656 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001657
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001658 // Sniff for the signature.
1659 if (Stream.Read(8) != 'B' ||
1660 Stream.Read(8) != 'C' ||
1661 Stream.Read(4) != 0x0 ||
1662 Stream.Read(4) != 0xC ||
1663 Stream.Read(4) != 0xE ||
1664 Stream.Read(4) != 0xD)
1665 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001666
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001667 // We expect a number of well-defined blocks, though we don't necessarily
1668 // need to understand them all.
1669 while (!Stream.AtEndOfStream()) {
1670 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001671
Rafael Espindolac9687b32011-05-26 18:59:54 +00001672 if (Code != bitc::ENTER_SUBBLOCK) {
1673
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001674 // The ranlib in xcode 4 will align archive members by appending newlines
1675 // to the end of them. If this file size is a multiple of 4 but not 8, we
1676 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001677 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1678 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1679 Stream.AtEndOfStream())
1680 return false;
1681
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001682 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001683 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001685 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001686
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001687 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001688 switch (BlockID) {
1689 case bitc::BLOCKINFO_BLOCK_ID:
1690 if (Stream.ReadBlockInfoBlock())
1691 return Error("Malformed BlockInfoBlock");
1692 break;
1693 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001694 // Reject multiple MODULE_BLOCK's in a single bitstream.
1695 if (TheModule)
1696 return Error("Multiple MODULE_BLOCKs in same stream");
1697 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001698 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001699 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001700 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001701 break;
1702 default:
1703 if (Stream.SkipBlock())
1704 return Error("Malformed block record");
1705 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001706 }
1707 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001708
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001709 return false;
1710}
Chris Lattnerc453f762007-04-29 07:54:31 +00001711
Bill Wendling34711742010-10-06 01:22:42 +00001712bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1713 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1714 return Error("Malformed block record");
1715
1716 SmallVector<uint64_t, 64> Record;
1717
1718 // Read all the records for this module.
1719 while (!Stream.AtEndOfStream()) {
1720 unsigned Code = Stream.ReadCode();
1721 if (Code == bitc::END_BLOCK) {
1722 if (Stream.ReadBlockEnd())
1723 return Error("Error at end of module block");
1724
1725 return false;
1726 }
1727
1728 if (Code == bitc::ENTER_SUBBLOCK) {
1729 switch (Stream.ReadSubBlockID()) {
1730 default: // Skip unknown content.
1731 if (Stream.SkipBlock())
1732 return Error("Malformed block record");
1733 break;
1734 }
1735 continue;
1736 }
1737
1738 if (Code == bitc::DEFINE_ABBREV) {
1739 Stream.ReadAbbrevRecord();
1740 continue;
1741 }
1742
1743 // Read a record.
1744 switch (Stream.ReadRecord(Code, Record)) {
1745 default: break; // Default behavior, ignore unknown content.
1746 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1747 if (Record.size() < 1)
1748 return Error("Malformed MODULE_CODE_VERSION");
1749 // Only version #0 is supported so far.
1750 if (Record[0] != 0)
1751 return Error("Unknown bitstream version!");
1752 break;
1753 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1754 std::string S;
1755 if (ConvertToString(Record, 0, S))
1756 return Error("Invalid MODULE_CODE_TRIPLE record");
1757 Triple = S;
1758 break;
1759 }
1760 }
1761 Record.clear();
1762 }
1763
1764 return Error("Premature end of bitstream");
1765}
1766
1767bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001768 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001769
1770 // Sniff for the signature.
1771 if (Stream.Read(8) != 'B' ||
1772 Stream.Read(8) != 'C' ||
1773 Stream.Read(4) != 0x0 ||
1774 Stream.Read(4) != 0xC ||
1775 Stream.Read(4) != 0xE ||
1776 Stream.Read(4) != 0xD)
1777 return Error("Invalid bitcode signature");
1778
1779 // We expect a number of well-defined blocks, though we don't necessarily
1780 // need to understand them all.
1781 while (!Stream.AtEndOfStream()) {
1782 unsigned Code = Stream.ReadCode();
1783
1784 if (Code != bitc::ENTER_SUBBLOCK)
1785 return Error("Invalid record at top-level");
1786
1787 unsigned BlockID = Stream.ReadSubBlockID();
1788
1789 // We only know the MODULE subblock ID.
1790 switch (BlockID) {
1791 case bitc::MODULE_BLOCK_ID:
1792 if (ParseModuleTriple(Triple))
1793 return true;
1794 break;
1795 default:
1796 if (Stream.SkipBlock())
1797 return Error("Malformed block record");
1798 break;
1799 }
1800 }
1801
1802 return false;
1803}
1804
Devang Patele8e02132009-09-18 19:26:43 +00001805/// ParseMetadataAttachment - Parse metadata attachments.
1806bool BitcodeReader::ParseMetadataAttachment() {
1807 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1808 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001809
Devang Patele8e02132009-09-18 19:26:43 +00001810 SmallVector<uint64_t, 64> Record;
1811 while(1) {
1812 unsigned Code = Stream.ReadCode();
1813 if (Code == bitc::END_BLOCK) {
1814 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001815 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001816 break;
1817 }
1818 if (Code == bitc::DEFINE_ABBREV) {
1819 Stream.ReadAbbrevRecord();
1820 continue;
1821 }
1822 // Read a metadata attachment record.
1823 Record.clear();
1824 switch (Stream.ReadRecord(Code, Record)) {
1825 default: // Default behavior: ignore.
1826 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001827 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001828 unsigned RecordLength = Record.size();
1829 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001830 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001831 Instruction *Inst = InstructionList[Record[0]];
1832 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001833 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001834 DenseMap<unsigned, unsigned>::iterator I =
1835 MDKindMap.find(Kind);
1836 if (I == MDKindMap.end())
1837 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001838 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001839 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001840 }
1841 break;
1842 }
1843 }
1844 }
1845 return false;
1846}
Chris Lattner48f84872007-05-01 04:59:48 +00001847
Chris Lattner980e5aa2007-05-01 05:52:21 +00001848/// ParseFunctionBody - Lazily parse the specified function body block.
1849bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001850 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001851 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001852
Nick Lewycky9a49f152010-02-25 08:30:17 +00001853 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001854 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001855 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001856
Chris Lattner980e5aa2007-05-01 05:52:21 +00001857 // Add all the function arguments to the value table.
1858 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1859 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001860
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001861 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001862 BasicBlock *CurBB = 0;
1863 unsigned CurBBNo = 0;
1864
Chris Lattnera6245242010-04-03 02:17:50 +00001865 DebugLoc LastLoc;
1866
Chris Lattner980e5aa2007-05-01 05:52:21 +00001867 // Read all the records.
1868 SmallVector<uint64_t, 64> Record;
1869 while (1) {
1870 unsigned Code = Stream.ReadCode();
1871 if (Code == bitc::END_BLOCK) {
1872 if (Stream.ReadBlockEnd())
1873 return Error("Error at end of function block");
1874 break;
1875 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001876
Chris Lattner980e5aa2007-05-01 05:52:21 +00001877 if (Code == bitc::ENTER_SUBBLOCK) {
1878 switch (Stream.ReadSubBlockID()) {
1879 default: // Skip unknown content.
1880 if (Stream.SkipBlock())
1881 return Error("Malformed block record");
1882 break;
1883 case bitc::CONSTANTS_BLOCK_ID:
1884 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001885 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001886 break;
1887 case bitc::VALUE_SYMTAB_BLOCK_ID:
1888 if (ParseValueSymbolTable()) return true;
1889 break;
Devang Patele8e02132009-09-18 19:26:43 +00001890 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001891 if (ParseMetadataAttachment()) return true;
1892 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001893 case bitc::METADATA_BLOCK_ID:
1894 if (ParseMetadata()) return true;
1895 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001896 }
1897 continue;
1898 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001899
Chris Lattner980e5aa2007-05-01 05:52:21 +00001900 if (Code == bitc::DEFINE_ABBREV) {
1901 Stream.ReadAbbrevRecord();
1902 continue;
1903 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001904
Chris Lattner980e5aa2007-05-01 05:52:21 +00001905 // Read a record.
1906 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001907 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001908 unsigned BitCode = Stream.ReadRecord(Code, Record);
1909 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001910 default: // Default behavior: reject
1911 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001912 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001913 if (Record.size() < 1 || Record[0] == 0)
1914 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001915 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001916 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001917 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001918 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001919 CurBB = FunctionBBs[0];
1920 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001921
1922 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1923 // This record indicates that the last instruction is at the same
1924 // location as the previous instruction with a location.
1925 I = 0;
1926
1927 // Get the last instruction emitted.
1928 if (CurBB && !CurBB->empty())
1929 I = &CurBB->back();
1930 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1931 !FunctionBBs[CurBBNo-1]->empty())
1932 I = &FunctionBBs[CurBBNo-1]->back();
1933
1934 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1935 I->setDebugLoc(LastLoc);
1936 I = 0;
1937 continue;
1938
Chris Lattner4f6bab92011-06-17 18:17:37 +00001939 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001940 I = 0; // Get the last instruction emitted.
1941 if (CurBB && !CurBB->empty())
1942 I = &CurBB->back();
1943 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1944 !FunctionBBs[CurBBNo-1]->empty())
1945 I = &FunctionBBs[CurBBNo-1]->back();
1946 if (I == 0 || Record.size() < 4)
1947 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1948
1949 unsigned Line = Record[0], Col = Record[1];
1950 unsigned ScopeID = Record[2], IAID = Record[3];
1951
1952 MDNode *Scope = 0, *IA = 0;
1953 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1954 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1955 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1956 I->setDebugLoc(LastLoc);
1957 I = 0;
1958 continue;
1959 }
1960
Chris Lattnerabfbf852007-05-06 00:21:25 +00001961 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1962 unsigned OpNum = 0;
1963 Value *LHS, *RHS;
1964 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1965 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001966 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001967 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001968
Dan Gohman1224c382009-07-20 21:19:07 +00001969 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001970 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001971 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001972 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001973 if (OpNum < Record.size()) {
1974 if (Opc == Instruction::Add ||
1975 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001976 Opc == Instruction::Mul ||
1977 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00001978 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001979 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00001980 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001981 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00001982 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001983 Opc == Instruction::UDiv ||
1984 Opc == Instruction::LShr ||
1985 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001986 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001987 cast<BinaryOperator>(I)->setIsExact(true);
1988 }
1989 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001990 break;
1991 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001992 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1993 unsigned OpNum = 0;
1994 Value *Op;
1995 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1996 OpNum+2 != Record.size())
1997 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001998
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001999 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002000 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2001 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002002 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002003 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002004 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002005 break;
2006 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002007 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002008 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002009 unsigned OpNum = 0;
2010 Value *BasePtr;
2011 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002012 return Error("Invalid GEP record");
2013
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002014 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002015 while (OpNum != Record.size()) {
2016 Value *Op;
2017 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002018 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002019 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002020 }
2021
Jay Foada9203102011-07-25 09:48:08 +00002022 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002023 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002024 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002025 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002026 break;
2027 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002028
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002029 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2030 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002031 unsigned OpNum = 0;
2032 Value *Agg;
2033 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2034 return Error("Invalid EXTRACTVAL record");
2035
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002036 SmallVector<unsigned, 4> EXTRACTVALIdx;
2037 for (unsigned RecSize = Record.size();
2038 OpNum != RecSize; ++OpNum) {
2039 uint64_t Index = Record[OpNum];
2040 if ((unsigned)Index != Index)
2041 return Error("Invalid EXTRACTVAL index");
2042 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002043 }
2044
Jay Foadfc6d3a42011-07-13 10:26:04 +00002045 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002046 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002047 break;
2048 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002049
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002050 case bitc::FUNC_CODE_INST_INSERTVAL: {
2051 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002052 unsigned OpNum = 0;
2053 Value *Agg;
2054 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2055 return Error("Invalid INSERTVAL record");
2056 Value *Val;
2057 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2058 return Error("Invalid INSERTVAL record");
2059
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002060 SmallVector<unsigned, 4> INSERTVALIdx;
2061 for (unsigned RecSize = Record.size();
2062 OpNum != RecSize; ++OpNum) {
2063 uint64_t Index = Record[OpNum];
2064 if ((unsigned)Index != Index)
2065 return Error("Invalid INSERTVAL index");
2066 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002067 }
2068
Jay Foadfc6d3a42011-07-13 10:26:04 +00002069 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002070 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002071 break;
2072 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002073
Chris Lattnerabfbf852007-05-06 00:21:25 +00002074 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002075 // obsolete form of select
2076 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002077 unsigned OpNum = 0;
2078 Value *TrueVal, *FalseVal, *Cond;
2079 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2080 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002081 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002082 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002083
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002084 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002085 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002086 break;
2087 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002088
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002089 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2090 // new form of select
2091 // handles select i1 or select [N x i1]
2092 unsigned OpNum = 0;
2093 Value *TrueVal, *FalseVal, *Cond;
2094 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2095 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2096 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2097 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002098
2099 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002100 if (VectorType* vector_type =
2101 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002102 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002103 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002104 return Error("Invalid SELECT condition type");
2105 } else {
2106 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002107 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002108 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002109 }
2110
Gabor Greif051a9502008-04-06 20:25:17 +00002111 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002112 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002113 break;
2114 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002115
Chris Lattner01ff65f2007-05-02 05:16:49 +00002116 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002117 unsigned OpNum = 0;
2118 Value *Vec, *Idx;
2119 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002120 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002121 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002122 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002123 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002124 break;
2125 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002126
Chris Lattner01ff65f2007-05-02 05:16:49 +00002127 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002128 unsigned OpNum = 0;
2129 Value *Vec, *Elt, *Idx;
2130 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002131 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002132 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002133 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002134 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002135 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002136 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002137 break;
2138 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002139
Chris Lattnerabfbf852007-05-06 00:21:25 +00002140 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2141 unsigned OpNum = 0;
2142 Value *Vec1, *Vec2, *Mask;
2143 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2144 getValue(Record, OpNum, Vec1->getType(), Vec2))
2145 return Error("Invalid SHUFFLEVEC record");
2146
Mon P Wangaeb06d22008-11-10 04:46:22 +00002147 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002148 return Error("Invalid SHUFFLEVEC record");
2149 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002150 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002151 break;
2152 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002153
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002154 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2155 // Old form of ICmp/FCmp returning bool
2156 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2157 // both legal on vectors but had different behaviour.
2158 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2159 // FCmp/ICmp returning bool or vector of bool
2160
Chris Lattner7337ab92007-05-06 00:00:00 +00002161 unsigned OpNum = 0;
2162 Value *LHS, *RHS;
2163 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2164 getValue(Record, OpNum, LHS->getType(), RHS) ||
2165 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002166 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002167
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002168 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002169 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002170 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002171 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002172 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002173 break;
2174 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002175
Chris Lattner231cbcb2007-05-02 04:27:25 +00002176 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002177 {
2178 unsigned Size = Record.size();
2179 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002180 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002181 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002182 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002183 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002184
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002185 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002186 Value *Op = NULL;
2187 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2188 return Error("Invalid RET record");
2189 if (OpNum != Record.size())
2190 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002191
Chris Lattner96a74c52011-06-17 18:09:11 +00002192 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002193 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002194 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002195 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002196 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002197 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002198 return Error("Invalid BR record");
2199 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2200 if (TrueDest == 0)
2201 return Error("Invalid BR record");
2202
Devang Patele8e02132009-09-18 19:26:43 +00002203 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002204 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002205 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002206 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002207 else {
2208 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002209 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002210 if (FalseDest == 0 || Cond == 0)
2211 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002212 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002213 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002214 }
2215 break;
2216 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002217 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002218 // Check magic
2219 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2220 // New SwitchInst format with case ranges.
2221
2222 Type *OpTy = getTypeByID(Record[1]);
2223 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2224
2225 Value *Cond = getFnValueByID(Record[2], OpTy);
2226 BasicBlock *Default = getBasicBlock(Record[3]);
2227 if (OpTy == 0 || Cond == 0 || Default == 0)
2228 return Error("Invalid SWITCH record");
2229
2230 unsigned NumCases = Record[4];
2231
2232 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2233 InstructionList.push_back(SI);
2234
2235 unsigned CurIdx = 5;
2236 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002237 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002238 unsigned NumItems = Record[CurIdx++];
2239 for (unsigned ci = 0; ci != NumItems; ++ci) {
2240 bool isSingleNumber = Record[CurIdx++];
2241
2242 APInt Low;
2243 unsigned ActiveWords = 1;
2244 if (ValueBitWidth > 64)
2245 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002246 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2247 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002248 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002249
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002250 if (!isSingleNumber) {
2251 ActiveWords = 1;
2252 if (ValueBitWidth > 64)
2253 ActiveWords = Record[CurIdx++];
2254 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002255 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2256 ValueBitWidth);
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002257
2258 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2259 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002260 CurIdx += ActiveWords;
2261 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002262 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002263 }
2264 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002265 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002266 SI->addCase(Case, DestBB);
2267 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002268 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002269 if (Hash != (Record[0] & 0xFFFF))
2270 return Error("Invalid SWITCH record");
2271 I = SI;
2272 break;
2273 }
2274
2275 // Old SwitchInst format without case ranges.
2276
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002277 if (Record.size() < 3 || (Record.size() & 1) == 0)
2278 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002279 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002280 Value *Cond = getFnValueByID(Record[1], OpTy);
2281 BasicBlock *Default = getBasicBlock(Record[2]);
2282 if (OpTy == 0 || Cond == 0 || Default == 0)
2283 return Error("Invalid SWITCH record");
2284 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002285 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002286 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002287 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002288 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002289 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2290 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2291 if (CaseVal == 0 || DestBB == 0) {
2292 delete SI;
2293 return Error("Invalid SWITCH record!");
2294 }
2295 SI->addCase(CaseVal, DestBB);
2296 }
2297 I = SI;
2298 break;
2299 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002300 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002301 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002302 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002303 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002304 Value *Address = getFnValueByID(Record[1], OpTy);
2305 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002306 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002307 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002308 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002309 InstructionList.push_back(IBI);
2310 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2311 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2312 IBI->addDestination(DestBB);
2313 } else {
2314 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002315 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002316 }
2317 }
2318 I = IBI;
2319 break;
2320 }
2321
Duncan Sandsdc024672007-11-27 13:23:08 +00002322 case bitc::FUNC_CODE_INST_INVOKE: {
2323 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002324 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002325 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002326 unsigned CCInfo = Record[1];
2327 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2328 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002329
Chris Lattnera9bb7132007-05-08 05:38:01 +00002330 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002331 Value *Callee;
2332 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002333 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002334
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002335 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2336 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002337 dyn_cast<FunctionType>(CalleeTy->getElementType());
2338
2339 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002340 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2341 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002342 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002343
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002344 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002345 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2346 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2347 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002348 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002349
Chris Lattner7337ab92007-05-06 00:00:00 +00002350 if (!FTy->isVarArg()) {
2351 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002352 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002353 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002354 // Read type/value pairs for varargs params.
2355 while (OpNum != Record.size()) {
2356 Value *Op;
2357 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2358 return Error("Invalid INVOKE record");
2359 Ops.push_back(Op);
2360 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002361 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002362
Jay Foada3efbb12011-07-15 08:37:34 +00002363 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002364 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002365 cast<InvokeInst>(I)->setCallingConv(
2366 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002367 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002368 break;
2369 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002370 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2371 unsigned Idx = 0;
2372 Value *Val = 0;
2373 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2374 return Error("Invalid RESUME record");
2375 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002376 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002377 break;
2378 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002379 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002380 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002381 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002382 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002383 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002384 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002385 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002386 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002387 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002388
Jay Foad3ecfc862011-03-30 11:28:46 +00002389 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002390 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002391
Chris Lattner15e6d172007-05-04 19:11:41 +00002392 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2393 Value *V = getFnValueByID(Record[1+i], Ty);
2394 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002395 if (!V || !BB) return Error("Invalid PHI record");
2396 PN->addIncoming(V, BB);
2397 }
2398 I = PN;
2399 break;
2400 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002401
Bill Wendlinge6e88262011-08-12 20:24:12 +00002402 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2403 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2404 unsigned Idx = 0;
2405 if (Record.size() < 4)
2406 return Error("Invalid LANDINGPAD record");
2407 Type *Ty = getTypeByID(Record[Idx++]);
2408 if (!Ty) return Error("Invalid LANDINGPAD record");
2409 Value *PersFn = 0;
2410 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2411 return Error("Invalid LANDINGPAD record");
2412
2413 bool IsCleanup = !!Record[Idx++];
2414 unsigned NumClauses = Record[Idx++];
2415 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2416 LP->setCleanup(IsCleanup);
2417 for (unsigned J = 0; J != NumClauses; ++J) {
2418 LandingPadInst::ClauseType CT =
2419 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2420 Value *Val;
2421
2422 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2423 delete LP;
2424 return Error("Invalid LANDINGPAD record");
2425 }
2426
2427 assert((CT != LandingPadInst::Catch ||
2428 !isa<ArrayType>(Val->getType())) &&
2429 "Catch clause has a invalid type!");
2430 assert((CT != LandingPadInst::Filter ||
2431 isa<ArrayType>(Val->getType())) &&
2432 "Filter clause has invalid type!");
2433 LP->addClause(Val);
2434 }
2435
2436 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002437 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002438 break;
2439 }
2440
Chris Lattner96a74c52011-06-17 18:09:11 +00002441 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2442 if (Record.size() != 4)
2443 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002444 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002445 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002446 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002447 Value *Size = getFnValueByID(Record[2], OpTy);
2448 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002449 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002450 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002451 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002452 break;
2453 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002454 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002455 unsigned OpNum = 0;
2456 Value *Op;
2457 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2458 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002459 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002460
Chris Lattner7337ab92007-05-06 00:00:00 +00002461 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002462 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002463 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002464 }
Eli Friedman21006d42011-08-09 23:02:53 +00002465 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2466 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2467 unsigned OpNum = 0;
2468 Value *Op;
2469 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2470 OpNum+4 != Record.size())
2471 return Error("Invalid LOADATOMIC record");
2472
2473
2474 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2475 if (Ordering == NotAtomic || Ordering == Release ||
2476 Ordering == AcquireRelease)
2477 return Error("Invalid LOADATOMIC record");
2478 if (Ordering != NotAtomic && Record[OpNum] == 0)
2479 return Error("Invalid LOADATOMIC record");
2480 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2481
2482 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2483 Ordering, SynchScope);
2484 InstructionList.push_back(I);
2485 break;
2486 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002487 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002488 unsigned OpNum = 0;
2489 Value *Val, *Ptr;
2490 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002491 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002492 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2493 OpNum+2 != Record.size())
2494 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002495
Christopher Lambfe63fb92007-12-11 08:59:05 +00002496 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002497 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002498 break;
2499 }
Eli Friedman21006d42011-08-09 23:02:53 +00002500 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2501 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2502 unsigned OpNum = 0;
2503 Value *Val, *Ptr;
2504 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2505 getValue(Record, OpNum,
2506 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2507 OpNum+4 != Record.size())
2508 return Error("Invalid STOREATOMIC record");
2509
2510 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002511 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002512 Ordering == AcquireRelease)
2513 return Error("Invalid STOREATOMIC record");
2514 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2515 if (Ordering != NotAtomic && Record[OpNum] == 0)
2516 return Error("Invalid STOREATOMIC record");
2517
2518 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2519 Ordering, SynchScope);
2520 InstructionList.push_back(I);
2521 break;
2522 }
Eli Friedmanff030482011-07-28 21:48:00 +00002523 case bitc::FUNC_CODE_INST_CMPXCHG: {
2524 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2525 unsigned OpNum = 0;
2526 Value *Ptr, *Cmp, *New;
2527 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2528 getValue(Record, OpNum,
2529 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2530 getValue(Record, OpNum,
2531 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2532 OpNum+3 != Record.size())
2533 return Error("Invalid CMPXCHG record");
2534 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002535 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002536 return Error("Invalid CMPXCHG record");
2537 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2538 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2539 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2540 InstructionList.push_back(I);
2541 break;
2542 }
2543 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2544 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2545 unsigned OpNum = 0;
2546 Value *Ptr, *Val;
2547 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2548 getValue(Record, OpNum,
2549 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2550 OpNum+4 != Record.size())
2551 return Error("Invalid ATOMICRMW record");
2552 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2553 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2554 Operation > AtomicRMWInst::LAST_BINOP)
2555 return Error("Invalid ATOMICRMW record");
2556 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002557 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002558 return Error("Invalid ATOMICRMW record");
2559 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2560 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2561 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2562 InstructionList.push_back(I);
2563 break;
2564 }
Eli Friedman47f35132011-07-25 23:16:38 +00002565 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2566 if (2 != Record.size())
2567 return Error("Invalid FENCE record");
2568 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2569 if (Ordering == NotAtomic || Ordering == Unordered ||
2570 Ordering == Monotonic)
2571 return Error("Invalid FENCE record");
2572 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2573 I = new FenceInst(Context, Ordering, SynchScope);
2574 InstructionList.push_back(I);
2575 break;
2576 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002577 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002578 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2579 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002580 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002581
Devang Patel05988662008-09-25 21:00:45 +00002582 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002583 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002584
Chris Lattnera9bb7132007-05-08 05:38:01 +00002585 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002586 Value *Callee;
2587 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2588 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002589
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002590 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2591 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002592 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002593 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002594 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002595
Chris Lattner0579f7f2007-05-03 22:04:19 +00002596 SmallVector<Value*, 16> Args;
2597 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002598 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002599 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002600 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002601 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002602 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002603 if (Args.back() == 0) return Error("Invalid CALL record");
2604 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002605
Chris Lattner0579f7f2007-05-03 22:04:19 +00002606 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002607 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002608 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002609 return Error("Invalid CALL record");
2610 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002611 while (OpNum != Record.size()) {
2612 Value *Op;
2613 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2614 return Error("Invalid CALL record");
2615 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002616 }
2617 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002618
Jay Foada3efbb12011-07-15 08:37:34 +00002619 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002620 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002621 cast<CallInst>(I)->setCallingConv(
2622 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002623 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002624 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002625 break;
2626 }
2627 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2628 if (Record.size() < 3)
2629 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002630 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002631 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002632 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002633 if (!OpTy || !Op || !ResTy)
2634 return Error("Invalid VAARG record");
2635 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002636 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002637 break;
2638 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002639 }
2640
2641 // Add instruction to end of current BB. If there is no current BB, reject
2642 // this file.
2643 if (CurBB == 0) {
2644 delete I;
2645 return Error("Invalid instruction with no BB");
2646 }
2647 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002648
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002649 // If this was a terminator instruction, move to the next block.
2650 if (isa<TerminatorInst>(I)) {
2651 ++CurBBNo;
2652 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2653 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002654
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002655 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002656 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002657 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002658 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002659
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002660 // Check the function list for unresolved values.
2661 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2662 if (A->getParent() == 0) {
2663 // We found at least one unresolved value. Nuke them all to avoid leaks.
2664 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002665 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002666 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002667 delete A;
2668 }
2669 }
Chris Lattner35a04702007-05-04 03:50:29 +00002670 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002671 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002672 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002673
Dan Gohman064ff3e2010-08-25 20:23:38 +00002674 // FIXME: Check for unresolved forward-declared metadata references
2675 // and clean up leaks.
2676
Chris Lattner50b136d2009-10-28 05:53:48 +00002677 // See if anything took the address of blocks in this function. If so,
2678 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002679 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2680 BlockAddrFwdRefs.find(F);
2681 if (BAFRI != BlockAddrFwdRefs.end()) {
2682 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2683 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2684 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002685 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002686 return Error("Invalid blockaddress block #");
2687
2688 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002689 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002690 FwdRef->eraseFromParent();
2691 }
2692
2693 BlockAddrFwdRefs.erase(BAFRI);
2694 }
2695
Chris Lattner980e5aa2007-05-01 05:52:21 +00002696 // Trim the value list down to the size it was before we parsed this function.
2697 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002698 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002699 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002700 return false;
2701}
2702
Derek Schuff2ea93872012-02-06 22:30:29 +00002703/// FindFunctionInStream - Find the function body in the bitcode stream
2704bool BitcodeReader::FindFunctionInStream(Function *F,
2705 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2706 while (DeferredFunctionInfoIterator->second == 0) {
2707 if (Stream.AtEndOfStream())
2708 return Error("Could not find Function in stream");
2709 // ParseModule will parse the next body in the stream and set its
2710 // position in the DeferredFunctionInfo map.
2711 if (ParseModule(true)) return true;
2712 }
2713 return false;
2714}
2715
Chris Lattnerb348bb82007-05-18 04:02:46 +00002716//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002717// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002718//===----------------------------------------------------------------------===//
2719
2720
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002721bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2722 if (const Function *F = dyn_cast<Function>(GV)) {
2723 return F->isDeclaration() &&
2724 DeferredFunctionInfo.count(const_cast<Function*>(F));
2725 }
2726 return false;
2727}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002728
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002729bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2730 Function *F = dyn_cast<Function>(GV);
2731 // If it's not a function or is already material, ignore the request.
2732 if (!F || !F->isMaterializable()) return false;
2733
2734 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002735 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002736 // If its position is recorded as 0, its body is somewhere in the stream
2737 // but we haven't seen it yet.
2738 if (DFII->second == 0)
2739 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002740
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002741 // Move the bit stream to the saved position of the deferred function body.
2742 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002743
Chris Lattnerb348bb82007-05-18 04:02:46 +00002744 if (ParseFunctionBody(F)) {
2745 if (ErrInfo) *ErrInfo = ErrorString;
2746 return true;
2747 }
Chandler Carruth69940402007-08-04 01:51:18 +00002748
2749 // Upgrade any old intrinsic calls in the function.
2750 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2751 E = UpgradedIntrinsics.end(); I != E; ++I) {
2752 if (I->first != I->second) {
2753 for (Value::use_iterator UI = I->first->use_begin(),
2754 UE = I->first->use_end(); UI != UE; ) {
2755 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2756 UpgradeIntrinsicCall(CI, I->second);
2757 }
2758 }
2759 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002760
Chris Lattnerb348bb82007-05-18 04:02:46 +00002761 return false;
2762}
2763
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002764bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2765 const Function *F = dyn_cast<Function>(GV);
2766 if (!F || F->isDeclaration())
2767 return false;
2768 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2769}
2770
2771void BitcodeReader::Dematerialize(GlobalValue *GV) {
2772 Function *F = dyn_cast<Function>(GV);
2773 // If this function isn't dematerializable, this is a noop.
2774 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002775 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002776
Chris Lattnerb348bb82007-05-18 04:02:46 +00002777 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002778
Chris Lattnerb348bb82007-05-18 04:02:46 +00002779 // Just forget the function body, we can remat it later.
2780 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002781}
2782
2783
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002784bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2785 assert(M == TheModule &&
2786 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002787 // Iterate over the module, deserializing any functions that are still on
2788 // disk.
2789 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2790 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002791 if (F->isMaterializable() &&
2792 Materialize(F, ErrInfo))
2793 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002794
Derek Schuff0ffe6982012-02-29 00:07:09 +00002795 // At this point, if there are any function bodies, the current bit is
2796 // pointing to the END_BLOCK record after them. Now make sure the rest
2797 // of the bits in the module have been read.
2798 if (NextUnreadBit)
2799 ParseModule(true);
2800
Daniel Dunbara279bc32009-09-20 02:20:51 +00002801 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2802 // delete the old functions to clean up. We can't do this unless the entire
2803 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002804 // with calls to the old function.
2805 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2806 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2807 if (I->first != I->second) {
2808 for (Value::use_iterator UI = I->first->use_begin(),
2809 UE = I->first->use_end(); UI != UE; ) {
2810 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2811 UpgradeIntrinsicCall(CI, I->second);
2812 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002813 if (!I->first->use_empty())
2814 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002815 I->first->eraseFromParent();
2816 }
2817 }
2818 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002819
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002820 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002821}
2822
Derek Schuff2ea93872012-02-06 22:30:29 +00002823bool BitcodeReader::InitStream() {
2824 if (LazyStreamer) return InitLazyStream();
2825 return InitStreamFromBuffer();
2826}
2827
2828bool BitcodeReader::InitStreamFromBuffer() {
2829 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2830 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2831
2832 if (Buffer->getBufferSize() & 3) {
2833 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2834 return Error("Invalid bitcode signature");
2835 else
2836 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2837 }
2838
2839 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2840 // The magic number is 0x0B17C0DE stored in little endian.
2841 if (isBitcodeWrapper(BufPtr, BufEnd))
2842 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2843 return Error("Invalid bitcode wrapper header");
2844
2845 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2846 Stream.init(*StreamFile);
2847
2848 return false;
2849}
2850
2851bool BitcodeReader::InitLazyStream() {
2852 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2853 // see it.
2854 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2855 StreamFile.reset(new BitstreamReader(Bytes));
2856 Stream.init(*StreamFile);
2857
2858 unsigned char buf[16];
2859 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2860 return Error("Bitcode stream must be at least 16 bytes in length");
2861
2862 if (!isBitcode(buf, buf + 16))
2863 return Error("Invalid bitcode signature");
2864
2865 if (isBitcodeWrapper(buf, buf + 4)) {
2866 const unsigned char *bitcodeStart = buf;
2867 const unsigned char *bitcodeEnd = buf + 16;
2868 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2869 Bytes->dropLeadingBytes(bitcodeStart - buf);
2870 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2871 }
2872 return false;
2873}
Chris Lattner48f84872007-05-01 04:59:48 +00002874
Chris Lattnerc453f762007-04-29 07:54:31 +00002875//===----------------------------------------------------------------------===//
2876// External interface
2877//===----------------------------------------------------------------------===//
2878
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002879/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002880///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002881Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2882 LLVMContext& Context,
2883 std::string *ErrMsg) {
2884 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002885 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002886 M->setMaterializer(R);
2887 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002888 if (ErrMsg)
2889 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002890
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002891 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002892 return 0;
2893 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002894 // Have the BitcodeReader dtor delete 'Buffer'.
2895 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002896
2897 R->materializeForwardReferencedFunctions();
2898
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002899 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002900}
2901
Derek Schuff2ea93872012-02-06 22:30:29 +00002902
2903Module *llvm::getStreamedBitcodeModule(const std::string &name,
2904 DataStreamer *streamer,
2905 LLVMContext &Context,
2906 std::string *ErrMsg) {
2907 Module *M = new Module(name, Context);
2908 BitcodeReader *R = new BitcodeReader(streamer, Context);
2909 M->setMaterializer(R);
2910 if (R->ParseBitcodeInto(M)) {
2911 if (ErrMsg)
2912 *ErrMsg = R->getErrorString();
2913 delete M; // Also deletes R.
2914 return 0;
2915 }
2916 R->setBufferOwned(false); // no buffer to delete
2917 return M;
2918}
2919
Chris Lattnerc453f762007-04-29 07:54:31 +00002920/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2921/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002922Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002923 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002924 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2925 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002926
2927 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2928 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002929 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002930
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002931 // Read in the entire module, and destroy the BitcodeReader.
2932 if (M->MaterializeAllPermanently(ErrMsg)) {
2933 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002934 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002935 }
Bill Wendling34711742010-10-06 01:22:42 +00002936
Chad Rosiercbbb0962011-12-07 21:44:12 +00002937 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2938 // written. We must defer until the Module has been fully materialized.
2939
Chris Lattnerc453f762007-04-29 07:54:31 +00002940 return M;
2941}
Bill Wendling34711742010-10-06 01:22:42 +00002942
2943std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2944 LLVMContext& Context,
2945 std::string *ErrMsg) {
2946 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2947 // Don't let the BitcodeReader dtor delete 'Buffer'.
2948 R->setBufferOwned(false);
2949
2950 std::string Triple("");
2951 if (R->ParseTriple(Triple))
2952 if (ErrMsg)
2953 *ErrMsg = R->getErrorString();
2954
2955 delete R;
2956 return Triple;
2957}