blob: 3ac6e038fda865c406889f019d791d375e2fab39 [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"
Tobias Grossere7bc5bb2013-07-26 04:16:55 +000015#include "llvm/Bitcode/LLVMBitCodes.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000016#include "llvm/IR/Constants.h"
17#include "llvm/IR/DerivedTypes.h"
18#include "llvm/IR/InlineAsm.h"
19#include "llvm/IR/IntrinsicInst.h"
20#include "llvm/IR/Module.h"
21#include "llvm/IR/OperandTraits.h"
22#include "llvm/IR/Operator.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000023#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000025#include "llvm/Support/MemoryBuffer.h"
Tobias Grossere7bc5bb2013-07-26 04:16:55 +000026#include "llvm/Support/raw_ostream.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000027using namespace llvm;
28
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000029enum {
30 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
31};
32
Rafael Espindola47f79bb2012-01-02 07:49:53 +000033void BitcodeReader::materializeForwardReferencedFunctions() {
34 while (!BlockAddrFwdRefs.empty()) {
35 Function *F = BlockAddrFwdRefs.begin()->first;
36 F->Materialize();
37 }
38}
39
Chris Lattnerb348bb82007-05-18 04:02:46 +000040void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000041 if (BufferOwned)
42 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000043 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000044 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000045 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000046 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000047
Bill Wendling99faa3b2012-12-07 23:16:57 +000048 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000049 std::vector<BasicBlock*>().swap(FunctionBBs);
50 std::vector<Function*>().swap(FunctionsWithBodies);
51 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000052 MDKindMap.clear();
Benjamin Kramer122f5e52012-09-21 14:34:31 +000053
54 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
Chris Lattnerc453f762007-04-29 07:54:31 +000055}
56
Chris Lattner48c85b82007-05-04 03:30:17 +000057//===----------------------------------------------------------------------===//
58// Helper functions to implement forward reference resolution, etc.
59//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000060
Chris Lattnercaee0dc2007-04-22 06:23:29 +000061/// ConvertToString - Convert a string from a record into an std::string, return
62/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000063template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000064static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000065 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000066 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000067 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000068
Chris Lattner15e6d172007-05-04 19:11:41 +000069 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
70 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000071 return false;
72}
73
74static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
75 switch (Val) {
76 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000077 case 0: return GlobalValue::ExternalLinkage;
78 case 1: return GlobalValue::WeakAnyLinkage;
79 case 2: return GlobalValue::AppendingLinkage;
80 case 3: return GlobalValue::InternalLinkage;
81 case 4: return GlobalValue::LinkOnceAnyLinkage;
82 case 5: return GlobalValue::DLLImportLinkage;
83 case 6: return GlobalValue::DLLExportLinkage;
84 case 7: return GlobalValue::ExternalWeakLinkage;
85 case 8: return GlobalValue::CommonLinkage;
86 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000087 case 10: return GlobalValue::WeakODRLinkage;
88 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000089 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000090 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000091 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000092 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000093 }
94}
95
96static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
97 switch (Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000101 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000102 }
103}
104
Hans Wennborgce718ff2012-06-23 11:37:03 +0000105static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
106 switch (Val) {
107 case 0: return GlobalVariable::NotThreadLocal;
108 default: // Map unknown non-zero value to general dynamic.
109 case 1: return GlobalVariable::GeneralDynamicTLSModel;
110 case 2: return GlobalVariable::LocalDynamicTLSModel;
111 case 3: return GlobalVariable::InitialExecTLSModel;
112 case 4: return GlobalVariable::LocalExecTLSModel;
113 }
114}
115
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000116static int GetDecodedCastOpcode(unsigned Val) {
117 switch (Val) {
118 default: return -1;
119 case bitc::CAST_TRUNC : return Instruction::Trunc;
120 case bitc::CAST_ZEXT : return Instruction::ZExt;
121 case bitc::CAST_SEXT : return Instruction::SExt;
122 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
123 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
124 case bitc::CAST_UITOFP : return Instruction::UIToFP;
125 case bitc::CAST_SITOFP : return Instruction::SIToFP;
126 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
127 case bitc::CAST_FPEXT : return Instruction::FPExt;
128 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
129 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
130 case bitc::CAST_BITCAST : return Instruction::BitCast;
131 }
132}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000133static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000134 switch (Val) {
135 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000136 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000137 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000138 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000139 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000140 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000141 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000142 case bitc::BINOP_UDIV: return Instruction::UDiv;
143 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000144 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000145 case bitc::BINOP_UREM: return Instruction::URem;
146 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000147 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000148 case bitc::BINOP_SHL: return Instruction::Shl;
149 case bitc::BINOP_LSHR: return Instruction::LShr;
150 case bitc::BINOP_ASHR: return Instruction::AShr;
151 case bitc::BINOP_AND: return Instruction::And;
152 case bitc::BINOP_OR: return Instruction::Or;
153 case bitc::BINOP_XOR: return Instruction::Xor;
154 }
155}
156
Eli Friedmanff030482011-07-28 21:48:00 +0000157static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
158 switch (Val) {
159 default: return AtomicRMWInst::BAD_BINOP;
160 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
161 case bitc::RMW_ADD: return AtomicRMWInst::Add;
162 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
163 case bitc::RMW_AND: return AtomicRMWInst::And;
164 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
165 case bitc::RMW_OR: return AtomicRMWInst::Or;
166 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
167 case bitc::RMW_MAX: return AtomicRMWInst::Max;
168 case bitc::RMW_MIN: return AtomicRMWInst::Min;
169 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
170 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
171 }
172}
173
Eli Friedman47f35132011-07-25 23:16:38 +0000174static AtomicOrdering GetDecodedOrdering(unsigned Val) {
175 switch (Val) {
176 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
177 case bitc::ORDERING_UNORDERED: return Unordered;
178 case bitc::ORDERING_MONOTONIC: return Monotonic;
179 case bitc::ORDERING_ACQUIRE: return Acquire;
180 case bitc::ORDERING_RELEASE: return Release;
181 case bitc::ORDERING_ACQREL: return AcquireRelease;
182 default: // Map unknown orderings to sequentially-consistent.
183 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
184 }
185}
186
187static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
188 switch (Val) {
189 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
190 default: // Map unknown scopes to cross-thread.
191 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
192 }
193}
194
Gabor Greifefe65362008-05-10 08:32:32 +0000195namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000196namespace {
197 /// @brief A class for maintaining the slot number definition
198 /// as a placeholder for the actual definition for forward constants defs.
199 class ConstantPlaceHolder : public ConstantExpr {
Craig Topper86a1c322012-09-15 17:09:36 +0000200 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greif051a9502008-04-06 20:25:17 +0000201 public:
202 // allocate space for exactly one operand
203 void *operator new(size_t s) {
204 return User::operator new(s, 1);
205 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000206 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000207 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000208 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000209 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000210
Chris Lattnerea693df2008-08-21 02:34:16 +0000211 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattnerea693df2008-08-21 02:34:16 +0000212 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000213 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000214 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
215 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000216
217
Gabor Greifefe65362008-05-10 08:32:32 +0000218 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000219 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000220 };
221}
222
Chris Lattner46e77402009-03-31 22:55:09 +0000223// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000224template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000225struct OperandTraits<ConstantPlaceHolder> :
226 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000227};
Gabor Greifefe65362008-05-10 08:32:32 +0000228}
229
Chris Lattner46e77402009-03-31 22:55:09 +0000230
231void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
232 if (Idx == size()) {
233 push_back(V);
234 return;
235 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000236
Chris Lattner46e77402009-03-31 22:55:09 +0000237 if (Idx >= size())
238 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000239
Chris Lattner46e77402009-03-31 22:55:09 +0000240 WeakVH &OldV = ValuePtrs[Idx];
241 if (OldV == 0) {
242 OldV = V;
243 return;
244 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000245
Chris Lattner46e77402009-03-31 22:55:09 +0000246 // Handle constants and non-constants (e.g. instrs) differently for
247 // efficiency.
248 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
249 ResolveConstants.push_back(std::make_pair(PHC, Idx));
250 OldV = V;
251 } else {
252 // If there was a forward reference to this value, replace it.
253 Value *PrevVal = OldV;
254 OldV->replaceAllUsesWith(V);
255 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000256 }
257}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000258
Gabor Greifefe65362008-05-10 08:32:32 +0000259
Chris Lattner522b7b12007-04-24 05:48:56 +0000260Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000261 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000262 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000263 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000264
Chris Lattner46e77402009-03-31 22:55:09 +0000265 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000266 assert(Ty == V->getType() && "Type mismatch in constant table!");
267 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000268 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000269
270 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000271 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000272 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000273 return C;
274}
275
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000276Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000277 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000278 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000279
Chris Lattner46e77402009-03-31 22:55:09 +0000280 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000281 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
282 return V;
283 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000284
Chris Lattner01ff65f2007-05-02 05:16:49 +0000285 // No type specified, must be invalid reference.
286 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000287
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000288 // Create and return a placeholder, which will later be RAUW'd.
289 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000290 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000291 return V;
292}
293
Chris Lattnerea693df2008-08-21 02:34:16 +0000294/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
295/// resolves any forward references. The idea behind this is that we sometimes
296/// get constants (such as large arrays) which reference *many* forward ref
297/// constants. Replacing each of these causes a lot of thrashing when
298/// building/reuniquing the constant. Instead of doing this, we look at all the
299/// uses and rewrite all the place holders at once for any constant that uses
300/// a placeholder.
301void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000302 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000303 // binary search.
304 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000307
Chris Lattnerea693df2008-08-21 02:34:16 +0000308 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000309 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000310 Constant *Placeholder = ResolveConstants.back().first;
311 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000312
Chris Lattnerea693df2008-08-21 02:34:16 +0000313 // Loop over all users of the placeholder, updating them to reference the
314 // new value. If they reference more than one placeholder, update them all
315 // at once.
316 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000317 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000318 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000319
Chris Lattnerea693df2008-08-21 02:34:16 +0000320 // If the using object isn't uniqued, just update the operands. This
321 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000322 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000323 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000324 continue;
325 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000326
Chris Lattnerea693df2008-08-21 02:34:16 +0000327 // Otherwise, we have a constant that uses the placeholder. Replace that
328 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000329 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000330 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
331 I != E; ++I) {
332 Value *NewOp;
333 if (!isa<ConstantPlaceHolder>(*I)) {
334 // Not a placeholder reference.
335 NewOp = *I;
336 } else if (*I == Placeholder) {
337 // Common case is that it just references this one placeholder.
338 NewOp = RealVal;
339 } else {
340 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000341 ResolveConstantsTy::iterator It =
342 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000343 std::pair<Constant*, unsigned>(cast<Constant>(*I),
344 0));
345 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000346 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000347 }
348
349 NewOps.push_back(cast<Constant>(NewOp));
350 }
351
352 // Make the new constant.
353 Constant *NewC;
354 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000355 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000356 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000357 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000358 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000359 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000360 } else {
361 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000362 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000363 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000364
Chris Lattnerea693df2008-08-21 02:34:16 +0000365 UserC->replaceAllUsesWith(NewC);
366 UserC->destroyConstant();
367 NewOps.clear();
368 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000369
Nick Lewyckycb337992009-05-10 20:57:05 +0000370 // Update all ValueHandles, they should be the only users at this point.
371 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000372 delete Placeholder;
373 }
374}
375
Devang Pateld5ac4042009-08-04 06:00:18 +0000376void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
377 if (Idx == size()) {
378 push_back(V);
379 return;
380 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000381
Devang Pateld5ac4042009-08-04 06:00:18 +0000382 if (Idx >= size())
383 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000384
Devang Pateld5ac4042009-08-04 06:00:18 +0000385 WeakVH &OldV = MDValuePtrs[Idx];
386 if (OldV == 0) {
387 OldV = V;
388 return;
389 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000390
Devang Pateld5ac4042009-08-04 06:00:18 +0000391 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000392 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000393 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000394 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000395 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
396 // value for Idx.
397 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000398}
399
400Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
401 if (Idx >= size())
402 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000403
Devang Pateld5ac4042009-08-04 06:00:18 +0000404 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000405 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000406 return V;
407 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000408
Devang Pateld5ac4042009-08-04 06:00:18 +0000409 // Create and return a placeholder, which will later be RAUW'd.
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000410 Value *V = MDNode::getTemporary(Context, None);
Devang Pateld5ac4042009-08-04 06:00:18 +0000411 MDValuePtrs[Idx] = V;
412 return V;
413}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000414
Chris Lattner1afcace2011-07-09 17:41:24 +0000415Type *BitcodeReader::getTypeByID(unsigned ID) {
416 // The type table size is always specified correctly.
417 if (ID >= TypeList.size())
418 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000419
Chris Lattner1afcace2011-07-09 17:41:24 +0000420 if (Type *Ty = TypeList[ID])
421 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000422
Chris Lattner1afcace2011-07-09 17:41:24 +0000423 // If we have a forward reference, the only possible case is when it is to a
424 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000425 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000426}
427
Chris Lattner1afcace2011-07-09 17:41:24 +0000428
Chris Lattner48c85b82007-05-04 03:30:17 +0000429//===----------------------------------------------------------------------===//
430// Functions for parsing blocks from the bitcode file
431//===----------------------------------------------------------------------===//
432
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000433
434/// \brief This fills an AttrBuilder object with the LLVM attributes that have
435/// been decoded from the given integer. This function must stay in sync with
436/// 'encodeLLVMAttributesForBitcode'.
437static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
438 uint64_t EncodedAttrs) {
439 // FIXME: Remove in 4.0.
440
441 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
442 // the bits above 31 down by 11 bits.
443 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
444 assert((!Alignment || isPowerOf2_32(Alignment)) &&
445 "Alignment must be a power of two.");
446
447 if (Alignment)
448 B.addAlignmentAttr(Alignment);
Kostya Serebryanyab39afa2013-02-11 08:13:54 +0000449 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000450 (EncodedAttrs & 0xffff));
451}
452
Devang Patel05988662008-09-25 21:00:45 +0000453bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000454 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000455 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000456
Devang Patel19c87462008-09-26 22:53:05 +0000457 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000458 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000459
Chris Lattner48c85b82007-05-04 03:30:17 +0000460 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000461
Bill Wendling0c2f0ff2013-01-27 00:36:48 +0000462 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000463
Chris Lattner48c85b82007-05-04 03:30:17 +0000464 // Read all the records.
465 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000466 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000467
Chris Lattner5a4251c2013-01-20 02:13:19 +0000468 switch (Entry.Kind) {
469 case BitstreamEntry::SubBlock: // Handled for us already.
470 case BitstreamEntry::Error:
471 return Error("Error at end of PARAMATTR block");
472 case BitstreamEntry::EndBlock:
Chris Lattner48c85b82007-05-04 03:30:17 +0000473 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000474 case BitstreamEntry::Record:
475 // The interesting case.
476 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000477 }
Joe Abbeyacb61942013-02-06 22:14:06 +0000478
Chris Lattner48c85b82007-05-04 03:30:17 +0000479 // Read a record.
480 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000481 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner48c85b82007-05-04 03:30:17 +0000482 default: // Default behavior: ignore.
483 break;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000484 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
485 // FIXME: Remove in 4.0.
Chris Lattner48c85b82007-05-04 03:30:17 +0000486 if (Record.size() & 1)
487 return Error("Invalid ENTRY record");
488
Chris Lattner48c85b82007-05-04 03:30:17 +0000489 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling8232ece2013-01-29 01:43:29 +0000490 AttrBuilder B;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000491 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling8232ece2013-01-29 01:43:29 +0000492 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patel19c87462008-09-26 22:53:05 +0000493 }
Devang Patel19c87462008-09-26 22:53:05 +0000494
Bill Wendling99faa3b2012-12-07 23:16:57 +0000495 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000496 Attrs.clear();
497 break;
498 }
Bill Wendling48fbcfe2013-02-12 08:13:50 +0000499 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
500 for (unsigned i = 0, e = Record.size(); i != e; ++i)
501 Attrs.push_back(MAttributeGroups[Record[i]]);
502
503 MAttributes.push_back(AttributeSet::get(Context, Attrs));
504 Attrs.clear();
505 break;
506 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000507 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000508 }
509}
510
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000511bool BitcodeReader::ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
512 switch (Code) {
513 case bitc::ATTR_KIND_ALIGNMENT:
514 *Kind = Attribute::Alignment;
515 return false;
516 case bitc::ATTR_KIND_ALWAYS_INLINE:
517 *Kind = Attribute::AlwaysInline;
518 return false;
519 case bitc::ATTR_KIND_BUILTIN:
520 *Kind = Attribute::Builtin;
521 return false;
522 case bitc::ATTR_KIND_BY_VAL:
523 *Kind = Attribute::ByVal;
524 return false;
525 case bitc::ATTR_KIND_COLD:
526 *Kind = Attribute::Cold;
527 return false;
528 case bitc::ATTR_KIND_INLINE_HINT:
529 *Kind = Attribute::InlineHint;
530 return false;
531 case bitc::ATTR_KIND_IN_REG:
532 *Kind = Attribute::InReg;
533 return false;
534 case bitc::ATTR_KIND_MIN_SIZE:
535 *Kind = Attribute::MinSize;
536 return false;
537 case bitc::ATTR_KIND_NAKED:
538 *Kind = Attribute::Naked;
539 return false;
540 case bitc::ATTR_KIND_NEST:
541 *Kind = Attribute::Nest;
542 return false;
543 case bitc::ATTR_KIND_NO_ALIAS:
544 *Kind = Attribute::NoAlias;
545 return false;
546 case bitc::ATTR_KIND_NO_BUILTIN:
547 *Kind = Attribute::NoBuiltin;
548 return false;
549 case bitc::ATTR_KIND_NO_CAPTURE:
550 *Kind = Attribute::NoCapture;
551 return false;
552 case bitc::ATTR_KIND_NO_DUPLICATE:
553 *Kind = Attribute::NoDuplicate;
554 return false;
555 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
556 *Kind = Attribute::NoImplicitFloat;
557 return false;
558 case bitc::ATTR_KIND_NO_INLINE:
559 *Kind = Attribute::NoInline;
560 return false;
561 case bitc::ATTR_KIND_NON_LAZY_BIND:
562 *Kind = Attribute::NonLazyBind;
563 return false;
564 case bitc::ATTR_KIND_NO_RED_ZONE:
565 *Kind = Attribute::NoRedZone;
566 return false;
567 case bitc::ATTR_KIND_NO_RETURN:
568 *Kind = Attribute::NoReturn;
569 return false;
570 case bitc::ATTR_KIND_NO_UNWIND:
571 *Kind = Attribute::NoUnwind;
572 return false;
573 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
574 *Kind = Attribute::OptimizeForSize;
575 return false;
Andrea Di Biagio5768bb82013-08-23 11:53:55 +0000576 case bitc::ATTR_KIND_OPTIMIZE_NONE:
577 *Kind = Attribute::OptimizeNone;
578 return false;
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000579 case bitc::ATTR_KIND_READ_NONE:
580 *Kind = Attribute::ReadNone;
581 return false;
582 case bitc::ATTR_KIND_READ_ONLY:
583 *Kind = Attribute::ReadOnly;
584 return false;
585 case bitc::ATTR_KIND_RETURNED:
586 *Kind = Attribute::Returned;
587 return false;
588 case bitc::ATTR_KIND_RETURNS_TWICE:
589 *Kind = Attribute::ReturnsTwice;
590 return false;
591 case bitc::ATTR_KIND_S_EXT:
592 *Kind = Attribute::SExt;
593 return false;
594 case bitc::ATTR_KIND_STACK_ALIGNMENT:
595 *Kind = Attribute::StackAlignment;
596 return false;
597 case bitc::ATTR_KIND_STACK_PROTECT:
598 *Kind = Attribute::StackProtect;
599 return false;
600 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
601 *Kind = Attribute::StackProtectReq;
602 return false;
603 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
604 *Kind = Attribute::StackProtectStrong;
605 return false;
606 case bitc::ATTR_KIND_STRUCT_RET:
607 *Kind = Attribute::StructRet;
608 return false;
609 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
610 *Kind = Attribute::SanitizeAddress;
611 return false;
612 case bitc::ATTR_KIND_SANITIZE_THREAD:
613 *Kind = Attribute::SanitizeThread;
614 return false;
615 case bitc::ATTR_KIND_SANITIZE_MEMORY:
616 *Kind = Attribute::SanitizeMemory;
617 return false;
618 case bitc::ATTR_KIND_UW_TABLE:
619 *Kind = Attribute::UWTable;
620 return false;
621 case bitc::ATTR_KIND_Z_EXT:
622 *Kind = Attribute::ZExt;
623 return false;
624 default:
625 std::string Buf;
626 raw_string_ostream fmt(Buf);
627 fmt << "Unknown attribute kind (" << Code << ")";
628 fmt.flush();
629 return Error(Buf.c_str());
630 }
631}
632
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000633bool BitcodeReader::ParseAttributeGroupBlock() {
634 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
635 return Error("Malformed block record");
636
637 if (!MAttributeGroups.empty())
638 return Error("Multiple PARAMATTR_GROUP blocks found!");
639
640 SmallVector<uint64_t, 64> Record;
641
642 // Read all the records.
643 while (1) {
644 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
645
646 switch (Entry.Kind) {
647 case BitstreamEntry::SubBlock: // Handled for us already.
648 case BitstreamEntry::Error:
649 return Error("Error at end of PARAMATTR_GROUP block");
650 case BitstreamEntry::EndBlock:
651 return false;
652 case BitstreamEntry::Record:
653 // The interesting case.
654 break;
655 }
656
657 // Read a record.
658 Record.clear();
659 switch (Stream.readRecord(Entry.ID, Record)) {
660 default: // Default behavior: ignore.
661 break;
662 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
663 if (Record.size() < 3)
664 return Error("Invalid ENTRY record");
665
Bill Wendling04ef4be2013-02-11 22:32:29 +0000666 uint64_t GrpID = Record[0];
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000667 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
668
669 AttrBuilder B;
670 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
671 if (Record[i] == 0) { // Enum attribute
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000672 Attribute::AttrKind Kind;
673 if (ParseAttrKind(Record[++i], &Kind))
674 return true;
675
676 B.addAttribute(Kind);
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000677 } else if (Record[i] == 1) { // Align attribute
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000678 Attribute::AttrKind Kind;
679 if (ParseAttrKind(Record[++i], &Kind))
680 return true;
681 if (Kind == Attribute::Alignment)
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000682 B.addAlignmentAttr(Record[++i]);
683 else
684 B.addStackAlignmentAttr(Record[++i]);
685 } else { // String attribute
Bill Wendling04ef4be2013-02-11 22:32:29 +0000686 assert((Record[i] == 3 || Record[i] == 4) &&
687 "Invalid attribute group entry");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000688 bool HasValue = (Record[i++] == 4);
689 SmallString<64> KindStr;
690 SmallString<64> ValStr;
691
692 while (Record[i] != 0 && i != e)
693 KindStr += Record[i++];
Bill Wendling04ef4be2013-02-11 22:32:29 +0000694 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000695
696 if (HasValue) {
697 // Has a value associated with it.
Bill Wendling04ef4be2013-02-11 22:32:29 +0000698 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000699 while (Record[i] != 0 && i != e)
700 ValStr += Record[i++];
Bill Wendling04ef4be2013-02-11 22:32:29 +0000701 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000702 }
703
704 B.addAttribute(KindStr.str(), ValStr.str());
705 }
706 }
707
Bill Wendling04ef4be2013-02-11 22:32:29 +0000708 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000709 break;
710 }
711 }
712 }
713}
714
Chris Lattner86697142007-05-01 05:01:34 +0000715bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000716 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000717 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000718
Chris Lattner1afcace2011-07-09 17:41:24 +0000719 return ParseTypeTableBody();
720}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000721
Chris Lattner1afcace2011-07-09 17:41:24 +0000722bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000723 if (!TypeList.empty())
724 return Error("Multiple TYPE_BLOCKs found!");
725
726 SmallVector<uint64_t, 64> Record;
727 unsigned NumRecords = 0;
728
Chris Lattner1afcace2011-07-09 17:41:24 +0000729 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000730
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000731 // Read all the records for this type table.
732 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000733 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000734
Chris Lattner5a4251c2013-01-20 02:13:19 +0000735 switch (Entry.Kind) {
736 case BitstreamEntry::SubBlock: // Handled for us already.
737 case BitstreamEntry::Error:
738 Error("Error in the type table block");
739 return true;
740 case BitstreamEntry::EndBlock:
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000741 if (NumRecords != TypeList.size())
742 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000743 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000744 case BitstreamEntry::Record:
745 // The interesting case.
746 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000747 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000748
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000749 // Read a record.
750 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000751 Type *ResultTy = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000752 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000753 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000754 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
755 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
756 // type list. This allows us to reserve space.
757 if (Record.size() < 1)
758 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000759 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000760 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000761 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000762 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000763 break;
Dan Gohmance163392011-12-17 00:04:22 +0000764 case bitc::TYPE_CODE_HALF: // HALF
765 ResultTy = Type::getHalfTy(Context);
766 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000767 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000768 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000769 break;
770 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000771 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000772 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000773 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000774 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000775 break;
776 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000777 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000778 break;
779 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000780 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000781 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000782 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000783 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000784 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000785 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000786 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000787 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000788 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
789 ResultTy = Type::getX86_MMXTy(Context);
790 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000791 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
792 if (Record.size() < 1)
793 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Owen Anderson1d0be152009-08-13 21:58:54 +0000795 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000796 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000797 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000798 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000799 if (Record.size() < 1)
800 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000801 unsigned AddressSpace = 0;
802 if (Record.size() == 2)
803 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000804 ResultTy = getTypeByID(Record[0]);
805 if (ResultTy == 0) return Error("invalid element type in pointer type");
806 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000807 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000808 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000809 case bitc::TYPE_CODE_FUNCTION_OLD: {
810 // FIXME: attrid is dead, remove it in LLVM 4.0
811 // FUNCTION: [vararg, attrid, retty, paramty x N]
812 if (Record.size() < 3)
813 return Error("Invalid FUNCTION type record");
814 SmallVector<Type*, 8> ArgTys;
815 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
816 if (Type *T = getTypeByID(Record[i]))
817 ArgTys.push_back(T);
818 else
819 break;
820 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000821
Nuno Lopesee8100d2012-05-23 15:19:39 +0000822 ResultTy = getTypeByID(Record[2]);
823 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
824 return Error("invalid type in function type");
825
826 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
827 break;
828 }
Chad Rosiercde54642011-11-03 00:14:01 +0000829 case bitc::TYPE_CODE_FUNCTION: {
830 // FUNCTION: [vararg, retty, paramty x N]
831 if (Record.size() < 2)
832 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000833 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000834 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
835 if (Type *T = getTypeByID(Record[i]))
836 ArgTys.push_back(T);
837 else
838 break;
839 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000840
Chad Rosiercde54642011-11-03 00:14:01 +0000841 ResultTy = getTypeByID(Record[1]);
842 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
843 return Error("invalid type in function type");
844
845 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
846 break;
847 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000848 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000849 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000850 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000851 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000852 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
853 if (Type *T = getTypeByID(Record[i]))
854 EltTys.push_back(T);
855 else
856 break;
857 }
858 if (EltTys.size() != Record.size()-1)
859 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000860 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000861 break;
862 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000863 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
864 if (ConvertToString(Record, 0, TypeName))
865 return Error("Invalid STRUCT_NAME record");
866 continue;
867
868 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
869 if (Record.size() < 1)
870 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000871
Chris Lattner1afcace2011-07-09 17:41:24 +0000872 if (NumRecords >= TypeList.size())
873 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000874
Chris Lattner1afcace2011-07-09 17:41:24 +0000875 // Check to see if this was forward referenced, if so fill in the temp.
876 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
877 if (Res) {
878 Res->setName(TypeName);
879 TypeList[NumRecords] = 0;
880 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000881 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000882 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000883
Chris Lattner1afcace2011-07-09 17:41:24 +0000884 SmallVector<Type*, 8> EltTys;
885 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
886 if (Type *T = getTypeByID(Record[i]))
887 EltTys.push_back(T);
888 else
889 break;
890 }
891 if (EltTys.size() != Record.size()-1)
892 return Error("invalid STRUCT type record");
893 Res->setBody(EltTys, Record[0]);
894 ResultTy = Res;
895 break;
896 }
897 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
898 if (Record.size() != 1)
899 return Error("Invalid OPAQUE type record");
900
901 if (NumRecords >= TypeList.size())
902 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000903
Chris Lattner1afcace2011-07-09 17:41:24 +0000904 // Check to see if this was forward referenced, if so fill in the temp.
905 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
906 if (Res) {
907 Res->setName(TypeName);
908 TypeList[NumRecords] = 0;
909 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000910 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000911 TypeName.clear();
912 ResultTy = Res;
913 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000914 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000915 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
916 if (Record.size() < 2)
917 return Error("Invalid ARRAY type record");
918 if ((ResultTy = getTypeByID(Record[1])))
919 ResultTy = ArrayType::get(ResultTy, Record[0]);
920 else
921 return Error("Invalid ARRAY type element");
922 break;
923 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
924 if (Record.size() < 2)
925 return Error("Invalid VECTOR type record");
926 if ((ResultTy = getTypeByID(Record[1])))
927 ResultTy = VectorType::get(ResultTy, Record[0]);
928 else
929 return Error("Invalid ARRAY type element");
930 break;
931 }
932
933 if (NumRecords >= TypeList.size())
934 return Error("invalid TYPE table");
935 assert(ResultTy && "Didn't read a type?");
936 assert(TypeList[NumRecords] == 0 && "Already read type?");
937 TypeList[NumRecords++] = ResultTy;
938 }
939}
940
Chris Lattner86697142007-05-01 05:01:34 +0000941bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000942 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000943 return Error("Malformed block record");
944
945 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000946
Chris Lattner0b2482a2007-04-23 21:26:05 +0000947 // Read all the records for this value table.
948 SmallString<128> ValueName;
949 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000950 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000951
Chris Lattner5a4251c2013-01-20 02:13:19 +0000952 switch (Entry.Kind) {
953 case BitstreamEntry::SubBlock: // Handled for us already.
954 case BitstreamEntry::Error:
955 return Error("malformed value symbol table block");
956 case BitstreamEntry::EndBlock:
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000957 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000958 case BitstreamEntry::Record:
959 // The interesting case.
960 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000961 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000962
Chris Lattner0b2482a2007-04-23 21:26:05 +0000963 // Read a record.
964 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000965 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000966 default: // Default behavior: unknown type.
967 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000968 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000969 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000970 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000971 unsigned ValueID = Record[0];
972 if (ValueID >= ValueList.size())
973 return Error("Invalid Value ID in VST_ENTRY record");
974 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000975
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000976 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000977 ValueName.clear();
978 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000979 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000980 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000981 if (ConvertToString(Record, 1, ValueName))
982 return Error("Invalid VST_BBENTRY record");
983 BasicBlock *BB = getBasicBlock(Record[0]);
984 if (BB == 0)
985 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000986
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000987 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000988 ValueName.clear();
989 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000990 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000991 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000992 }
993}
994
Devang Patele54abc92009-07-22 17:43:22 +0000995bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000996 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000997
998 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
999 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001000
Devang Patele54abc92009-07-22 17:43:22 +00001001 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001002
Devang Patele54abc92009-07-22 17:43:22 +00001003 // Read all the records.
1004 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001005 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001006
Chris Lattner5a4251c2013-01-20 02:13:19 +00001007 switch (Entry.Kind) {
1008 case BitstreamEntry::SubBlock: // Handled for us already.
1009 case BitstreamEntry::Error:
1010 Error("malformed metadata block");
1011 return true;
1012 case BitstreamEntry::EndBlock:
Devang Patele54abc92009-07-22 17:43:22 +00001013 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001014 case BitstreamEntry::Record:
1015 // The interesting case.
1016 break;
Devang Patele54abc92009-07-22 17:43:22 +00001017 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001018
Victor Hernandez24e64df2010-01-10 07:14:18 +00001019 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +00001020 // Read a record.
1021 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001022 unsigned Code = Stream.readRecord(Entry.ID, Record);
Dan Gohman9b10dfb2010-09-13 18:00:48 +00001023 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +00001024 default: // Default behavior: ignore.
1025 break;
Devang Patelaa993142009-07-29 22:34:41 +00001026 case bitc::METADATA_NAME: {
Chris Lattner1ca114a2013-01-20 02:54:05 +00001027 // Read name of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001028 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +00001029 Record.clear();
1030 Code = Stream.ReadCode();
1031
Chris Lattner9d61dd92011-06-17 17:50:30 +00001032 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001033 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001034 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +00001035
1036 // Read named metadata elements.
1037 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +00001038 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +00001039 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +00001040 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1041 if (MD == 0)
1042 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +00001043 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +00001044 }
Devang Patelaa993142009-07-29 22:34:41 +00001045 break;
1046 }
Chris Lattner9d61dd92011-06-17 17:50:30 +00001047 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +00001048 IsFunctionLocal = true;
1049 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +00001050 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +00001051 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +00001052 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001053
Devang Patel104cf9e2009-07-23 01:07:34 +00001054 unsigned Size = Record.size();
1055 SmallVector<Value*, 8> Elts;
1056 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001057 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001058 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001059 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +00001060 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +00001061 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +00001062 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1063 else
1064 Elts.push_back(NULL);
1065 }
Jay Foadec9186b2011-04-21 19:59:31 +00001066 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +00001067 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +00001068 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +00001069 break;
1070 }
Devang Patele54abc92009-07-22 17:43:22 +00001071 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001072 SmallString<8> String(Record.begin(), Record.end());
1073 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +00001074 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +00001075 break;
1076 }
Devang Patele8e02132009-09-18 19:26:43 +00001077 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001078 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001079 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001080
Devang Patela2148402009-09-28 21:14:55 +00001081 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001082 SmallString<8> Name(Record.begin()+1, Record.end());
1083
Chris Lattner08113472009-12-29 09:01:33 +00001084 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +00001085 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1086 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +00001087 break;
1088 }
Devang Patele54abc92009-07-22 17:43:22 +00001089 }
1090 }
1091}
1092
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001093/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +00001094/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001095uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +00001096 if ((V & 1) == 0)
1097 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001098 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +00001099 return -(V >> 1);
1100 // There is no such thing as -0 with integers. "-0" really means MININT.
1101 return 1ULL << 63;
1102}
1103
Chris Lattner07d98b42007-04-26 02:46:40 +00001104/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1105/// values and aliases that we can.
1106bool BitcodeReader::ResolveGlobalAndAliasInits() {
1107 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1108 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001109
Chris Lattner07d98b42007-04-26 02:46:40 +00001110 GlobalInitWorklist.swap(GlobalInits);
1111 AliasInitWorklist.swap(AliasInits);
1112
1113 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +00001114 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +00001115 if (ValID >= ValueList.size()) {
1116 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +00001117 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +00001118 } else {
1119 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1120 GlobalInitWorklist.back().first->setInitializer(C);
1121 else
1122 return Error("Global variable initializer is not a constant!");
1123 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001124 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001125 }
1126
1127 while (!AliasInitWorklist.empty()) {
1128 unsigned ValID = AliasInitWorklist.back().second;
1129 if (ValID >= ValueList.size()) {
1130 AliasInits.push_back(AliasInitWorklist.back());
1131 } else {
1132 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +00001133 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +00001134 else
1135 return Error("Alias initializer is not a constant!");
1136 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001137 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001138 }
1139 return false;
1140}
1141
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001142static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1143 SmallVector<uint64_t, 8> Words(Vals.size());
1144 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001145 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001146
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001147 return APInt(TypeBits, Words);
1148}
1149
Chris Lattner86697142007-05-01 05:01:34 +00001150bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001151 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +00001152 return Error("Malformed block record");
1153
1154 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001155
Chris Lattnere16504e2007-04-24 03:30:34 +00001156 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001157 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +00001158 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +00001159 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001160 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001161
Chris Lattner5a4251c2013-01-20 02:13:19 +00001162 switch (Entry.Kind) {
1163 case BitstreamEntry::SubBlock: // Handled for us already.
1164 case BitstreamEntry::Error:
1165 return Error("malformed block record in AST file");
1166 case BitstreamEntry::EndBlock:
1167 if (NextCstNo != ValueList.size())
1168 return Error("Invalid constant reference!");
Joe Abbeyacb61942013-02-06 22:14:06 +00001169
Chris Lattner5a4251c2013-01-20 02:13:19 +00001170 // Once all the constants have been read, go through and resolve forward
1171 // references.
1172 ValueList.ResolveConstantForwardRefs();
1173 return false;
1174 case BitstreamEntry::Record:
1175 // The interesting case.
Chris Lattnerea693df2008-08-21 02:34:16 +00001176 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001177 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001178
Chris Lattnere16504e2007-04-24 03:30:34 +00001179 // Read a record.
1180 Record.clear();
1181 Value *V = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001182 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00001183 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001184 default: // Default behavior: unknown constant
1185 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001186 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001187 break;
1188 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1189 if (Record.empty())
1190 return Error("Malformed CST_SETTYPE record");
1191 if (Record[0] >= TypeList.size())
1192 return Error("Invalid Type ID in CST_SETTYPE record");
1193 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001194 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001195 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001196 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001197 break;
1198 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001199 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001200 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001201 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001202 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001203 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001204 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001205 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001206
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001207 APInt VInt = ReadWideAPInt(Record,
1208 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001209 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +00001210
Chris Lattner0eef0802007-04-24 04:04:35 +00001211 break;
1212 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001213 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001214 if (Record.empty())
1215 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001216 if (CurTy->isHalfTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001217 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1218 APInt(16, (uint16_t)Record[0])));
Dan Gohmance163392011-12-17 00:04:22 +00001219 else if (CurTy->isFloatTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001220 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1221 APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001222 else if (CurTy->isDoubleTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001223 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1224 APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001225 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001226 // Bits are not stored the same way as a normal i80 APInt, compensate.
1227 uint64_t Rearrange[2];
1228 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1229 Rearrange[1] = Record[0] >> 48;
Tim Northover0a29cb02013-01-22 09:46:31 +00001230 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1231 APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001232 } else if (CurTy->isFP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001233 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1234 APInt(128, Record)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001235 else if (CurTy->isPPC_FP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001236 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1237 APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001238 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001239 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001240 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001241 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001242
Chris Lattner15e6d172007-05-04 19:11:41 +00001243 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1244 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001245 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001246
Chris Lattner15e6d172007-05-04 19:11:41 +00001247 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001248 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001249
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001250 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001251 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001252 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001253 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001254 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001255 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1256 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001257 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001258 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001259 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001260 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1261 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001262 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001263 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001264 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001265 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001266 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001267 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001268 break;
1269 }
Chris Lattner2237f842012-02-05 02:41:35 +00001270 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001271 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1272 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001273 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001274
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001275 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001276 V = ConstantDataArray::getString(Context, Elts,
1277 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001278 break;
1279 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001280 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1281 if (Record.empty())
1282 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001283
Chris Lattnerd408f062012-01-30 00:51:16 +00001284 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1285 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001286
Chris Lattnerd408f062012-01-30 00:51:16 +00001287 if (EltTy->isIntegerTy(8)) {
1288 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1289 if (isa<VectorType>(CurTy))
1290 V = ConstantDataVector::get(Context, Elts);
1291 else
1292 V = ConstantDataArray::get(Context, Elts);
1293 } else if (EltTy->isIntegerTy(16)) {
1294 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1295 if (isa<VectorType>(CurTy))
1296 V = ConstantDataVector::get(Context, Elts);
1297 else
1298 V = ConstantDataArray::get(Context, Elts);
1299 } else if (EltTy->isIntegerTy(32)) {
1300 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1301 if (isa<VectorType>(CurTy))
1302 V = ConstantDataVector::get(Context, Elts);
1303 else
1304 V = ConstantDataArray::get(Context, Elts);
1305 } else if (EltTy->isIntegerTy(64)) {
1306 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1307 if (isa<VectorType>(CurTy))
1308 V = ConstantDataVector::get(Context, Elts);
1309 else
1310 V = ConstantDataArray::get(Context, Elts);
1311 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001312 SmallVector<float, 16> Elts(Size);
1313 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001314 if (isa<VectorType>(CurTy))
1315 V = ConstantDataVector::get(Context, Elts);
1316 else
1317 V = ConstantDataArray::get(Context, Elts);
1318 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001319 SmallVector<double, 16> Elts(Size);
1320 std::transform(Record.begin(), Record.end(), Elts.begin(),
1321 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001322 if (isa<VectorType>(CurTy))
1323 V = ConstantDataVector::get(Context, Elts);
1324 else
1325 V = ConstantDataArray::get(Context, Elts);
1326 } else {
1327 return Error("Unknown element type in CE_DATA");
1328 }
1329 break;
1330 }
1331
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001332 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1333 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1334 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001335 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001336 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001337 } else {
1338 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1339 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001340 unsigned Flags = 0;
1341 if (Record.size() >= 4) {
1342 if (Opc == Instruction::Add ||
1343 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001344 Opc == Instruction::Mul ||
1345 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001346 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1347 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1348 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1349 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001350 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001351 Opc == Instruction::UDiv ||
1352 Opc == Instruction::LShr ||
1353 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001354 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001355 Flags |= SDivOperator::IsExact;
1356 }
1357 }
1358 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001359 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001360 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001361 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001362 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1363 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1364 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001365 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001366 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001367 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001368 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001369 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001370 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001371 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001372 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001373 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001374 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001375 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001376 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001377 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001378 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001379 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001380 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001381 if (!ElTy) return Error("Invalid CE_GEP record");
1382 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1383 }
Jay Foaddab3d292011-07-21 14:31:17 +00001384 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001385 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1386 BitCode ==
1387 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001388 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001389 }
1390 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1391 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbeye46b14a2012-11-19 19:22:55 +00001392 V = ConstantExpr::getSelect(
1393 ValueList.getConstantFwdRef(Record[0],
1394 Type::getInt1Ty(Context)),
1395 ValueList.getConstantFwdRef(Record[1],CurTy),
1396 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001397 break;
1398 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1399 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001400 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001401 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1402 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1403 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001404 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001405 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001406 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001407 break;
1408 }
1409 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001410 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001411 if (Record.size() < 3 || OpTy == 0)
1412 return Error("Invalid CE_INSERTELT record");
1413 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1414 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1415 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001416 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001417 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001418 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001419 break;
1420 }
1421 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001422 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001423 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001424 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001425 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1426 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001427 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001428 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001429 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001430 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001431 break;
1432 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001433 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001434 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1435 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001436 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001437 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1438 return Error("Invalid CE_SHUFVEC_EX record");
1439 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1440 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001441 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001442 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001443 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001444 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001445 break;
1446 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001447 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1448 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001449 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001450 if (OpTy == 0) return Error("Invalid CE_CMP record");
1451 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1452 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1453
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001454 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001455 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001456 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001457 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001458 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001459 }
Chad Rosier581600b2012-09-05 19:00:49 +00001460 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001461 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001462 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001463 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1464 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001465 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001466 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001467 unsigned AsmStrSize = Record[1];
1468 if (2+AsmStrSize >= Record.size())
1469 return Error("Invalid INLINEASM record");
1470 unsigned ConstStrSize = Record[2+AsmStrSize];
1471 if (3+AsmStrSize+ConstStrSize > Record.size())
1472 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001473
Chris Lattner2bce93a2007-05-06 01:58:20 +00001474 for (unsigned i = 0; i != AsmStrSize; ++i)
1475 AsmStr += (char)Record[2+i];
1476 for (unsigned i = 0; i != ConstStrSize; ++i)
1477 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001478 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001479 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001480 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001481 break;
1482 }
Chad Rosier581600b2012-09-05 19:00:49 +00001483 // This version adds support for the asm dialect keywords (e.g.,
1484 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001485 case bitc::CST_CODE_INLINEASM: {
1486 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1487 std::string AsmStr, ConstrStr;
1488 bool HasSideEffects = Record[0] & 1;
1489 bool IsAlignStack = (Record[0] >> 1) & 1;
1490 unsigned AsmDialect = Record[0] >> 2;
1491 unsigned AsmStrSize = Record[1];
1492 if (2+AsmStrSize >= Record.size())
1493 return Error("Invalid INLINEASM record");
1494 unsigned ConstStrSize = Record[2+AsmStrSize];
1495 if (3+AsmStrSize+ConstStrSize > Record.size())
1496 return Error("Invalid INLINEASM record");
1497
1498 for (unsigned i = 0; i != AsmStrSize; ++i)
1499 AsmStr += (char)Record[2+i];
1500 for (unsigned i = 0; i != ConstStrSize; ++i)
1501 ConstrStr += (char)Record[3+AsmStrSize+i];
1502 PointerType *PTy = cast<PointerType>(CurTy);
1503 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1504 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001505 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001506 break;
1507 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001508 case bitc::CST_CODE_BLOCKADDRESS:{
1509 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001510 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001511 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1512 Function *Fn =
1513 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1514 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001515
1516 // If the function is already parsed we can insert the block address right
1517 // away.
1518 if (!Fn->empty()) {
1519 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1520 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1521 if (BBI == BBE)
1522 return Error("Invalid blockaddress block #");
1523 ++BBI;
1524 }
1525 V = BlockAddress::get(Fn, BBI);
1526 } else {
1527 // Otherwise insert a placeholder and remember it so it can be inserted
1528 // when the function is parsed.
1529 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1530 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001531 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001532 0, "");
1533 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1534 V = FwdRef;
1535 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001536 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001537 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001538 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001539
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001540 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001541 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001542 }
1543}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001544
Chad Rosiercbbb0962011-12-07 21:44:12 +00001545bool BitcodeReader::ParseUseLists() {
1546 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1547 return Error("Malformed block record");
1548
1549 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001550
Chad Rosiercbbb0962011-12-07 21:44:12 +00001551 // Read all the records.
1552 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001553 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001554
Chris Lattner5a4251c2013-01-20 02:13:19 +00001555 switch (Entry.Kind) {
1556 case BitstreamEntry::SubBlock: // Handled for us already.
1557 case BitstreamEntry::Error:
1558 return Error("malformed use list block");
1559 case BitstreamEntry::EndBlock:
Chad Rosiercbbb0962011-12-07 21:44:12 +00001560 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001561 case BitstreamEntry::Record:
1562 // The interesting case.
1563 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001564 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001565
Chad Rosiercbbb0962011-12-07 21:44:12 +00001566 // Read a use list record.
1567 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001568 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosiercbbb0962011-12-07 21:44:12 +00001569 default: // Default behavior: unknown type.
1570 break;
1571 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1572 unsigned RecordLength = Record.size();
1573 if (RecordLength < 1)
1574 return Error ("Invalid UseList reader!");
1575 UseListRecords.push_back(Record);
1576 break;
1577 }
1578 }
1579 }
1580}
1581
Chris Lattner980e5aa2007-05-01 05:52:21 +00001582/// RememberAndSkipFunctionBody - When we see the block for a function body,
1583/// remember where it is and then skip it. This lets us lazily deserialize the
1584/// functions.
1585bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001586 // Get the function we are talking about.
1587 if (FunctionsWithBodies.empty())
1588 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001589
Chris Lattner48f84872007-05-01 04:59:48 +00001590 Function *Fn = FunctionsWithBodies.back();
1591 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001592
Chris Lattner48f84872007-05-01 04:59:48 +00001593 // Save the current stream state.
1594 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001595 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001596
Chris Lattner48f84872007-05-01 04:59:48 +00001597 // Skip over the function block for now.
1598 if (Stream.SkipBlock())
1599 return Error("Malformed block record");
1600 return false;
1601}
1602
Derek Schuff2ea93872012-02-06 22:30:29 +00001603bool BitcodeReader::GlobalCleanup() {
1604 // Patch the initializers for globals and aliases up.
1605 ResolveGlobalAndAliasInits();
1606 if (!GlobalInits.empty() || !AliasInits.empty())
1607 return Error("Malformed global initializer set");
1608
1609 // Look for intrinsic functions which need to be upgraded at some point
1610 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1611 FI != FE; ++FI) {
1612 Function *NewFn;
1613 if (UpgradeIntrinsicFunction(FI, NewFn))
1614 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1615 }
1616
1617 // Look for global variables which need to be renamed.
1618 for (Module::global_iterator
1619 GI = TheModule->global_begin(), GE = TheModule->global_end();
1620 GI != GE; ++GI)
1621 UpgradeGlobalVariable(GI);
1622 // Force deallocation of memory for these vectors to favor the client that
1623 // want lazy deserialization.
1624 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1625 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1626 return false;
1627}
1628
1629bool BitcodeReader::ParseModule(bool Resume) {
1630 if (Resume)
1631 Stream.JumpToBit(NextUnreadBit);
1632 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001633 return Error("Malformed block record");
1634
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001635 SmallVector<uint64_t, 64> Record;
1636 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001637 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001638
1639 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001640 while (1) {
1641 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00001642
Chris Lattner5a4251c2013-01-20 02:13:19 +00001643 switch (Entry.Kind) {
1644 case BitstreamEntry::Error:
1645 Error("malformed module block");
1646 return true;
1647 case BitstreamEntry::EndBlock:
Derek Schuff2ea93872012-02-06 22:30:29 +00001648 return GlobalCleanup();
Joe Abbeyacb61942013-02-06 22:14:06 +00001649
Chris Lattner5a4251c2013-01-20 02:13:19 +00001650 case BitstreamEntry::SubBlock:
1651 switch (Entry.ID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001652 default: // Skip unknown content.
1653 if (Stream.SkipBlock())
1654 return Error("Malformed block record");
1655 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001656 case bitc::BLOCKINFO_BLOCK_ID:
1657 if (Stream.ReadBlockInfoBlock())
1658 return Error("Malformed BlockInfoBlock");
1659 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001660 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001661 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001662 return true;
1663 break;
Bill Wendlingc3ba0a82013-02-10 23:24:25 +00001664 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1665 if (ParseAttributeGroupBlock())
1666 return true;
1667 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001668 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001669 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001670 return true;
1671 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001672 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001673 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001674 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001675 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001676 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001677 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001678 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001679 return true;
1680 break;
Devang Patele54abc92009-07-22 17:43:22 +00001681 case bitc::METADATA_BLOCK_ID:
1682 if (ParseMetadata())
1683 return true;
1684 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001685 case bitc::FUNCTION_BLOCK_ID:
1686 // If this is the first function body we've seen, reverse the
1687 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001688 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001689 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001690 if (GlobalCleanup())
1691 return true;
1692 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001693 }
Joe Abbeyacb61942013-02-06 22:14:06 +00001694
Chris Lattner980e5aa2007-05-01 05:52:21 +00001695 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001696 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001697 // For streaming bitcode, suspend parsing when we reach the function
1698 // bodies. Subsequent materialization calls will resume it when
1699 // necessary. For streaming, the function bodies must be at the end of
1700 // the bitcode. If the bitcode file is old, the symbol table will be
1701 // at the end instead and will not have been seen yet. In this case,
1702 // just finish the parse now.
1703 if (LazyStreamer && SeenValueSymbolTable) {
1704 NextUnreadBit = Stream.GetCurrentBitNo();
1705 return false;
1706 }
Chris Lattner48f84872007-05-01 04:59:48 +00001707 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001708 case bitc::USELIST_BLOCK_ID:
1709 if (ParseUseLists())
1710 return true;
1711 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001712 }
1713 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00001714
Chris Lattner5a4251c2013-01-20 02:13:19 +00001715 case BitstreamEntry::Record:
1716 // The interesting case.
1717 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001718 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001719
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001721 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001722 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001723 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001724 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001725 if (Record.size() < 1)
1726 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001727 // Only version #0 and #1 are supported so far.
1728 unsigned module_version = Record[0];
1729 switch (module_version) {
1730 default: return Error("Unknown bitstream version!");
1731 case 0:
1732 UseRelativeIDs = false;
1733 break;
1734 case 1:
1735 UseRelativeIDs = true;
1736 break;
1737 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001738 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001739 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001740 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001741 std::string S;
1742 if (ConvertToString(Record, 0, S))
1743 return Error("Invalid MODULE_CODE_TRIPLE record");
1744 TheModule->setTargetTriple(S);
1745 break;
1746 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001747 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001748 std::string S;
1749 if (ConvertToString(Record, 0, S))
1750 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1751 TheModule->setDataLayout(S);
1752 break;
1753 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001754 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001755 std::string S;
1756 if (ConvertToString(Record, 0, S))
1757 return Error("Invalid MODULE_CODE_ASM record");
1758 TheModule->setModuleInlineAsm(S);
1759 break;
1760 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001761 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1762 // FIXME: Remove in 4.0.
1763 std::string S;
1764 if (ConvertToString(Record, 0, S))
1765 return Error("Invalid MODULE_CODE_DEPLIB record");
1766 // Ignore value.
1767 break;
1768 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001769 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001770 std::string S;
1771 if (ConvertToString(Record, 0, S))
1772 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1773 SectionTable.push_back(S);
1774 break;
1775 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001776 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001777 std::string S;
1778 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001779 return Error("Invalid MODULE_CODE_GCNAME record");
1780 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001781 break;
1782 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001783 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001784 // linkage, alignment, section, visibility, threadlocal,
1785 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001786 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001787 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001788 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001789 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001790 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001791 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001792 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001793 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001794 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001795
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001796 bool isConstant = Record[1];
1797 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1798 unsigned Alignment = (1 << Record[4]) >> 1;
1799 std::string Section;
1800 if (Record[5]) {
1801 if (Record[5]-1 >= SectionTable.size())
1802 return Error("Invalid section ID");
1803 Section = SectionTable[Record[5]-1];
1804 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001805 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001806 if (Record.size() > 6)
1807 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001808
1809 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001810 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001811 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001812
Rafael Espindolabea46262011-01-08 16:42:36 +00001813 bool UnnamedAddr = false;
1814 if (Record.size() > 8)
1815 UnnamedAddr = Record[8];
1816
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001817 bool ExternallyInitialized = false;
1818 if (Record.size() > 9)
1819 ExternallyInitialized = Record[9];
1820
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001821 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001822 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001823 TLM, AddressSpace, ExternallyInitialized);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001824 NewGV->setAlignment(Alignment);
1825 if (!Section.empty())
1826 NewGV->setSection(Section);
1827 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001828 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001829
Chris Lattner0b2482a2007-04-23 21:26:05 +00001830 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001831
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001832 // Remember which value to use for the global initializer.
1833 if (unsigned InitID = Record[2])
1834 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001835 break;
1836 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001837 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001838 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001839 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001840 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001841 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001842 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001843 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001844 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001845 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001846 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001847 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1848 if (!FTy)
1849 return Error("Function not a pointer to function type!");
1850
Gabor Greif051a9502008-04-06 20:25:17 +00001851 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1852 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001853
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001854 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001855 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001856 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001857 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001858
Chris Lattnera9bb7132007-05-08 05:38:01 +00001859 Func->setAlignment((1 << Record[5]) >> 1);
1860 if (Record[6]) {
1861 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001862 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001863 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001864 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001865 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001866 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001867 if (Record[8]-1 > GCTable.size())
1868 return Error("Invalid GC ID");
1869 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001870 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001871 bool UnnamedAddr = false;
1872 if (Record.size() > 9)
1873 UnnamedAddr = Record[9];
1874 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001875 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001876
Chris Lattner48f84872007-05-01 04:59:48 +00001877 // If this is a function with a body, remember the prototype we are
1878 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001879 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001880 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001881 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1882 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001883 break;
1884 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001885 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001886 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001887 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001888 if (Record.size() < 3)
1889 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001890 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001891 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001892 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001893 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894
Chris Lattner07d98b42007-04-26 02:46:40 +00001895 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1896 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001897 // Old bitcode files didn't have visibility field.
1898 if (Record.size() > 3)
1899 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001900 ValueList.push_back(NewGA);
1901 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1902 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001903 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001904 /// MODULE_CODE_PURGEVALS: [numvals]
1905 case bitc::MODULE_CODE_PURGEVALS:
1906 // Trim down the value list to the specified size.
1907 if (Record.size() < 1 || Record[0] > ValueList.size())
1908 return Error("Invalid MODULE_PURGEVALS record");
1909 ValueList.shrinkTo(Record[0]);
1910 break;
1911 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001912 Record.clear();
1913 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001914}
1915
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001916bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001917 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001918
Derek Schuff2ea93872012-02-06 22:30:29 +00001919 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001920
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001921 // Sniff for the signature.
1922 if (Stream.Read(8) != 'B' ||
1923 Stream.Read(8) != 'C' ||
1924 Stream.Read(4) != 0x0 ||
1925 Stream.Read(4) != 0xC ||
1926 Stream.Read(4) != 0xE ||
1927 Stream.Read(4) != 0xD)
1928 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001929
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001930 // We expect a number of well-defined blocks, though we don't necessarily
1931 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001932 while (1) {
1933 if (Stream.AtEndOfStream())
1934 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001935
Chris Lattner5a4251c2013-01-20 02:13:19 +00001936 BitstreamEntry Entry =
1937 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbeyacb61942013-02-06 22:14:06 +00001938
Chris Lattner5a4251c2013-01-20 02:13:19 +00001939 switch (Entry.Kind) {
1940 case BitstreamEntry::Error:
1941 Error("malformed module file");
1942 return true;
1943 case BitstreamEntry::EndBlock:
1944 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001945
Chris Lattner5a4251c2013-01-20 02:13:19 +00001946 case BitstreamEntry::SubBlock:
1947 switch (Entry.ID) {
1948 case bitc::BLOCKINFO_BLOCK_ID:
1949 if (Stream.ReadBlockInfoBlock())
1950 return Error("Malformed BlockInfoBlock");
1951 break;
1952 case bitc::MODULE_BLOCK_ID:
1953 // Reject multiple MODULE_BLOCK's in a single bitstream.
1954 if (TheModule)
1955 return Error("Multiple MODULE_BLOCKs in same stream");
1956 TheModule = M;
1957 if (ParseModule(false))
1958 return true;
1959 if (LazyStreamer) return false;
1960 break;
1961 default:
1962 if (Stream.SkipBlock())
1963 return Error("Malformed block record");
1964 break;
1965 }
1966 continue;
1967 case BitstreamEntry::Record:
1968 // There should be no records in the top-level of blocks.
Joe Abbeyacb61942013-02-06 22:14:06 +00001969
Chris Lattner5a4251c2013-01-20 02:13:19 +00001970 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001971 // to the end of them. If this file size is a multiple of 4 but not 8, we
1972 // have to read and ignore these final 4 bytes :-(
Chris Lattner5a4251c2013-01-20 02:13:19 +00001973 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolac9687b32011-05-26 18:59:54 +00001974 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001975 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001976 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001977
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001978 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001979 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001980 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001981}
Chris Lattnerc453f762007-04-29 07:54:31 +00001982
Bill Wendling34711742010-10-06 01:22:42 +00001983bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1984 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1985 return Error("Malformed block record");
1986
1987 SmallVector<uint64_t, 64> Record;
1988
1989 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001990 while (1) {
1991 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001992
Chris Lattner5a4251c2013-01-20 02:13:19 +00001993 switch (Entry.Kind) {
1994 case BitstreamEntry::SubBlock: // Handled for us already.
1995 case BitstreamEntry::Error:
1996 return Error("malformed module block");
1997 case BitstreamEntry::EndBlock:
Bill Wendling34711742010-10-06 01:22:42 +00001998 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001999 case BitstreamEntry::Record:
2000 // The interesting case.
2001 break;
Bill Wendling34711742010-10-06 01:22:42 +00002002 }
2003
2004 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00002005 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling34711742010-10-06 01:22:42 +00002006 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00002007 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2008 std::string S;
2009 if (ConvertToString(Record, 0, S))
2010 return Error("Invalid MODULE_CODE_TRIPLE record");
2011 Triple = S;
2012 break;
2013 }
2014 }
2015 Record.clear();
2016 }
Bill Wendling34711742010-10-06 01:22:42 +00002017}
2018
2019bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00002020 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00002021
2022 // Sniff for the signature.
2023 if (Stream.Read(8) != 'B' ||
2024 Stream.Read(8) != 'C' ||
2025 Stream.Read(4) != 0x0 ||
2026 Stream.Read(4) != 0xC ||
2027 Stream.Read(4) != 0xE ||
2028 Stream.Read(4) != 0xD)
2029 return Error("Invalid bitcode signature");
2030
2031 // We expect a number of well-defined blocks, though we don't necessarily
2032 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00002033 while (1) {
2034 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00002035
Chris Lattner5a4251c2013-01-20 02:13:19 +00002036 switch (Entry.Kind) {
2037 case BitstreamEntry::Error:
2038 Error("malformed module file");
2039 return true;
2040 case BitstreamEntry::EndBlock:
2041 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00002042
Chris Lattner5a4251c2013-01-20 02:13:19 +00002043 case BitstreamEntry::SubBlock:
2044 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2045 return ParseModuleTriple(Triple);
Joe Abbeyacb61942013-02-06 22:14:06 +00002046
Chris Lattner5a4251c2013-01-20 02:13:19 +00002047 // Ignore other sub-blocks.
2048 if (Stream.SkipBlock()) {
2049 Error("malformed block record in AST file");
Bill Wendling34711742010-10-06 01:22:42 +00002050 return true;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002051 }
2052 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00002053
Chris Lattner5a4251c2013-01-20 02:13:19 +00002054 case BitstreamEntry::Record:
2055 Stream.skipRecord(Entry.ID);
2056 continue;
Bill Wendling34711742010-10-06 01:22:42 +00002057 }
2058 }
Bill Wendling34711742010-10-06 01:22:42 +00002059}
2060
Devang Patele8e02132009-09-18 19:26:43 +00002061/// ParseMetadataAttachment - Parse metadata attachments.
2062bool BitcodeReader::ParseMetadataAttachment() {
2063 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2064 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002065
Devang Patele8e02132009-09-18 19:26:43 +00002066 SmallVector<uint64_t, 64> Record;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002067 while (1) {
2068 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00002069
Chris Lattner5a4251c2013-01-20 02:13:19 +00002070 switch (Entry.Kind) {
2071 case BitstreamEntry::SubBlock: // Handled for us already.
2072 case BitstreamEntry::Error:
2073 return Error("malformed metadata block");
2074 case BitstreamEntry::EndBlock:
2075 return false;
2076 case BitstreamEntry::Record:
2077 // The interesting case.
Devang Patele8e02132009-09-18 19:26:43 +00002078 break;
2079 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00002080
Devang Patele8e02132009-09-18 19:26:43 +00002081 // Read a metadata attachment record.
2082 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00002083 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patele8e02132009-09-18 19:26:43 +00002084 default: // Default behavior: ignore.
2085 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00002086 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00002087 unsigned RecordLength = Record.size();
2088 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002089 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00002090 Instruction *Inst = InstructionList[Record[0]];
2091 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00002092 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00002093 DenseMap<unsigned, unsigned>::iterator I =
2094 MDKindMap.find(Kind);
2095 if (I == MDKindMap.end())
2096 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002097 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00002098 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00002099 }
2100 break;
2101 }
2102 }
2103 }
Devang Patele8e02132009-09-18 19:26:43 +00002104}
Chris Lattner48f84872007-05-01 04:59:48 +00002105
Chris Lattner980e5aa2007-05-01 05:52:21 +00002106/// ParseFunctionBody - Lazily parse the specified function body block.
2107bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00002108 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00002109 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002110
Nick Lewycky9a49f152010-02-25 08:30:17 +00002111 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002112 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00002113 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002114
Chris Lattner980e5aa2007-05-01 05:52:21 +00002115 // Add all the function arguments to the value table.
2116 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2117 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002118
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002119 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00002120 BasicBlock *CurBB = 0;
2121 unsigned CurBBNo = 0;
2122
Chris Lattnera6245242010-04-03 02:17:50 +00002123 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00002124
Chris Lattner980e5aa2007-05-01 05:52:21 +00002125 // Read all the records.
2126 SmallVector<uint64_t, 64> Record;
2127 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00002128 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00002129
Chris Lattner5a4251c2013-01-20 02:13:19 +00002130 switch (Entry.Kind) {
2131 case BitstreamEntry::Error:
2132 return Error("Bitcode error in function block");
2133 case BitstreamEntry::EndBlock:
2134 goto OutOfRecordLoop;
Joe Abbeyacb61942013-02-06 22:14:06 +00002135
Chris Lattner5a4251c2013-01-20 02:13:19 +00002136 case BitstreamEntry::SubBlock:
2137 switch (Entry.ID) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00002138 default: // Skip unknown content.
2139 if (Stream.SkipBlock())
2140 return Error("Malformed block record");
2141 break;
2142 case bitc::CONSTANTS_BLOCK_ID:
2143 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002144 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002145 break;
2146 case bitc::VALUE_SYMTAB_BLOCK_ID:
2147 if (ParseValueSymbolTable()) return true;
2148 break;
Devang Patele8e02132009-09-18 19:26:43 +00002149 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002150 if (ParseMetadataAttachment()) return true;
2151 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00002152 case bitc::METADATA_BLOCK_ID:
2153 if (ParseMetadata()) return true;
2154 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002155 }
2156 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00002157
Chris Lattner5a4251c2013-01-20 02:13:19 +00002158 case BitstreamEntry::Record:
2159 // The interesting case.
2160 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002161 }
Joe Abbeyacb61942013-02-06 22:14:06 +00002162
Chris Lattner980e5aa2007-05-01 05:52:21 +00002163 // Read a record.
2164 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002165 Instruction *I = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002166 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00002167 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002168 default: // Default behavior: reject
2169 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002170 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002171 if (Record.size() < 1 || Record[0] == 0)
2172 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002173 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00002174 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002175 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00002176 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002177 CurBB = FunctionBBs[0];
2178 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002179
Chris Lattnera6245242010-04-03 02:17:50 +00002180 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2181 // This record indicates that the last instruction is at the same
2182 // location as the previous instruction with a location.
2183 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00002184
Chris Lattnera6245242010-04-03 02:17:50 +00002185 // Get the last instruction emitted.
2186 if (CurBB && !CurBB->empty())
2187 I = &CurBB->back();
2188 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2189 !FunctionBBs[CurBBNo-1]->empty())
2190 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00002191
Chris Lattnera6245242010-04-03 02:17:50 +00002192 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2193 I->setDebugLoc(LastLoc);
2194 I = 0;
2195 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002196
Chris Lattner4f6bab92011-06-17 18:17:37 +00002197 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002198 I = 0; // Get the last instruction emitted.
2199 if (CurBB && !CurBB->empty())
2200 I = &CurBB->back();
2201 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2202 !FunctionBBs[CurBBNo-1]->empty())
2203 I = &FunctionBBs[CurBBNo-1]->back();
2204 if (I == 0 || Record.size() < 4)
2205 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002206
Chris Lattnera6245242010-04-03 02:17:50 +00002207 unsigned Line = Record[0], Col = Record[1];
2208 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00002209
Chris Lattnera6245242010-04-03 02:17:50 +00002210 MDNode *Scope = 0, *IA = 0;
2211 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2212 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2213 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2214 I->setDebugLoc(LastLoc);
2215 I = 0;
2216 continue;
2217 }
2218
Chris Lattnerabfbf852007-05-06 00:21:25 +00002219 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2220 unsigned OpNum = 0;
2221 Value *LHS, *RHS;
2222 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002223 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002224 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002225 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002226
Dan Gohman1224c382009-07-20 21:19:07 +00002227 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002228 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002229 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002230 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002231 if (OpNum < Record.size()) {
2232 if (Opc == Instruction::Add ||
2233 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002234 Opc == Instruction::Mul ||
2235 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002236 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002237 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002238 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002239 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002240 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002241 Opc == Instruction::UDiv ||
2242 Opc == Instruction::LShr ||
2243 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002244 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002245 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002246 } else if (isa<FPMathOperator>(I)) {
2247 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002248 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2249 FMF.setUnsafeAlgebra();
2250 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2251 FMF.setNoNaNs();
2252 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2253 FMF.setNoInfs();
2254 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2255 FMF.setNoSignedZeros();
2256 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2257 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002258 if (FMF.any())
2259 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002260 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002261
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002262 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002263 break;
2264 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002265 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2266 unsigned OpNum = 0;
2267 Value *Op;
2268 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2269 OpNum+2 != Record.size())
2270 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002271
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002272 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002273 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2274 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002275 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002276 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002277 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002278 break;
2279 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002280 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002281 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002282 unsigned OpNum = 0;
2283 Value *BasePtr;
2284 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002285 return Error("Invalid GEP record");
2286
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002287 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002288 while (OpNum != Record.size()) {
2289 Value *Op;
2290 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002291 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002292 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002293 }
2294
Jay Foada9203102011-07-25 09:48:08 +00002295 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002296 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002297 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002298 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002299 break;
2300 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002301
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002302 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2303 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002304 unsigned OpNum = 0;
2305 Value *Agg;
2306 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2307 return Error("Invalid EXTRACTVAL record");
2308
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002309 SmallVector<unsigned, 4> EXTRACTVALIdx;
2310 for (unsigned RecSize = Record.size();
2311 OpNum != RecSize; ++OpNum) {
2312 uint64_t Index = Record[OpNum];
2313 if ((unsigned)Index != Index)
2314 return Error("Invalid EXTRACTVAL index");
2315 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002316 }
2317
Jay Foadfc6d3a42011-07-13 10:26:04 +00002318 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002319 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002320 break;
2321 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002322
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002323 case bitc::FUNC_CODE_INST_INSERTVAL: {
2324 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002325 unsigned OpNum = 0;
2326 Value *Agg;
2327 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2328 return Error("Invalid INSERTVAL record");
2329 Value *Val;
2330 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2331 return Error("Invalid INSERTVAL record");
2332
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002333 SmallVector<unsigned, 4> INSERTVALIdx;
2334 for (unsigned RecSize = Record.size();
2335 OpNum != RecSize; ++OpNum) {
2336 uint64_t Index = Record[OpNum];
2337 if ((unsigned)Index != Index)
2338 return Error("Invalid INSERTVAL index");
2339 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002340 }
2341
Jay Foadfc6d3a42011-07-13 10:26:04 +00002342 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002343 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002344 break;
2345 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002346
Chris Lattnerabfbf852007-05-06 00:21:25 +00002347 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002348 // obsolete form of select
2349 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002350 unsigned OpNum = 0;
2351 Value *TrueVal, *FalseVal, *Cond;
2352 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002353 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2354 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002355 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002356
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002357 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002358 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002359 break;
2360 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002361
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002362 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2363 // new form of select
2364 // handles select i1 or select [N x i1]
2365 unsigned OpNum = 0;
2366 Value *TrueVal, *FalseVal, *Cond;
2367 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002368 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002369 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2370 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002371
2372 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002373 if (VectorType* vector_type =
2374 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002375 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002376 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002377 return Error("Invalid SELECT condition type");
2378 } else {
2379 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002380 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002381 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002382 }
2383
Gabor Greif051a9502008-04-06 20:25:17 +00002384 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002385 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002386 break;
2387 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002388
Chris Lattner01ff65f2007-05-02 05:16:49 +00002389 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002390 unsigned OpNum = 0;
2391 Value *Vec, *Idx;
2392 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002393 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002394 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002395 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002396 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002397 break;
2398 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002399
Chris Lattner01ff65f2007-05-02 05:16:49 +00002400 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002401 unsigned OpNum = 0;
2402 Value *Vec, *Elt, *Idx;
2403 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002404 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002405 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002406 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002407 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002408 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002409 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002410 break;
2411 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002412
Chris Lattnerabfbf852007-05-06 00:21:25 +00002413 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2414 unsigned OpNum = 0;
2415 Value *Vec1, *Vec2, *Mask;
2416 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002417 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002418 return Error("Invalid SHUFFLEVEC record");
2419
Mon P Wangaeb06d22008-11-10 04:46:22 +00002420 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002421 return Error("Invalid SHUFFLEVEC record");
2422 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002423 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002424 break;
2425 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002426
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002427 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2428 // Old form of ICmp/FCmp returning bool
2429 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2430 // both legal on vectors but had different behaviour.
2431 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2432 // FCmp/ICmp returning bool or vector of bool
2433
Chris Lattner7337ab92007-05-06 00:00:00 +00002434 unsigned OpNum = 0;
2435 Value *LHS, *RHS;
2436 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002437 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002438 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002439 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002440
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002441 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002442 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002443 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002444 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002445 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002446 break;
2447 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002448
Chris Lattner231cbcb2007-05-02 04:27:25 +00002449 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002450 {
2451 unsigned Size = Record.size();
2452 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002453 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002454 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002455 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002456 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002457
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002458 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002459 Value *Op = NULL;
2460 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2461 return Error("Invalid RET record");
2462 if (OpNum != Record.size())
2463 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002464
Chris Lattner96a74c52011-06-17 18:09:11 +00002465 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002466 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002467 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002468 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002469 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002470 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002471 return Error("Invalid BR record");
2472 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2473 if (TrueDest == 0)
2474 return Error("Invalid BR record");
2475
Devang Patele8e02132009-09-18 19:26:43 +00002476 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002477 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002478 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002479 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002480 else {
2481 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002482 Value *Cond = getValue(Record, 2, NextValueNo,
2483 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002484 if (FalseDest == 0 || Cond == 0)
2485 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002486 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002487 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002488 }
2489 break;
2490 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002491 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002492 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002493 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002494 // "New" SwitchInst format with case ranges. The changes to write this
2495 // format were reverted but we still recognize bitcode that uses it.
2496 // Hopefully someday we will have support for case ranges and can use
2497 // this format again.
Michael Ilseman407a6162012-11-15 22:34:00 +00002498
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002499 Type *OpTy = getTypeByID(Record[1]);
2500 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2501
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002502 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002503 BasicBlock *Default = getBasicBlock(Record[3]);
2504 if (OpTy == 0 || Cond == 0 || Default == 0)
2505 return Error("Invalid SWITCH record");
2506
2507 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002508
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002509 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2510 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002511
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002512 unsigned CurIdx = 5;
2513 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002514 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002515 unsigned NumItems = Record[CurIdx++];
2516 for (unsigned ci = 0; ci != NumItems; ++ci) {
2517 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002518
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002519 APInt Low;
2520 unsigned ActiveWords = 1;
2521 if (ValueBitWidth > 64)
2522 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002523 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2524 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002525 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002526
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002527 if (!isSingleNumber) {
2528 ActiveWords = 1;
2529 if (ValueBitWidth > 64)
2530 ActiveWords = Record[CurIdx++];
2531 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002532 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2533 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002534 CurIdx += ActiveWords;
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002535
2536 // FIXME: It is not clear whether values in the range should be
2537 // compared as signed or unsigned values. The partially
2538 // implemented changes that used this format in the past used
2539 // unsigned comparisons.
2540 for ( ; Low.ule(High); ++Low)
2541 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002542 } else
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002543 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002544 }
2545 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002546 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2547 cve = CaseVals.end(); cvi != cve; ++cvi)
2548 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002549 }
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002550 I = SI;
2551 break;
2552 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002553
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002554 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002555
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002556 if (Record.size() < 3 || (Record.size() & 1) == 0)
2557 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002558 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002559 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002560 BasicBlock *Default = getBasicBlock(Record[2]);
2561 if (OpTy == 0 || Cond == 0 || Default == 0)
2562 return Error("Invalid SWITCH record");
2563 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002564 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002565 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002566 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002567 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002568 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2569 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2570 if (CaseVal == 0 || DestBB == 0) {
2571 delete SI;
2572 return Error("Invalid SWITCH record!");
2573 }
2574 SI->addCase(CaseVal, DestBB);
2575 }
2576 I = SI;
2577 break;
2578 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002579 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002580 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002581 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002582 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002583 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002584 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002585 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002586 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002587 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002588 InstructionList.push_back(IBI);
2589 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2590 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2591 IBI->addDestination(DestBB);
2592 } else {
2593 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002594 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002595 }
2596 }
2597 I = IBI;
2598 break;
2599 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002600
Duncan Sandsdc024672007-11-27 13:23:08 +00002601 case bitc::FUNC_CODE_INST_INVOKE: {
2602 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002603 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002604 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002605 unsigned CCInfo = Record[1];
2606 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2607 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002608
Chris Lattnera9bb7132007-05-08 05:38:01 +00002609 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002610 Value *Callee;
2611 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002612 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002613
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002614 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2615 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002616 dyn_cast<FunctionType>(CalleeTy->getElementType());
2617
2618 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002619 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2620 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002621 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002622
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002623 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002624 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002625 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2626 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002627 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002628 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002629
Chris Lattner7337ab92007-05-06 00:00:00 +00002630 if (!FTy->isVarArg()) {
2631 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002632 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002633 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002634 // Read type/value pairs for varargs params.
2635 while (OpNum != Record.size()) {
2636 Value *Op;
2637 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2638 return Error("Invalid INVOKE record");
2639 Ops.push_back(Op);
2640 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002641 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002642
Jay Foada3efbb12011-07-15 08:37:34 +00002643 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002644 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002645 cast<InvokeInst>(I)->setCallingConv(
2646 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002647 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002648 break;
2649 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002650 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2651 unsigned Idx = 0;
2652 Value *Val = 0;
2653 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2654 return Error("Invalid RESUME record");
2655 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002656 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002657 break;
2658 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002659 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002660 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002661 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002662 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002663 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002664 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002665 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002666 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002667 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002668
Jay Foad3ecfc862011-03-30 11:28:46 +00002669 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002670 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002671
Chris Lattner15e6d172007-05-04 19:11:41 +00002672 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002673 Value *V;
2674 // With the new function encoding, it is possible that operands have
2675 // negative IDs (for forward references). Use a signed VBR
2676 // representation to keep the encoding small.
2677 if (UseRelativeIDs)
2678 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2679 else
2680 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002681 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002682 if (!V || !BB) return Error("Invalid PHI record");
2683 PN->addIncoming(V, BB);
2684 }
2685 I = PN;
2686 break;
2687 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002688
Bill Wendlinge6e88262011-08-12 20:24:12 +00002689 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2690 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2691 unsigned Idx = 0;
2692 if (Record.size() < 4)
2693 return Error("Invalid LANDINGPAD record");
2694 Type *Ty = getTypeByID(Record[Idx++]);
2695 if (!Ty) return Error("Invalid LANDINGPAD record");
2696 Value *PersFn = 0;
2697 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2698 return Error("Invalid LANDINGPAD record");
2699
2700 bool IsCleanup = !!Record[Idx++];
2701 unsigned NumClauses = Record[Idx++];
2702 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2703 LP->setCleanup(IsCleanup);
2704 for (unsigned J = 0; J != NumClauses; ++J) {
2705 LandingPadInst::ClauseType CT =
2706 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2707 Value *Val;
2708
2709 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2710 delete LP;
2711 return Error("Invalid LANDINGPAD record");
2712 }
2713
2714 assert((CT != LandingPadInst::Catch ||
2715 !isa<ArrayType>(Val->getType())) &&
2716 "Catch clause has a invalid type!");
2717 assert((CT != LandingPadInst::Filter ||
2718 isa<ArrayType>(Val->getType())) &&
2719 "Filter clause has invalid type!");
2720 LP->addClause(Val);
2721 }
2722
2723 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002724 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002725 break;
2726 }
2727
Chris Lattner96a74c52011-06-17 18:09:11 +00002728 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2729 if (Record.size() != 4)
2730 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002731 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002732 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002733 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002734 Value *Size = getFnValueByID(Record[2], OpTy);
2735 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002736 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002737 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002738 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002739 break;
2740 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002741 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002742 unsigned OpNum = 0;
2743 Value *Op;
2744 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2745 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002746 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002747
Chris Lattner7337ab92007-05-06 00:00:00 +00002748 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002749 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002750 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002751 }
Eli Friedman21006d42011-08-09 23:02:53 +00002752 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2753 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2754 unsigned OpNum = 0;
2755 Value *Op;
2756 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2757 OpNum+4 != Record.size())
2758 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002759
Eli Friedman21006d42011-08-09 23:02:53 +00002760
2761 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2762 if (Ordering == NotAtomic || Ordering == Release ||
2763 Ordering == AcquireRelease)
2764 return Error("Invalid LOADATOMIC record");
2765 if (Ordering != NotAtomic && Record[OpNum] == 0)
2766 return Error("Invalid LOADATOMIC record");
2767 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2768
2769 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2770 Ordering, SynchScope);
2771 InstructionList.push_back(I);
2772 break;
2773 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002774 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002775 unsigned OpNum = 0;
2776 Value *Val, *Ptr;
2777 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002778 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002779 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2780 OpNum+2 != Record.size())
2781 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002782
Christopher Lambfe63fb92007-12-11 08:59:05 +00002783 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002784 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002785 break;
2786 }
Eli Friedman21006d42011-08-09 23:02:53 +00002787 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2788 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2789 unsigned OpNum = 0;
2790 Value *Val, *Ptr;
2791 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002792 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002793 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2794 OpNum+4 != Record.size())
2795 return Error("Invalid STOREATOMIC record");
2796
2797 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002798 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002799 Ordering == AcquireRelease)
2800 return Error("Invalid STOREATOMIC record");
2801 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2802 if (Ordering != NotAtomic && Record[OpNum] == 0)
2803 return Error("Invalid STOREATOMIC record");
2804
2805 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2806 Ordering, SynchScope);
2807 InstructionList.push_back(I);
2808 break;
2809 }
Eli Friedmanff030482011-07-28 21:48:00 +00002810 case bitc::FUNC_CODE_INST_CMPXCHG: {
2811 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2812 unsigned OpNum = 0;
2813 Value *Ptr, *Cmp, *New;
2814 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002815 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002816 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002817 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002818 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2819 OpNum+3 != Record.size())
2820 return Error("Invalid CMPXCHG record");
2821 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002822 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002823 return Error("Invalid CMPXCHG record");
2824 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2825 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2826 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2827 InstructionList.push_back(I);
2828 break;
2829 }
2830 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2831 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2832 unsigned OpNum = 0;
2833 Value *Ptr, *Val;
2834 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002835 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002836 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2837 OpNum+4 != Record.size())
2838 return Error("Invalid ATOMICRMW record");
2839 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2840 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2841 Operation > AtomicRMWInst::LAST_BINOP)
2842 return Error("Invalid ATOMICRMW record");
2843 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002844 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002845 return Error("Invalid ATOMICRMW record");
2846 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2847 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2848 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2849 InstructionList.push_back(I);
2850 break;
2851 }
Eli Friedman47f35132011-07-25 23:16:38 +00002852 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2853 if (2 != Record.size())
2854 return Error("Invalid FENCE record");
2855 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2856 if (Ordering == NotAtomic || Ordering == Unordered ||
2857 Ordering == Monotonic)
2858 return Error("Invalid FENCE record");
2859 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2860 I = new FenceInst(Context, Ordering, SynchScope);
2861 InstructionList.push_back(I);
2862 break;
2863 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002864 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002865 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2866 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002867 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002868
Bill Wendling99faa3b2012-12-07 23:16:57 +00002869 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002870 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002871
Chris Lattnera9bb7132007-05-08 05:38:01 +00002872 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002873 Value *Callee;
2874 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2875 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002876
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002877 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2878 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002879 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002880 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002881 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002882
Chris Lattner0579f7f2007-05-03 22:04:19 +00002883 SmallVector<Value*, 16> Args;
2884 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002885 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002886 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002887 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002888 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002889 Args.push_back(getValue(Record, OpNum, NextValueNo,
2890 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002891 if (Args.back() == 0) return Error("Invalid CALL record");
2892 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002893
Chris Lattner0579f7f2007-05-03 22:04:19 +00002894 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002895 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002896 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002897 return Error("Invalid CALL record");
2898 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002899 while (OpNum != Record.size()) {
2900 Value *Op;
2901 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2902 return Error("Invalid CALL record");
2903 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002904 }
2905 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002906
Jay Foada3efbb12011-07-15 08:37:34 +00002907 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002908 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002909 cast<CallInst>(I)->setCallingConv(
2910 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002911 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002912 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002913 break;
2914 }
2915 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2916 if (Record.size() < 3)
2917 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002918 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002919 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002920 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002921 if (!OpTy || !Op || !ResTy)
2922 return Error("Invalid VAARG record");
2923 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002924 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002925 break;
2926 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002927 }
2928
2929 // Add instruction to end of current BB. If there is no current BB, reject
2930 // this file.
2931 if (CurBB == 0) {
2932 delete I;
2933 return Error("Invalid instruction with no BB");
2934 }
2935 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002936
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002937 // If this was a terminator instruction, move to the next block.
2938 if (isa<TerminatorInst>(I)) {
2939 ++CurBBNo;
2940 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2941 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002942
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002943 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002944 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002945 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002946 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002947
Chris Lattner5a4251c2013-01-20 02:13:19 +00002948OutOfRecordLoop:
Joe Abbeyacb61942013-02-06 22:14:06 +00002949
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002950 // Check the function list for unresolved values.
2951 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2952 if (A->getParent() == 0) {
2953 // We found at least one unresolved value. Nuke them all to avoid leaks.
2954 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002955 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002956 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002957 delete A;
2958 }
2959 }
Chris Lattner35a04702007-05-04 03:50:29 +00002960 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002961 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002962 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002963
Dan Gohman064ff3e2010-08-25 20:23:38 +00002964 // FIXME: Check for unresolved forward-declared metadata references
2965 // and clean up leaks.
2966
Chris Lattner50b136d2009-10-28 05:53:48 +00002967 // See if anything took the address of blocks in this function. If so,
2968 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002969 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2970 BlockAddrFwdRefs.find(F);
2971 if (BAFRI != BlockAddrFwdRefs.end()) {
2972 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2973 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2974 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002975 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002976 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00002977
Chris Lattner50b136d2009-10-28 05:53:48 +00002978 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002979 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002980 FwdRef->eraseFromParent();
2981 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002982
Chris Lattner50b136d2009-10-28 05:53:48 +00002983 BlockAddrFwdRefs.erase(BAFRI);
2984 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002985
Chris Lattner980e5aa2007-05-01 05:52:21 +00002986 // Trim the value list down to the size it was before we parsed this function.
2987 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002988 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002989 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002990 return false;
2991}
2992
Derek Schuff2ea93872012-02-06 22:30:29 +00002993/// FindFunctionInStream - Find the function body in the bitcode stream
2994bool BitcodeReader::FindFunctionInStream(Function *F,
2995 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2996 while (DeferredFunctionInfoIterator->second == 0) {
2997 if (Stream.AtEndOfStream())
2998 return Error("Could not find Function in stream");
2999 // ParseModule will parse the next body in the stream and set its
3000 // position in the DeferredFunctionInfo map.
3001 if (ParseModule(true)) return true;
3002 }
3003 return false;
3004}
3005
Chris Lattnerb348bb82007-05-18 04:02:46 +00003006//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003007// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00003008//===----------------------------------------------------------------------===//
3009
3010
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003011bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3012 if (const Function *F = dyn_cast<Function>(GV)) {
3013 return F->isDeclaration() &&
3014 DeferredFunctionInfo.count(const_cast<Function*>(F));
3015 }
3016 return false;
3017}
Daniel Dunbara279bc32009-09-20 02:20:51 +00003018
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003019bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
3020 Function *F = dyn_cast<Function>(GV);
3021 // If it's not a function or is already material, ignore the request.
3022 if (!F || !F->isMaterializable()) return false;
3023
3024 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00003025 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00003026 // If its position is recorded as 0, its body is somewhere in the stream
3027 // but we haven't seen it yet.
3028 if (DFII->second == 0)
3029 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003030
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003031 // Move the bit stream to the saved position of the deferred function body.
3032 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003033
Chris Lattnerb348bb82007-05-18 04:02:46 +00003034 if (ParseFunctionBody(F)) {
3035 if (ErrInfo) *ErrInfo = ErrorString;
3036 return true;
3037 }
Chandler Carruth69940402007-08-04 01:51:18 +00003038
3039 // Upgrade any old intrinsic calls in the function.
3040 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3041 E = UpgradedIntrinsics.end(); I != E; ++I) {
3042 if (I->first != I->second) {
3043 for (Value::use_iterator UI = I->first->use_begin(),
3044 UE = I->first->use_end(); UI != UE; ) {
3045 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3046 UpgradeIntrinsicCall(CI, I->second);
3047 }
3048 }
3049 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003050
Chris Lattnerb348bb82007-05-18 04:02:46 +00003051 return false;
3052}
3053
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003054bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3055 const Function *F = dyn_cast<Function>(GV);
3056 if (!F || F->isDeclaration())
3057 return false;
3058 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3059}
3060
3061void BitcodeReader::Dematerialize(GlobalValue *GV) {
3062 Function *F = dyn_cast<Function>(GV);
3063 // If this function isn't dematerializable, this is a noop.
3064 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00003065 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003066
Chris Lattnerb348bb82007-05-18 04:02:46 +00003067 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003068
Chris Lattnerb348bb82007-05-18 04:02:46 +00003069 // Just forget the function body, we can remat it later.
3070 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00003071}
3072
3073
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003074bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
3075 assert(M == TheModule &&
3076 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00003077 // Iterate over the module, deserializing any functions that are still on
3078 // disk.
3079 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3080 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003081 if (F->isMaterializable() &&
3082 Materialize(F, ErrInfo))
3083 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00003084
Derek Schuff0ffe6982012-02-29 00:07:09 +00003085 // At this point, if there are any function bodies, the current bit is
3086 // pointing to the END_BLOCK record after them. Now make sure the rest
3087 // of the bits in the module have been read.
3088 if (NextUnreadBit)
3089 ParseModule(true);
3090
Daniel Dunbara279bc32009-09-20 02:20:51 +00003091 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3092 // delete the old functions to clean up. We can't do this unless the entire
3093 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00003094 // with calls to the old function.
3095 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3096 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3097 if (I->first != I->second) {
3098 for (Value::use_iterator UI = I->first->use_begin(),
3099 UE = I->first->use_end(); UI != UE; ) {
3100 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3101 UpgradeIntrinsicCall(CI, I->second);
3102 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00003103 if (!I->first->use_empty())
3104 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00003105 I->first->eraseFromParent();
3106 }
3107 }
3108 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00003109
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003110 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003111}
3112
Derek Schuff2ea93872012-02-06 22:30:29 +00003113bool BitcodeReader::InitStream() {
3114 if (LazyStreamer) return InitLazyStream();
3115 return InitStreamFromBuffer();
3116}
3117
3118bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00003119 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00003120 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3121
3122 if (Buffer->getBufferSize() & 3) {
3123 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3124 return Error("Invalid bitcode signature");
3125 else
3126 return Error("Bitcode stream should be a multiple of 4 bytes in length");
3127 }
3128
3129 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3130 // The magic number is 0x0B17C0DE stored in little endian.
3131 if (isBitcodeWrapper(BufPtr, BufEnd))
3132 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3133 return Error("Invalid bitcode wrapper header");
3134
3135 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3136 Stream.init(*StreamFile);
3137
3138 return false;
3139}
3140
3141bool BitcodeReader::InitLazyStream() {
3142 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3143 // see it.
3144 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3145 StreamFile.reset(new BitstreamReader(Bytes));
3146 Stream.init(*StreamFile);
3147
3148 unsigned char buf[16];
Benjamin Kramer49a6a8d2013-05-24 10:54:58 +00003149 if (Bytes->readBytes(0, 16, buf) == -1)
Derek Schuff2ea93872012-02-06 22:30:29 +00003150 return Error("Bitcode stream must be at least 16 bytes in length");
3151
3152 if (!isBitcode(buf, buf + 16))
3153 return Error("Invalid bitcode signature");
3154
3155 if (isBitcodeWrapper(buf, buf + 4)) {
3156 const unsigned char *bitcodeStart = buf;
3157 const unsigned char *bitcodeEnd = buf + 16;
3158 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3159 Bytes->dropLeadingBytes(bitcodeStart - buf);
3160 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3161 }
3162 return false;
3163}
Chris Lattner48f84872007-05-01 04:59:48 +00003164
Chris Lattnerc453f762007-04-29 07:54:31 +00003165//===----------------------------------------------------------------------===//
3166// External interface
3167//===----------------------------------------------------------------------===//
3168
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003169/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00003170///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003171Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3172 LLVMContext& Context,
3173 std::string *ErrMsg) {
3174 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00003175 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003176 M->setMaterializer(R);
3177 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00003178 if (ErrMsg)
3179 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003180
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003181 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00003182 return 0;
3183 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003184 // Have the BitcodeReader dtor delete 'Buffer'.
3185 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00003186
3187 R->materializeForwardReferencedFunctions();
3188
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003189 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00003190}
3191
Derek Schuff2ea93872012-02-06 22:30:29 +00003192
3193Module *llvm::getStreamedBitcodeModule(const std::string &name,
3194 DataStreamer *streamer,
3195 LLVMContext &Context,
3196 std::string *ErrMsg) {
3197 Module *M = new Module(name, Context);
3198 BitcodeReader *R = new BitcodeReader(streamer, Context);
3199 M->setMaterializer(R);
3200 if (R->ParseBitcodeInto(M)) {
3201 if (ErrMsg)
3202 *ErrMsg = R->getErrorString();
3203 delete M; // Also deletes R.
3204 return 0;
3205 }
3206 R->setBufferOwned(false); // no buffer to delete
3207 return M;
3208}
3209
Chris Lattnerc453f762007-04-29 07:54:31 +00003210/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3211/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003212Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00003213 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003214 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3215 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003216
3217 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3218 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003219 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003220
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003221 // Read in the entire module, and destroy the BitcodeReader.
3222 if (M->MaterializeAllPermanently(ErrMsg)) {
3223 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003224 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003225 }
Bill Wendling34711742010-10-06 01:22:42 +00003226
Chad Rosiercbbb0962011-12-07 21:44:12 +00003227 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3228 // written. We must defer until the Module has been fully materialized.
3229
Chris Lattnerc453f762007-04-29 07:54:31 +00003230 return M;
3231}
Bill Wendling34711742010-10-06 01:22:42 +00003232
3233std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3234 LLVMContext& Context,
3235 std::string *ErrMsg) {
3236 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3237 // Don't let the BitcodeReader dtor delete 'Buffer'.
3238 R->setBufferOwned(false);
3239
3240 std::string Triple("");
3241 if (R->ParseTriple(Triple))
3242 if (ErrMsg)
3243 *ErrMsg = R->getErrorString();
3244
3245 delete R;
3246 return Triple;
3247}