blob: b14250b0662fd681747f6b3b7c23022178589e17 [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) {
444 unsigned Code = Stream.ReadCode();
445 if (Code == bitc::END_BLOCK) {
446 if (Stream.ReadBlockEnd())
447 return Error("Error at end of PARAMATTR block");
448 return false;
449 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000450
Chris Lattner48c85b82007-05-04 03:30:17 +0000451 if (Code == bitc::ENTER_SUBBLOCK) {
452 // No known subblocks, always skip them.
453 Stream.ReadSubBlockID();
454 if (Stream.SkipBlock())
455 return Error("Malformed block record");
456 continue;
457 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000458
Chris Lattner48c85b82007-05-04 03:30:17 +0000459 if (Code == bitc::DEFINE_ABBREV) {
460 Stream.ReadAbbrevRecord();
461 continue;
462 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000463
Chris Lattner48c85b82007-05-04 03:30:17 +0000464 // Read a record.
465 Record.clear();
466 switch (Stream.ReadRecord(Code, Record)) {
467 default: // Default behavior: ignore.
468 break;
469 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
470 if (Record.size() & 1)
471 return Error("Invalid ENTRY record");
472
Chris Lattner48c85b82007-05-04 03:30:17 +0000473 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling034b94b2012-12-19 07:18:57 +0000474 Attribute ReconstitutedAttr =
475 Attribute::decodeLLVMAttributesForBitcode(Context, Record[i+1]);
Bill Wendling1db9b692013-01-09 23:36:50 +0000476 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000477 }
Chris Lattner461edd92008-03-12 02:25:52 +0000478
Devang Patel19c87462008-09-26 22:53:05 +0000479 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling702cc912012-10-15 20:35:56 +0000480 AttrBuilder B(Record[i+1]);
Bill Wendlingcb3de0b2012-10-15 04:46:55 +0000481 if (B.hasAttributes())
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000482 Attrs.push_back(AttributeWithIndex::get(Record[i],
Bill Wendling034b94b2012-12-19 07:18:57 +0000483 Attribute::get(Context, B)));
Devang Patel19c87462008-09-26 22:53:05 +0000484 }
Devang Patel19c87462008-09-26 22:53:05 +0000485
Bill Wendling99faa3b2012-12-07 23:16:57 +0000486 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000487 Attrs.clear();
488 break;
489 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000490 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000491 }
492}
493
Chris Lattner86697142007-05-01 05:01:34 +0000494bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000495 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000496 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000497
Chris Lattner1afcace2011-07-09 17:41:24 +0000498 return ParseTypeTableBody();
499}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000500
Chris Lattner1afcace2011-07-09 17:41:24 +0000501bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000502 if (!TypeList.empty())
503 return Error("Multiple TYPE_BLOCKs found!");
504
505 SmallVector<uint64_t, 64> Record;
506 unsigned NumRecords = 0;
507
Chris Lattner1afcace2011-07-09 17:41:24 +0000508 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000509
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000510 // Read all the records for this type table.
511 while (1) {
512 unsigned Code = Stream.ReadCode();
513 if (Code == bitc::END_BLOCK) {
514 if (NumRecords != TypeList.size())
515 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000516 if (Stream.ReadBlockEnd())
517 return Error("Error at end of type table block");
518 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000519 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000520
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000521 if (Code == bitc::ENTER_SUBBLOCK) {
522 // No known subblocks, always skip them.
523 Stream.ReadSubBlockID();
524 if (Stream.SkipBlock())
525 return Error("Malformed block record");
526 continue;
527 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000528
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000529 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000530 Stream.ReadAbbrevRecord();
531 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000532 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000533
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000534 // Read a record.
535 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000536 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000537 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000538 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000539 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
540 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
541 // type list. This allows us to reserve space.
542 if (Record.size() < 1)
543 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000544 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000545 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000546 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000547 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000548 break;
Dan Gohmance163392011-12-17 00:04:22 +0000549 case bitc::TYPE_CODE_HALF: // HALF
550 ResultTy = Type::getHalfTy(Context);
551 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000552 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000553 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000554 break;
555 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000556 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000557 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000558 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000559 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000560 break;
561 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000562 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000563 break;
564 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000565 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000566 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000567 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000568 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000569 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000570 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000571 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000572 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000573 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
574 ResultTy = Type::getX86_MMXTy(Context);
575 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000576 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
577 if (Record.size() < 1)
578 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000579
Owen Anderson1d0be152009-08-13 21:58:54 +0000580 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000581 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000582 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000583 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000584 if (Record.size() < 1)
585 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000586 unsigned AddressSpace = 0;
587 if (Record.size() == 2)
588 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000589 ResultTy = getTypeByID(Record[0]);
590 if (ResultTy == 0) return Error("invalid element type in pointer type");
591 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000592 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000593 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000594 case bitc::TYPE_CODE_FUNCTION_OLD: {
595 // FIXME: attrid is dead, remove it in LLVM 4.0
596 // FUNCTION: [vararg, attrid, retty, paramty x N]
597 if (Record.size() < 3)
598 return Error("Invalid FUNCTION type record");
599 SmallVector<Type*, 8> ArgTys;
600 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
601 if (Type *T = getTypeByID(Record[i]))
602 ArgTys.push_back(T);
603 else
604 break;
605 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000606
Nuno Lopesee8100d2012-05-23 15:19:39 +0000607 ResultTy = getTypeByID(Record[2]);
608 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
609 return Error("invalid type in function type");
610
611 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
612 break;
613 }
Chad Rosiercde54642011-11-03 00:14:01 +0000614 case bitc::TYPE_CODE_FUNCTION: {
615 // FUNCTION: [vararg, retty, paramty x N]
616 if (Record.size() < 2)
617 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000618 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000619 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
620 if (Type *T = getTypeByID(Record[i]))
621 ArgTys.push_back(T);
622 else
623 break;
624 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000625
Chad Rosiercde54642011-11-03 00:14:01 +0000626 ResultTy = getTypeByID(Record[1]);
627 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
628 return Error("invalid type in function type");
629
630 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
631 break;
632 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000633 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000634 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000635 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000636 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000637 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
638 if (Type *T = getTypeByID(Record[i]))
639 EltTys.push_back(T);
640 else
641 break;
642 }
643 if (EltTys.size() != Record.size()-1)
644 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000645 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000646 break;
647 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000648 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
649 if (ConvertToString(Record, 0, TypeName))
650 return Error("Invalid STRUCT_NAME record");
651 continue;
652
653 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
654 if (Record.size() < 1)
655 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000656
Chris Lattner1afcace2011-07-09 17:41:24 +0000657 if (NumRecords >= TypeList.size())
658 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000659
Chris Lattner1afcace2011-07-09 17:41:24 +0000660 // Check to see if this was forward referenced, if so fill in the temp.
661 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
662 if (Res) {
663 Res->setName(TypeName);
664 TypeList[NumRecords] = 0;
665 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000666 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000667 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000668
Chris Lattner1afcace2011-07-09 17:41:24 +0000669 SmallVector<Type*, 8> EltTys;
670 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
671 if (Type *T = getTypeByID(Record[i]))
672 EltTys.push_back(T);
673 else
674 break;
675 }
676 if (EltTys.size() != Record.size()-1)
677 return Error("invalid STRUCT type record");
678 Res->setBody(EltTys, Record[0]);
679 ResultTy = Res;
680 break;
681 }
682 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
683 if (Record.size() != 1)
684 return Error("Invalid OPAQUE type record");
685
686 if (NumRecords >= TypeList.size())
687 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000688
Chris Lattner1afcace2011-07-09 17:41:24 +0000689 // Check to see if this was forward referenced, if so fill in the temp.
690 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
691 if (Res) {
692 Res->setName(TypeName);
693 TypeList[NumRecords] = 0;
694 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000695 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000696 TypeName.clear();
697 ResultTy = Res;
698 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000699 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000700 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
701 if (Record.size() < 2)
702 return Error("Invalid ARRAY type record");
703 if ((ResultTy = getTypeByID(Record[1])))
704 ResultTy = ArrayType::get(ResultTy, Record[0]);
705 else
706 return Error("Invalid ARRAY type element");
707 break;
708 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
709 if (Record.size() < 2)
710 return Error("Invalid VECTOR type record");
711 if ((ResultTy = getTypeByID(Record[1])))
712 ResultTy = VectorType::get(ResultTy, Record[0]);
713 else
714 return Error("Invalid ARRAY type element");
715 break;
716 }
717
718 if (NumRecords >= TypeList.size())
719 return Error("invalid TYPE table");
720 assert(ResultTy && "Didn't read a type?");
721 assert(TypeList[NumRecords] == 0 && "Already read type?");
722 TypeList[NumRecords++] = ResultTy;
723 }
724}
725
Chris Lattner86697142007-05-01 05:01:34 +0000726bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000727 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000728 return Error("Malformed block record");
729
730 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000731
Chris Lattner0b2482a2007-04-23 21:26:05 +0000732 // Read all the records for this value table.
733 SmallString<128> ValueName;
734 while (1) {
735 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000736 if (Code == bitc::END_BLOCK) {
737 if (Stream.ReadBlockEnd())
738 return Error("Error at end of value symbol table block");
739 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000740 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000741 if (Code == bitc::ENTER_SUBBLOCK) {
742 // No known subblocks, always skip them.
743 Stream.ReadSubBlockID();
744 if (Stream.SkipBlock())
745 return Error("Malformed block record");
746 continue;
747 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000748
Chris Lattner0b2482a2007-04-23 21:26:05 +0000749 if (Code == bitc::DEFINE_ABBREV) {
750 Stream.ReadAbbrevRecord();
751 continue;
752 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000753
Chris Lattner0b2482a2007-04-23 21:26:05 +0000754 // Read a record.
755 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000756 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000757 default: // Default behavior: unknown type.
758 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000759 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000760 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000761 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000762 unsigned ValueID = Record[0];
763 if (ValueID >= ValueList.size())
764 return Error("Invalid Value ID in VST_ENTRY record");
765 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000766
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000767 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000768 ValueName.clear();
769 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000770 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000771 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000772 if (ConvertToString(Record, 1, ValueName))
773 return Error("Invalid VST_BBENTRY record");
774 BasicBlock *BB = getBasicBlock(Record[0]);
775 if (BB == 0)
776 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000777
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000778 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000779 ValueName.clear();
780 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000781 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000782 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000783 }
784}
785
Devang Patele54abc92009-07-22 17:43:22 +0000786bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000787 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000788
789 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
790 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000791
Devang Patele54abc92009-07-22 17:43:22 +0000792 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000793
Devang Patele54abc92009-07-22 17:43:22 +0000794 // Read all the records.
795 while (1) {
796 unsigned Code = Stream.ReadCode();
797 if (Code == bitc::END_BLOCK) {
798 if (Stream.ReadBlockEnd())
799 return Error("Error at end of PARAMATTR block");
800 return false;
801 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000802
Devang Patele54abc92009-07-22 17:43:22 +0000803 if (Code == bitc::ENTER_SUBBLOCK) {
804 // No known subblocks, always skip them.
805 Stream.ReadSubBlockID();
806 if (Stream.SkipBlock())
807 return Error("Malformed block record");
808 continue;
809 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000810
Devang Patele54abc92009-07-22 17:43:22 +0000811 if (Code == bitc::DEFINE_ABBREV) {
812 Stream.ReadAbbrevRecord();
813 continue;
814 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000815
Victor Hernandez24e64df2010-01-10 07:14:18 +0000816 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000817 // Read a record.
818 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000819 Code = Stream.ReadRecord(Code, Record);
820 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000821 default: // Default behavior: ignore.
822 break;
Devang Patelaa993142009-07-29 22:34:41 +0000823 case bitc::METADATA_NAME: {
824 // Read named of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000825 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000826 Record.clear();
827 Code = Stream.ReadCode();
828
Chris Lattner9d61dd92011-06-17 17:50:30 +0000829 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000830 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000831 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000832
833 // Read named metadata elements.
834 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000835 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000836 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000837 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
838 if (MD == 0)
839 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000840 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000841 }
Devang Patelaa993142009-07-29 22:34:41 +0000842 break;
843 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000844 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000845 IsFunctionLocal = true;
846 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000847 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000848 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000849 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000850
Devang Patel104cf9e2009-07-23 01:07:34 +0000851 unsigned Size = Record.size();
852 SmallVector<Value*, 8> Elts;
853 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000854 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000855 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000856 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000857 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000858 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000859 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
860 else
861 Elts.push_back(NULL);
862 }
Jay Foadec9186b2011-04-21 19:59:31 +0000863 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000864 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000865 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000866 break;
867 }
Devang Patele54abc92009-07-22 17:43:22 +0000868 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000869 SmallString<8> String(Record.begin(), Record.end());
870 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000871 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000872 break;
873 }
Devang Patele8e02132009-09-18 19:26:43 +0000874 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000875 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000876 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000877
Devang Patela2148402009-09-28 21:14:55 +0000878 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000879 SmallString<8> Name(Record.begin()+1, Record.end());
880
Chris Lattner08113472009-12-29 09:01:33 +0000881 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000882 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
883 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000884 break;
885 }
Devang Patele54abc92009-07-22 17:43:22 +0000886 }
887 }
888}
889
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000890/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +0000891/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000892uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +0000893 if ((V & 1) == 0)
894 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000895 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000896 return -(V >> 1);
897 // There is no such thing as -0 with integers. "-0" really means MININT.
898 return 1ULL << 63;
899}
900
Chris Lattner07d98b42007-04-26 02:46:40 +0000901/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
902/// values and aliases that we can.
903bool BitcodeReader::ResolveGlobalAndAliasInits() {
904 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
905 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000906
Chris Lattner07d98b42007-04-26 02:46:40 +0000907 GlobalInitWorklist.swap(GlobalInits);
908 AliasInitWorklist.swap(AliasInits);
909
910 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000911 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000912 if (ValID >= ValueList.size()) {
913 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000914 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000915 } else {
916 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
917 GlobalInitWorklist.back().first->setInitializer(C);
918 else
919 return Error("Global variable initializer is not a constant!");
920 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000921 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000922 }
923
924 while (!AliasInitWorklist.empty()) {
925 unsigned ValID = AliasInitWorklist.back().second;
926 if (ValID >= ValueList.size()) {
927 AliasInits.push_back(AliasInitWorklist.back());
928 } else {
929 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000930 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000931 else
932 return Error("Alias initializer is not a constant!");
933 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000934 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000935 }
936 return false;
937}
938
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000939static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
940 SmallVector<uint64_t, 8> Words(Vals.size());
941 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000942 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000943
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000944 return APInt(TypeBits, Words);
945}
946
Chris Lattner86697142007-05-01 05:01:34 +0000947bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000948 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000949 return Error("Malformed block record");
950
951 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000952
Chris Lattnere16504e2007-04-24 03:30:34 +0000953 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000954 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000955 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000956 while (1) {
957 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000958 if (Code == bitc::END_BLOCK)
959 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000960
Chris Lattnere16504e2007-04-24 03:30:34 +0000961 if (Code == bitc::ENTER_SUBBLOCK) {
962 // No known subblocks, always skip them.
963 Stream.ReadSubBlockID();
964 if (Stream.SkipBlock())
965 return Error("Malformed block record");
966 continue;
967 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000968
Chris Lattnere16504e2007-04-24 03:30:34 +0000969 if (Code == bitc::DEFINE_ABBREV) {
970 Stream.ReadAbbrevRecord();
971 continue;
972 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000973
Chris Lattnere16504e2007-04-24 03:30:34 +0000974 // Read a record.
975 Record.clear();
976 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000977 unsigned BitCode = Stream.ReadRecord(Code, Record);
978 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000979 default: // Default behavior: unknown constant
980 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000981 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000982 break;
983 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
984 if (Record.empty())
985 return Error("Malformed CST_SETTYPE record");
986 if (Record[0] >= TypeList.size())
987 return Error("Invalid Type ID in CST_SETTYPE record");
988 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000989 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000990 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000991 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000992 break;
993 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000994 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000995 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000996 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000997 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000998 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000999 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001000 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001001
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001002 APInt VInt = ReadWideAPInt(Record,
1003 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001004 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +00001005
Chris Lattner0eef0802007-04-24 04:04:35 +00001006 break;
1007 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001008 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001009 if (Record.empty())
1010 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001011 if (CurTy->isHalfTy())
1012 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1013 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001014 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001015 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001016 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001017 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001018 // Bits are not stored the same way as a normal i80 APInt, compensate.
1019 uint64_t Rearrange[2];
1020 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1021 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001022 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001023 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001024 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001025 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001026 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001027 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001028 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001029 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001030 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001031
Chris Lattner15e6d172007-05-04 19:11:41 +00001032 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1033 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001034 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001035
Chris Lattner15e6d172007-05-04 19:11:41 +00001036 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001037 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001038
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001039 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001040 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001041 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001042 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001043 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001044 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1045 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001046 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001047 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001048 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001049 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1050 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001051 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001052 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001053 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001054 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001055 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001056 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001057 break;
1058 }
Chris Lattner2237f842012-02-05 02:41:35 +00001059 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001060 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1061 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001062 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001063
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001064 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001065 V = ConstantDataArray::getString(Context, Elts,
1066 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001067 break;
1068 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001069 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1070 if (Record.empty())
1071 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001072
Chris Lattnerd408f062012-01-30 00:51:16 +00001073 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1074 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001075
Chris Lattnerd408f062012-01-30 00:51:16 +00001076 if (EltTy->isIntegerTy(8)) {
1077 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1078 if (isa<VectorType>(CurTy))
1079 V = ConstantDataVector::get(Context, Elts);
1080 else
1081 V = ConstantDataArray::get(Context, Elts);
1082 } else if (EltTy->isIntegerTy(16)) {
1083 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1084 if (isa<VectorType>(CurTy))
1085 V = ConstantDataVector::get(Context, Elts);
1086 else
1087 V = ConstantDataArray::get(Context, Elts);
1088 } else if (EltTy->isIntegerTy(32)) {
1089 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1090 if (isa<VectorType>(CurTy))
1091 V = ConstantDataVector::get(Context, Elts);
1092 else
1093 V = ConstantDataArray::get(Context, Elts);
1094 } else if (EltTy->isIntegerTy(64)) {
1095 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1096 if (isa<VectorType>(CurTy))
1097 V = ConstantDataVector::get(Context, Elts);
1098 else
1099 V = ConstantDataArray::get(Context, Elts);
1100 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001101 SmallVector<float, 16> Elts(Size);
1102 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001103 if (isa<VectorType>(CurTy))
1104 V = ConstantDataVector::get(Context, Elts);
1105 else
1106 V = ConstantDataArray::get(Context, Elts);
1107 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001108 SmallVector<double, 16> Elts(Size);
1109 std::transform(Record.begin(), Record.end(), Elts.begin(),
1110 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001111 if (isa<VectorType>(CurTy))
1112 V = ConstantDataVector::get(Context, Elts);
1113 else
1114 V = ConstantDataArray::get(Context, Elts);
1115 } else {
1116 return Error("Unknown element type in CE_DATA");
1117 }
1118 break;
1119 }
1120
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001121 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1122 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1123 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001124 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001125 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001126 } else {
1127 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1128 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001129 unsigned Flags = 0;
1130 if (Record.size() >= 4) {
1131 if (Opc == Instruction::Add ||
1132 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001133 Opc == Instruction::Mul ||
1134 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001135 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1136 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1137 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1138 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001139 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001140 Opc == Instruction::UDiv ||
1141 Opc == Instruction::LShr ||
1142 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001143 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001144 Flags |= SDivOperator::IsExact;
1145 }
1146 }
1147 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001148 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001149 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001150 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001151 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1152 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1153 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001154 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001155 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001156 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001157 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001158 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001159 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001160 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001161 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001162 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001163 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001164 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001165 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001166 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001167 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001168 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001169 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001170 if (!ElTy) return Error("Invalid CE_GEP record");
1171 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1172 }
Jay Foaddab3d292011-07-21 14:31:17 +00001173 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001174 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1175 BitCode ==
1176 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001177 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001178 }
1179 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1180 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbeye46b14a2012-11-19 19:22:55 +00001181 V = ConstantExpr::getSelect(
1182 ValueList.getConstantFwdRef(Record[0],
1183 Type::getInt1Ty(Context)),
1184 ValueList.getConstantFwdRef(Record[1],CurTy),
1185 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001186 break;
1187 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1188 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001189 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001190 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1191 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1192 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001193 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001194 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001195 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001196 break;
1197 }
1198 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001199 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001200 if (Record.size() < 3 || OpTy == 0)
1201 return Error("Invalid CE_INSERTELT record");
1202 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1203 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1204 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001205 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001206 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001207 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001208 break;
1209 }
1210 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001211 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001212 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001213 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001214 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1215 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001216 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001217 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001218 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001219 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001220 break;
1221 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001222 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001223 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1224 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001225 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001226 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1227 return Error("Invalid CE_SHUFVEC_EX record");
1228 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1229 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001230 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001231 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001232 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001233 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001234 break;
1235 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001236 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1237 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001238 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001239 if (OpTy == 0) return Error("Invalid CE_CMP record");
1240 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1241 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1242
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001243 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001244 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001245 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001246 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001247 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001248 }
Chad Rosier581600b2012-09-05 19:00:49 +00001249 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001250 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001251 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001252 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1253 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001254 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001255 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001256 unsigned AsmStrSize = Record[1];
1257 if (2+AsmStrSize >= Record.size())
1258 return Error("Invalid INLINEASM record");
1259 unsigned ConstStrSize = Record[2+AsmStrSize];
1260 if (3+AsmStrSize+ConstStrSize > Record.size())
1261 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001262
Chris Lattner2bce93a2007-05-06 01:58:20 +00001263 for (unsigned i = 0; i != AsmStrSize; ++i)
1264 AsmStr += (char)Record[2+i];
1265 for (unsigned i = 0; i != ConstStrSize; ++i)
1266 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001267 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001268 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001269 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001270 break;
1271 }
Chad Rosier581600b2012-09-05 19:00:49 +00001272 // This version adds support for the asm dialect keywords (e.g.,
1273 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001274 case bitc::CST_CODE_INLINEASM: {
1275 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1276 std::string AsmStr, ConstrStr;
1277 bool HasSideEffects = Record[0] & 1;
1278 bool IsAlignStack = (Record[0] >> 1) & 1;
1279 unsigned AsmDialect = Record[0] >> 2;
1280 unsigned AsmStrSize = Record[1];
1281 if (2+AsmStrSize >= Record.size())
1282 return Error("Invalid INLINEASM record");
1283 unsigned ConstStrSize = Record[2+AsmStrSize];
1284 if (3+AsmStrSize+ConstStrSize > Record.size())
1285 return Error("Invalid INLINEASM record");
1286
1287 for (unsigned i = 0; i != AsmStrSize; ++i)
1288 AsmStr += (char)Record[2+i];
1289 for (unsigned i = 0; i != ConstStrSize; ++i)
1290 ConstrStr += (char)Record[3+AsmStrSize+i];
1291 PointerType *PTy = cast<PointerType>(CurTy);
1292 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1293 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001294 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001295 break;
1296 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001297 case bitc::CST_CODE_BLOCKADDRESS:{
1298 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001299 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001300 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1301 Function *Fn =
1302 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1303 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001304
1305 // If the function is already parsed we can insert the block address right
1306 // away.
1307 if (!Fn->empty()) {
1308 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1309 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1310 if (BBI == BBE)
1311 return Error("Invalid blockaddress block #");
1312 ++BBI;
1313 }
1314 V = BlockAddress::get(Fn, BBI);
1315 } else {
1316 // Otherwise insert a placeholder and remember it so it can be inserted
1317 // when the function is parsed.
1318 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1319 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001320 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001321 0, "");
1322 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1323 V = FwdRef;
1324 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001325 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001326 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001327 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001328
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001329 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001330 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001331 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001332
Chris Lattnerea693df2008-08-21 02:34:16 +00001333 if (NextCstNo != ValueList.size())
1334 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001335
Chris Lattnerea693df2008-08-21 02:34:16 +00001336 if (Stream.ReadBlockEnd())
1337 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001338
Chris Lattnerea693df2008-08-21 02:34:16 +00001339 // Once all the constants have been read, go through and resolve forward
1340 // references.
1341 ValueList.ResolveConstantForwardRefs();
1342 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001343}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001344
Chad Rosiercbbb0962011-12-07 21:44:12 +00001345bool BitcodeReader::ParseUseLists() {
1346 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1347 return Error("Malformed block record");
1348
1349 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001350
Chad Rosiercbbb0962011-12-07 21:44:12 +00001351 // Read all the records.
1352 while (1) {
1353 unsigned Code = Stream.ReadCode();
1354 if (Code == bitc::END_BLOCK) {
1355 if (Stream.ReadBlockEnd())
1356 return Error("Error at end of use-list table block");
1357 return false;
1358 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001359
Chad Rosiercbbb0962011-12-07 21:44:12 +00001360 if (Code == bitc::ENTER_SUBBLOCK) {
1361 // No known subblocks, always skip them.
1362 Stream.ReadSubBlockID();
1363 if (Stream.SkipBlock())
1364 return Error("Malformed block record");
1365 continue;
1366 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001367
Chad Rosiercbbb0962011-12-07 21:44:12 +00001368 if (Code == bitc::DEFINE_ABBREV) {
1369 Stream.ReadAbbrevRecord();
1370 continue;
1371 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001372
Chad Rosiercbbb0962011-12-07 21:44:12 +00001373 // Read a use list record.
1374 Record.clear();
1375 switch (Stream.ReadRecord(Code, Record)) {
1376 default: // Default behavior: unknown type.
1377 break;
1378 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1379 unsigned RecordLength = Record.size();
1380 if (RecordLength < 1)
1381 return Error ("Invalid UseList reader!");
1382 UseListRecords.push_back(Record);
1383 break;
1384 }
1385 }
1386 }
1387}
1388
Chris Lattner980e5aa2007-05-01 05:52:21 +00001389/// RememberAndSkipFunctionBody - When we see the block for a function body,
1390/// remember where it is and then skip it. This lets us lazily deserialize the
1391/// functions.
1392bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001393 // Get the function we are talking about.
1394 if (FunctionsWithBodies.empty())
1395 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001396
Chris Lattner48f84872007-05-01 04:59:48 +00001397 Function *Fn = FunctionsWithBodies.back();
1398 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001399
Chris Lattner48f84872007-05-01 04:59:48 +00001400 // Save the current stream state.
1401 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001402 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001403
Chris Lattner48f84872007-05-01 04:59:48 +00001404 // Skip over the function block for now.
1405 if (Stream.SkipBlock())
1406 return Error("Malformed block record");
1407 return false;
1408}
1409
Derek Schuff2ea93872012-02-06 22:30:29 +00001410bool BitcodeReader::GlobalCleanup() {
1411 // Patch the initializers for globals and aliases up.
1412 ResolveGlobalAndAliasInits();
1413 if (!GlobalInits.empty() || !AliasInits.empty())
1414 return Error("Malformed global initializer set");
1415
1416 // Look for intrinsic functions which need to be upgraded at some point
1417 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1418 FI != FE; ++FI) {
1419 Function *NewFn;
1420 if (UpgradeIntrinsicFunction(FI, NewFn))
1421 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1422 }
1423
1424 // Look for global variables which need to be renamed.
1425 for (Module::global_iterator
1426 GI = TheModule->global_begin(), GE = TheModule->global_end();
1427 GI != GE; ++GI)
1428 UpgradeGlobalVariable(GI);
1429 // Force deallocation of memory for these vectors to favor the client that
1430 // want lazy deserialization.
1431 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1432 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1433 return false;
1434}
1435
1436bool BitcodeReader::ParseModule(bool Resume) {
1437 if (Resume)
1438 Stream.JumpToBit(NextUnreadBit);
1439 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001440 return Error("Malformed block record");
1441
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001442 SmallVector<uint64_t, 64> Record;
1443 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001444 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001445
1446 // Read all the records for this module.
1447 while (!Stream.AtEndOfStream()) {
1448 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001449 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001450 if (Stream.ReadBlockEnd())
1451 return Error("Error at end of module block");
1452
Derek Schuff2ea93872012-02-06 22:30:29 +00001453 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001455
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001456 if (Code == bitc::ENTER_SUBBLOCK) {
1457 switch (Stream.ReadSubBlockID()) {
1458 default: // Skip unknown content.
1459 if (Stream.SkipBlock())
1460 return Error("Malformed block record");
1461 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001462 case bitc::BLOCKINFO_BLOCK_ID:
1463 if (Stream.ReadBlockInfoBlock())
1464 return Error("Malformed BlockInfoBlock");
1465 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001466 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001467 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001468 return true;
1469 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001470 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001471 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001472 return true;
1473 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001474 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001475 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001476 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001477 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001478 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001479 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001480 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001481 return true;
1482 break;
Devang Patele54abc92009-07-22 17:43:22 +00001483 case bitc::METADATA_BLOCK_ID:
1484 if (ParseMetadata())
1485 return true;
1486 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001487 case bitc::FUNCTION_BLOCK_ID:
1488 // If this is the first function body we've seen, reverse the
1489 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001490 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001491 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001492 if (GlobalCleanup())
1493 return true;
1494 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001495 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001496
Chris Lattner980e5aa2007-05-01 05:52:21 +00001497 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001498 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001499 // For streaming bitcode, suspend parsing when we reach the function
1500 // bodies. Subsequent materialization calls will resume it when
1501 // necessary. For streaming, the function bodies must be at the end of
1502 // the bitcode. If the bitcode file is old, the symbol table will be
1503 // at the end instead and will not have been seen yet. In this case,
1504 // just finish the parse now.
1505 if (LazyStreamer && SeenValueSymbolTable) {
1506 NextUnreadBit = Stream.GetCurrentBitNo();
1507 return false;
1508 }
Chris Lattner48f84872007-05-01 04:59:48 +00001509 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001510 case bitc::USELIST_BLOCK_ID:
1511 if (ParseUseLists())
1512 return true;
1513 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001514 }
1515 continue;
1516 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001517
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001518 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001519 Stream.ReadAbbrevRecord();
1520 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001521 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001522
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001523 // Read a record.
1524 switch (Stream.ReadRecord(Code, Record)) {
1525 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001526 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001527 if (Record.size() < 1)
1528 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001529 // Only version #0 and #1 are supported so far.
1530 unsigned module_version = Record[0];
1531 switch (module_version) {
1532 default: return Error("Unknown bitstream version!");
1533 case 0:
1534 UseRelativeIDs = false;
1535 break;
1536 case 1:
1537 UseRelativeIDs = true;
1538 break;
1539 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001540 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001541 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001542 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001543 std::string S;
1544 if (ConvertToString(Record, 0, S))
1545 return Error("Invalid MODULE_CODE_TRIPLE record");
1546 TheModule->setTargetTriple(S);
1547 break;
1548 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001549 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001550 std::string S;
1551 if (ConvertToString(Record, 0, S))
1552 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1553 TheModule->setDataLayout(S);
1554 break;
1555 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001556 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001557 std::string S;
1558 if (ConvertToString(Record, 0, S))
1559 return Error("Invalid MODULE_CODE_ASM record");
1560 TheModule->setModuleInlineAsm(S);
1561 break;
1562 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001563 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1564 // FIXME: Remove in 4.0.
1565 std::string S;
1566 if (ConvertToString(Record, 0, S))
1567 return Error("Invalid MODULE_CODE_DEPLIB record");
1568 // Ignore value.
1569 break;
1570 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001571 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001572 std::string S;
1573 if (ConvertToString(Record, 0, S))
1574 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1575 SectionTable.push_back(S);
1576 break;
1577 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001578 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001579 std::string S;
1580 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001581 return Error("Invalid MODULE_CODE_GCNAME record");
1582 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001583 break;
1584 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001585 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001586 // linkage, alignment, section, visibility, threadlocal,
1587 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001588 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001589 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001590 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001591 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001592 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001593 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001595 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001596 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001597
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001598 bool isConstant = Record[1];
1599 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1600 unsigned Alignment = (1 << Record[4]) >> 1;
1601 std::string Section;
1602 if (Record[5]) {
1603 if (Record[5]-1 >= SectionTable.size())
1604 return Error("Invalid section ID");
1605 Section = SectionTable[Record[5]-1];
1606 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001607 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001608 if (Record.size() > 6)
1609 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001610
1611 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001612 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001613 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001614
Rafael Espindolabea46262011-01-08 16:42:36 +00001615 bool UnnamedAddr = false;
1616 if (Record.size() > 8)
1617 UnnamedAddr = Record[8];
1618
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001619 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001620 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001621 TLM, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001622 NewGV->setAlignment(Alignment);
1623 if (!Section.empty())
1624 NewGV->setSection(Section);
1625 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001626 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001627
Chris Lattner0b2482a2007-04-23 21:26:05 +00001628 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001630 // Remember which value to use for the global initializer.
1631 if (unsigned InitID = Record[2])
1632 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001633 break;
1634 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001635 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001636 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001637 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001638 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001639 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001640 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001641 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001642 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001643 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001644 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001645 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1646 if (!FTy)
1647 return Error("Function not a pointer to function type!");
1648
Gabor Greif051a9502008-04-06 20:25:17 +00001649 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1650 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001651
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001652 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001653 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001654 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001655 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattnera9bb7132007-05-08 05:38:01 +00001657 Func->setAlignment((1 << Record[5]) >> 1);
1658 if (Record[6]) {
1659 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001660 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001661 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001662 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001663 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001664 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001665 if (Record[8]-1 > GCTable.size())
1666 return Error("Invalid GC ID");
1667 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001668 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001669 bool UnnamedAddr = false;
1670 if (Record.size() > 9)
1671 UnnamedAddr = Record[9];
1672 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001673 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001674
Chris Lattner48f84872007-05-01 04:59:48 +00001675 // If this is a function with a body, remember the prototype we are
1676 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001677 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001678 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001679 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1680 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001681 break;
1682 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001683 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001684 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001685 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001686 if (Record.size() < 3)
1687 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001688 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001689 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001690 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001691 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001692
Chris Lattner07d98b42007-04-26 02:46:40 +00001693 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1694 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001695 // Old bitcode files didn't have visibility field.
1696 if (Record.size() > 3)
1697 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001698 ValueList.push_back(NewGA);
1699 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1700 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001701 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001702 /// MODULE_CODE_PURGEVALS: [numvals]
1703 case bitc::MODULE_CODE_PURGEVALS:
1704 // Trim down the value list to the specified size.
1705 if (Record.size() < 1 || Record[0] > ValueList.size())
1706 return Error("Invalid MODULE_PURGEVALS record");
1707 ValueList.shrinkTo(Record[0]);
1708 break;
1709 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001710 Record.clear();
1711 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001712
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001713 return Error("Premature end of bitstream");
1714}
1715
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001716bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001717 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001718
Derek Schuff2ea93872012-02-06 22:30:29 +00001719 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001721 // Sniff for the signature.
1722 if (Stream.Read(8) != 'B' ||
1723 Stream.Read(8) != 'C' ||
1724 Stream.Read(4) != 0x0 ||
1725 Stream.Read(4) != 0xC ||
1726 Stream.Read(4) != 0xE ||
1727 Stream.Read(4) != 0xD)
1728 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001729
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001730 // We expect a number of well-defined blocks, though we don't necessarily
1731 // need to understand them all.
1732 while (!Stream.AtEndOfStream()) {
1733 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001734
Rafael Espindolac9687b32011-05-26 18:59:54 +00001735 if (Code != bitc::ENTER_SUBBLOCK) {
1736
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001737 // The ranlib in xcode 4 will align archive members by appending newlines
1738 // to the end of them. If this file size is a multiple of 4 but not 8, we
1739 // have to read and ignore these final 4 bytes :-(
Chris Lattner63246aa2013-01-19 21:35:24 +00001740 if (Stream.getAbbrevIDWidth() == 2 && Code == 2 &&
Rafael Espindolac9687b32011-05-26 18:59:54 +00001741 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001742 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001743 return false;
1744
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001745 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001746 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001747
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001748 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001749
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001750 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001751 switch (BlockID) {
1752 case bitc::BLOCKINFO_BLOCK_ID:
1753 if (Stream.ReadBlockInfoBlock())
1754 return Error("Malformed BlockInfoBlock");
1755 break;
1756 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001757 // Reject multiple MODULE_BLOCK's in a single bitstream.
1758 if (TheModule)
1759 return Error("Multiple MODULE_BLOCKs in same stream");
1760 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001761 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001762 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001763 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001764 break;
1765 default:
1766 if (Stream.SkipBlock())
1767 return Error("Malformed block record");
1768 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001769 }
1770 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001771
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001772 return false;
1773}
Chris Lattnerc453f762007-04-29 07:54:31 +00001774
Bill Wendling34711742010-10-06 01:22:42 +00001775bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1776 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1777 return Error("Malformed block record");
1778
1779 SmallVector<uint64_t, 64> Record;
1780
1781 // Read all the records for this module.
1782 while (!Stream.AtEndOfStream()) {
1783 unsigned Code = Stream.ReadCode();
1784 if (Code == bitc::END_BLOCK) {
1785 if (Stream.ReadBlockEnd())
1786 return Error("Error at end of module block");
1787
1788 return false;
1789 }
1790
1791 if (Code == bitc::ENTER_SUBBLOCK) {
1792 switch (Stream.ReadSubBlockID()) {
1793 default: // Skip unknown content.
1794 if (Stream.SkipBlock())
1795 return Error("Malformed block record");
1796 break;
1797 }
1798 continue;
1799 }
1800
1801 if (Code == bitc::DEFINE_ABBREV) {
1802 Stream.ReadAbbrevRecord();
1803 continue;
1804 }
1805
1806 // Read a record.
1807 switch (Stream.ReadRecord(Code, Record)) {
1808 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00001809 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1810 std::string S;
1811 if (ConvertToString(Record, 0, S))
1812 return Error("Invalid MODULE_CODE_TRIPLE record");
1813 Triple = S;
1814 break;
1815 }
1816 }
1817 Record.clear();
1818 }
1819
1820 return Error("Premature end of bitstream");
1821}
1822
1823bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001824 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001825
1826 // Sniff for the signature.
1827 if (Stream.Read(8) != 'B' ||
1828 Stream.Read(8) != 'C' ||
1829 Stream.Read(4) != 0x0 ||
1830 Stream.Read(4) != 0xC ||
1831 Stream.Read(4) != 0xE ||
1832 Stream.Read(4) != 0xD)
1833 return Error("Invalid bitcode signature");
1834
1835 // We expect a number of well-defined blocks, though we don't necessarily
1836 // need to understand them all.
1837 while (!Stream.AtEndOfStream()) {
1838 unsigned Code = Stream.ReadCode();
1839
1840 if (Code != bitc::ENTER_SUBBLOCK)
1841 return Error("Invalid record at top-level");
1842
1843 unsigned BlockID = Stream.ReadSubBlockID();
1844
1845 // We only know the MODULE subblock ID.
1846 switch (BlockID) {
1847 case bitc::MODULE_BLOCK_ID:
1848 if (ParseModuleTriple(Triple))
1849 return true;
1850 break;
1851 default:
1852 if (Stream.SkipBlock())
1853 return Error("Malformed block record");
1854 break;
1855 }
1856 }
1857
1858 return false;
1859}
1860
Devang Patele8e02132009-09-18 19:26:43 +00001861/// ParseMetadataAttachment - Parse metadata attachments.
1862bool BitcodeReader::ParseMetadataAttachment() {
1863 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1864 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001865
Devang Patele8e02132009-09-18 19:26:43 +00001866 SmallVector<uint64_t, 64> Record;
1867 while(1) {
1868 unsigned Code = Stream.ReadCode();
1869 if (Code == bitc::END_BLOCK) {
1870 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001871 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001872 break;
1873 }
1874 if (Code == bitc::DEFINE_ABBREV) {
1875 Stream.ReadAbbrevRecord();
1876 continue;
1877 }
1878 // Read a metadata attachment record.
1879 Record.clear();
1880 switch (Stream.ReadRecord(Code, Record)) {
1881 default: // Default behavior: ignore.
1882 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001883 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001884 unsigned RecordLength = Record.size();
1885 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001886 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001887 Instruction *Inst = InstructionList[Record[0]];
1888 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001889 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001890 DenseMap<unsigned, unsigned>::iterator I =
1891 MDKindMap.find(Kind);
1892 if (I == MDKindMap.end())
1893 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001895 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001896 }
1897 break;
1898 }
1899 }
1900 }
1901 return false;
1902}
Chris Lattner48f84872007-05-01 04:59:48 +00001903
Chris Lattner980e5aa2007-05-01 05:52:21 +00001904/// ParseFunctionBody - Lazily parse the specified function body block.
1905bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001906 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001907 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001908
Nick Lewycky9a49f152010-02-25 08:30:17 +00001909 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001910 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001911 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912
Chris Lattner980e5aa2007-05-01 05:52:21 +00001913 // Add all the function arguments to the value table.
1914 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1915 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001917 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001918 BasicBlock *CurBB = 0;
1919 unsigned CurBBNo = 0;
1920
Chris Lattnera6245242010-04-03 02:17:50 +00001921 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00001922
Chris Lattner980e5aa2007-05-01 05:52:21 +00001923 // Read all the records.
1924 SmallVector<uint64_t, 64> Record;
1925 while (1) {
1926 unsigned Code = Stream.ReadCode();
1927 if (Code == bitc::END_BLOCK) {
1928 if (Stream.ReadBlockEnd())
1929 return Error("Error at end of function block");
1930 break;
1931 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001932
Chris Lattner980e5aa2007-05-01 05:52:21 +00001933 if (Code == bitc::ENTER_SUBBLOCK) {
1934 switch (Stream.ReadSubBlockID()) {
1935 default: // Skip unknown content.
1936 if (Stream.SkipBlock())
1937 return Error("Malformed block record");
1938 break;
1939 case bitc::CONSTANTS_BLOCK_ID:
1940 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001941 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001942 break;
1943 case bitc::VALUE_SYMTAB_BLOCK_ID:
1944 if (ParseValueSymbolTable()) return true;
1945 break;
Devang Patele8e02132009-09-18 19:26:43 +00001946 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001947 if (ParseMetadataAttachment()) return true;
1948 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001949 case bitc::METADATA_BLOCK_ID:
1950 if (ParseMetadata()) return true;
1951 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001952 }
1953 continue;
1954 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001955
Chris Lattner980e5aa2007-05-01 05:52:21 +00001956 if (Code == bitc::DEFINE_ABBREV) {
1957 Stream.ReadAbbrevRecord();
1958 continue;
1959 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001960
Chris Lattner980e5aa2007-05-01 05:52:21 +00001961 // Read a record.
1962 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001963 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001964 unsigned BitCode = Stream.ReadRecord(Code, Record);
1965 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001966 default: // Default behavior: reject
1967 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001968 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001969 if (Record.size() < 1 || Record[0] == 0)
1970 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001971 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001972 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001973 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001974 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001975 CurBB = FunctionBBs[0];
1976 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001977
Chris Lattnera6245242010-04-03 02:17:50 +00001978 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1979 // This record indicates that the last instruction is at the same
1980 // location as the previous instruction with a location.
1981 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00001982
Chris Lattnera6245242010-04-03 02:17:50 +00001983 // Get the last instruction emitted.
1984 if (CurBB && !CurBB->empty())
1985 I = &CurBB->back();
1986 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1987 !FunctionBBs[CurBBNo-1]->empty())
1988 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00001989
Chris Lattnera6245242010-04-03 02:17:50 +00001990 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1991 I->setDebugLoc(LastLoc);
1992 I = 0;
1993 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001994
Chris Lattner4f6bab92011-06-17 18:17:37 +00001995 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001996 I = 0; // Get the last instruction emitted.
1997 if (CurBB && !CurBB->empty())
1998 I = &CurBB->back();
1999 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2000 !FunctionBBs[CurBBNo-1]->empty())
2001 I = &FunctionBBs[CurBBNo-1]->back();
2002 if (I == 0 || Record.size() < 4)
2003 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002004
Chris Lattnera6245242010-04-03 02:17:50 +00002005 unsigned Line = Record[0], Col = Record[1];
2006 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00002007
Chris Lattnera6245242010-04-03 02:17:50 +00002008 MDNode *Scope = 0, *IA = 0;
2009 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2010 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2011 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2012 I->setDebugLoc(LastLoc);
2013 I = 0;
2014 continue;
2015 }
2016
Chris Lattnerabfbf852007-05-06 00:21:25 +00002017 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2018 unsigned OpNum = 0;
2019 Value *LHS, *RHS;
2020 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002021 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002022 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002023 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002024
Dan Gohman1224c382009-07-20 21:19:07 +00002025 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002026 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002027 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002028 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002029 if (OpNum < Record.size()) {
2030 if (Opc == Instruction::Add ||
2031 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002032 Opc == Instruction::Mul ||
2033 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002034 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002035 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002036 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002037 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002038 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002039 Opc == Instruction::UDiv ||
2040 Opc == Instruction::LShr ||
2041 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002042 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002043 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002044 } else if (isa<FPMathOperator>(I)) {
2045 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002046 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2047 FMF.setUnsafeAlgebra();
2048 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2049 FMF.setNoNaNs();
2050 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2051 FMF.setNoInfs();
2052 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2053 FMF.setNoSignedZeros();
2054 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2055 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002056 if (FMF.any())
2057 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002058 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002059
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002060 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002061 break;
2062 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002063 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2064 unsigned OpNum = 0;
2065 Value *Op;
2066 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2067 OpNum+2 != Record.size())
2068 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002069
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002070 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002071 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2072 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002073 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002074 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002075 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002076 break;
2077 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002078 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002079 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002080 unsigned OpNum = 0;
2081 Value *BasePtr;
2082 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002083 return Error("Invalid GEP record");
2084
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002085 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002086 while (OpNum != Record.size()) {
2087 Value *Op;
2088 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002089 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002090 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002091 }
2092
Jay Foada9203102011-07-25 09:48:08 +00002093 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002094 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002095 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002096 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002097 break;
2098 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002099
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002100 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2101 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002102 unsigned OpNum = 0;
2103 Value *Agg;
2104 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2105 return Error("Invalid EXTRACTVAL record");
2106
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002107 SmallVector<unsigned, 4> EXTRACTVALIdx;
2108 for (unsigned RecSize = Record.size();
2109 OpNum != RecSize; ++OpNum) {
2110 uint64_t Index = Record[OpNum];
2111 if ((unsigned)Index != Index)
2112 return Error("Invalid EXTRACTVAL index");
2113 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002114 }
2115
Jay Foadfc6d3a42011-07-13 10:26:04 +00002116 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002117 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002118 break;
2119 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002120
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002121 case bitc::FUNC_CODE_INST_INSERTVAL: {
2122 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002123 unsigned OpNum = 0;
2124 Value *Agg;
2125 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2126 return Error("Invalid INSERTVAL record");
2127 Value *Val;
2128 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2129 return Error("Invalid INSERTVAL record");
2130
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002131 SmallVector<unsigned, 4> INSERTVALIdx;
2132 for (unsigned RecSize = Record.size();
2133 OpNum != RecSize; ++OpNum) {
2134 uint64_t Index = Record[OpNum];
2135 if ((unsigned)Index != Index)
2136 return Error("Invalid INSERTVAL index");
2137 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002138 }
2139
Jay Foadfc6d3a42011-07-13 10:26:04 +00002140 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002141 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002142 break;
2143 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002144
Chris Lattnerabfbf852007-05-06 00:21:25 +00002145 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002146 // obsolete form of select
2147 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002148 unsigned OpNum = 0;
2149 Value *TrueVal, *FalseVal, *Cond;
2150 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002151 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2152 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002153 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002154
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002155 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002156 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002157 break;
2158 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002159
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002160 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2161 // new form of select
2162 // handles select i1 or select [N x i1]
2163 unsigned OpNum = 0;
2164 Value *TrueVal, *FalseVal, *Cond;
2165 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002166 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002167 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2168 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002169
2170 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002171 if (VectorType* vector_type =
2172 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002173 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002174 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002175 return Error("Invalid SELECT condition type");
2176 } else {
2177 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002178 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002179 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002180 }
2181
Gabor Greif051a9502008-04-06 20:25:17 +00002182 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002183 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002184 break;
2185 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002186
Chris Lattner01ff65f2007-05-02 05:16:49 +00002187 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002188 unsigned OpNum = 0;
2189 Value *Vec, *Idx;
2190 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002191 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002192 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002193 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002194 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002195 break;
2196 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002197
Chris Lattner01ff65f2007-05-02 05:16:49 +00002198 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002199 unsigned OpNum = 0;
2200 Value *Vec, *Elt, *Idx;
2201 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002202 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002203 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002204 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002205 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002206 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002207 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002208 break;
2209 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002210
Chris Lattnerabfbf852007-05-06 00:21:25 +00002211 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2212 unsigned OpNum = 0;
2213 Value *Vec1, *Vec2, *Mask;
2214 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002215 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002216 return Error("Invalid SHUFFLEVEC record");
2217
Mon P Wangaeb06d22008-11-10 04:46:22 +00002218 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002219 return Error("Invalid SHUFFLEVEC record");
2220 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002221 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002222 break;
2223 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002224
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002225 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2226 // Old form of ICmp/FCmp returning bool
2227 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2228 // both legal on vectors but had different behaviour.
2229 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2230 // FCmp/ICmp returning bool or vector of bool
2231
Chris Lattner7337ab92007-05-06 00:00:00 +00002232 unsigned OpNum = 0;
2233 Value *LHS, *RHS;
2234 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002235 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002236 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002237 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002238
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002239 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002240 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002241 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002242 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002243 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002244 break;
2245 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002246
Chris Lattner231cbcb2007-05-02 04:27:25 +00002247 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002248 {
2249 unsigned Size = Record.size();
2250 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002251 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002252 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002253 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002254 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002255
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002256 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002257 Value *Op = NULL;
2258 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2259 return Error("Invalid RET record");
2260 if (OpNum != Record.size())
2261 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002262
Chris Lattner96a74c52011-06-17 18:09:11 +00002263 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002264 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002265 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002266 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002267 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002268 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002269 return Error("Invalid BR record");
2270 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2271 if (TrueDest == 0)
2272 return Error("Invalid BR record");
2273
Devang Patele8e02132009-09-18 19:26:43 +00002274 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002275 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002276 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002277 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002278 else {
2279 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002280 Value *Cond = getValue(Record, 2, NextValueNo,
2281 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002282 if (FalseDest == 0 || Cond == 0)
2283 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002284 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002285 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002286 }
2287 break;
2288 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002289 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002290 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002291 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2292 // New SwitchInst format with case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002293
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002294 Type *OpTy = getTypeByID(Record[1]);
2295 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2296
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002297 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002298 BasicBlock *Default = getBasicBlock(Record[3]);
2299 if (OpTy == 0 || Cond == 0 || Default == 0)
2300 return Error("Invalid SWITCH record");
2301
2302 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002303
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002304 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2305 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002306
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002307 unsigned CurIdx = 5;
2308 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002309 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002310 unsigned NumItems = Record[CurIdx++];
2311 for (unsigned ci = 0; ci != NumItems; ++ci) {
2312 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002313
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002314 APInt Low;
2315 unsigned ActiveWords = 1;
2316 if (ValueBitWidth > 64)
2317 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002318 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2319 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002320 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002321
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002322 if (!isSingleNumber) {
2323 ActiveWords = 1;
2324 if (ValueBitWidth > 64)
2325 ActiveWords = Record[CurIdx++];
2326 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002327 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2328 ValueBitWidth);
Michael Ilseman407a6162012-11-15 22:34:00 +00002329
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002330 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2331 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002332 CurIdx += ActiveWords;
2333 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002334 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002335 }
2336 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Michael Ilseman407a6162012-11-15 22:34:00 +00002337 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002338 SI->addCase(Case, DestBB);
2339 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002340 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002341 if (Hash != (Record[0] & 0xFFFF))
2342 return Error("Invalid SWITCH record");
2343 I = SI;
2344 break;
2345 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002346
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002347 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002348
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002349 if (Record.size() < 3 || (Record.size() & 1) == 0)
2350 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002351 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002352 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002353 BasicBlock *Default = getBasicBlock(Record[2]);
2354 if (OpTy == 0 || Cond == 0 || Default == 0)
2355 return Error("Invalid SWITCH record");
2356 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002357 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002358 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002359 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002360 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002361 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2362 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2363 if (CaseVal == 0 || DestBB == 0) {
2364 delete SI;
2365 return Error("Invalid SWITCH record!");
2366 }
2367 SI->addCase(CaseVal, DestBB);
2368 }
2369 I = SI;
2370 break;
2371 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002372 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002373 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002374 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002375 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002376 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002377 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002378 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002379 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002380 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002381 InstructionList.push_back(IBI);
2382 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2383 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2384 IBI->addDestination(DestBB);
2385 } else {
2386 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002387 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002388 }
2389 }
2390 I = IBI;
2391 break;
2392 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002393
Duncan Sandsdc024672007-11-27 13:23:08 +00002394 case bitc::FUNC_CODE_INST_INVOKE: {
2395 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002396 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002397 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002398 unsigned CCInfo = Record[1];
2399 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2400 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002401
Chris Lattnera9bb7132007-05-08 05:38:01 +00002402 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002403 Value *Callee;
2404 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002405 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002406
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002407 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2408 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002409 dyn_cast<FunctionType>(CalleeTy->getElementType());
2410
2411 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002412 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2413 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002414 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002415
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002416 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002417 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002418 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2419 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002420 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002421 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002422
Chris Lattner7337ab92007-05-06 00:00:00 +00002423 if (!FTy->isVarArg()) {
2424 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002425 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002426 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002427 // Read type/value pairs for varargs params.
2428 while (OpNum != Record.size()) {
2429 Value *Op;
2430 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2431 return Error("Invalid INVOKE record");
2432 Ops.push_back(Op);
2433 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002434 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002435
Jay Foada3efbb12011-07-15 08:37:34 +00002436 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002437 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002438 cast<InvokeInst>(I)->setCallingConv(
2439 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002440 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002441 break;
2442 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002443 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2444 unsigned Idx = 0;
2445 Value *Val = 0;
2446 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2447 return Error("Invalid RESUME record");
2448 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002449 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002450 break;
2451 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002452 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002453 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002454 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002455 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002456 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002457 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002458 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002459 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002460 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002461
Jay Foad3ecfc862011-03-30 11:28:46 +00002462 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002463 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002464
Chris Lattner15e6d172007-05-04 19:11:41 +00002465 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002466 Value *V;
2467 // With the new function encoding, it is possible that operands have
2468 // negative IDs (for forward references). Use a signed VBR
2469 // representation to keep the encoding small.
2470 if (UseRelativeIDs)
2471 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2472 else
2473 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002474 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002475 if (!V || !BB) return Error("Invalid PHI record");
2476 PN->addIncoming(V, BB);
2477 }
2478 I = PN;
2479 break;
2480 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002481
Bill Wendlinge6e88262011-08-12 20:24:12 +00002482 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2483 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2484 unsigned Idx = 0;
2485 if (Record.size() < 4)
2486 return Error("Invalid LANDINGPAD record");
2487 Type *Ty = getTypeByID(Record[Idx++]);
2488 if (!Ty) return Error("Invalid LANDINGPAD record");
2489 Value *PersFn = 0;
2490 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2491 return Error("Invalid LANDINGPAD record");
2492
2493 bool IsCleanup = !!Record[Idx++];
2494 unsigned NumClauses = Record[Idx++];
2495 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2496 LP->setCleanup(IsCleanup);
2497 for (unsigned J = 0; J != NumClauses; ++J) {
2498 LandingPadInst::ClauseType CT =
2499 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2500 Value *Val;
2501
2502 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2503 delete LP;
2504 return Error("Invalid LANDINGPAD record");
2505 }
2506
2507 assert((CT != LandingPadInst::Catch ||
2508 !isa<ArrayType>(Val->getType())) &&
2509 "Catch clause has a invalid type!");
2510 assert((CT != LandingPadInst::Filter ||
2511 isa<ArrayType>(Val->getType())) &&
2512 "Filter clause has invalid type!");
2513 LP->addClause(Val);
2514 }
2515
2516 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002517 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002518 break;
2519 }
2520
Chris Lattner96a74c52011-06-17 18:09:11 +00002521 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2522 if (Record.size() != 4)
2523 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002524 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002525 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002526 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002527 Value *Size = getFnValueByID(Record[2], OpTy);
2528 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002529 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002530 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002531 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002532 break;
2533 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002534 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002535 unsigned OpNum = 0;
2536 Value *Op;
2537 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2538 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002539 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002540
Chris Lattner7337ab92007-05-06 00:00:00 +00002541 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002542 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002543 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002544 }
Eli Friedman21006d42011-08-09 23:02:53 +00002545 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2546 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2547 unsigned OpNum = 0;
2548 Value *Op;
2549 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2550 OpNum+4 != Record.size())
2551 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002552
Eli Friedman21006d42011-08-09 23:02:53 +00002553
2554 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2555 if (Ordering == NotAtomic || Ordering == Release ||
2556 Ordering == AcquireRelease)
2557 return Error("Invalid LOADATOMIC record");
2558 if (Ordering != NotAtomic && Record[OpNum] == 0)
2559 return Error("Invalid LOADATOMIC record");
2560 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2561
2562 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2563 Ordering, SynchScope);
2564 InstructionList.push_back(I);
2565 break;
2566 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002567 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002568 unsigned OpNum = 0;
2569 Value *Val, *Ptr;
2570 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002571 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002572 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2573 OpNum+2 != Record.size())
2574 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002575
Christopher Lambfe63fb92007-12-11 08:59:05 +00002576 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002577 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002578 break;
2579 }
Eli Friedman21006d42011-08-09 23:02:53 +00002580 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2581 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2582 unsigned OpNum = 0;
2583 Value *Val, *Ptr;
2584 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002585 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002586 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2587 OpNum+4 != Record.size())
2588 return Error("Invalid STOREATOMIC record");
2589
2590 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002591 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002592 Ordering == AcquireRelease)
2593 return Error("Invalid STOREATOMIC record");
2594 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2595 if (Ordering != NotAtomic && Record[OpNum] == 0)
2596 return Error("Invalid STOREATOMIC record");
2597
2598 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2599 Ordering, SynchScope);
2600 InstructionList.push_back(I);
2601 break;
2602 }
Eli Friedmanff030482011-07-28 21:48:00 +00002603 case bitc::FUNC_CODE_INST_CMPXCHG: {
2604 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2605 unsigned OpNum = 0;
2606 Value *Ptr, *Cmp, *New;
2607 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002608 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002609 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002610 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002611 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2612 OpNum+3 != Record.size())
2613 return Error("Invalid CMPXCHG record");
2614 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002615 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002616 return Error("Invalid CMPXCHG record");
2617 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2618 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2619 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2620 InstructionList.push_back(I);
2621 break;
2622 }
2623 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2624 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2625 unsigned OpNum = 0;
2626 Value *Ptr, *Val;
2627 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002628 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002629 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2630 OpNum+4 != Record.size())
2631 return Error("Invalid ATOMICRMW record");
2632 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2633 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2634 Operation > AtomicRMWInst::LAST_BINOP)
2635 return Error("Invalid ATOMICRMW record");
2636 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002637 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002638 return Error("Invalid ATOMICRMW record");
2639 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2640 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2641 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2642 InstructionList.push_back(I);
2643 break;
2644 }
Eli Friedman47f35132011-07-25 23:16:38 +00002645 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2646 if (2 != Record.size())
2647 return Error("Invalid FENCE record");
2648 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2649 if (Ordering == NotAtomic || Ordering == Unordered ||
2650 Ordering == Monotonic)
2651 return Error("Invalid FENCE record");
2652 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2653 I = new FenceInst(Context, Ordering, SynchScope);
2654 InstructionList.push_back(I);
2655 break;
2656 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002657 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002658 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2659 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002660 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002661
Bill Wendling99faa3b2012-12-07 23:16:57 +00002662 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002663 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002664
Chris Lattnera9bb7132007-05-08 05:38:01 +00002665 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002666 Value *Callee;
2667 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2668 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002669
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002670 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2671 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002672 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002673 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002674 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002675
Chris Lattner0579f7f2007-05-03 22:04:19 +00002676 SmallVector<Value*, 16> Args;
2677 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002678 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002679 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002680 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002681 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002682 Args.push_back(getValue(Record, OpNum, NextValueNo,
2683 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002684 if (Args.back() == 0) return Error("Invalid CALL record");
2685 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002686
Chris Lattner0579f7f2007-05-03 22:04:19 +00002687 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002688 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002689 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002690 return Error("Invalid CALL record");
2691 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002692 while (OpNum != Record.size()) {
2693 Value *Op;
2694 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2695 return Error("Invalid CALL record");
2696 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002697 }
2698 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002699
Jay Foada3efbb12011-07-15 08:37:34 +00002700 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002701 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002702 cast<CallInst>(I)->setCallingConv(
2703 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002704 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002705 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002706 break;
2707 }
2708 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2709 if (Record.size() < 3)
2710 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002711 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002712 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002713 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002714 if (!OpTy || !Op || !ResTy)
2715 return Error("Invalid VAARG record");
2716 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002717 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002718 break;
2719 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002720 }
2721
2722 // Add instruction to end of current BB. If there is no current BB, reject
2723 // this file.
2724 if (CurBB == 0) {
2725 delete I;
2726 return Error("Invalid instruction with no BB");
2727 }
2728 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002729
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002730 // If this was a terminator instruction, move to the next block.
2731 if (isa<TerminatorInst>(I)) {
2732 ++CurBBNo;
2733 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2734 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002735
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002736 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002737 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002738 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002739 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002740
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002741 // Check the function list for unresolved values.
2742 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2743 if (A->getParent() == 0) {
2744 // We found at least one unresolved value. Nuke them all to avoid leaks.
2745 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002746 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002747 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002748 delete A;
2749 }
2750 }
Chris Lattner35a04702007-05-04 03:50:29 +00002751 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002752 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002753 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002754
Dan Gohman064ff3e2010-08-25 20:23:38 +00002755 // FIXME: Check for unresolved forward-declared metadata references
2756 // and clean up leaks.
2757
Chris Lattner50b136d2009-10-28 05:53:48 +00002758 // See if anything took the address of blocks in this function. If so,
2759 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002760 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2761 BlockAddrFwdRefs.find(F);
2762 if (BAFRI != BlockAddrFwdRefs.end()) {
2763 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2764 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2765 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002766 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002767 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00002768
Chris Lattner50b136d2009-10-28 05:53:48 +00002769 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002770 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002771 FwdRef->eraseFromParent();
2772 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002773
Chris Lattner50b136d2009-10-28 05:53:48 +00002774 BlockAddrFwdRefs.erase(BAFRI);
2775 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002776
Chris Lattner980e5aa2007-05-01 05:52:21 +00002777 // Trim the value list down to the size it was before we parsed this function.
2778 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002779 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002780 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002781 return false;
2782}
2783
Derek Schuff2ea93872012-02-06 22:30:29 +00002784/// FindFunctionInStream - Find the function body in the bitcode stream
2785bool BitcodeReader::FindFunctionInStream(Function *F,
2786 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2787 while (DeferredFunctionInfoIterator->second == 0) {
2788 if (Stream.AtEndOfStream())
2789 return Error("Could not find Function in stream");
2790 // ParseModule will parse the next body in the stream and set its
2791 // position in the DeferredFunctionInfo map.
2792 if (ParseModule(true)) return true;
2793 }
2794 return false;
2795}
2796
Chris Lattnerb348bb82007-05-18 04:02:46 +00002797//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002798// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002799//===----------------------------------------------------------------------===//
2800
2801
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002802bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2803 if (const Function *F = dyn_cast<Function>(GV)) {
2804 return F->isDeclaration() &&
2805 DeferredFunctionInfo.count(const_cast<Function*>(F));
2806 }
2807 return false;
2808}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002809
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002810bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2811 Function *F = dyn_cast<Function>(GV);
2812 // If it's not a function or is already material, ignore the request.
2813 if (!F || !F->isMaterializable()) return false;
2814
2815 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002816 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002817 // If its position is recorded as 0, its body is somewhere in the stream
2818 // but we haven't seen it yet.
2819 if (DFII->second == 0)
2820 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002821
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002822 // Move the bit stream to the saved position of the deferred function body.
2823 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002824
Chris Lattnerb348bb82007-05-18 04:02:46 +00002825 if (ParseFunctionBody(F)) {
2826 if (ErrInfo) *ErrInfo = ErrorString;
2827 return true;
2828 }
Chandler Carruth69940402007-08-04 01:51:18 +00002829
2830 // Upgrade any old intrinsic calls in the function.
2831 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2832 E = UpgradedIntrinsics.end(); I != E; ++I) {
2833 if (I->first != I->second) {
2834 for (Value::use_iterator UI = I->first->use_begin(),
2835 UE = I->first->use_end(); UI != UE; ) {
2836 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2837 UpgradeIntrinsicCall(CI, I->second);
2838 }
2839 }
2840 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002841
Chris Lattnerb348bb82007-05-18 04:02:46 +00002842 return false;
2843}
2844
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002845bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2846 const Function *F = dyn_cast<Function>(GV);
2847 if (!F || F->isDeclaration())
2848 return false;
2849 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2850}
2851
2852void BitcodeReader::Dematerialize(GlobalValue *GV) {
2853 Function *F = dyn_cast<Function>(GV);
2854 // If this function isn't dematerializable, this is a noop.
2855 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002856 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002857
Chris Lattnerb348bb82007-05-18 04:02:46 +00002858 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002859
Chris Lattnerb348bb82007-05-18 04:02:46 +00002860 // Just forget the function body, we can remat it later.
2861 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002862}
2863
2864
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002865bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2866 assert(M == TheModule &&
2867 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002868 // Iterate over the module, deserializing any functions that are still on
2869 // disk.
2870 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2871 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002872 if (F->isMaterializable() &&
2873 Materialize(F, ErrInfo))
2874 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002875
Derek Schuff0ffe6982012-02-29 00:07:09 +00002876 // At this point, if there are any function bodies, the current bit is
2877 // pointing to the END_BLOCK record after them. Now make sure the rest
2878 // of the bits in the module have been read.
2879 if (NextUnreadBit)
2880 ParseModule(true);
2881
Daniel Dunbara279bc32009-09-20 02:20:51 +00002882 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2883 // delete the old functions to clean up. We can't do this unless the entire
2884 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002885 // with calls to the old function.
2886 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2887 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2888 if (I->first != I->second) {
2889 for (Value::use_iterator UI = I->first->use_begin(),
2890 UE = I->first->use_end(); UI != UE; ) {
2891 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2892 UpgradeIntrinsicCall(CI, I->second);
2893 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002894 if (!I->first->use_empty())
2895 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002896 I->first->eraseFromParent();
2897 }
2898 }
2899 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002900
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002901 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002902}
2903
Derek Schuff2ea93872012-02-06 22:30:29 +00002904bool BitcodeReader::InitStream() {
2905 if (LazyStreamer) return InitLazyStream();
2906 return InitStreamFromBuffer();
2907}
2908
2909bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00002910 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00002911 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2912
2913 if (Buffer->getBufferSize() & 3) {
2914 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2915 return Error("Invalid bitcode signature");
2916 else
2917 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2918 }
2919
2920 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2921 // The magic number is 0x0B17C0DE stored in little endian.
2922 if (isBitcodeWrapper(BufPtr, BufEnd))
2923 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2924 return Error("Invalid bitcode wrapper header");
2925
2926 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2927 Stream.init(*StreamFile);
2928
2929 return false;
2930}
2931
2932bool BitcodeReader::InitLazyStream() {
2933 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2934 // see it.
2935 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2936 StreamFile.reset(new BitstreamReader(Bytes));
2937 Stream.init(*StreamFile);
2938
2939 unsigned char buf[16];
2940 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2941 return Error("Bitcode stream must be at least 16 bytes in length");
2942
2943 if (!isBitcode(buf, buf + 16))
2944 return Error("Invalid bitcode signature");
2945
2946 if (isBitcodeWrapper(buf, buf + 4)) {
2947 const unsigned char *bitcodeStart = buf;
2948 const unsigned char *bitcodeEnd = buf + 16;
2949 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2950 Bytes->dropLeadingBytes(bitcodeStart - buf);
2951 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2952 }
2953 return false;
2954}
Chris Lattner48f84872007-05-01 04:59:48 +00002955
Chris Lattnerc453f762007-04-29 07:54:31 +00002956//===----------------------------------------------------------------------===//
2957// External interface
2958//===----------------------------------------------------------------------===//
2959
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002960/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002961///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002962Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2963 LLVMContext& Context,
2964 std::string *ErrMsg) {
2965 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002966 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002967 M->setMaterializer(R);
2968 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002969 if (ErrMsg)
2970 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002971
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002972 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002973 return 0;
2974 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002975 // Have the BitcodeReader dtor delete 'Buffer'.
2976 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002977
2978 R->materializeForwardReferencedFunctions();
2979
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002980 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002981}
2982
Derek Schuff2ea93872012-02-06 22:30:29 +00002983
2984Module *llvm::getStreamedBitcodeModule(const std::string &name,
2985 DataStreamer *streamer,
2986 LLVMContext &Context,
2987 std::string *ErrMsg) {
2988 Module *M = new Module(name, Context);
2989 BitcodeReader *R = new BitcodeReader(streamer, Context);
2990 M->setMaterializer(R);
2991 if (R->ParseBitcodeInto(M)) {
2992 if (ErrMsg)
2993 *ErrMsg = R->getErrorString();
2994 delete M; // Also deletes R.
2995 return 0;
2996 }
2997 R->setBufferOwned(false); // no buffer to delete
2998 return M;
2999}
3000
Chris Lattnerc453f762007-04-29 07:54:31 +00003001/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3002/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003003Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00003004 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003005 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3006 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003007
3008 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3009 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003010 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003011
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003012 // Read in the entire module, and destroy the BitcodeReader.
3013 if (M->MaterializeAllPermanently(ErrMsg)) {
3014 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003015 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003016 }
Bill Wendling34711742010-10-06 01:22:42 +00003017
Chad Rosiercbbb0962011-12-07 21:44:12 +00003018 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3019 // written. We must defer until the Module has been fully materialized.
3020
Chris Lattnerc453f762007-04-29 07:54:31 +00003021 return M;
3022}
Bill Wendling34711742010-10-06 01:22:42 +00003023
3024std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3025 LLVMContext& Context,
3026 std::string *ErrMsg) {
3027 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3028 // Don't let the BitcodeReader dtor delete 'Buffer'.
3029 R->setBufferOwned(false);
3030
3031 std::string Triple("");
3032 if (R->ParseTriple(Triple))
3033 if (ErrMsg)
3034 *ErrMsg = R->getErrorString();
3035
3036 delete R;
3037 return Triple;
3038}