blob: f09b93b33a5b32a83d32d50d4b718f7926ada990 [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//===----------------------------------------------------------------------===//
Chris Lattnercaee0dc2007-04-22 06:23:29 +00009
Chris Lattnerc453f762007-04-29 07:54:31 +000010#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000011#include "BitcodeReader.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000012#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/AutoUpgrade.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000015#include "llvm/IR/Constants.h"
16#include "llvm/IR/DerivedTypes.h"
17#include "llvm/IR/InlineAsm.h"
18#include "llvm/IR/IntrinsicInst.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/OperandTraits.h"
21#include "llvm/IR/Operator.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000022#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000023#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000024#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000025using namespace llvm;
26
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000027enum {
28 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
29};
30
Rafael Espindola47f79bb2012-01-02 07:49:53 +000031void BitcodeReader::materializeForwardReferencedFunctions() {
32 while (!BlockAddrFwdRefs.empty()) {
33 Function *F = BlockAddrFwdRefs.begin()->first;
34 F->Materialize();
35 }
36}
37
Chris Lattnerb348bb82007-05-18 04:02:46 +000038void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000039 if (BufferOwned)
40 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000041 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000042 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000043 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000044 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000045
Bill Wendling99faa3b2012-12-07 23:16:57 +000046 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 std::vector<BasicBlock*>().swap(FunctionBBs);
48 std::vector<Function*>().swap(FunctionsWithBodies);
49 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000050 MDKindMap.clear();
Benjamin Kramer122f5e52012-09-21 14:34:31 +000051
52 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
Chris Lattnerc453f762007-04-29 07:54:31 +000053}
54
Chris Lattner48c85b82007-05-04 03:30:17 +000055//===----------------------------------------------------------------------===//
56// Helper functions to implement forward reference resolution, etc.
57//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000058
Chris Lattnercaee0dc2007-04-22 06:23:29 +000059/// ConvertToString - Convert a string from a record into an std::string, return
60/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000061template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000062static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000063 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000064 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000065 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000066
Chris Lattner15e6d172007-05-04 19:11:41 +000067 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
68 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000069 return false;
70}
71
72static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
73 switch (Val) {
74 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000075 case 0: return GlobalValue::ExternalLinkage;
76 case 1: return GlobalValue::WeakAnyLinkage;
77 case 2: return GlobalValue::AppendingLinkage;
78 case 3: return GlobalValue::InternalLinkage;
79 case 4: return GlobalValue::LinkOnceAnyLinkage;
80 case 5: return GlobalValue::DLLImportLinkage;
81 case 6: return GlobalValue::DLLExportLinkage;
82 case 7: return GlobalValue::ExternalWeakLinkage;
83 case 8: return GlobalValue::CommonLinkage;
84 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000085 case 10: return GlobalValue::WeakODRLinkage;
86 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000087 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000088 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000089 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000090 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000091 }
92}
93
94static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
95 switch (Val) {
96 default: // Map unknown visibilities to default.
97 case 0: return GlobalValue::DefaultVisibility;
98 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000099 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000100 }
101}
102
Hans Wennborgce718ff2012-06-23 11:37:03 +0000103static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
104 switch (Val) {
105 case 0: return GlobalVariable::NotThreadLocal;
106 default: // Map unknown non-zero value to general dynamic.
107 case 1: return GlobalVariable::GeneralDynamicTLSModel;
108 case 2: return GlobalVariable::LocalDynamicTLSModel;
109 case 3: return GlobalVariable::InitialExecTLSModel;
110 case 4: return GlobalVariable::LocalExecTLSModel;
111 }
112}
113
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000114static int GetDecodedCastOpcode(unsigned Val) {
115 switch (Val) {
116 default: return -1;
117 case bitc::CAST_TRUNC : return Instruction::Trunc;
118 case bitc::CAST_ZEXT : return Instruction::ZExt;
119 case bitc::CAST_SEXT : return Instruction::SExt;
120 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
121 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
122 case bitc::CAST_UITOFP : return Instruction::UIToFP;
123 case bitc::CAST_SITOFP : return Instruction::SIToFP;
124 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
125 case bitc::CAST_FPEXT : return Instruction::FPExt;
126 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
127 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
128 case bitc::CAST_BITCAST : return Instruction::BitCast;
129 }
130}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000131static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000132 switch (Val) {
133 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000134 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000135 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000136 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000137 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000138 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000139 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000140 case bitc::BINOP_UDIV: return Instruction::UDiv;
141 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000142 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000143 case bitc::BINOP_UREM: return Instruction::URem;
144 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000145 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000146 case bitc::BINOP_SHL: return Instruction::Shl;
147 case bitc::BINOP_LSHR: return Instruction::LShr;
148 case bitc::BINOP_ASHR: return Instruction::AShr;
149 case bitc::BINOP_AND: return Instruction::And;
150 case bitc::BINOP_OR: return Instruction::Or;
151 case bitc::BINOP_XOR: return Instruction::Xor;
152 }
153}
154
Eli Friedmanff030482011-07-28 21:48:00 +0000155static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
156 switch (Val) {
157 default: return AtomicRMWInst::BAD_BINOP;
158 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
159 case bitc::RMW_ADD: return AtomicRMWInst::Add;
160 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
161 case bitc::RMW_AND: return AtomicRMWInst::And;
162 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
163 case bitc::RMW_OR: return AtomicRMWInst::Or;
164 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
165 case bitc::RMW_MAX: return AtomicRMWInst::Max;
166 case bitc::RMW_MIN: return AtomicRMWInst::Min;
167 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
168 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
169 }
170}
171
Eli Friedman47f35132011-07-25 23:16:38 +0000172static AtomicOrdering GetDecodedOrdering(unsigned Val) {
173 switch (Val) {
174 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
175 case bitc::ORDERING_UNORDERED: return Unordered;
176 case bitc::ORDERING_MONOTONIC: return Monotonic;
177 case bitc::ORDERING_ACQUIRE: return Acquire;
178 case bitc::ORDERING_RELEASE: return Release;
179 case bitc::ORDERING_ACQREL: return AcquireRelease;
180 default: // Map unknown orderings to sequentially-consistent.
181 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
182 }
183}
184
185static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
186 switch (Val) {
187 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
188 default: // Map unknown scopes to cross-thread.
189 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
190 }
191}
192
Gabor Greifefe65362008-05-10 08:32:32 +0000193namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000194namespace {
195 /// @brief A class for maintaining the slot number definition
196 /// as a placeholder for the actual definition for forward constants defs.
197 class ConstantPlaceHolder : public ConstantExpr {
Craig Topper86a1c322012-09-15 17:09:36 +0000198 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greif051a9502008-04-06 20:25:17 +0000199 public:
200 // allocate space for exactly one operand
201 void *operator new(size_t s) {
202 return User::operator new(s, 1);
203 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000204 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000205 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000206 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000207 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000208
Chris Lattnerea693df2008-08-21 02:34:16 +0000209 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattnerea693df2008-08-21 02:34:16 +0000210 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000211 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000212 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000214
215
Gabor Greifefe65362008-05-10 08:32:32 +0000216 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000217 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000218 };
219}
220
Chris Lattner46e77402009-03-31 22:55:09 +0000221// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000222template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000223struct OperandTraits<ConstantPlaceHolder> :
224 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000225};
Gabor Greifefe65362008-05-10 08:32:32 +0000226}
227
Chris Lattner46e77402009-03-31 22:55:09 +0000228
229void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
230 if (Idx == size()) {
231 push_back(V);
232 return;
233 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000234
Chris Lattner46e77402009-03-31 22:55:09 +0000235 if (Idx >= size())
236 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000237
Chris Lattner46e77402009-03-31 22:55:09 +0000238 WeakVH &OldV = ValuePtrs[Idx];
239 if (OldV == 0) {
240 OldV = V;
241 return;
242 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000243
Chris Lattner46e77402009-03-31 22:55:09 +0000244 // Handle constants and non-constants (e.g. instrs) differently for
245 // efficiency.
246 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
247 ResolveConstants.push_back(std::make_pair(PHC, Idx));
248 OldV = V;
249 } else {
250 // If there was a forward reference to this value, replace it.
251 Value *PrevVal = OldV;
252 OldV->replaceAllUsesWith(V);
253 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000254 }
255}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000256
Gabor Greifefe65362008-05-10 08:32:32 +0000257
Chris Lattner522b7b12007-04-24 05:48:56 +0000258Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000259 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000260 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000261 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000262
Chris Lattner46e77402009-03-31 22:55:09 +0000263 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000264 assert(Ty == V->getType() && "Type mismatch in constant table!");
265 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000266 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000267
268 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000269 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000270 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000271 return C;
272}
273
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000274Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000275 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000276 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000277
Chris Lattner46e77402009-03-31 22:55:09 +0000278 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000279 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
280 return V;
281 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000282
Chris Lattner01ff65f2007-05-02 05:16:49 +0000283 // No type specified, must be invalid reference.
284 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000285
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000286 // Create and return a placeholder, which will later be RAUW'd.
287 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000288 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000289 return V;
290}
291
Chris Lattnerea693df2008-08-21 02:34:16 +0000292/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
293/// resolves any forward references. The idea behind this is that we sometimes
294/// get constants (such as large arrays) which reference *many* forward ref
295/// constants. Replacing each of these causes a lot of thrashing when
296/// building/reuniquing the constant. Instead of doing this, we look at all the
297/// uses and rewrite all the place holders at once for any constant that uses
298/// a placeholder.
299void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000300 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000301 // binary search.
302 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000303
Chris Lattnerea693df2008-08-21 02:34:16 +0000304 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000307 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000308 Constant *Placeholder = ResolveConstants.back().first;
309 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000310
Chris Lattnerea693df2008-08-21 02:34:16 +0000311 // Loop over all users of the placeholder, updating them to reference the
312 // new value. If they reference more than one placeholder, update them all
313 // at once.
314 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000315 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000316 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000317
Chris Lattnerea693df2008-08-21 02:34:16 +0000318 // If the using object isn't uniqued, just update the operands. This
319 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000320 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000321 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000322 continue;
323 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000324
Chris Lattnerea693df2008-08-21 02:34:16 +0000325 // Otherwise, we have a constant that uses the placeholder. Replace that
326 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000327 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000328 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
329 I != E; ++I) {
330 Value *NewOp;
331 if (!isa<ConstantPlaceHolder>(*I)) {
332 // Not a placeholder reference.
333 NewOp = *I;
334 } else if (*I == Placeholder) {
335 // Common case is that it just references this one placeholder.
336 NewOp = RealVal;
337 } else {
338 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339 ResolveConstantsTy::iterator It =
340 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000341 std::pair<Constant*, unsigned>(cast<Constant>(*I),
342 0));
343 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000344 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000345 }
346
347 NewOps.push_back(cast<Constant>(NewOp));
348 }
349
350 // Make the new constant.
351 Constant *NewC;
352 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000353 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000354 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000355 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000356 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000357 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000358 } else {
359 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000360 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000361 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerea693df2008-08-21 02:34:16 +0000363 UserC->replaceAllUsesWith(NewC);
364 UserC->destroyConstant();
365 NewOps.clear();
366 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Nick Lewyckycb337992009-05-10 20:57:05 +0000368 // Update all ValueHandles, they should be the only users at this point.
369 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000370 delete Placeholder;
371 }
372}
373
Devang Pateld5ac4042009-08-04 06:00:18 +0000374void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
375 if (Idx == size()) {
376 push_back(V);
377 return;
378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Devang Pateld5ac4042009-08-04 06:00:18 +0000380 if (Idx >= size())
381 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000382
Devang Pateld5ac4042009-08-04 06:00:18 +0000383 WeakVH &OldV = MDValuePtrs[Idx];
384 if (OldV == 0) {
385 OldV = V;
386 return;
387 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Devang Pateld5ac4042009-08-04 06:00:18 +0000389 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000390 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000391 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000392 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000393 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
394 // value for Idx.
395 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000396}
397
398Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
399 if (Idx >= size())
400 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000401
Devang Pateld5ac4042009-08-04 06:00:18 +0000402 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000403 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000404 return V;
405 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000406
Devang Pateld5ac4042009-08-04 06:00:18 +0000407 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000408 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000409 MDValuePtrs[Idx] = V;
410 return V;
411}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413Type *BitcodeReader::getTypeByID(unsigned ID) {
414 // The type table size is always specified correctly.
415 if (ID >= TypeList.size())
416 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000417
Chris Lattner1afcace2011-07-09 17:41:24 +0000418 if (Type *Ty = TypeList[ID])
419 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000420
Chris Lattner1afcace2011-07-09 17:41:24 +0000421 // If we have a forward reference, the only possible case is when it is to a
422 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000423 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000424}
425
Chris Lattner1afcace2011-07-09 17:41:24 +0000426
Chris Lattner48c85b82007-05-04 03:30:17 +0000427//===----------------------------------------------------------------------===//
428// Functions for parsing blocks from the bitcode file
429//===----------------------------------------------------------------------===//
430
Devang Patel05988662008-09-25 21:00:45 +0000431bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000432 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000433 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000434
Devang Patel19c87462008-09-26 22:53:05 +0000435 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000436 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000437
Chris Lattner48c85b82007-05-04 03:30:17 +0000438 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000439
Devang Patel05988662008-09-25 21:00:45 +0000440 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000441
Chris Lattner48c85b82007-05-04 03:30:17 +0000442 // Read all the records.
443 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000444 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
445
446 switch (Entry.Kind) {
447 case BitstreamEntry::SubBlock: // Handled for us already.
448 case BitstreamEntry::Error:
449 return Error("Error at end of PARAMATTR block");
450 case BitstreamEntry::EndBlock:
Chris Lattner48c85b82007-05-04 03:30:17 +0000451 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000452 case BitstreamEntry::Record:
453 // The interesting case.
454 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000455 }
Chris Lattner5a4251c2013-01-20 02:13:19 +0000456
Chris Lattner48c85b82007-05-04 03:30:17 +0000457 // Read a record.
458 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000459 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner48c85b82007-05-04 03:30:17 +0000460 default: // Default behavior: ignore.
461 break;
462 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
463 if (Record.size() & 1)
464 return Error("Invalid ENTRY record");
465
Chris Lattner48c85b82007-05-04 03:30:17 +0000466 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling034b94b2012-12-19 07:18:57 +0000467 Attribute ReconstitutedAttr =
468 Attribute::decodeLLVMAttributesForBitcode(Context, Record[i+1]);
Bill Wendling1db9b692013-01-09 23:36:50 +0000469 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000470 }
Chris Lattner461edd92008-03-12 02:25:52 +0000471
Devang Patel19c87462008-09-26 22:53:05 +0000472 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling702cc912012-10-15 20:35:56 +0000473 AttrBuilder B(Record[i+1]);
Bill Wendlingcb3de0b2012-10-15 04:46:55 +0000474 if (B.hasAttributes())
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000475 Attrs.push_back(AttributeWithIndex::get(Record[i],
Bill Wendling034b94b2012-12-19 07:18:57 +0000476 Attribute::get(Context, B)));
Devang Patel19c87462008-09-26 22:53:05 +0000477 }
Devang Patel19c87462008-09-26 22:53:05 +0000478
Bill Wendling99faa3b2012-12-07 23:16:57 +0000479 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000480 Attrs.clear();
481 break;
482 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000483 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000484 }
485}
486
Chris Lattner86697142007-05-01 05:01:34 +0000487bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000488 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000489 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000490
Chris Lattner1afcace2011-07-09 17:41:24 +0000491 return ParseTypeTableBody();
492}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000493
Chris Lattner1afcace2011-07-09 17:41:24 +0000494bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000495 if (!TypeList.empty())
496 return Error("Multiple TYPE_BLOCKs found!");
497
498 SmallVector<uint64_t, 64> Record;
499 unsigned NumRecords = 0;
500
Chris Lattner1afcace2011-07-09 17:41:24 +0000501 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000502
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000503 // Read all the records for this type table.
504 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000505 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
506
507 switch (Entry.Kind) {
508 case BitstreamEntry::SubBlock: // Handled for us already.
509 case BitstreamEntry::Error:
510 Error("Error in the type table block");
511 return true;
512 case BitstreamEntry::EndBlock:
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000513 if (NumRecords != TypeList.size())
514 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000515 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000516 case BitstreamEntry::Record:
517 // The interesting case.
518 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000519 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000520
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000521 // Read a record.
522 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000523 Type *ResultTy = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000524 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000525 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000526 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
527 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
528 // type list. This allows us to reserve space.
529 if (Record.size() < 1)
530 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000531 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000532 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000533 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000534 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000535 break;
Dan Gohmance163392011-12-17 00:04:22 +0000536 case bitc::TYPE_CODE_HALF: // HALF
537 ResultTy = Type::getHalfTy(Context);
538 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000539 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000540 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000541 break;
542 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000543 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000544 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000545 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000546 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000547 break;
548 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000549 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000550 break;
551 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000552 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000553 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000554 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000555 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000556 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000557 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000558 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000559 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000560 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
561 ResultTy = Type::getX86_MMXTy(Context);
562 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000563 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
564 if (Record.size() < 1)
565 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000566
Owen Anderson1d0be152009-08-13 21:58:54 +0000567 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000568 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000569 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000570 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000571 if (Record.size() < 1)
572 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000573 unsigned AddressSpace = 0;
574 if (Record.size() == 2)
575 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000576 ResultTy = getTypeByID(Record[0]);
577 if (ResultTy == 0) return Error("invalid element type in pointer type");
578 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000579 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000580 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000581 case bitc::TYPE_CODE_FUNCTION_OLD: {
582 // FIXME: attrid is dead, remove it in LLVM 4.0
583 // FUNCTION: [vararg, attrid, retty, paramty x N]
584 if (Record.size() < 3)
585 return Error("Invalid FUNCTION type record");
586 SmallVector<Type*, 8> ArgTys;
587 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
588 if (Type *T = getTypeByID(Record[i]))
589 ArgTys.push_back(T);
590 else
591 break;
592 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000593
Nuno Lopesee8100d2012-05-23 15:19:39 +0000594 ResultTy = getTypeByID(Record[2]);
595 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
596 return Error("invalid type in function type");
597
598 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
599 break;
600 }
Chad Rosiercde54642011-11-03 00:14:01 +0000601 case bitc::TYPE_CODE_FUNCTION: {
602 // FUNCTION: [vararg, retty, paramty x N]
603 if (Record.size() < 2)
604 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000605 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000606 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
607 if (Type *T = getTypeByID(Record[i]))
608 ArgTys.push_back(T);
609 else
610 break;
611 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000612
Chad Rosiercde54642011-11-03 00:14:01 +0000613 ResultTy = getTypeByID(Record[1]);
614 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
615 return Error("invalid type in function type");
616
617 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
618 break;
619 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000620 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000621 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000622 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000623 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000624 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
625 if (Type *T = getTypeByID(Record[i]))
626 EltTys.push_back(T);
627 else
628 break;
629 }
630 if (EltTys.size() != Record.size()-1)
631 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000632 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000633 break;
634 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000635 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
636 if (ConvertToString(Record, 0, TypeName))
637 return Error("Invalid STRUCT_NAME record");
638 continue;
639
640 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
641 if (Record.size() < 1)
642 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000643
Chris Lattner1afcace2011-07-09 17:41:24 +0000644 if (NumRecords >= TypeList.size())
645 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000646
Chris Lattner1afcace2011-07-09 17:41:24 +0000647 // Check to see if this was forward referenced, if so fill in the temp.
648 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
649 if (Res) {
650 Res->setName(TypeName);
651 TypeList[NumRecords] = 0;
652 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000653 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000654 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000655
Chris Lattner1afcace2011-07-09 17:41:24 +0000656 SmallVector<Type*, 8> EltTys;
657 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
658 if (Type *T = getTypeByID(Record[i]))
659 EltTys.push_back(T);
660 else
661 break;
662 }
663 if (EltTys.size() != Record.size()-1)
664 return Error("invalid STRUCT type record");
665 Res->setBody(EltTys, Record[0]);
666 ResultTy = Res;
667 break;
668 }
669 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
670 if (Record.size() != 1)
671 return Error("Invalid OPAQUE type record");
672
673 if (NumRecords >= TypeList.size())
674 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000675
Chris Lattner1afcace2011-07-09 17:41:24 +0000676 // Check to see if this was forward referenced, if so fill in the temp.
677 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
678 if (Res) {
679 Res->setName(TypeName);
680 TypeList[NumRecords] = 0;
681 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000682 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000683 TypeName.clear();
684 ResultTy = Res;
685 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000686 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000687 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
688 if (Record.size() < 2)
689 return Error("Invalid ARRAY type record");
690 if ((ResultTy = getTypeByID(Record[1])))
691 ResultTy = ArrayType::get(ResultTy, Record[0]);
692 else
693 return Error("Invalid ARRAY type element");
694 break;
695 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
696 if (Record.size() < 2)
697 return Error("Invalid VECTOR type record");
698 if ((ResultTy = getTypeByID(Record[1])))
699 ResultTy = VectorType::get(ResultTy, Record[0]);
700 else
701 return Error("Invalid ARRAY type element");
702 break;
703 }
704
705 if (NumRecords >= TypeList.size())
706 return Error("invalid TYPE table");
707 assert(ResultTy && "Didn't read a type?");
708 assert(TypeList[NumRecords] == 0 && "Already read type?");
709 TypeList[NumRecords++] = ResultTy;
710 }
711}
712
Chris Lattner86697142007-05-01 05:01:34 +0000713bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000714 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000715 return Error("Malformed block record");
716
717 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000718
Chris Lattner0b2482a2007-04-23 21:26:05 +0000719 // Read all the records for this value table.
720 SmallString<128> ValueName;
721 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000722 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
723
724 switch (Entry.Kind) {
725 case BitstreamEntry::SubBlock: // Handled for us already.
726 case BitstreamEntry::Error:
727 return Error("malformed value symbol table block");
728 case BitstreamEntry::EndBlock:
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000729 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000730 case BitstreamEntry::Record:
731 // The interesting case.
732 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000733 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000734
Chris Lattner0b2482a2007-04-23 21:26:05 +0000735 // Read a record.
736 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000737 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000738 default: // Default behavior: unknown type.
739 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000740 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000741 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000742 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000743 unsigned ValueID = Record[0];
744 if (ValueID >= ValueList.size())
745 return Error("Invalid Value ID in VST_ENTRY record");
746 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000747
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000748 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000749 ValueName.clear();
750 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000751 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000752 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000753 if (ConvertToString(Record, 1, ValueName))
754 return Error("Invalid VST_BBENTRY record");
755 BasicBlock *BB = getBasicBlock(Record[0]);
756 if (BB == 0)
757 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000758
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000759 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000760 ValueName.clear();
761 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000762 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000763 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000764 }
765}
766
Devang Patele54abc92009-07-22 17:43:22 +0000767bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000768 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000769
770 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
771 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000772
Devang Patele54abc92009-07-22 17:43:22 +0000773 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000774
Devang Patele54abc92009-07-22 17:43:22 +0000775 // Read all the records.
776 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000777 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
778
779 switch (Entry.Kind) {
780 case BitstreamEntry::SubBlock: // Handled for us already.
781 case BitstreamEntry::Error:
782 Error("malformed metadata block");
783 return true;
784 case BitstreamEntry::EndBlock:
Devang Patele54abc92009-07-22 17:43:22 +0000785 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000786 case BitstreamEntry::Record:
787 // The interesting case.
788 break;
Devang Patele54abc92009-07-22 17:43:22 +0000789 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000790
Victor Hernandez24e64df2010-01-10 07:14:18 +0000791 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000792 // Read a record.
793 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000794 unsigned Code = Stream.readRecord(Entry.ID, Record);
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000795 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000796 default: // Default behavior: ignore.
797 break;
Devang Patelaa993142009-07-29 22:34:41 +0000798 case bitc::METADATA_NAME: {
Chris Lattner1ca114a2013-01-20 02:54:05 +0000799 // Read name of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000800 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000801 Record.clear();
802 Code = Stream.ReadCode();
803
Chris Lattner9d61dd92011-06-17 17:50:30 +0000804 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner5a4251c2013-01-20 02:13:19 +0000805 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000806 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000807
808 // Read named metadata elements.
809 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000810 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000811 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000812 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
813 if (MD == 0)
814 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000815 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000816 }
Devang Patelaa993142009-07-29 22:34:41 +0000817 break;
818 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000819 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000820 IsFunctionLocal = true;
821 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000822 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000823 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000824 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000825
Devang Patel104cf9e2009-07-23 01:07:34 +0000826 unsigned Size = Record.size();
827 SmallVector<Value*, 8> Elts;
828 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000829 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000830 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000831 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000832 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000833 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000834 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
835 else
836 Elts.push_back(NULL);
837 }
Jay Foadec9186b2011-04-21 19:59:31 +0000838 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000839 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000840 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000841 break;
842 }
Devang Patele54abc92009-07-22 17:43:22 +0000843 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000844 SmallString<8> String(Record.begin(), Record.end());
845 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000846 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000847 break;
848 }
Devang Patele8e02132009-09-18 19:26:43 +0000849 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000850 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000851 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000852
Devang Patela2148402009-09-28 21:14:55 +0000853 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000854 SmallString<8> Name(Record.begin()+1, Record.end());
855
Chris Lattner08113472009-12-29 09:01:33 +0000856 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000857 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
858 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000859 break;
860 }
Devang Patele54abc92009-07-22 17:43:22 +0000861 }
862 }
863}
864
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000865/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +0000866/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000867uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +0000868 if ((V & 1) == 0)
869 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000870 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000871 return -(V >> 1);
872 // There is no such thing as -0 with integers. "-0" really means MININT.
873 return 1ULL << 63;
874}
875
Chris Lattner07d98b42007-04-26 02:46:40 +0000876/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
877/// values and aliases that we can.
878bool BitcodeReader::ResolveGlobalAndAliasInits() {
879 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
880 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000881
Chris Lattner07d98b42007-04-26 02:46:40 +0000882 GlobalInitWorklist.swap(GlobalInits);
883 AliasInitWorklist.swap(AliasInits);
884
885 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000886 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000887 if (ValID >= ValueList.size()) {
888 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000889 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000890 } else {
891 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
892 GlobalInitWorklist.back().first->setInitializer(C);
893 else
894 return Error("Global variable initializer is not a constant!");
895 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000896 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000897 }
898
899 while (!AliasInitWorklist.empty()) {
900 unsigned ValID = AliasInitWorklist.back().second;
901 if (ValID >= ValueList.size()) {
902 AliasInits.push_back(AliasInitWorklist.back());
903 } else {
904 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000905 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000906 else
907 return Error("Alias initializer is not a constant!");
908 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000909 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000910 }
911 return false;
912}
913
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000914static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
915 SmallVector<uint64_t, 8> Words(Vals.size());
916 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000917 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000918
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000919 return APInt(TypeBits, Words);
920}
921
Chris Lattner86697142007-05-01 05:01:34 +0000922bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000923 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000924 return Error("Malformed block record");
925
926 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000927
Chris Lattnere16504e2007-04-24 03:30:34 +0000928 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000929 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000930 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000931 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000932 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
933
934 switch (Entry.Kind) {
935 case BitstreamEntry::SubBlock: // Handled for us already.
936 case BitstreamEntry::Error:
937 return Error("malformed block record in AST file");
938 case BitstreamEntry::EndBlock:
939 if (NextCstNo != ValueList.size())
940 return Error("Invalid constant reference!");
941
942 // Once all the constants have been read, go through and resolve forward
943 // references.
944 ValueList.ResolveConstantForwardRefs();
945 return false;
946 case BitstreamEntry::Record:
947 // The interesting case.
Chris Lattnerea693df2008-08-21 02:34:16 +0000948 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000949 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000950
Chris Lattnere16504e2007-04-24 03:30:34 +0000951 // Read a record.
952 Record.clear();
953 Value *V = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000954 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +0000955 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000956 default: // Default behavior: unknown constant
957 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000958 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000959 break;
960 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
961 if (Record.empty())
962 return Error("Malformed CST_SETTYPE record");
963 if (Record[0] >= TypeList.size())
964 return Error("Invalid Type ID in CST_SETTYPE record");
965 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000966 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000967 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000968 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000969 break;
970 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000971 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000972 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000973 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000974 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000975 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000976 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000977 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000978
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000979 APInt VInt = ReadWideAPInt(Record,
980 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000981 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +0000982
Chris Lattner0eef0802007-04-24 04:04:35 +0000983 break;
984 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000985 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000986 if (Record.empty())
987 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +0000988 if (CurTy->isHalfTy())
Tim Northover0a29cb02013-01-22 09:46:31 +0000989 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
990 APInt(16, (uint16_t)Record[0])));
Dan Gohmance163392011-12-17 00:04:22 +0000991 else if (CurTy->isFloatTy())
Tim Northover0a29cb02013-01-22 09:46:31 +0000992 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
993 APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000994 else if (CurTy->isDoubleTy())
Tim Northover0a29cb02013-01-22 09:46:31 +0000995 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
996 APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000997 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000998 // Bits are not stored the same way as a normal i80 APInt, compensate.
999 uint64_t Rearrange[2];
1000 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1001 Rearrange[1] = Record[0] >> 48;
Tim Northover0a29cb02013-01-22 09:46:31 +00001002 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1003 APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001004 } else if (CurTy->isFP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001005 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1006 APInt(128, Record)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001007 else if (CurTy->isPPC_FP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001008 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1009 APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001010 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001011 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001012 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001013 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001014
Chris Lattner15e6d172007-05-04 19:11:41 +00001015 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1016 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001017 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001018
Chris Lattner15e6d172007-05-04 19:11:41 +00001019 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001020 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001021
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001022 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001023 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001024 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001025 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001026 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001027 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1028 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001029 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001030 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001031 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001032 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1033 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001034 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001035 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001036 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001037 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001038 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001039 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001040 break;
1041 }
Chris Lattner2237f842012-02-05 02:41:35 +00001042 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001043 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1044 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001045 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001046
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001047 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001048 V = ConstantDataArray::getString(Context, Elts,
1049 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001050 break;
1051 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001052 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1053 if (Record.empty())
1054 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001055
Chris Lattnerd408f062012-01-30 00:51:16 +00001056 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1057 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001058
Chris Lattnerd408f062012-01-30 00:51:16 +00001059 if (EltTy->isIntegerTy(8)) {
1060 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1061 if (isa<VectorType>(CurTy))
1062 V = ConstantDataVector::get(Context, Elts);
1063 else
1064 V = ConstantDataArray::get(Context, Elts);
1065 } else if (EltTy->isIntegerTy(16)) {
1066 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1067 if (isa<VectorType>(CurTy))
1068 V = ConstantDataVector::get(Context, Elts);
1069 else
1070 V = ConstantDataArray::get(Context, Elts);
1071 } else if (EltTy->isIntegerTy(32)) {
1072 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1073 if (isa<VectorType>(CurTy))
1074 V = ConstantDataVector::get(Context, Elts);
1075 else
1076 V = ConstantDataArray::get(Context, Elts);
1077 } else if (EltTy->isIntegerTy(64)) {
1078 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1079 if (isa<VectorType>(CurTy))
1080 V = ConstantDataVector::get(Context, Elts);
1081 else
1082 V = ConstantDataArray::get(Context, Elts);
1083 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001084 SmallVector<float, 16> Elts(Size);
1085 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001086 if (isa<VectorType>(CurTy))
1087 V = ConstantDataVector::get(Context, Elts);
1088 else
1089 V = ConstantDataArray::get(Context, Elts);
1090 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001091 SmallVector<double, 16> Elts(Size);
1092 std::transform(Record.begin(), Record.end(), Elts.begin(),
1093 BitsToDouble);
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 {
1099 return Error("Unknown element type in CE_DATA");
1100 }
1101 break;
1102 }
1103
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001104 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1105 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1106 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001107 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001108 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001109 } else {
1110 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1111 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001112 unsigned Flags = 0;
1113 if (Record.size() >= 4) {
1114 if (Opc == Instruction::Add ||
1115 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001116 Opc == Instruction::Mul ||
1117 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001118 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1119 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1120 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1121 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001122 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001123 Opc == Instruction::UDiv ||
1124 Opc == Instruction::LShr ||
1125 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001126 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001127 Flags |= SDivOperator::IsExact;
1128 }
1129 }
1130 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001131 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001132 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001133 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001134 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1135 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1136 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001137 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001138 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001139 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001140 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001141 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001142 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001143 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001144 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001145 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001146 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001147 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001148 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001149 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001150 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001151 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001152 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001153 if (!ElTy) return Error("Invalid CE_GEP record");
1154 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1155 }
Jay Foaddab3d292011-07-21 14:31:17 +00001156 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001157 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1158 BitCode ==
1159 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001160 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001161 }
1162 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1163 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbeye46b14a2012-11-19 19:22:55 +00001164 V = ConstantExpr::getSelect(
1165 ValueList.getConstantFwdRef(Record[0],
1166 Type::getInt1Ty(Context)),
1167 ValueList.getConstantFwdRef(Record[1],CurTy),
1168 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001169 break;
1170 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1171 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001172 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001173 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1174 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1175 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001176 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001177 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001178 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001179 break;
1180 }
1181 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001182 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001183 if (Record.size() < 3 || OpTy == 0)
1184 return Error("Invalid CE_INSERTELT record");
1185 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1186 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1187 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001188 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001189 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001190 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001191 break;
1192 }
1193 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001194 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001195 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001196 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001197 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1198 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001199 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001200 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001201 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001202 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001203 break;
1204 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001205 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001206 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1207 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001208 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001209 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1210 return Error("Invalid CE_SHUFVEC_EX record");
1211 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1212 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001213 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001214 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001215 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001216 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001217 break;
1218 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001219 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1220 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001221 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001222 if (OpTy == 0) return Error("Invalid CE_CMP record");
1223 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1224 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1225
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001226 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001227 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001228 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001229 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001230 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001231 }
Chad Rosier581600b2012-09-05 19:00:49 +00001232 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001233 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001234 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001235 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1236 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001237 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001238 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001239 unsigned AsmStrSize = Record[1];
1240 if (2+AsmStrSize >= Record.size())
1241 return Error("Invalid INLINEASM record");
1242 unsigned ConstStrSize = Record[2+AsmStrSize];
1243 if (3+AsmStrSize+ConstStrSize > Record.size())
1244 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001245
Chris Lattner2bce93a2007-05-06 01:58:20 +00001246 for (unsigned i = 0; i != AsmStrSize; ++i)
1247 AsmStr += (char)Record[2+i];
1248 for (unsigned i = 0; i != ConstStrSize; ++i)
1249 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001250 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001251 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001252 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001253 break;
1254 }
Chad Rosier581600b2012-09-05 19:00:49 +00001255 // This version adds support for the asm dialect keywords (e.g.,
1256 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001257 case bitc::CST_CODE_INLINEASM: {
1258 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1259 std::string AsmStr, ConstrStr;
1260 bool HasSideEffects = Record[0] & 1;
1261 bool IsAlignStack = (Record[0] >> 1) & 1;
1262 unsigned AsmDialect = Record[0] >> 2;
1263 unsigned AsmStrSize = Record[1];
1264 if (2+AsmStrSize >= Record.size())
1265 return Error("Invalid INLINEASM record");
1266 unsigned ConstStrSize = Record[2+AsmStrSize];
1267 if (3+AsmStrSize+ConstStrSize > Record.size())
1268 return Error("Invalid INLINEASM record");
1269
1270 for (unsigned i = 0; i != AsmStrSize; ++i)
1271 AsmStr += (char)Record[2+i];
1272 for (unsigned i = 0; i != ConstStrSize; ++i)
1273 ConstrStr += (char)Record[3+AsmStrSize+i];
1274 PointerType *PTy = cast<PointerType>(CurTy);
1275 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1276 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001277 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001278 break;
1279 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001280 case bitc::CST_CODE_BLOCKADDRESS:{
1281 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001282 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001283 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1284 Function *Fn =
1285 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1286 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001287
1288 // If the function is already parsed we can insert the block address right
1289 // away.
1290 if (!Fn->empty()) {
1291 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1292 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1293 if (BBI == BBE)
1294 return Error("Invalid blockaddress block #");
1295 ++BBI;
1296 }
1297 V = BlockAddress::get(Fn, BBI);
1298 } else {
1299 // Otherwise insert a placeholder and remember it so it can be inserted
1300 // when the function is parsed.
1301 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1302 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001303 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001304 0, "");
1305 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1306 V = FwdRef;
1307 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001308 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001309 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001310 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001311
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001312 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001313 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001314 }
1315}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001316
Chad Rosiercbbb0962011-12-07 21:44:12 +00001317bool BitcodeReader::ParseUseLists() {
1318 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1319 return Error("Malformed block record");
1320
1321 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001322
Chad Rosiercbbb0962011-12-07 21:44:12 +00001323 // Read all the records.
1324 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001325 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1326
1327 switch (Entry.Kind) {
1328 case BitstreamEntry::SubBlock: // Handled for us already.
1329 case BitstreamEntry::Error:
1330 return Error("malformed use list block");
1331 case BitstreamEntry::EndBlock:
Chad Rosiercbbb0962011-12-07 21:44:12 +00001332 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001333 case BitstreamEntry::Record:
1334 // The interesting case.
1335 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001336 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001337
Chad Rosiercbbb0962011-12-07 21:44:12 +00001338 // Read a use list record.
1339 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001340 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosiercbbb0962011-12-07 21:44:12 +00001341 default: // Default behavior: unknown type.
1342 break;
1343 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1344 unsigned RecordLength = Record.size();
1345 if (RecordLength < 1)
1346 return Error ("Invalid UseList reader!");
1347 UseListRecords.push_back(Record);
1348 break;
1349 }
1350 }
1351 }
1352}
1353
Chris Lattner980e5aa2007-05-01 05:52:21 +00001354/// RememberAndSkipFunctionBody - When we see the block for a function body,
1355/// remember where it is and then skip it. This lets us lazily deserialize the
1356/// functions.
1357bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001358 // Get the function we are talking about.
1359 if (FunctionsWithBodies.empty())
1360 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001361
Chris Lattner48f84872007-05-01 04:59:48 +00001362 Function *Fn = FunctionsWithBodies.back();
1363 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001364
Chris Lattner48f84872007-05-01 04:59:48 +00001365 // Save the current stream state.
1366 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001367 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001368
Chris Lattner48f84872007-05-01 04:59:48 +00001369 // Skip over the function block for now.
1370 if (Stream.SkipBlock())
1371 return Error("Malformed block record");
1372 return false;
1373}
1374
Derek Schuff2ea93872012-02-06 22:30:29 +00001375bool BitcodeReader::GlobalCleanup() {
1376 // Patch the initializers for globals and aliases up.
1377 ResolveGlobalAndAliasInits();
1378 if (!GlobalInits.empty() || !AliasInits.empty())
1379 return Error("Malformed global initializer set");
1380
1381 // Look for intrinsic functions which need to be upgraded at some point
1382 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1383 FI != FE; ++FI) {
1384 Function *NewFn;
1385 if (UpgradeIntrinsicFunction(FI, NewFn))
1386 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1387 }
1388
1389 // Look for global variables which need to be renamed.
1390 for (Module::global_iterator
1391 GI = TheModule->global_begin(), GE = TheModule->global_end();
1392 GI != GE; ++GI)
1393 UpgradeGlobalVariable(GI);
1394 // Force deallocation of memory for these vectors to favor the client that
1395 // want lazy deserialization.
1396 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1397 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1398 return false;
1399}
1400
1401bool BitcodeReader::ParseModule(bool Resume) {
1402 if (Resume)
1403 Stream.JumpToBit(NextUnreadBit);
1404 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001405 return Error("Malformed block record");
1406
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001407 SmallVector<uint64_t, 64> Record;
1408 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001409 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001410
1411 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001412 while (1) {
1413 BitstreamEntry Entry = Stream.advance();
1414
1415 switch (Entry.Kind) {
1416 case BitstreamEntry::Error:
1417 Error("malformed module block");
1418 return true;
1419 case BitstreamEntry::EndBlock:
Derek Schuff2ea93872012-02-06 22:30:29 +00001420 return GlobalCleanup();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001421
1422 case BitstreamEntry::SubBlock:
1423 switch (Entry.ID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001424 default: // Skip unknown content.
1425 if (Stream.SkipBlock())
1426 return Error("Malformed block record");
1427 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001428 case bitc::BLOCKINFO_BLOCK_ID:
1429 if (Stream.ReadBlockInfoBlock())
1430 return Error("Malformed BlockInfoBlock");
1431 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001432 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001433 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001434 return true;
1435 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001436 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001437 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001438 return true;
1439 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001440 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001441 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001442 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001443 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001444 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001445 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001446 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001447 return true;
1448 break;
Devang Patele54abc92009-07-22 17:43:22 +00001449 case bitc::METADATA_BLOCK_ID:
1450 if (ParseMetadata())
1451 return true;
1452 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001453 case bitc::FUNCTION_BLOCK_ID:
1454 // If this is the first function body we've seen, reverse the
1455 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001456 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001457 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001458 if (GlobalCleanup())
1459 return true;
1460 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001461 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001462
Chris Lattner980e5aa2007-05-01 05:52:21 +00001463 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001464 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001465 // For streaming bitcode, suspend parsing when we reach the function
1466 // bodies. Subsequent materialization calls will resume it when
1467 // necessary. For streaming, the function bodies must be at the end of
1468 // the bitcode. If the bitcode file is old, the symbol table will be
1469 // at the end instead and will not have been seen yet. In this case,
1470 // just finish the parse now.
1471 if (LazyStreamer && SeenValueSymbolTable) {
1472 NextUnreadBit = Stream.GetCurrentBitNo();
1473 return false;
1474 }
Chris Lattner48f84872007-05-01 04:59:48 +00001475 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001476 case bitc::USELIST_BLOCK_ID:
1477 if (ParseUseLists())
1478 return true;
1479 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001480 }
1481 continue;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001482
1483 case BitstreamEntry::Record:
1484 // The interesting case.
1485 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001486 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001487
Daniel Dunbara279bc32009-09-20 02:20:51 +00001488
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001489 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001490 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001491 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001492 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001493 if (Record.size() < 1)
1494 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001495 // Only version #0 and #1 are supported so far.
1496 unsigned module_version = Record[0];
1497 switch (module_version) {
1498 default: return Error("Unknown bitstream version!");
1499 case 0:
1500 UseRelativeIDs = false;
1501 break;
1502 case 1:
1503 UseRelativeIDs = true;
1504 break;
1505 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001506 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001507 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001508 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [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_TRIPLE record");
1512 TheModule->setTargetTriple(S);
1513 break;
1514 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001515 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001516 std::string S;
1517 if (ConvertToString(Record, 0, S))
1518 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1519 TheModule->setDataLayout(S);
1520 break;
1521 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001522 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001523 std::string S;
1524 if (ConvertToString(Record, 0, S))
1525 return Error("Invalid MODULE_CODE_ASM record");
1526 TheModule->setModuleInlineAsm(S);
1527 break;
1528 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001529 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1530 // FIXME: Remove in 4.0.
1531 std::string S;
1532 if (ConvertToString(Record, 0, S))
1533 return Error("Invalid MODULE_CODE_DEPLIB record");
1534 // Ignore value.
1535 break;
1536 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001537 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001538 std::string S;
1539 if (ConvertToString(Record, 0, S))
1540 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1541 SectionTable.push_back(S);
1542 break;
1543 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001544 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001545 std::string S;
1546 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001547 return Error("Invalid MODULE_CODE_GCNAME record");
1548 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001549 break;
1550 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001551 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001552 // linkage, alignment, section, visibility, threadlocal,
1553 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001554 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001555 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001556 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001557 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001558 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001559 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001560 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001561 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001562 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001563
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001564 bool isConstant = Record[1];
1565 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1566 unsigned Alignment = (1 << Record[4]) >> 1;
1567 std::string Section;
1568 if (Record[5]) {
1569 if (Record[5]-1 >= SectionTable.size())
1570 return Error("Invalid section ID");
1571 Section = SectionTable[Record[5]-1];
1572 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001573 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001574 if (Record.size() > 6)
1575 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001576
1577 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001578 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001579 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001580
Rafael Espindolabea46262011-01-08 16:42:36 +00001581 bool UnnamedAddr = false;
1582 if (Record.size() > 8)
1583 UnnamedAddr = Record[8];
1584
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001585 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001586 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001587 TLM, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001588 NewGV->setAlignment(Alignment);
1589 if (!Section.empty())
1590 NewGV->setSection(Section);
1591 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001592 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001593
Chris Lattner0b2482a2007-04-23 21:26:05 +00001594 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001595
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001596 // Remember which value to use for the global initializer.
1597 if (unsigned InitID = Record[2])
1598 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001599 break;
1600 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001601 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001602 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001603 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001604 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001605 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001606 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001607 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001608 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001609 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001610 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001611 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1612 if (!FTy)
1613 return Error("Function not a pointer to function type!");
1614
Gabor Greif051a9502008-04-06 20:25:17 +00001615 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1616 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001617
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001618 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001619 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001620 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001621 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Chris Lattnera9bb7132007-05-08 05:38:01 +00001623 Func->setAlignment((1 << Record[5]) >> 1);
1624 if (Record[6]) {
1625 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001626 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001627 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001628 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001629 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001630 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001631 if (Record[8]-1 > GCTable.size())
1632 return Error("Invalid GC ID");
1633 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001634 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001635 bool UnnamedAddr = false;
1636 if (Record.size() > 9)
1637 UnnamedAddr = Record[9];
1638 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001639 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001640
Chris Lattner48f84872007-05-01 04:59:48 +00001641 // If this is a function with a body, remember the prototype we are
1642 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001643 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001644 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001645 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1646 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001647 break;
1648 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001649 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001650 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001651 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001652 if (Record.size() < 3)
1653 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001654 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001655 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001656 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001657 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001658
Chris Lattner07d98b42007-04-26 02:46:40 +00001659 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1660 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001661 // Old bitcode files didn't have visibility field.
1662 if (Record.size() > 3)
1663 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001664 ValueList.push_back(NewGA);
1665 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1666 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001667 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001668 /// MODULE_CODE_PURGEVALS: [numvals]
1669 case bitc::MODULE_CODE_PURGEVALS:
1670 // Trim down the value list to the specified size.
1671 if (Record.size() < 1 || Record[0] > ValueList.size())
1672 return Error("Invalid MODULE_PURGEVALS record");
1673 ValueList.shrinkTo(Record[0]);
1674 break;
1675 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001676 Record.clear();
1677 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001678}
1679
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001680bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001681 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001682
Derek Schuff2ea93872012-02-06 22:30:29 +00001683 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001685 // Sniff for the signature.
1686 if (Stream.Read(8) != 'B' ||
1687 Stream.Read(8) != 'C' ||
1688 Stream.Read(4) != 0x0 ||
1689 Stream.Read(4) != 0xC ||
1690 Stream.Read(4) != 0xE ||
1691 Stream.Read(4) != 0xD)
1692 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001693
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001694 // We expect a number of well-defined blocks, though we don't necessarily
1695 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001696 while (1) {
1697 if (Stream.AtEndOfStream())
1698 return false;
1699
1700 BitstreamEntry Entry =
1701 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1702
1703 switch (Entry.Kind) {
1704 case BitstreamEntry::Error:
1705 Error("malformed module file");
1706 return true;
1707 case BitstreamEntry::EndBlock:
1708 return false;
1709
1710 case BitstreamEntry::SubBlock:
1711 switch (Entry.ID) {
1712 case bitc::BLOCKINFO_BLOCK_ID:
1713 if (Stream.ReadBlockInfoBlock())
1714 return Error("Malformed BlockInfoBlock");
1715 break;
1716 case bitc::MODULE_BLOCK_ID:
1717 // Reject multiple MODULE_BLOCK's in a single bitstream.
1718 if (TheModule)
1719 return Error("Multiple MODULE_BLOCKs in same stream");
1720 TheModule = M;
1721 if (ParseModule(false))
1722 return true;
1723 if (LazyStreamer) return false;
1724 break;
1725 default:
1726 if (Stream.SkipBlock())
1727 return Error("Malformed block record");
1728 break;
1729 }
1730 continue;
1731 case BitstreamEntry::Record:
1732 // There should be no records in the top-level of blocks.
1733
1734 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001735 // to the end of them. If this file size is a multiple of 4 but not 8, we
1736 // have to read and ignore these final 4 bytes :-(
Chris Lattner5a4251c2013-01-20 02:13:19 +00001737 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolac9687b32011-05-26 18:59:54 +00001738 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001739 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001740 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001741
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001742 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001743 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001744 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001745}
Chris Lattnerc453f762007-04-29 07:54:31 +00001746
Bill Wendling34711742010-10-06 01:22:42 +00001747bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1748 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1749 return Error("Malformed block record");
1750
1751 SmallVector<uint64_t, 64> Record;
1752
1753 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001754 while (1) {
1755 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1756
1757 switch (Entry.Kind) {
1758 case BitstreamEntry::SubBlock: // Handled for us already.
1759 case BitstreamEntry::Error:
1760 return Error("malformed module block");
1761 case BitstreamEntry::EndBlock:
Bill Wendling34711742010-10-06 01:22:42 +00001762 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001763 case BitstreamEntry::Record:
1764 // The interesting case.
1765 break;
Bill Wendling34711742010-10-06 01:22:42 +00001766 }
1767
1768 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001769 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling34711742010-10-06 01:22:42 +00001770 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00001771 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1772 std::string S;
1773 if (ConvertToString(Record, 0, S))
1774 return Error("Invalid MODULE_CODE_TRIPLE record");
1775 Triple = S;
1776 break;
1777 }
1778 }
1779 Record.clear();
1780 }
Bill Wendling34711742010-10-06 01:22:42 +00001781}
1782
1783bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001784 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001785
1786 // Sniff for the signature.
1787 if (Stream.Read(8) != 'B' ||
1788 Stream.Read(8) != 'C' ||
1789 Stream.Read(4) != 0x0 ||
1790 Stream.Read(4) != 0xC ||
1791 Stream.Read(4) != 0xE ||
1792 Stream.Read(4) != 0xD)
1793 return Error("Invalid bitcode signature");
1794
1795 // We expect a number of well-defined blocks, though we don't necessarily
1796 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001797 while (1) {
1798 BitstreamEntry Entry = Stream.advance();
1799
1800 switch (Entry.Kind) {
1801 case BitstreamEntry::Error:
1802 Error("malformed module file");
1803 return true;
1804 case BitstreamEntry::EndBlock:
1805 return false;
1806
1807 case BitstreamEntry::SubBlock:
1808 if (Entry.ID == bitc::MODULE_BLOCK_ID)
1809 return ParseModuleTriple(Triple);
1810
1811 // Ignore other sub-blocks.
1812 if (Stream.SkipBlock()) {
1813 Error("malformed block record in AST file");
Bill Wendling34711742010-10-06 01:22:42 +00001814 return true;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001815 }
1816 continue;
1817
1818 case BitstreamEntry::Record:
1819 Stream.skipRecord(Entry.ID);
1820 continue;
Bill Wendling34711742010-10-06 01:22:42 +00001821 }
1822 }
Bill Wendling34711742010-10-06 01:22:42 +00001823}
1824
Devang Patele8e02132009-09-18 19:26:43 +00001825/// ParseMetadataAttachment - Parse metadata attachments.
1826bool BitcodeReader::ParseMetadataAttachment() {
1827 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1828 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001829
Devang Patele8e02132009-09-18 19:26:43 +00001830 SmallVector<uint64_t, 64> Record;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001831 while (1) {
1832 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1833
1834 switch (Entry.Kind) {
1835 case BitstreamEntry::SubBlock: // Handled for us already.
1836 case BitstreamEntry::Error:
1837 return Error("malformed metadata block");
1838 case BitstreamEntry::EndBlock:
1839 return false;
1840 case BitstreamEntry::Record:
1841 // The interesting case.
Devang Patele8e02132009-09-18 19:26:43 +00001842 break;
1843 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001844
Devang Patele8e02132009-09-18 19:26:43 +00001845 // Read a metadata attachment record.
1846 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001847 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patele8e02132009-09-18 19:26:43 +00001848 default: // Default behavior: ignore.
1849 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001850 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001851 unsigned RecordLength = Record.size();
1852 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001853 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001854 Instruction *Inst = InstructionList[Record[0]];
1855 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001856 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001857 DenseMap<unsigned, unsigned>::iterator I =
1858 MDKindMap.find(Kind);
1859 if (I == MDKindMap.end())
1860 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001861 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001862 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001863 }
1864 break;
1865 }
1866 }
1867 }
Devang Patele8e02132009-09-18 19:26:43 +00001868}
Chris Lattner48f84872007-05-01 04:59:48 +00001869
Chris Lattner980e5aa2007-05-01 05:52:21 +00001870/// ParseFunctionBody - Lazily parse the specified function body block.
1871bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001872 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001873 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001874
Nick Lewycky9a49f152010-02-25 08:30:17 +00001875 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001876 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001877 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001878
Chris Lattner980e5aa2007-05-01 05:52:21 +00001879 // Add all the function arguments to the value table.
1880 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1881 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001882
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001883 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001884 BasicBlock *CurBB = 0;
1885 unsigned CurBBNo = 0;
1886
Chris Lattnera6245242010-04-03 02:17:50 +00001887 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00001888
Chris Lattner980e5aa2007-05-01 05:52:21 +00001889 // Read all the records.
1890 SmallVector<uint64_t, 64> Record;
1891 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001892 BitstreamEntry Entry = Stream.advance();
1893
1894 switch (Entry.Kind) {
1895 case BitstreamEntry::Error:
1896 return Error("Bitcode error in function block");
1897 case BitstreamEntry::EndBlock:
1898 goto OutOfRecordLoop;
1899
1900 case BitstreamEntry::SubBlock:
1901 switch (Entry.ID) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001902 default: // Skip unknown content.
1903 if (Stream.SkipBlock())
1904 return Error("Malformed block record");
1905 break;
1906 case bitc::CONSTANTS_BLOCK_ID:
1907 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001908 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001909 break;
1910 case bitc::VALUE_SYMTAB_BLOCK_ID:
1911 if (ParseValueSymbolTable()) return true;
1912 break;
Devang Patele8e02132009-09-18 19:26:43 +00001913 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001914 if (ParseMetadataAttachment()) return true;
1915 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001916 case bitc::METADATA_BLOCK_ID:
1917 if (ParseMetadata()) return true;
1918 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001919 }
1920 continue;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001921
1922 case BitstreamEntry::Record:
1923 // The interesting case.
1924 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001925 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001926
Chris Lattner980e5aa2007-05-01 05:52:21 +00001927 // Read a record.
1928 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001929 Instruction *I = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001930 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00001931 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001932 default: // Default behavior: reject
1933 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001934 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001935 if (Record.size() < 1 || Record[0] == 0)
1936 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001937 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001938 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001939 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001940 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001941 CurBB = FunctionBBs[0];
1942 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001943
Chris Lattnera6245242010-04-03 02:17:50 +00001944 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1945 // This record indicates that the last instruction is at the same
1946 // location as the previous instruction with a location.
1947 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00001948
Chris Lattnera6245242010-04-03 02:17:50 +00001949 // Get the last instruction emitted.
1950 if (CurBB && !CurBB->empty())
1951 I = &CurBB->back();
1952 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1953 !FunctionBBs[CurBBNo-1]->empty())
1954 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00001955
Chris Lattnera6245242010-04-03 02:17:50 +00001956 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1957 I->setDebugLoc(LastLoc);
1958 I = 0;
1959 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001960
Chris Lattner4f6bab92011-06-17 18:17:37 +00001961 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001962 I = 0; // Get the last instruction emitted.
1963 if (CurBB && !CurBB->empty())
1964 I = &CurBB->back();
1965 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1966 !FunctionBBs[CurBBNo-1]->empty())
1967 I = &FunctionBBs[CurBBNo-1]->back();
1968 if (I == 0 || Record.size() < 4)
1969 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001970
Chris Lattnera6245242010-04-03 02:17:50 +00001971 unsigned Line = Record[0], Col = Record[1];
1972 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00001973
Chris Lattnera6245242010-04-03 02:17:50 +00001974 MDNode *Scope = 0, *IA = 0;
1975 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1976 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1977 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1978 I->setDebugLoc(LastLoc);
1979 I = 0;
1980 continue;
1981 }
1982
Chris Lattnerabfbf852007-05-06 00:21:25 +00001983 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1984 unsigned OpNum = 0;
1985 Value *LHS, *RHS;
1986 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001987 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001988 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001989 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001990
Dan Gohman1224c382009-07-20 21:19:07 +00001991 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001992 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001993 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001994 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001995 if (OpNum < Record.size()) {
1996 if (Opc == Instruction::Add ||
1997 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001998 Opc == Instruction::Mul ||
1999 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002000 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002001 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002002 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002003 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002004 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002005 Opc == Instruction::UDiv ||
2006 Opc == Instruction::LShr ||
2007 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002008 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002009 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002010 } else if (isa<FPMathOperator>(I)) {
2011 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002012 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2013 FMF.setUnsafeAlgebra();
2014 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2015 FMF.setNoNaNs();
2016 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2017 FMF.setNoInfs();
2018 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2019 FMF.setNoSignedZeros();
2020 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2021 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002022 if (FMF.any())
2023 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002024 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002025
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002026 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002027 break;
2028 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002029 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2030 unsigned OpNum = 0;
2031 Value *Op;
2032 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2033 OpNum+2 != Record.size())
2034 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002035
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002036 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002037 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2038 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002039 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002041 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002042 break;
2043 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002044 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002045 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002046 unsigned OpNum = 0;
2047 Value *BasePtr;
2048 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002049 return Error("Invalid GEP record");
2050
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002051 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002052 while (OpNum != Record.size()) {
2053 Value *Op;
2054 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002055 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002056 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002057 }
2058
Jay Foada9203102011-07-25 09:48:08 +00002059 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002060 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002061 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002062 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002063 break;
2064 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002065
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002066 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2067 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002068 unsigned OpNum = 0;
2069 Value *Agg;
2070 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2071 return Error("Invalid EXTRACTVAL record");
2072
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002073 SmallVector<unsigned, 4> EXTRACTVALIdx;
2074 for (unsigned RecSize = Record.size();
2075 OpNum != RecSize; ++OpNum) {
2076 uint64_t Index = Record[OpNum];
2077 if ((unsigned)Index != Index)
2078 return Error("Invalid EXTRACTVAL index");
2079 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002080 }
2081
Jay Foadfc6d3a42011-07-13 10:26:04 +00002082 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002083 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002084 break;
2085 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002086
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002087 case bitc::FUNC_CODE_INST_INSERTVAL: {
2088 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002089 unsigned OpNum = 0;
2090 Value *Agg;
2091 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2092 return Error("Invalid INSERTVAL record");
2093 Value *Val;
2094 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2095 return Error("Invalid INSERTVAL record");
2096
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002097 SmallVector<unsigned, 4> INSERTVALIdx;
2098 for (unsigned RecSize = Record.size();
2099 OpNum != RecSize; ++OpNum) {
2100 uint64_t Index = Record[OpNum];
2101 if ((unsigned)Index != Index)
2102 return Error("Invalid INSERTVAL index");
2103 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002104 }
2105
Jay Foadfc6d3a42011-07-13 10:26:04 +00002106 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002107 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002108 break;
2109 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002110
Chris Lattnerabfbf852007-05-06 00:21:25 +00002111 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002112 // obsolete form of select
2113 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002114 unsigned OpNum = 0;
2115 Value *TrueVal, *FalseVal, *Cond;
2116 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002117 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2118 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002119 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002120
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002121 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002122 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002123 break;
2124 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002125
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002126 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2127 // new form of select
2128 // handles select i1 or select [N x i1]
2129 unsigned OpNum = 0;
2130 Value *TrueVal, *FalseVal, *Cond;
2131 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002132 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002133 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2134 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002135
2136 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002137 if (VectorType* vector_type =
2138 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002139 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002140 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002141 return Error("Invalid SELECT condition type");
2142 } else {
2143 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002144 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002145 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002146 }
2147
Gabor Greif051a9502008-04-06 20:25:17 +00002148 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002149 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002150 break;
2151 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002152
Chris Lattner01ff65f2007-05-02 05:16:49 +00002153 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002154 unsigned OpNum = 0;
2155 Value *Vec, *Idx;
2156 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002157 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002158 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002159 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002160 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002161 break;
2162 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163
Chris Lattner01ff65f2007-05-02 05:16:49 +00002164 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002165 unsigned OpNum = 0;
2166 Value *Vec, *Elt, *Idx;
2167 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002168 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002169 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002170 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002171 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002172 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002173 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002174 break;
2175 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002176
Chris Lattnerabfbf852007-05-06 00:21:25 +00002177 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2178 unsigned OpNum = 0;
2179 Value *Vec1, *Vec2, *Mask;
2180 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002181 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002182 return Error("Invalid SHUFFLEVEC record");
2183
Mon P Wangaeb06d22008-11-10 04:46:22 +00002184 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002185 return Error("Invalid SHUFFLEVEC record");
2186 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002187 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002188 break;
2189 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002190
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002191 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2192 // Old form of ICmp/FCmp returning bool
2193 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2194 // both legal on vectors but had different behaviour.
2195 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2196 // FCmp/ICmp returning bool or vector of bool
2197
Chris Lattner7337ab92007-05-06 00:00:00 +00002198 unsigned OpNum = 0;
2199 Value *LHS, *RHS;
2200 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002201 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002202 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002203 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002204
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002205 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002206 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002207 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002208 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002209 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002210 break;
2211 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002212
Chris Lattner231cbcb2007-05-02 04:27:25 +00002213 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002214 {
2215 unsigned Size = Record.size();
2216 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002217 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002218 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002219 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002220 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002221
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002222 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002223 Value *Op = NULL;
2224 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2225 return Error("Invalid RET record");
2226 if (OpNum != Record.size())
2227 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002228
Chris Lattner96a74c52011-06-17 18:09:11 +00002229 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002230 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002231 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002232 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002233 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002234 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002235 return Error("Invalid BR record");
2236 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2237 if (TrueDest == 0)
2238 return Error("Invalid BR record");
2239
Devang Patele8e02132009-09-18 19:26:43 +00002240 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002241 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002242 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002243 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002244 else {
2245 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002246 Value *Cond = getValue(Record, 2, NextValueNo,
2247 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002248 if (FalseDest == 0 || Cond == 0)
2249 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002250 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002251 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002252 }
2253 break;
2254 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002255 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002256 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002257 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2258 // New SwitchInst format with case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002259
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002260 Type *OpTy = getTypeByID(Record[1]);
2261 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2262
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002263 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002264 BasicBlock *Default = getBasicBlock(Record[3]);
2265 if (OpTy == 0 || Cond == 0 || Default == 0)
2266 return Error("Invalid SWITCH record");
2267
2268 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002269
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002270 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2271 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002272
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002273 unsigned CurIdx = 5;
2274 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002275 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002276 unsigned NumItems = Record[CurIdx++];
2277 for (unsigned ci = 0; ci != NumItems; ++ci) {
2278 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002279
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002280 APInt Low;
2281 unsigned ActiveWords = 1;
2282 if (ValueBitWidth > 64)
2283 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002284 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2285 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002286 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002287
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002288 if (!isSingleNumber) {
2289 ActiveWords = 1;
2290 if (ValueBitWidth > 64)
2291 ActiveWords = Record[CurIdx++];
2292 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002293 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2294 ValueBitWidth);
Michael Ilseman407a6162012-11-15 22:34:00 +00002295
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002296 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2297 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002298 CurIdx += ActiveWords;
2299 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002300 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002301 }
2302 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Michael Ilseman407a6162012-11-15 22:34:00 +00002303 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002304 SI->addCase(Case, DestBB);
2305 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002306 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002307 if (Hash != (Record[0] & 0xFFFF))
2308 return Error("Invalid SWITCH record");
2309 I = SI;
2310 break;
2311 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002312
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002313 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002314
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002315 if (Record.size() < 3 || (Record.size() & 1) == 0)
2316 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002317 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002318 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002319 BasicBlock *Default = getBasicBlock(Record[2]);
2320 if (OpTy == 0 || Cond == 0 || Default == 0)
2321 return Error("Invalid SWITCH record");
2322 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002323 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002324 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002325 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002326 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002327 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2328 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2329 if (CaseVal == 0 || DestBB == 0) {
2330 delete SI;
2331 return Error("Invalid SWITCH record!");
2332 }
2333 SI->addCase(CaseVal, DestBB);
2334 }
2335 I = SI;
2336 break;
2337 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002338 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002339 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002340 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002341 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002342 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002343 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002344 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002345 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002346 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002347 InstructionList.push_back(IBI);
2348 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2349 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2350 IBI->addDestination(DestBB);
2351 } else {
2352 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002353 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002354 }
2355 }
2356 I = IBI;
2357 break;
2358 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002359
Duncan Sandsdc024672007-11-27 13:23:08 +00002360 case bitc::FUNC_CODE_INST_INVOKE: {
2361 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002362 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002363 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002364 unsigned CCInfo = Record[1];
2365 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2366 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002367
Chris Lattnera9bb7132007-05-08 05:38:01 +00002368 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002369 Value *Callee;
2370 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002371 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002372
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002373 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2374 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002375 dyn_cast<FunctionType>(CalleeTy->getElementType());
2376
2377 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002378 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2379 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002380 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002381
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002382 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002383 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002384 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2385 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002386 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002387 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002388
Chris Lattner7337ab92007-05-06 00:00:00 +00002389 if (!FTy->isVarArg()) {
2390 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002391 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002392 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002393 // Read type/value pairs for varargs params.
2394 while (OpNum != Record.size()) {
2395 Value *Op;
2396 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2397 return Error("Invalid INVOKE record");
2398 Ops.push_back(Op);
2399 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002400 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002401
Jay Foada3efbb12011-07-15 08:37:34 +00002402 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002403 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002404 cast<InvokeInst>(I)->setCallingConv(
2405 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002406 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002407 break;
2408 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002409 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2410 unsigned Idx = 0;
2411 Value *Val = 0;
2412 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2413 return Error("Invalid RESUME record");
2414 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002415 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002416 break;
2417 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002418 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002419 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002420 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002421 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002422 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002423 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002424 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002425 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002426 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002427
Jay Foad3ecfc862011-03-30 11:28:46 +00002428 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002429 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002430
Chris Lattner15e6d172007-05-04 19:11:41 +00002431 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002432 Value *V;
2433 // With the new function encoding, it is possible that operands have
2434 // negative IDs (for forward references). Use a signed VBR
2435 // representation to keep the encoding small.
2436 if (UseRelativeIDs)
2437 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2438 else
2439 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002440 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002441 if (!V || !BB) return Error("Invalid PHI record");
2442 PN->addIncoming(V, BB);
2443 }
2444 I = PN;
2445 break;
2446 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002447
Bill Wendlinge6e88262011-08-12 20:24:12 +00002448 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2449 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2450 unsigned Idx = 0;
2451 if (Record.size() < 4)
2452 return Error("Invalid LANDINGPAD record");
2453 Type *Ty = getTypeByID(Record[Idx++]);
2454 if (!Ty) return Error("Invalid LANDINGPAD record");
2455 Value *PersFn = 0;
2456 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2457 return Error("Invalid LANDINGPAD record");
2458
2459 bool IsCleanup = !!Record[Idx++];
2460 unsigned NumClauses = Record[Idx++];
2461 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2462 LP->setCleanup(IsCleanup);
2463 for (unsigned J = 0; J != NumClauses; ++J) {
2464 LandingPadInst::ClauseType CT =
2465 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2466 Value *Val;
2467
2468 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2469 delete LP;
2470 return Error("Invalid LANDINGPAD record");
2471 }
2472
2473 assert((CT != LandingPadInst::Catch ||
2474 !isa<ArrayType>(Val->getType())) &&
2475 "Catch clause has a invalid type!");
2476 assert((CT != LandingPadInst::Filter ||
2477 isa<ArrayType>(Val->getType())) &&
2478 "Filter clause has invalid type!");
2479 LP->addClause(Val);
2480 }
2481
2482 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002483 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002484 break;
2485 }
2486
Chris Lattner96a74c52011-06-17 18:09:11 +00002487 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2488 if (Record.size() != 4)
2489 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002490 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002491 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002492 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002493 Value *Size = getFnValueByID(Record[2], OpTy);
2494 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002495 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002496 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002497 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002498 break;
2499 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002500 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002501 unsigned OpNum = 0;
2502 Value *Op;
2503 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2504 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002505 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002506
Chris Lattner7337ab92007-05-06 00:00:00 +00002507 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002508 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002509 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002510 }
Eli Friedman21006d42011-08-09 23:02:53 +00002511 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2512 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2513 unsigned OpNum = 0;
2514 Value *Op;
2515 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2516 OpNum+4 != Record.size())
2517 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002518
Eli Friedman21006d42011-08-09 23:02:53 +00002519
2520 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2521 if (Ordering == NotAtomic || Ordering == Release ||
2522 Ordering == AcquireRelease)
2523 return Error("Invalid LOADATOMIC record");
2524 if (Ordering != NotAtomic && Record[OpNum] == 0)
2525 return Error("Invalid LOADATOMIC record");
2526 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2527
2528 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2529 Ordering, SynchScope);
2530 InstructionList.push_back(I);
2531 break;
2532 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002533 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002534 unsigned OpNum = 0;
2535 Value *Val, *Ptr;
2536 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002537 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002538 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2539 OpNum+2 != Record.size())
2540 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002541
Christopher Lambfe63fb92007-12-11 08:59:05 +00002542 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002543 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002544 break;
2545 }
Eli Friedman21006d42011-08-09 23:02:53 +00002546 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2547 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2548 unsigned OpNum = 0;
2549 Value *Val, *Ptr;
2550 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002551 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002552 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2553 OpNum+4 != Record.size())
2554 return Error("Invalid STOREATOMIC record");
2555
2556 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002557 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002558 Ordering == AcquireRelease)
2559 return Error("Invalid STOREATOMIC record");
2560 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2561 if (Ordering != NotAtomic && Record[OpNum] == 0)
2562 return Error("Invalid STOREATOMIC record");
2563
2564 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2565 Ordering, SynchScope);
2566 InstructionList.push_back(I);
2567 break;
2568 }
Eli Friedmanff030482011-07-28 21:48:00 +00002569 case bitc::FUNC_CODE_INST_CMPXCHG: {
2570 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2571 unsigned OpNum = 0;
2572 Value *Ptr, *Cmp, *New;
2573 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002574 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002575 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002576 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002577 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2578 OpNum+3 != Record.size())
2579 return Error("Invalid CMPXCHG record");
2580 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002581 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002582 return Error("Invalid CMPXCHG record");
2583 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2584 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2585 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2586 InstructionList.push_back(I);
2587 break;
2588 }
2589 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2590 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2591 unsigned OpNum = 0;
2592 Value *Ptr, *Val;
2593 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002594 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002595 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2596 OpNum+4 != Record.size())
2597 return Error("Invalid ATOMICRMW record");
2598 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2599 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2600 Operation > AtomicRMWInst::LAST_BINOP)
2601 return Error("Invalid ATOMICRMW record");
2602 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002603 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002604 return Error("Invalid ATOMICRMW record");
2605 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2606 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2607 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2608 InstructionList.push_back(I);
2609 break;
2610 }
Eli Friedman47f35132011-07-25 23:16:38 +00002611 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2612 if (2 != Record.size())
2613 return Error("Invalid FENCE record");
2614 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2615 if (Ordering == NotAtomic || Ordering == Unordered ||
2616 Ordering == Monotonic)
2617 return Error("Invalid FENCE record");
2618 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2619 I = new FenceInst(Context, Ordering, SynchScope);
2620 InstructionList.push_back(I);
2621 break;
2622 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002623 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002624 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2625 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002626 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002627
Bill Wendling99faa3b2012-12-07 23:16:57 +00002628 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002629 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002630
Chris Lattnera9bb7132007-05-08 05:38:01 +00002631 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002632 Value *Callee;
2633 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2634 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002635
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002636 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2637 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002638 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002639 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002640 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002641
Chris Lattner0579f7f2007-05-03 22:04:19 +00002642 SmallVector<Value*, 16> Args;
2643 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002644 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002645 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002646 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002647 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002648 Args.push_back(getValue(Record, OpNum, NextValueNo,
2649 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002650 if (Args.back() == 0) return Error("Invalid CALL record");
2651 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002652
Chris Lattner0579f7f2007-05-03 22:04:19 +00002653 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002654 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002655 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002656 return Error("Invalid CALL record");
2657 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002658 while (OpNum != Record.size()) {
2659 Value *Op;
2660 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2661 return Error("Invalid CALL record");
2662 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002663 }
2664 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002665
Jay Foada3efbb12011-07-15 08:37:34 +00002666 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002667 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002668 cast<CallInst>(I)->setCallingConv(
2669 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002670 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002671 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002672 break;
2673 }
2674 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2675 if (Record.size() < 3)
2676 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002677 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002678 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002679 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002680 if (!OpTy || !Op || !ResTy)
2681 return Error("Invalid VAARG record");
2682 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002683 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002684 break;
2685 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002686 }
2687
2688 // Add instruction to end of current BB. If there is no current BB, reject
2689 // this file.
2690 if (CurBB == 0) {
2691 delete I;
2692 return Error("Invalid instruction with no BB");
2693 }
2694 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002695
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002696 // If this was a terminator instruction, move to the next block.
2697 if (isa<TerminatorInst>(I)) {
2698 ++CurBBNo;
2699 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2700 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002701
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002702 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002703 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002704 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002705 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002706
Chris Lattner5a4251c2013-01-20 02:13:19 +00002707OutOfRecordLoop:
2708
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002709 // Check the function list for unresolved values.
2710 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2711 if (A->getParent() == 0) {
2712 // We found at least one unresolved value. Nuke them all to avoid leaks.
2713 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002714 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002715 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002716 delete A;
2717 }
2718 }
Chris Lattner35a04702007-05-04 03:50:29 +00002719 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002720 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002721 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002722
Dan Gohman064ff3e2010-08-25 20:23:38 +00002723 // FIXME: Check for unresolved forward-declared metadata references
2724 // and clean up leaks.
2725
Chris Lattner50b136d2009-10-28 05:53:48 +00002726 // See if anything took the address of blocks in this function. If so,
2727 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002728 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2729 BlockAddrFwdRefs.find(F);
2730 if (BAFRI != BlockAddrFwdRefs.end()) {
2731 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2732 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2733 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002734 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002735 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00002736
Chris Lattner50b136d2009-10-28 05:53:48 +00002737 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002738 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002739 FwdRef->eraseFromParent();
2740 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002741
Chris Lattner50b136d2009-10-28 05:53:48 +00002742 BlockAddrFwdRefs.erase(BAFRI);
2743 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002744
Chris Lattner980e5aa2007-05-01 05:52:21 +00002745 // Trim the value list down to the size it was before we parsed this function.
2746 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002747 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002748 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002749 return false;
2750}
2751
Derek Schuff2ea93872012-02-06 22:30:29 +00002752/// FindFunctionInStream - Find the function body in the bitcode stream
2753bool BitcodeReader::FindFunctionInStream(Function *F,
2754 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2755 while (DeferredFunctionInfoIterator->second == 0) {
2756 if (Stream.AtEndOfStream())
2757 return Error("Could not find Function in stream");
2758 // ParseModule will parse the next body in the stream and set its
2759 // position in the DeferredFunctionInfo map.
2760 if (ParseModule(true)) return true;
2761 }
2762 return false;
2763}
2764
Chris Lattnerb348bb82007-05-18 04:02:46 +00002765//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002766// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002767//===----------------------------------------------------------------------===//
2768
2769
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002770bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2771 if (const Function *F = dyn_cast<Function>(GV)) {
2772 return F->isDeclaration() &&
2773 DeferredFunctionInfo.count(const_cast<Function*>(F));
2774 }
2775 return false;
2776}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002777
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002778bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2779 Function *F = dyn_cast<Function>(GV);
2780 // If it's not a function or is already material, ignore the request.
2781 if (!F || !F->isMaterializable()) return false;
2782
2783 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002784 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002785 // If its position is recorded as 0, its body is somewhere in the stream
2786 // but we haven't seen it yet.
2787 if (DFII->second == 0)
2788 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002789
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002790 // Move the bit stream to the saved position of the deferred function body.
2791 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002792
Chris Lattnerb348bb82007-05-18 04:02:46 +00002793 if (ParseFunctionBody(F)) {
2794 if (ErrInfo) *ErrInfo = ErrorString;
2795 return true;
2796 }
Chandler Carruth69940402007-08-04 01:51:18 +00002797
2798 // Upgrade any old intrinsic calls in the function.
2799 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2800 E = UpgradedIntrinsics.end(); I != E; ++I) {
2801 if (I->first != I->second) {
2802 for (Value::use_iterator UI = I->first->use_begin(),
2803 UE = I->first->use_end(); UI != UE; ) {
2804 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2805 UpgradeIntrinsicCall(CI, I->second);
2806 }
2807 }
2808 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002809
Chris Lattnerb348bb82007-05-18 04:02:46 +00002810 return false;
2811}
2812
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002813bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2814 const Function *F = dyn_cast<Function>(GV);
2815 if (!F || F->isDeclaration())
2816 return false;
2817 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2818}
2819
2820void BitcodeReader::Dematerialize(GlobalValue *GV) {
2821 Function *F = dyn_cast<Function>(GV);
2822 // If this function isn't dematerializable, this is a noop.
2823 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002824 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002825
Chris Lattnerb348bb82007-05-18 04:02:46 +00002826 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002827
Chris Lattnerb348bb82007-05-18 04:02:46 +00002828 // Just forget the function body, we can remat it later.
2829 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002830}
2831
2832
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002833bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2834 assert(M == TheModule &&
2835 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002836 // Iterate over the module, deserializing any functions that are still on
2837 // disk.
2838 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2839 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002840 if (F->isMaterializable() &&
2841 Materialize(F, ErrInfo))
2842 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002843
Derek Schuff0ffe6982012-02-29 00:07:09 +00002844 // At this point, if there are any function bodies, the current bit is
2845 // pointing to the END_BLOCK record after them. Now make sure the rest
2846 // of the bits in the module have been read.
2847 if (NextUnreadBit)
2848 ParseModule(true);
2849
Daniel Dunbara279bc32009-09-20 02:20:51 +00002850 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2851 // delete the old functions to clean up. We can't do this unless the entire
2852 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002853 // with calls to the old function.
2854 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2855 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2856 if (I->first != I->second) {
2857 for (Value::use_iterator UI = I->first->use_begin(),
2858 UE = I->first->use_end(); UI != UE; ) {
2859 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2860 UpgradeIntrinsicCall(CI, I->second);
2861 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002862 if (!I->first->use_empty())
2863 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002864 I->first->eraseFromParent();
2865 }
2866 }
2867 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002868
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002869 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002870}
2871
Derek Schuff2ea93872012-02-06 22:30:29 +00002872bool BitcodeReader::InitStream() {
2873 if (LazyStreamer) return InitLazyStream();
2874 return InitStreamFromBuffer();
2875}
2876
2877bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00002878 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00002879 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2880
2881 if (Buffer->getBufferSize() & 3) {
2882 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2883 return Error("Invalid bitcode signature");
2884 else
2885 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2886 }
2887
2888 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2889 // The magic number is 0x0B17C0DE stored in little endian.
2890 if (isBitcodeWrapper(BufPtr, BufEnd))
2891 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2892 return Error("Invalid bitcode wrapper header");
2893
2894 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2895 Stream.init(*StreamFile);
2896
2897 return false;
2898}
2899
2900bool BitcodeReader::InitLazyStream() {
2901 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2902 // see it.
2903 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2904 StreamFile.reset(new BitstreamReader(Bytes));
2905 Stream.init(*StreamFile);
2906
2907 unsigned char buf[16];
2908 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2909 return Error("Bitcode stream must be at least 16 bytes in length");
2910
2911 if (!isBitcode(buf, buf + 16))
2912 return Error("Invalid bitcode signature");
2913
2914 if (isBitcodeWrapper(buf, buf + 4)) {
2915 const unsigned char *bitcodeStart = buf;
2916 const unsigned char *bitcodeEnd = buf + 16;
2917 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2918 Bytes->dropLeadingBytes(bitcodeStart - buf);
2919 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2920 }
2921 return false;
2922}
Chris Lattner48f84872007-05-01 04:59:48 +00002923
Chris Lattnerc453f762007-04-29 07:54:31 +00002924//===----------------------------------------------------------------------===//
2925// External interface
2926//===----------------------------------------------------------------------===//
2927
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002928/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002929///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002930Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2931 LLVMContext& Context,
2932 std::string *ErrMsg) {
2933 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002934 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002935 M->setMaterializer(R);
2936 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002937 if (ErrMsg)
2938 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002939
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002940 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002941 return 0;
2942 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002943 // Have the BitcodeReader dtor delete 'Buffer'.
2944 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002945
2946 R->materializeForwardReferencedFunctions();
2947
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002948 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002949}
2950
Derek Schuff2ea93872012-02-06 22:30:29 +00002951
2952Module *llvm::getStreamedBitcodeModule(const std::string &name,
2953 DataStreamer *streamer,
2954 LLVMContext &Context,
2955 std::string *ErrMsg) {
2956 Module *M = new Module(name, Context);
2957 BitcodeReader *R = new BitcodeReader(streamer, Context);
2958 M->setMaterializer(R);
2959 if (R->ParseBitcodeInto(M)) {
2960 if (ErrMsg)
2961 *ErrMsg = R->getErrorString();
2962 delete M; // Also deletes R.
2963 return 0;
2964 }
2965 R->setBufferOwned(false); // no buffer to delete
2966 return M;
2967}
2968
Chris Lattnerc453f762007-04-29 07:54:31 +00002969/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2970/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002971Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002972 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002973 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2974 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002975
2976 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2977 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002978 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002979
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002980 // Read in the entire module, and destroy the BitcodeReader.
2981 if (M->MaterializeAllPermanently(ErrMsg)) {
2982 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002983 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002984 }
Bill Wendling34711742010-10-06 01:22:42 +00002985
Chad Rosiercbbb0962011-12-07 21:44:12 +00002986 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2987 // written. We must defer until the Module has been fully materialized.
2988
Chris Lattnerc453f762007-04-29 07:54:31 +00002989 return M;
2990}
Bill Wendling34711742010-10-06 01:22:42 +00002991
2992std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2993 LLVMContext& Context,
2994 std::string *ErrMsg) {
2995 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2996 // Don't let the BitcodeReader dtor delete 'Buffer'.
2997 R->setBufferOwned(false);
2998
2999 std::string Triple("");
3000 if (R->ParseTriple(Triple))
3001 if (ErrMsg)
3002 *ErrMsg = R->getErrorString();
3003
3004 delete R;
3005 return Triple;
3006}