blob: 1661990f065d918c70e13b7ba314eb4e7afe401d [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"
Manman Ren804f0342013-09-28 00:22:27 +000020#include "llvm/IR/LLVMContext.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/Module.h"
22#include "llvm/IR/OperandTraits.h"
23#include "llvm/IR/Operator.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000024#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000025#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000026#include "llvm/Support/MemoryBuffer.h"
Tobias Grossere7bc5bb2013-07-26 04:16:55 +000027#include "llvm/Support/raw_ostream.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000028using namespace llvm;
29
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000030enum {
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
32};
33
Rafael Espindola47f79bb2012-01-02 07:49:53 +000034void BitcodeReader::materializeForwardReferencedFunctions() {
35 while (!BlockAddrFwdRefs.empty()) {
36 Function *F = BlockAddrFwdRefs.begin()->first;
37 F->Materialize();
38 }
39}
40
Chris Lattnerb348bb82007-05-18 04:02:46 +000041void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000042 if (BufferOwned)
43 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000044 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000045 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000046 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000047 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000048
Bill Wendling99faa3b2012-12-07 23:16:57 +000049 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000050 std::vector<BasicBlock*>().swap(FunctionBBs);
51 std::vector<Function*>().swap(FunctionsWithBodies);
52 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000053 MDKindMap.clear();
Benjamin Kramer122f5e52012-09-21 14:34:31 +000054
55 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
Chris Lattnerc453f762007-04-29 07:54:31 +000056}
57
Chris Lattner48c85b82007-05-04 03:30:17 +000058//===----------------------------------------------------------------------===//
59// Helper functions to implement forward reference resolution, etc.
60//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000061
Chris Lattnercaee0dc2007-04-22 06:23:29 +000062/// ConvertToString - Convert a string from a record into an std::string, return
63/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000064template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000065static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000066 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000067 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000068 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000069
Chris Lattner15e6d172007-05-04 19:11:41 +000070 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
71 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000072 return false;
73}
74
75static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
76 switch (Val) {
77 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000078 case 0: return GlobalValue::ExternalLinkage;
79 case 1: return GlobalValue::WeakAnyLinkage;
80 case 2: return GlobalValue::AppendingLinkage;
81 case 3: return GlobalValue::InternalLinkage;
82 case 4: return GlobalValue::LinkOnceAnyLinkage;
83 case 5: return GlobalValue::DLLImportLinkage;
84 case 6: return GlobalValue::DLLExportLinkage;
85 case 7: return GlobalValue::ExternalWeakLinkage;
86 case 8: return GlobalValue::CommonLinkage;
87 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000088 case 10: return GlobalValue::WeakODRLinkage;
89 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000090 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000091 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000092 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000093 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000094 }
95}
96
97static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
98 switch (Val) {
99 default: // Map unknown visibilities to default.
100 case 0: return GlobalValue::DefaultVisibility;
101 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000102 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000103 }
104}
105
Hans Wennborgce718ff2012-06-23 11:37:03 +0000106static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
107 switch (Val) {
108 case 0: return GlobalVariable::NotThreadLocal;
109 default: // Map unknown non-zero value to general dynamic.
110 case 1: return GlobalVariable::GeneralDynamicTLSModel;
111 case 2: return GlobalVariable::LocalDynamicTLSModel;
112 case 3: return GlobalVariable::InitialExecTLSModel;
113 case 4: return GlobalVariable::LocalExecTLSModel;
114 }
115}
116
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000117static int GetDecodedCastOpcode(unsigned Val) {
118 switch (Val) {
119 default: return -1;
120 case bitc::CAST_TRUNC : return Instruction::Trunc;
121 case bitc::CAST_ZEXT : return Instruction::ZExt;
122 case bitc::CAST_SEXT : return Instruction::SExt;
123 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
124 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
125 case bitc::CAST_UITOFP : return Instruction::UIToFP;
126 case bitc::CAST_SITOFP : return Instruction::SIToFP;
127 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
128 case bitc::CAST_FPEXT : return Instruction::FPExt;
129 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
130 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
131 case bitc::CAST_BITCAST : return Instruction::BitCast;
132 }
133}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000134static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000135 switch (Val) {
136 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000137 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000138 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000139 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000140 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000141 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000142 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000143 case bitc::BINOP_UDIV: return Instruction::UDiv;
144 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000145 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000146 case bitc::BINOP_UREM: return Instruction::URem;
147 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000148 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000149 case bitc::BINOP_SHL: return Instruction::Shl;
150 case bitc::BINOP_LSHR: return Instruction::LShr;
151 case bitc::BINOP_ASHR: return Instruction::AShr;
152 case bitc::BINOP_AND: return Instruction::And;
153 case bitc::BINOP_OR: return Instruction::Or;
154 case bitc::BINOP_XOR: return Instruction::Xor;
155 }
156}
157
Eli Friedmanff030482011-07-28 21:48:00 +0000158static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
159 switch (Val) {
160 default: return AtomicRMWInst::BAD_BINOP;
161 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
162 case bitc::RMW_ADD: return AtomicRMWInst::Add;
163 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
164 case bitc::RMW_AND: return AtomicRMWInst::And;
165 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
166 case bitc::RMW_OR: return AtomicRMWInst::Or;
167 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
168 case bitc::RMW_MAX: return AtomicRMWInst::Max;
169 case bitc::RMW_MIN: return AtomicRMWInst::Min;
170 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
171 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
172 }
173}
174
Eli Friedman47f35132011-07-25 23:16:38 +0000175static AtomicOrdering GetDecodedOrdering(unsigned Val) {
176 switch (Val) {
177 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
178 case bitc::ORDERING_UNORDERED: return Unordered;
179 case bitc::ORDERING_MONOTONIC: return Monotonic;
180 case bitc::ORDERING_ACQUIRE: return Acquire;
181 case bitc::ORDERING_RELEASE: return Release;
182 case bitc::ORDERING_ACQREL: return AcquireRelease;
183 default: // Map unknown orderings to sequentially-consistent.
184 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
185 }
186}
187
188static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
189 switch (Val) {
190 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
191 default: // Map unknown scopes to cross-thread.
192 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
193 }
194}
195
Gabor Greifefe65362008-05-10 08:32:32 +0000196namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000197namespace {
198 /// @brief A class for maintaining the slot number definition
199 /// as a placeholder for the actual definition for forward constants defs.
200 class ConstantPlaceHolder : public ConstantExpr {
Craig Topper86a1c322012-09-15 17:09:36 +0000201 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greif051a9502008-04-06 20:25:17 +0000202 public:
203 // allocate space for exactly one operand
204 void *operator new(size_t s) {
205 return User::operator new(s, 1);
206 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000207 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000208 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000209 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000210 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000211
Chris Lattnerea693df2008-08-21 02:34:16 +0000212 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattnerea693df2008-08-21 02:34:16 +0000213 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000214 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000215 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
216 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000217
218
Gabor Greifefe65362008-05-10 08:32:32 +0000219 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000220 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000221 };
222}
223
Chris Lattner46e77402009-03-31 22:55:09 +0000224// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000225template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000226struct OperandTraits<ConstantPlaceHolder> :
227 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000228};
Gabor Greifefe65362008-05-10 08:32:32 +0000229}
230
Chris Lattner46e77402009-03-31 22:55:09 +0000231
232void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
233 if (Idx == size()) {
234 push_back(V);
235 return;
236 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000237
Chris Lattner46e77402009-03-31 22:55:09 +0000238 if (Idx >= size())
239 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000240
Chris Lattner46e77402009-03-31 22:55:09 +0000241 WeakVH &OldV = ValuePtrs[Idx];
242 if (OldV == 0) {
243 OldV = V;
244 return;
245 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000246
Chris Lattner46e77402009-03-31 22:55:09 +0000247 // Handle constants and non-constants (e.g. instrs) differently for
248 // efficiency.
249 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
250 ResolveConstants.push_back(std::make_pair(PHC, Idx));
251 OldV = V;
252 } else {
253 // If there was a forward reference to this value, replace it.
254 Value *PrevVal = OldV;
255 OldV->replaceAllUsesWith(V);
256 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000257 }
258}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000259
Gabor Greifefe65362008-05-10 08:32:32 +0000260
Chris Lattner522b7b12007-04-24 05:48:56 +0000261Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000262 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000263 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000264 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000265
Chris Lattner46e77402009-03-31 22:55:09 +0000266 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000267 assert(Ty == V->getType() && "Type mismatch in constant table!");
268 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000269 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000270
271 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000272 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000273 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000274 return C;
275}
276
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000277Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000278 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000279 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000280
Chris Lattner46e77402009-03-31 22:55:09 +0000281 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000282 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
283 return V;
284 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000285
Chris Lattner01ff65f2007-05-02 05:16:49 +0000286 // No type specified, must be invalid reference.
287 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000288
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000289 // Create and return a placeholder, which will later be RAUW'd.
290 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000291 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000292 return V;
293}
294
Chris Lattnerea693df2008-08-21 02:34:16 +0000295/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
296/// resolves any forward references. The idea behind this is that we sometimes
297/// get constants (such as large arrays) which reference *many* forward ref
298/// constants. Replacing each of these causes a lot of thrashing when
299/// building/reuniquing the constant. Instead of doing this, we look at all the
300/// uses and rewrite all the place holders at once for any constant that uses
301/// a placeholder.
302void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000303 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000304 // binary search.
305 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000306
Chris Lattnerea693df2008-08-21 02:34:16 +0000307 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000308
Chris Lattnerea693df2008-08-21 02:34:16 +0000309 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000310 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000311 Constant *Placeholder = ResolveConstants.back().first;
312 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000313
Chris Lattnerea693df2008-08-21 02:34:16 +0000314 // Loop over all users of the placeholder, updating them to reference the
315 // new value. If they reference more than one placeholder, update them all
316 // at once.
317 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000318 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000319 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000320
Chris Lattnerea693df2008-08-21 02:34:16 +0000321 // If the using object isn't uniqued, just update the operands. This
322 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000323 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000324 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000325 continue;
326 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000327
Chris Lattnerea693df2008-08-21 02:34:16 +0000328 // Otherwise, we have a constant that uses the placeholder. Replace that
329 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000330 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000331 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
332 I != E; ++I) {
333 Value *NewOp;
334 if (!isa<ConstantPlaceHolder>(*I)) {
335 // Not a placeholder reference.
336 NewOp = *I;
337 } else if (*I == Placeholder) {
338 // Common case is that it just references this one placeholder.
339 NewOp = RealVal;
340 } else {
341 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000342 ResolveConstantsTy::iterator It =
343 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000344 std::pair<Constant*, unsigned>(cast<Constant>(*I),
345 0));
346 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000347 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000348 }
349
350 NewOps.push_back(cast<Constant>(NewOp));
351 }
352
353 // Make the new constant.
354 Constant *NewC;
355 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000356 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000357 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000358 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000359 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000360 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000361 } else {
362 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000363 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000364 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000365
Chris Lattnerea693df2008-08-21 02:34:16 +0000366 UserC->replaceAllUsesWith(NewC);
367 UserC->destroyConstant();
368 NewOps.clear();
369 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000370
Nick Lewyckycb337992009-05-10 20:57:05 +0000371 // Update all ValueHandles, they should be the only users at this point.
372 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000373 delete Placeholder;
374 }
375}
376
Devang Pateld5ac4042009-08-04 06:00:18 +0000377void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
378 if (Idx == size()) {
379 push_back(V);
380 return;
381 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000382
Devang Pateld5ac4042009-08-04 06:00:18 +0000383 if (Idx >= size())
384 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000385
Devang Pateld5ac4042009-08-04 06:00:18 +0000386 WeakVH &OldV = MDValuePtrs[Idx];
387 if (OldV == 0) {
388 OldV = V;
389 return;
390 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000391
Devang Pateld5ac4042009-08-04 06:00:18 +0000392 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000393 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000394 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000395 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000396 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
397 // value for Idx.
398 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000399}
400
401Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
402 if (Idx >= size())
403 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000404
Devang Pateld5ac4042009-08-04 06:00:18 +0000405 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000406 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000407 return V;
408 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000409
Devang Pateld5ac4042009-08-04 06:00:18 +0000410 // Create and return a placeholder, which will later be RAUW'd.
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000411 Value *V = MDNode::getTemporary(Context, None);
Devang Pateld5ac4042009-08-04 06:00:18 +0000412 MDValuePtrs[Idx] = V;
413 return V;
414}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000415
Chris Lattner1afcace2011-07-09 17:41:24 +0000416Type *BitcodeReader::getTypeByID(unsigned ID) {
417 // The type table size is always specified correctly.
418 if (ID >= TypeList.size())
419 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000420
Chris Lattner1afcace2011-07-09 17:41:24 +0000421 if (Type *Ty = TypeList[ID])
422 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000423
Chris Lattner1afcace2011-07-09 17:41:24 +0000424 // If we have a forward reference, the only possible case is when it is to a
425 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000426 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000427}
428
Chris Lattner1afcace2011-07-09 17:41:24 +0000429
Chris Lattner48c85b82007-05-04 03:30:17 +0000430//===----------------------------------------------------------------------===//
431// Functions for parsing blocks from the bitcode file
432//===----------------------------------------------------------------------===//
433
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000434
435/// \brief This fills an AttrBuilder object with the LLVM attributes that have
436/// been decoded from the given integer. This function must stay in sync with
437/// 'encodeLLVMAttributesForBitcode'.
438static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
439 uint64_t EncodedAttrs) {
440 // FIXME: Remove in 4.0.
441
442 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
443 // the bits above 31 down by 11 bits.
444 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
445 assert((!Alignment || isPowerOf2_32(Alignment)) &&
446 "Alignment must be a power of two.");
447
448 if (Alignment)
449 B.addAlignmentAttr(Alignment);
Kostya Serebryanyab39afa2013-02-11 08:13:54 +0000450 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000451 (EncodedAttrs & 0xffff));
452}
453
Devang Patel05988662008-09-25 21:00:45 +0000454bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000455 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000456 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000457
Devang Patel19c87462008-09-26 22:53:05 +0000458 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000459 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000460
Chris Lattner48c85b82007-05-04 03:30:17 +0000461 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000462
Bill Wendling0c2f0ff2013-01-27 00:36:48 +0000463 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000464
Chris Lattner48c85b82007-05-04 03:30:17 +0000465 // Read all the records.
466 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000467 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000468
Chris Lattner5a4251c2013-01-20 02:13:19 +0000469 switch (Entry.Kind) {
470 case BitstreamEntry::SubBlock: // Handled for us already.
471 case BitstreamEntry::Error:
472 return Error("Error at end of PARAMATTR block");
473 case BitstreamEntry::EndBlock:
Chris Lattner48c85b82007-05-04 03:30:17 +0000474 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000475 case BitstreamEntry::Record:
476 // The interesting case.
477 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000478 }
Joe Abbeyacb61942013-02-06 22:14:06 +0000479
Chris Lattner48c85b82007-05-04 03:30:17 +0000480 // Read a record.
481 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000482 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner48c85b82007-05-04 03:30:17 +0000483 default: // Default behavior: ignore.
484 break;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000485 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
486 // FIXME: Remove in 4.0.
Chris Lattner48c85b82007-05-04 03:30:17 +0000487 if (Record.size() & 1)
488 return Error("Invalid ENTRY record");
489
Chris Lattner48c85b82007-05-04 03:30:17 +0000490 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling8232ece2013-01-29 01:43:29 +0000491 AttrBuilder B;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000492 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling8232ece2013-01-29 01:43:29 +0000493 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patel19c87462008-09-26 22:53:05 +0000494 }
Devang Patel19c87462008-09-26 22:53:05 +0000495
Bill Wendling99faa3b2012-12-07 23:16:57 +0000496 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000497 Attrs.clear();
498 break;
499 }
Bill Wendling48fbcfe2013-02-12 08:13:50 +0000500 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
501 for (unsigned i = 0, e = Record.size(); i != e; ++i)
502 Attrs.push_back(MAttributeGroups[Record[i]]);
503
504 MAttributes.push_back(AttributeSet::get(Context, Attrs));
505 Attrs.clear();
506 break;
507 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000508 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000509 }
510}
511
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000512bool BitcodeReader::ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
513 switch (Code) {
514 case bitc::ATTR_KIND_ALIGNMENT:
515 *Kind = Attribute::Alignment;
516 return false;
517 case bitc::ATTR_KIND_ALWAYS_INLINE:
518 *Kind = Attribute::AlwaysInline;
519 return false;
520 case bitc::ATTR_KIND_BUILTIN:
521 *Kind = Attribute::Builtin;
522 return false;
523 case bitc::ATTR_KIND_BY_VAL:
524 *Kind = Attribute::ByVal;
525 return false;
526 case bitc::ATTR_KIND_COLD:
527 *Kind = Attribute::Cold;
528 return false;
529 case bitc::ATTR_KIND_INLINE_HINT:
530 *Kind = Attribute::InlineHint;
531 return false;
532 case bitc::ATTR_KIND_IN_REG:
533 *Kind = Attribute::InReg;
534 return false;
535 case bitc::ATTR_KIND_MIN_SIZE:
536 *Kind = Attribute::MinSize;
537 return false;
538 case bitc::ATTR_KIND_NAKED:
539 *Kind = Attribute::Naked;
540 return false;
541 case bitc::ATTR_KIND_NEST:
542 *Kind = Attribute::Nest;
543 return false;
544 case bitc::ATTR_KIND_NO_ALIAS:
545 *Kind = Attribute::NoAlias;
546 return false;
547 case bitc::ATTR_KIND_NO_BUILTIN:
548 *Kind = Attribute::NoBuiltin;
549 return false;
550 case bitc::ATTR_KIND_NO_CAPTURE:
551 *Kind = Attribute::NoCapture;
552 return false;
553 case bitc::ATTR_KIND_NO_DUPLICATE:
554 *Kind = Attribute::NoDuplicate;
555 return false;
556 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
557 *Kind = Attribute::NoImplicitFloat;
558 return false;
559 case bitc::ATTR_KIND_NO_INLINE:
560 *Kind = Attribute::NoInline;
561 return false;
562 case bitc::ATTR_KIND_NON_LAZY_BIND:
563 *Kind = Attribute::NonLazyBind;
564 return false;
565 case bitc::ATTR_KIND_NO_RED_ZONE:
566 *Kind = Attribute::NoRedZone;
567 return false;
568 case bitc::ATTR_KIND_NO_RETURN:
569 *Kind = Attribute::NoReturn;
570 return false;
571 case bitc::ATTR_KIND_NO_UNWIND:
572 *Kind = Attribute::NoUnwind;
573 return false;
574 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
575 *Kind = Attribute::OptimizeForSize;
576 return false;
Andrea Di Biagio5768bb82013-08-23 11:53:55 +0000577 case bitc::ATTR_KIND_OPTIMIZE_NONE:
578 *Kind = Attribute::OptimizeNone;
579 return false;
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000580 case bitc::ATTR_KIND_READ_NONE:
581 *Kind = Attribute::ReadNone;
582 return false;
583 case bitc::ATTR_KIND_READ_ONLY:
584 *Kind = Attribute::ReadOnly;
585 return false;
586 case bitc::ATTR_KIND_RETURNED:
587 *Kind = Attribute::Returned;
588 return false;
589 case bitc::ATTR_KIND_RETURNS_TWICE:
590 *Kind = Attribute::ReturnsTwice;
591 return false;
592 case bitc::ATTR_KIND_S_EXT:
593 *Kind = Attribute::SExt;
594 return false;
595 case bitc::ATTR_KIND_STACK_ALIGNMENT:
596 *Kind = Attribute::StackAlignment;
597 return false;
598 case bitc::ATTR_KIND_STACK_PROTECT:
599 *Kind = Attribute::StackProtect;
600 return false;
601 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
602 *Kind = Attribute::StackProtectReq;
603 return false;
604 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
605 *Kind = Attribute::StackProtectStrong;
606 return false;
607 case bitc::ATTR_KIND_STRUCT_RET:
608 *Kind = Attribute::StructRet;
609 return false;
610 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
611 *Kind = Attribute::SanitizeAddress;
612 return false;
613 case bitc::ATTR_KIND_SANITIZE_THREAD:
614 *Kind = Attribute::SanitizeThread;
615 return false;
616 case bitc::ATTR_KIND_SANITIZE_MEMORY:
617 *Kind = Attribute::SanitizeMemory;
618 return false;
619 case bitc::ATTR_KIND_UW_TABLE:
620 *Kind = Attribute::UWTable;
621 return false;
622 case bitc::ATTR_KIND_Z_EXT:
623 *Kind = Attribute::ZExt;
624 return false;
625 default:
Rafael Espindolacc8c6732013-10-31 04:20:23 +0000626 return Error("Unknown attribute kind");
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000627 }
628}
629
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000630bool BitcodeReader::ParseAttributeGroupBlock() {
631 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
632 return Error("Malformed block record");
633
634 if (!MAttributeGroups.empty())
635 return Error("Multiple PARAMATTR_GROUP blocks found!");
636
637 SmallVector<uint64_t, 64> Record;
638
639 // Read all the records.
640 while (1) {
641 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
642
643 switch (Entry.Kind) {
644 case BitstreamEntry::SubBlock: // Handled for us already.
645 case BitstreamEntry::Error:
646 return Error("Error at end of PARAMATTR_GROUP block");
647 case BitstreamEntry::EndBlock:
648 return false;
649 case BitstreamEntry::Record:
650 // The interesting case.
651 break;
652 }
653
654 // Read a record.
655 Record.clear();
656 switch (Stream.readRecord(Entry.ID, Record)) {
657 default: // Default behavior: ignore.
658 break;
659 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
660 if (Record.size() < 3)
661 return Error("Invalid ENTRY record");
662
Bill Wendling04ef4be2013-02-11 22:32:29 +0000663 uint64_t GrpID = Record[0];
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000664 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
665
666 AttrBuilder B;
667 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
668 if (Record[i] == 0) { // Enum attribute
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000669 Attribute::AttrKind Kind;
670 if (ParseAttrKind(Record[++i], &Kind))
671 return true;
672
673 B.addAttribute(Kind);
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000674 } else if (Record[i] == 1) { // Align attribute
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000675 Attribute::AttrKind Kind;
676 if (ParseAttrKind(Record[++i], &Kind))
677 return true;
678 if (Kind == Attribute::Alignment)
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000679 B.addAlignmentAttr(Record[++i]);
680 else
681 B.addStackAlignmentAttr(Record[++i]);
682 } else { // String attribute
Bill Wendling04ef4be2013-02-11 22:32:29 +0000683 assert((Record[i] == 3 || Record[i] == 4) &&
684 "Invalid attribute group entry");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000685 bool HasValue = (Record[i++] == 4);
686 SmallString<64> KindStr;
687 SmallString<64> ValStr;
688
689 while (Record[i] != 0 && i != e)
690 KindStr += Record[i++];
Bill Wendling04ef4be2013-02-11 22:32:29 +0000691 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000692
693 if (HasValue) {
694 // Has a value associated with it.
Bill Wendling04ef4be2013-02-11 22:32:29 +0000695 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000696 while (Record[i] != 0 && i != e)
697 ValStr += Record[i++];
Bill Wendling04ef4be2013-02-11 22:32:29 +0000698 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000699 }
700
701 B.addAttribute(KindStr.str(), ValStr.str());
702 }
703 }
704
Bill Wendling04ef4be2013-02-11 22:32:29 +0000705 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000706 break;
707 }
708 }
709 }
710}
711
Chris Lattner86697142007-05-01 05:01:34 +0000712bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000713 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000714 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000715
Chris Lattner1afcace2011-07-09 17:41:24 +0000716 return ParseTypeTableBody();
717}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000718
Chris Lattner1afcace2011-07-09 17:41:24 +0000719bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000720 if (!TypeList.empty())
721 return Error("Multiple TYPE_BLOCKs found!");
722
723 SmallVector<uint64_t, 64> Record;
724 unsigned NumRecords = 0;
725
Chris Lattner1afcace2011-07-09 17:41:24 +0000726 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000727
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000728 // Read all the records for this type table.
729 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000730 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000731
Chris Lattner5a4251c2013-01-20 02:13:19 +0000732 switch (Entry.Kind) {
733 case BitstreamEntry::SubBlock: // Handled for us already.
734 case BitstreamEntry::Error:
735 Error("Error in the type table block");
736 return true;
737 case BitstreamEntry::EndBlock:
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000738 if (NumRecords != TypeList.size())
739 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000740 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000741 case BitstreamEntry::Record:
742 // The interesting case.
743 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000744 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000745
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000746 // Read a record.
747 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000748 Type *ResultTy = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000749 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000750 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000751 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
752 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
753 // type list. This allows us to reserve space.
754 if (Record.size() < 1)
755 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000756 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000757 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000758 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000759 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000760 break;
Dan Gohmance163392011-12-17 00:04:22 +0000761 case bitc::TYPE_CODE_HALF: // HALF
762 ResultTy = Type::getHalfTy(Context);
763 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000764 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000765 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000766 break;
767 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000768 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000769 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000770 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000771 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000772 break;
773 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000774 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000775 break;
776 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000777 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000778 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000779 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000780 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000781 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000782 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000783 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000784 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000785 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
786 ResultTy = Type::getX86_MMXTy(Context);
787 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000788 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
789 if (Record.size() < 1)
790 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000791
Owen Anderson1d0be152009-08-13 21:58:54 +0000792 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000793 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000795 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000796 if (Record.size() < 1)
797 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000798 unsigned AddressSpace = 0;
799 if (Record.size() == 2)
800 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000801 ResultTy = getTypeByID(Record[0]);
802 if (ResultTy == 0) return Error("invalid element type in pointer type");
803 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000804 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000805 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000806 case bitc::TYPE_CODE_FUNCTION_OLD: {
807 // FIXME: attrid is dead, remove it in LLVM 4.0
808 // FUNCTION: [vararg, attrid, retty, paramty x N]
809 if (Record.size() < 3)
810 return Error("Invalid FUNCTION type record");
811 SmallVector<Type*, 8> ArgTys;
812 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
813 if (Type *T = getTypeByID(Record[i]))
814 ArgTys.push_back(T);
815 else
816 break;
817 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000818
Nuno Lopesee8100d2012-05-23 15:19:39 +0000819 ResultTy = getTypeByID(Record[2]);
820 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
821 return Error("invalid type in function type");
822
823 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
824 break;
825 }
Chad Rosiercde54642011-11-03 00:14:01 +0000826 case bitc::TYPE_CODE_FUNCTION: {
827 // FUNCTION: [vararg, retty, paramty x N]
828 if (Record.size() < 2)
829 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000830 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000831 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
832 if (Type *T = getTypeByID(Record[i]))
833 ArgTys.push_back(T);
834 else
835 break;
836 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000837
Chad Rosiercde54642011-11-03 00:14:01 +0000838 ResultTy = getTypeByID(Record[1]);
839 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
840 return Error("invalid type in function type");
841
842 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
843 break;
844 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000845 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000846 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000847 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000848 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000849 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
850 if (Type *T = getTypeByID(Record[i]))
851 EltTys.push_back(T);
852 else
853 break;
854 }
855 if (EltTys.size() != Record.size()-1)
856 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000857 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000858 break;
859 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000860 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
861 if (ConvertToString(Record, 0, TypeName))
862 return Error("Invalid STRUCT_NAME record");
863 continue;
864
865 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
866 if (Record.size() < 1)
867 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000868
Chris Lattner1afcace2011-07-09 17:41:24 +0000869 if (NumRecords >= TypeList.size())
870 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000871
Chris Lattner1afcace2011-07-09 17:41:24 +0000872 // Check to see if this was forward referenced, if so fill in the temp.
873 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
874 if (Res) {
875 Res->setName(TypeName);
876 TypeList[NumRecords] = 0;
877 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000878 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000879 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000880
Chris Lattner1afcace2011-07-09 17:41:24 +0000881 SmallVector<Type*, 8> EltTys;
882 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
883 if (Type *T = getTypeByID(Record[i]))
884 EltTys.push_back(T);
885 else
886 break;
887 }
888 if (EltTys.size() != Record.size()-1)
889 return Error("invalid STRUCT type record");
890 Res->setBody(EltTys, Record[0]);
891 ResultTy = Res;
892 break;
893 }
894 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
895 if (Record.size() != 1)
896 return Error("Invalid OPAQUE type record");
897
898 if (NumRecords >= TypeList.size())
899 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000900
Chris Lattner1afcace2011-07-09 17:41:24 +0000901 // Check to see if this was forward referenced, if so fill in the temp.
902 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
903 if (Res) {
904 Res->setName(TypeName);
905 TypeList[NumRecords] = 0;
906 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000907 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000908 TypeName.clear();
909 ResultTy = Res;
910 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000911 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000912 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
913 if (Record.size() < 2)
914 return Error("Invalid ARRAY type record");
915 if ((ResultTy = getTypeByID(Record[1])))
916 ResultTy = ArrayType::get(ResultTy, Record[0]);
917 else
918 return Error("Invalid ARRAY type element");
919 break;
920 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
921 if (Record.size() < 2)
922 return Error("Invalid VECTOR type record");
923 if ((ResultTy = getTypeByID(Record[1])))
924 ResultTy = VectorType::get(ResultTy, Record[0]);
925 else
926 return Error("Invalid ARRAY type element");
927 break;
928 }
929
930 if (NumRecords >= TypeList.size())
931 return Error("invalid TYPE table");
932 assert(ResultTy && "Didn't read a type?");
933 assert(TypeList[NumRecords] == 0 && "Already read type?");
934 TypeList[NumRecords++] = ResultTy;
935 }
936}
937
Chris Lattner86697142007-05-01 05:01:34 +0000938bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000939 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000940 return Error("Malformed block record");
941
942 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000943
Chris Lattner0b2482a2007-04-23 21:26:05 +0000944 // Read all the records for this value table.
945 SmallString<128> ValueName;
946 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000947 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000948
Chris Lattner5a4251c2013-01-20 02:13:19 +0000949 switch (Entry.Kind) {
950 case BitstreamEntry::SubBlock: // Handled for us already.
951 case BitstreamEntry::Error:
952 return Error("malformed value symbol table block");
953 case BitstreamEntry::EndBlock:
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000954 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000955 case BitstreamEntry::Record:
956 // The interesting case.
957 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000958 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000959
Chris Lattner0b2482a2007-04-23 21:26:05 +0000960 // Read a record.
961 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000962 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000963 default: // Default behavior: unknown type.
964 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000965 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000966 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000967 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000968 unsigned ValueID = Record[0];
969 if (ValueID >= ValueList.size())
970 return Error("Invalid Value ID in VST_ENTRY record");
971 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000972
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000973 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000974 ValueName.clear();
975 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000976 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000977 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000978 if (ConvertToString(Record, 1, ValueName))
979 return Error("Invalid VST_BBENTRY record");
980 BasicBlock *BB = getBasicBlock(Record[0]);
981 if (BB == 0)
982 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000983
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000984 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000985 ValueName.clear();
986 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000987 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000988 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000989 }
990}
991
Devang Patele54abc92009-07-22 17:43:22 +0000992bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000993 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000994
995 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
996 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000997
Devang Patele54abc92009-07-22 17:43:22 +0000998 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000999
Devang Patele54abc92009-07-22 17:43:22 +00001000 // Read all the records.
1001 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001002 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001003
Chris Lattner5a4251c2013-01-20 02:13:19 +00001004 switch (Entry.Kind) {
1005 case BitstreamEntry::SubBlock: // Handled for us already.
1006 case BitstreamEntry::Error:
1007 Error("malformed metadata block");
1008 return true;
1009 case BitstreamEntry::EndBlock:
Devang Patele54abc92009-07-22 17:43:22 +00001010 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001011 case BitstreamEntry::Record:
1012 // The interesting case.
1013 break;
Devang Patele54abc92009-07-22 17:43:22 +00001014 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001015
Victor Hernandez24e64df2010-01-10 07:14:18 +00001016 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +00001017 // Read a record.
1018 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001019 unsigned Code = Stream.readRecord(Entry.ID, Record);
Dan Gohman9b10dfb2010-09-13 18:00:48 +00001020 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +00001021 default: // Default behavior: ignore.
1022 break;
Devang Patelaa993142009-07-29 22:34:41 +00001023 case bitc::METADATA_NAME: {
Chris Lattner1ca114a2013-01-20 02:54:05 +00001024 // Read name of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001025 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +00001026 Record.clear();
1027 Code = Stream.ReadCode();
1028
Chris Lattner9d61dd92011-06-17 17:50:30 +00001029 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001030 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001031 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +00001032
1033 // Read named metadata elements.
1034 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +00001035 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +00001036 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +00001037 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1038 if (MD == 0)
1039 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +00001040 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +00001041 }
Devang Patelaa993142009-07-29 22:34:41 +00001042 break;
1043 }
Chris Lattner9d61dd92011-06-17 17:50:30 +00001044 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +00001045 IsFunctionLocal = true;
1046 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +00001047 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +00001048 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +00001049 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001050
Devang Patel104cf9e2009-07-23 01:07:34 +00001051 unsigned Size = Record.size();
1052 SmallVector<Value*, 8> Elts;
1053 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001054 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001055 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001056 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +00001057 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +00001058 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +00001059 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1060 else
1061 Elts.push_back(NULL);
1062 }
Jay Foadec9186b2011-04-21 19:59:31 +00001063 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +00001064 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +00001065 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +00001066 break;
1067 }
Devang Patele54abc92009-07-22 17:43:22 +00001068 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001069 SmallString<8> String(Record.begin(), Record.end());
1070 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +00001071 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +00001072 break;
1073 }
Devang Patele8e02132009-09-18 19:26:43 +00001074 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001075 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001076 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001077
Devang Patela2148402009-09-28 21:14:55 +00001078 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001079 SmallString<8> Name(Record.begin()+1, Record.end());
1080
Chris Lattner08113472009-12-29 09:01:33 +00001081 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +00001082 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1083 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +00001084 break;
1085 }
Devang Patele54abc92009-07-22 17:43:22 +00001086 }
1087 }
1088}
1089
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001090/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +00001091/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001092uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +00001093 if ((V & 1) == 0)
1094 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001095 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +00001096 return -(V >> 1);
1097 // There is no such thing as -0 with integers. "-0" really means MININT.
1098 return 1ULL << 63;
1099}
1100
Chris Lattner07d98b42007-04-26 02:46:40 +00001101/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1102/// values and aliases that we can.
1103bool BitcodeReader::ResolveGlobalAndAliasInits() {
1104 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1105 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001106 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001107
Chris Lattner07d98b42007-04-26 02:46:40 +00001108 GlobalInitWorklist.swap(GlobalInits);
1109 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001110 FunctionPrefixWorklist.swap(FunctionPrefixes);
Chris Lattner07d98b42007-04-26 02:46:40 +00001111
1112 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +00001113 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +00001114 if (ValID >= ValueList.size()) {
1115 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +00001116 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +00001117 } else {
1118 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1119 GlobalInitWorklist.back().first->setInitializer(C);
1120 else
1121 return Error("Global variable initializer is not a constant!");
1122 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001123 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001124 }
1125
1126 while (!AliasInitWorklist.empty()) {
1127 unsigned ValID = AliasInitWorklist.back().second;
1128 if (ValID >= ValueList.size()) {
1129 AliasInits.push_back(AliasInitWorklist.back());
1130 } else {
1131 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +00001132 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +00001133 else
1134 return Error("Alias initializer is not a constant!");
1135 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001136 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001137 }
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001138
1139 while (!FunctionPrefixWorklist.empty()) {
1140 unsigned ValID = FunctionPrefixWorklist.back().second;
1141 if (ValID >= ValueList.size()) {
1142 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1143 } else {
1144 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1145 FunctionPrefixWorklist.back().first->setPrefixData(C);
1146 else
1147 return Error("Function prefix is not a constant!");
1148 }
1149 FunctionPrefixWorklist.pop_back();
1150 }
1151
Chris Lattner07d98b42007-04-26 02:46:40 +00001152 return false;
1153}
1154
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001155static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1156 SmallVector<uint64_t, 8> Words(Vals.size());
1157 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001158 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001159
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001160 return APInt(TypeBits, Words);
1161}
1162
Chris Lattner86697142007-05-01 05:01:34 +00001163bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001164 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +00001165 return Error("Malformed block record");
1166
1167 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001168
Chris Lattnere16504e2007-04-24 03:30:34 +00001169 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001170 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +00001171 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +00001172 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001173 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001174
Chris Lattner5a4251c2013-01-20 02:13:19 +00001175 switch (Entry.Kind) {
1176 case BitstreamEntry::SubBlock: // Handled for us already.
1177 case BitstreamEntry::Error:
1178 return Error("malformed block record in AST file");
1179 case BitstreamEntry::EndBlock:
1180 if (NextCstNo != ValueList.size())
1181 return Error("Invalid constant reference!");
Joe Abbeyacb61942013-02-06 22:14:06 +00001182
Chris Lattner5a4251c2013-01-20 02:13:19 +00001183 // Once all the constants have been read, go through and resolve forward
1184 // references.
1185 ValueList.ResolveConstantForwardRefs();
1186 return false;
1187 case BitstreamEntry::Record:
1188 // The interesting case.
Chris Lattnerea693df2008-08-21 02:34:16 +00001189 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001190 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001191
Chris Lattnere16504e2007-04-24 03:30:34 +00001192 // Read a record.
1193 Record.clear();
1194 Value *V = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001195 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00001196 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001197 default: // Default behavior: unknown constant
1198 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001199 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001200 break;
1201 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1202 if (Record.empty())
1203 return Error("Malformed CST_SETTYPE record");
1204 if (Record[0] >= TypeList.size())
1205 return Error("Invalid Type ID in CST_SETTYPE record");
1206 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001207 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001208 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001209 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001210 break;
1211 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001212 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001213 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001214 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001215 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001216 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001217 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001218 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001219
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001220 APInt VInt = ReadWideAPInt(Record,
1221 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001222 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +00001223
Chris Lattner0eef0802007-04-24 04:04:35 +00001224 break;
1225 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001226 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001227 if (Record.empty())
1228 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001229 if (CurTy->isHalfTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001230 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1231 APInt(16, (uint16_t)Record[0])));
Dan Gohmance163392011-12-17 00:04:22 +00001232 else if (CurTy->isFloatTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001233 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1234 APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001235 else if (CurTy->isDoubleTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001236 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1237 APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001238 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001239 // Bits are not stored the same way as a normal i80 APInt, compensate.
1240 uint64_t Rearrange[2];
1241 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1242 Rearrange[1] = Record[0] >> 48;
Tim Northover0a29cb02013-01-22 09:46:31 +00001243 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1244 APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001245 } else if (CurTy->isFP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001246 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1247 APInt(128, Record)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001248 else if (CurTy->isPPC_FP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001249 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1250 APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001251 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001252 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001253 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001254 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001255
Chris Lattner15e6d172007-05-04 19:11:41 +00001256 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1257 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001258 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001259
Chris Lattner15e6d172007-05-04 19:11:41 +00001260 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001261 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001262
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001263 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001264 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001265 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001266 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001267 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001268 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1269 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001270 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001271 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001272 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001273 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1274 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001275 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001276 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001277 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001278 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001279 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001280 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001281 break;
1282 }
Chris Lattner2237f842012-02-05 02:41:35 +00001283 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001284 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1285 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001286 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001287
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001288 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001289 V = ConstantDataArray::getString(Context, Elts,
1290 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001291 break;
1292 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001293 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1294 if (Record.empty())
1295 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001296
Chris Lattnerd408f062012-01-30 00:51:16 +00001297 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1298 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001299
Chris Lattnerd408f062012-01-30 00:51:16 +00001300 if (EltTy->isIntegerTy(8)) {
1301 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1302 if (isa<VectorType>(CurTy))
1303 V = ConstantDataVector::get(Context, Elts);
1304 else
1305 V = ConstantDataArray::get(Context, Elts);
1306 } else if (EltTy->isIntegerTy(16)) {
1307 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1308 if (isa<VectorType>(CurTy))
1309 V = ConstantDataVector::get(Context, Elts);
1310 else
1311 V = ConstantDataArray::get(Context, Elts);
1312 } else if (EltTy->isIntegerTy(32)) {
1313 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1314 if (isa<VectorType>(CurTy))
1315 V = ConstantDataVector::get(Context, Elts);
1316 else
1317 V = ConstantDataArray::get(Context, Elts);
1318 } else if (EltTy->isIntegerTy(64)) {
1319 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1320 if (isa<VectorType>(CurTy))
1321 V = ConstantDataVector::get(Context, Elts);
1322 else
1323 V = ConstantDataArray::get(Context, Elts);
1324 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001325 SmallVector<float, 16> Elts(Size);
1326 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001327 if (isa<VectorType>(CurTy))
1328 V = ConstantDataVector::get(Context, Elts);
1329 else
1330 V = ConstantDataArray::get(Context, Elts);
1331 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001332 SmallVector<double, 16> Elts(Size);
1333 std::transform(Record.begin(), Record.end(), Elts.begin(),
1334 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001335 if (isa<VectorType>(CurTy))
1336 V = ConstantDataVector::get(Context, Elts);
1337 else
1338 V = ConstantDataArray::get(Context, Elts);
1339 } else {
1340 return Error("Unknown element type in CE_DATA");
1341 }
1342 break;
1343 }
1344
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001345 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1346 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1347 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001348 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001349 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001350 } else {
1351 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1352 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001353 unsigned Flags = 0;
1354 if (Record.size() >= 4) {
1355 if (Opc == Instruction::Add ||
1356 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001357 Opc == Instruction::Mul ||
1358 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001359 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1360 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1361 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1362 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001363 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001364 Opc == Instruction::UDiv ||
1365 Opc == Instruction::LShr ||
1366 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001367 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001368 Flags |= SDivOperator::IsExact;
1369 }
1370 }
1371 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
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 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001375 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1376 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1377 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001378 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001379 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001380 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001381 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001382 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001383 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001384 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001385 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001386 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001387 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001388 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001389 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001390 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001391 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001392 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001393 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001394 if (!ElTy) return Error("Invalid CE_GEP record");
1395 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1396 }
Jay Foaddab3d292011-07-21 14:31:17 +00001397 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001398 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1399 BitCode ==
1400 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001401 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001402 }
Joe Abbey405b6502013-09-12 22:02:31 +00001403 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001404 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbey405b6502013-09-12 22:02:31 +00001405
1406 Type *SelectorTy = Type::getInt1Ty(Context);
1407
1408 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1409 // vector. Otherwise, it must be a single bit.
1410 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1411 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1412 VTy->getNumElements());
1413
1414 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1415 SelectorTy),
1416 ValueList.getConstantFwdRef(Record[1],CurTy),
1417 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001418 break;
Joe Abbey405b6502013-09-12 22:02:31 +00001419 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001420 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1421 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001422 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001423 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1424 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1425 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001426 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001427 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001428 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001429 break;
1430 }
1431 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001432 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001433 if (Record.size() < 3 || OpTy == 0)
1434 return Error("Invalid CE_INSERTELT record");
1435 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1436 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1437 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001438 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001439 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001440 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001441 break;
1442 }
1443 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001444 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001445 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001446 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001447 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1448 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001449 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001450 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001451 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001452 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001453 break;
1454 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001455 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001456 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1457 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001458 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001459 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1460 return Error("Invalid CE_SHUFVEC_EX record");
1461 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1462 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001463 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001464 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001465 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001466 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001467 break;
1468 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001469 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1470 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001471 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001472 if (OpTy == 0) return Error("Invalid CE_CMP record");
1473 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1474 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1475
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001476 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001477 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001478 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001479 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001480 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001481 }
Chad Rosier581600b2012-09-05 19:00:49 +00001482 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001483 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001484 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001485 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1486 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001487 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001488 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001489 unsigned AsmStrSize = Record[1];
1490 if (2+AsmStrSize >= Record.size())
1491 return Error("Invalid INLINEASM record");
1492 unsigned ConstStrSize = Record[2+AsmStrSize];
1493 if (3+AsmStrSize+ConstStrSize > Record.size())
1494 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001495
Chris Lattner2bce93a2007-05-06 01:58:20 +00001496 for (unsigned i = 0; i != AsmStrSize; ++i)
1497 AsmStr += (char)Record[2+i];
1498 for (unsigned i = 0; i != ConstStrSize; ++i)
1499 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001500 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001501 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001502 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001503 break;
1504 }
Chad Rosier581600b2012-09-05 19:00:49 +00001505 // This version adds support for the asm dialect keywords (e.g.,
1506 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001507 case bitc::CST_CODE_INLINEASM: {
1508 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1509 std::string AsmStr, ConstrStr;
1510 bool HasSideEffects = Record[0] & 1;
1511 bool IsAlignStack = (Record[0] >> 1) & 1;
1512 unsigned AsmDialect = Record[0] >> 2;
1513 unsigned AsmStrSize = Record[1];
1514 if (2+AsmStrSize >= Record.size())
1515 return Error("Invalid INLINEASM record");
1516 unsigned ConstStrSize = Record[2+AsmStrSize];
1517 if (3+AsmStrSize+ConstStrSize > Record.size())
1518 return Error("Invalid INLINEASM record");
1519
1520 for (unsigned i = 0; i != AsmStrSize; ++i)
1521 AsmStr += (char)Record[2+i];
1522 for (unsigned i = 0; i != ConstStrSize; ++i)
1523 ConstrStr += (char)Record[3+AsmStrSize+i];
1524 PointerType *PTy = cast<PointerType>(CurTy);
1525 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1526 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001527 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001528 break;
1529 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001530 case bitc::CST_CODE_BLOCKADDRESS:{
1531 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001532 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001533 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1534 Function *Fn =
1535 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1536 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001537
1538 // If the function is already parsed we can insert the block address right
1539 // away.
1540 if (!Fn->empty()) {
1541 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1542 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1543 if (BBI == BBE)
1544 return Error("Invalid blockaddress block #");
1545 ++BBI;
1546 }
1547 V = BlockAddress::get(Fn, BBI);
1548 } else {
1549 // Otherwise insert a placeholder and remember it so it can be inserted
1550 // when the function is parsed.
1551 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1552 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001553 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001554 0, "");
1555 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1556 V = FwdRef;
1557 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001558 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001559 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001560 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001561
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001562 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001563 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001564 }
1565}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001566
Chad Rosiercbbb0962011-12-07 21:44:12 +00001567bool BitcodeReader::ParseUseLists() {
1568 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1569 return Error("Malformed block record");
1570
1571 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001572
Chad Rosiercbbb0962011-12-07 21:44:12 +00001573 // Read all the records.
1574 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001575 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001576
Chris Lattner5a4251c2013-01-20 02:13:19 +00001577 switch (Entry.Kind) {
1578 case BitstreamEntry::SubBlock: // Handled for us already.
1579 case BitstreamEntry::Error:
1580 return Error("malformed use list block");
1581 case BitstreamEntry::EndBlock:
Chad Rosiercbbb0962011-12-07 21:44:12 +00001582 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001583 case BitstreamEntry::Record:
1584 // The interesting case.
1585 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001586 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001587
Chad Rosiercbbb0962011-12-07 21:44:12 +00001588 // Read a use list record.
1589 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001590 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosiercbbb0962011-12-07 21:44:12 +00001591 default: // Default behavior: unknown type.
1592 break;
1593 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1594 unsigned RecordLength = Record.size();
1595 if (RecordLength < 1)
1596 return Error ("Invalid UseList reader!");
1597 UseListRecords.push_back(Record);
1598 break;
1599 }
1600 }
1601 }
1602}
1603
Chris Lattner980e5aa2007-05-01 05:52:21 +00001604/// RememberAndSkipFunctionBody - When we see the block for a function body,
1605/// remember where it is and then skip it. This lets us lazily deserialize the
1606/// functions.
1607bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001608 // Get the function we are talking about.
1609 if (FunctionsWithBodies.empty())
1610 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001611
Chris Lattner48f84872007-05-01 04:59:48 +00001612 Function *Fn = FunctionsWithBodies.back();
1613 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001614
Chris Lattner48f84872007-05-01 04:59:48 +00001615 // Save the current stream state.
1616 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001617 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001618
Chris Lattner48f84872007-05-01 04:59:48 +00001619 // Skip over the function block for now.
1620 if (Stream.SkipBlock())
1621 return Error("Malformed block record");
1622 return false;
1623}
1624
Derek Schuff2ea93872012-02-06 22:30:29 +00001625bool BitcodeReader::GlobalCleanup() {
1626 // Patch the initializers for globals and aliases up.
1627 ResolveGlobalAndAliasInits();
1628 if (!GlobalInits.empty() || !AliasInits.empty())
1629 return Error("Malformed global initializer set");
1630
1631 // Look for intrinsic functions which need to be upgraded at some point
1632 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1633 FI != FE; ++FI) {
1634 Function *NewFn;
1635 if (UpgradeIntrinsicFunction(FI, NewFn))
1636 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1637 }
1638
1639 // Look for global variables which need to be renamed.
1640 for (Module::global_iterator
1641 GI = TheModule->global_begin(), GE = TheModule->global_end();
1642 GI != GE; ++GI)
1643 UpgradeGlobalVariable(GI);
1644 // Force deallocation of memory for these vectors to favor the client that
1645 // want lazy deserialization.
1646 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1647 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1648 return false;
1649}
1650
1651bool BitcodeReader::ParseModule(bool Resume) {
1652 if (Resume)
1653 Stream.JumpToBit(NextUnreadBit);
1654 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001655 return Error("Malformed block record");
1656
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001657 SmallVector<uint64_t, 64> Record;
1658 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001659 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001660
1661 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001662 while (1) {
1663 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00001664
Chris Lattner5a4251c2013-01-20 02:13:19 +00001665 switch (Entry.Kind) {
1666 case BitstreamEntry::Error:
1667 Error("malformed module block");
1668 return true;
1669 case BitstreamEntry::EndBlock:
Derek Schuff2ea93872012-02-06 22:30:29 +00001670 return GlobalCleanup();
Joe Abbeyacb61942013-02-06 22:14:06 +00001671
Chris Lattner5a4251c2013-01-20 02:13:19 +00001672 case BitstreamEntry::SubBlock:
1673 switch (Entry.ID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001674 default: // Skip unknown content.
1675 if (Stream.SkipBlock())
1676 return Error("Malformed block record");
1677 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001678 case bitc::BLOCKINFO_BLOCK_ID:
1679 if (Stream.ReadBlockInfoBlock())
1680 return Error("Malformed BlockInfoBlock");
1681 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001682 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001683 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001684 return true;
1685 break;
Bill Wendlingc3ba0a82013-02-10 23:24:25 +00001686 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1687 if (ParseAttributeGroupBlock())
1688 return true;
1689 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001690 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001691 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001692 return true;
1693 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001694 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001695 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001696 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001697 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001698 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001699 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001700 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001701 return true;
1702 break;
Devang Patele54abc92009-07-22 17:43:22 +00001703 case bitc::METADATA_BLOCK_ID:
1704 if (ParseMetadata())
1705 return true;
1706 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001707 case bitc::FUNCTION_BLOCK_ID:
1708 // If this is the first function body we've seen, reverse the
1709 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001710 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001711 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001712 if (GlobalCleanup())
1713 return true;
1714 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001715 }
Joe Abbeyacb61942013-02-06 22:14:06 +00001716
Chris Lattner980e5aa2007-05-01 05:52:21 +00001717 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001718 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001719 // For streaming bitcode, suspend parsing when we reach the function
1720 // bodies. Subsequent materialization calls will resume it when
1721 // necessary. For streaming, the function bodies must be at the end of
1722 // the bitcode. If the bitcode file is old, the symbol table will be
1723 // at the end instead and will not have been seen yet. In this case,
1724 // just finish the parse now.
1725 if (LazyStreamer && SeenValueSymbolTable) {
1726 NextUnreadBit = Stream.GetCurrentBitNo();
1727 return false;
1728 }
Chris Lattner48f84872007-05-01 04:59:48 +00001729 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001730 case bitc::USELIST_BLOCK_ID:
1731 if (ParseUseLists())
1732 return true;
1733 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001734 }
1735 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00001736
Chris Lattner5a4251c2013-01-20 02:13:19 +00001737 case BitstreamEntry::Record:
1738 // The interesting case.
1739 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001740 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001741
Daniel Dunbara279bc32009-09-20 02:20:51 +00001742
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001743 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001744 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001745 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001746 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001747 if (Record.size() < 1)
1748 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001749 // Only version #0 and #1 are supported so far.
1750 unsigned module_version = Record[0];
1751 switch (module_version) {
1752 default: return Error("Unknown bitstream version!");
1753 case 0:
1754 UseRelativeIDs = false;
1755 break;
1756 case 1:
1757 UseRelativeIDs = true;
1758 break;
1759 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001760 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001761 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001762 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001763 std::string S;
1764 if (ConvertToString(Record, 0, S))
1765 return Error("Invalid MODULE_CODE_TRIPLE record");
1766 TheModule->setTargetTriple(S);
1767 break;
1768 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001769 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [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_DATALAYOUT record");
1773 TheModule->setDataLayout(S);
1774 break;
1775 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001776 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001777 std::string S;
1778 if (ConvertToString(Record, 0, S))
1779 return Error("Invalid MODULE_CODE_ASM record");
1780 TheModule->setModuleInlineAsm(S);
1781 break;
1782 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001783 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1784 // FIXME: Remove in 4.0.
1785 std::string S;
1786 if (ConvertToString(Record, 0, S))
1787 return Error("Invalid MODULE_CODE_DEPLIB record");
1788 // Ignore value.
1789 break;
1790 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001791 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001792 std::string S;
1793 if (ConvertToString(Record, 0, S))
1794 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1795 SectionTable.push_back(S);
1796 break;
1797 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001798 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001799 std::string S;
1800 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001801 return Error("Invalid MODULE_CODE_GCNAME record");
1802 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001803 break;
1804 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001805 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001806 // linkage, alignment, section, visibility, threadlocal,
1807 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001808 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001809 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001810 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001811 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001812 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001813 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001814 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001815 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001816 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001817
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001818 bool isConstant = Record[1];
1819 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1820 unsigned Alignment = (1 << Record[4]) >> 1;
1821 std::string Section;
1822 if (Record[5]) {
1823 if (Record[5]-1 >= SectionTable.size())
1824 return Error("Invalid section ID");
1825 Section = SectionTable[Record[5]-1];
1826 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001827 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001828 if (Record.size() > 6)
1829 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001830
1831 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001832 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001833 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001834
Rafael Espindolabea46262011-01-08 16:42:36 +00001835 bool UnnamedAddr = false;
1836 if (Record.size() > 8)
1837 UnnamedAddr = Record[8];
1838
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001839 bool ExternallyInitialized = false;
1840 if (Record.size() > 9)
1841 ExternallyInitialized = Record[9];
1842
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001843 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001844 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001845 TLM, AddressSpace, ExternallyInitialized);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001846 NewGV->setAlignment(Alignment);
1847 if (!Section.empty())
1848 NewGV->setSection(Section);
1849 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001850 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001851
Chris Lattner0b2482a2007-04-23 21:26:05 +00001852 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001853
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001854 // Remember which value to use for the global initializer.
1855 if (unsigned InitID = Record[2])
1856 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001857 break;
1858 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001859 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001860 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001861 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001862 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001863 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001864 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001865 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001866 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001867 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001868 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001869 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1870 if (!FTy)
1871 return Error("Function not a pointer to function type!");
1872
Gabor Greif051a9502008-04-06 20:25:17 +00001873 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1874 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001875
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001876 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001877 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001878 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001879 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001880
Chris Lattnera9bb7132007-05-08 05:38:01 +00001881 Func->setAlignment((1 << Record[5]) >> 1);
1882 if (Record[6]) {
1883 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001884 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001885 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001886 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001887 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001888 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001889 if (Record[8]-1 > GCTable.size())
1890 return Error("Invalid GC ID");
1891 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001892 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001893 bool UnnamedAddr = false;
1894 if (Record.size() > 9)
1895 UnnamedAddr = Record[9];
1896 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001897 if (Record.size() > 10 && Record[10] != 0)
1898 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
Chris Lattner0b2482a2007-04-23 21:26:05 +00001899 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001900
Chris Lattner48f84872007-05-01 04:59:48 +00001901 // If this is a function with a body, remember the prototype we are
1902 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001903 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001904 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001905 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1906 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001907 break;
1908 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001909 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001910 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001911 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001912 if (Record.size() < 3)
1913 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001914 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001915 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001916 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001917 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001918
Chris Lattner07d98b42007-04-26 02:46:40 +00001919 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1920 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001921 // Old bitcode files didn't have visibility field.
1922 if (Record.size() > 3)
1923 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001924 ValueList.push_back(NewGA);
1925 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1926 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001927 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001928 /// MODULE_CODE_PURGEVALS: [numvals]
1929 case bitc::MODULE_CODE_PURGEVALS:
1930 // Trim down the value list to the specified size.
1931 if (Record.size() < 1 || Record[0] > ValueList.size())
1932 return Error("Invalid MODULE_PURGEVALS record");
1933 ValueList.shrinkTo(Record[0]);
1934 break;
1935 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001936 Record.clear();
1937 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001938}
1939
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001940bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001941 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001942
Derek Schuff2ea93872012-02-06 22:30:29 +00001943 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001944
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001945 // Sniff for the signature.
1946 if (Stream.Read(8) != 'B' ||
1947 Stream.Read(8) != 'C' ||
1948 Stream.Read(4) != 0x0 ||
1949 Stream.Read(4) != 0xC ||
1950 Stream.Read(4) != 0xE ||
1951 Stream.Read(4) != 0xD)
1952 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001953
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001954 // We expect a number of well-defined blocks, though we don't necessarily
1955 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001956 while (1) {
1957 if (Stream.AtEndOfStream())
1958 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001959
Chris Lattner5a4251c2013-01-20 02:13:19 +00001960 BitstreamEntry Entry =
1961 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbeyacb61942013-02-06 22:14:06 +00001962
Chris Lattner5a4251c2013-01-20 02:13:19 +00001963 switch (Entry.Kind) {
1964 case BitstreamEntry::Error:
1965 Error("malformed module file");
1966 return true;
1967 case BitstreamEntry::EndBlock:
1968 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001969
Chris Lattner5a4251c2013-01-20 02:13:19 +00001970 case BitstreamEntry::SubBlock:
1971 switch (Entry.ID) {
1972 case bitc::BLOCKINFO_BLOCK_ID:
1973 if (Stream.ReadBlockInfoBlock())
1974 return Error("Malformed BlockInfoBlock");
1975 break;
1976 case bitc::MODULE_BLOCK_ID:
1977 // Reject multiple MODULE_BLOCK's in a single bitstream.
1978 if (TheModule)
1979 return Error("Multiple MODULE_BLOCKs in same stream");
1980 TheModule = M;
1981 if (ParseModule(false))
1982 return true;
1983 if (LazyStreamer) return false;
1984 break;
1985 default:
1986 if (Stream.SkipBlock())
1987 return Error("Malformed block record");
1988 break;
1989 }
1990 continue;
1991 case BitstreamEntry::Record:
1992 // There should be no records in the top-level of blocks.
Joe Abbeyacb61942013-02-06 22:14:06 +00001993
Chris Lattner5a4251c2013-01-20 02:13:19 +00001994 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001995 // to the end of them. If this file size is a multiple of 4 but not 8, we
1996 // have to read and ignore these final 4 bytes :-(
Chris Lattner5a4251c2013-01-20 02:13:19 +00001997 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolac9687b32011-05-26 18:59:54 +00001998 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001999 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00002000 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00002001
Chris Lattnercaee0dc2007-04-22 06:23:29 +00002002 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00002003 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00002004 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00002005}
Chris Lattnerc453f762007-04-29 07:54:31 +00002006
Bill Wendling34711742010-10-06 01:22:42 +00002007bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
2008 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2009 return Error("Malformed block record");
2010
2011 SmallVector<uint64_t, 64> Record;
2012
2013 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00002014 while (1) {
2015 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00002016
Chris Lattner5a4251c2013-01-20 02:13:19 +00002017 switch (Entry.Kind) {
2018 case BitstreamEntry::SubBlock: // Handled for us already.
2019 case BitstreamEntry::Error:
2020 return Error("malformed module block");
2021 case BitstreamEntry::EndBlock:
Bill Wendling34711742010-10-06 01:22:42 +00002022 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002023 case BitstreamEntry::Record:
2024 // The interesting case.
2025 break;
Bill Wendling34711742010-10-06 01:22:42 +00002026 }
2027
2028 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00002029 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling34711742010-10-06 01:22:42 +00002030 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00002031 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2032 std::string S;
2033 if (ConvertToString(Record, 0, S))
2034 return Error("Invalid MODULE_CODE_TRIPLE record");
2035 Triple = S;
2036 break;
2037 }
2038 }
2039 Record.clear();
2040 }
Bill Wendling34711742010-10-06 01:22:42 +00002041}
2042
2043bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00002044 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00002045
2046 // Sniff for the signature.
2047 if (Stream.Read(8) != 'B' ||
2048 Stream.Read(8) != 'C' ||
2049 Stream.Read(4) != 0x0 ||
2050 Stream.Read(4) != 0xC ||
2051 Stream.Read(4) != 0xE ||
2052 Stream.Read(4) != 0xD)
2053 return Error("Invalid bitcode signature");
2054
2055 // We expect a number of well-defined blocks, though we don't necessarily
2056 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00002057 while (1) {
2058 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00002059
Chris Lattner5a4251c2013-01-20 02:13:19 +00002060 switch (Entry.Kind) {
2061 case BitstreamEntry::Error:
2062 Error("malformed module file");
2063 return true;
2064 case BitstreamEntry::EndBlock:
2065 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00002066
Chris Lattner5a4251c2013-01-20 02:13:19 +00002067 case BitstreamEntry::SubBlock:
2068 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2069 return ParseModuleTriple(Triple);
Joe Abbeyacb61942013-02-06 22:14:06 +00002070
Chris Lattner5a4251c2013-01-20 02:13:19 +00002071 // Ignore other sub-blocks.
2072 if (Stream.SkipBlock()) {
2073 Error("malformed block record in AST file");
Bill Wendling34711742010-10-06 01:22:42 +00002074 return true;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002075 }
2076 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00002077
Chris Lattner5a4251c2013-01-20 02:13:19 +00002078 case BitstreamEntry::Record:
2079 Stream.skipRecord(Entry.ID);
2080 continue;
Bill Wendling34711742010-10-06 01:22:42 +00002081 }
2082 }
Bill Wendling34711742010-10-06 01:22:42 +00002083}
2084
Devang Patele8e02132009-09-18 19:26:43 +00002085/// ParseMetadataAttachment - Parse metadata attachments.
2086bool BitcodeReader::ParseMetadataAttachment() {
2087 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2088 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002089
Devang Patele8e02132009-09-18 19:26:43 +00002090 SmallVector<uint64_t, 64> Record;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002091 while (1) {
2092 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00002093
Chris Lattner5a4251c2013-01-20 02:13:19 +00002094 switch (Entry.Kind) {
2095 case BitstreamEntry::SubBlock: // Handled for us already.
2096 case BitstreamEntry::Error:
2097 return Error("malformed metadata block");
2098 case BitstreamEntry::EndBlock:
2099 return false;
2100 case BitstreamEntry::Record:
2101 // The interesting case.
Devang Patele8e02132009-09-18 19:26:43 +00002102 break;
2103 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00002104
Devang Patele8e02132009-09-18 19:26:43 +00002105 // Read a metadata attachment record.
2106 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00002107 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patele8e02132009-09-18 19:26:43 +00002108 default: // Default behavior: ignore.
2109 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00002110 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00002111 unsigned RecordLength = Record.size();
2112 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002113 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00002114 Instruction *Inst = InstructionList[Record[0]];
2115 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00002116 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00002117 DenseMap<unsigned, unsigned>::iterator I =
2118 MDKindMap.find(Kind);
2119 if (I == MDKindMap.end())
2120 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002121 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00002122 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren804f0342013-09-28 00:22:27 +00002123 if (I->second == LLVMContext::MD_tbaa)
2124 InstsWithTBAATag.push_back(Inst);
Devang Patele8e02132009-09-18 19:26:43 +00002125 }
2126 break;
2127 }
2128 }
2129 }
Devang Patele8e02132009-09-18 19:26:43 +00002130}
Chris Lattner48f84872007-05-01 04:59:48 +00002131
Chris Lattner980e5aa2007-05-01 05:52:21 +00002132/// ParseFunctionBody - Lazily parse the specified function body block.
2133bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00002134 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00002135 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002136
Nick Lewycky9a49f152010-02-25 08:30:17 +00002137 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002138 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00002139 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002140
Chris Lattner980e5aa2007-05-01 05:52:21 +00002141 // Add all the function arguments to the value table.
2142 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2143 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002144
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002145 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00002146 BasicBlock *CurBB = 0;
2147 unsigned CurBBNo = 0;
2148
Chris Lattnera6245242010-04-03 02:17:50 +00002149 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00002150
Chris Lattner980e5aa2007-05-01 05:52:21 +00002151 // Read all the records.
2152 SmallVector<uint64_t, 64> Record;
2153 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00002154 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00002155
Chris Lattner5a4251c2013-01-20 02:13:19 +00002156 switch (Entry.Kind) {
2157 case BitstreamEntry::Error:
2158 return Error("Bitcode error in function block");
2159 case BitstreamEntry::EndBlock:
2160 goto OutOfRecordLoop;
Joe Abbeyacb61942013-02-06 22:14:06 +00002161
Chris Lattner5a4251c2013-01-20 02:13:19 +00002162 case BitstreamEntry::SubBlock:
2163 switch (Entry.ID) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00002164 default: // Skip unknown content.
2165 if (Stream.SkipBlock())
2166 return Error("Malformed block record");
2167 break;
2168 case bitc::CONSTANTS_BLOCK_ID:
2169 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002170 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002171 break;
2172 case bitc::VALUE_SYMTAB_BLOCK_ID:
2173 if (ParseValueSymbolTable()) return true;
2174 break;
Devang Patele8e02132009-09-18 19:26:43 +00002175 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002176 if (ParseMetadataAttachment()) return true;
2177 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00002178 case bitc::METADATA_BLOCK_ID:
2179 if (ParseMetadata()) return true;
2180 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002181 }
2182 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00002183
Chris Lattner5a4251c2013-01-20 02:13:19 +00002184 case BitstreamEntry::Record:
2185 // The interesting case.
2186 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002187 }
Joe Abbeyacb61942013-02-06 22:14:06 +00002188
Chris Lattner980e5aa2007-05-01 05:52:21 +00002189 // Read a record.
2190 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002191 Instruction *I = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002192 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00002193 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002194 default: // Default behavior: reject
2195 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002196 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002197 if (Record.size() < 1 || Record[0] == 0)
2198 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002199 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00002200 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002201 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00002202 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002203 CurBB = FunctionBBs[0];
2204 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002205
Chris Lattnera6245242010-04-03 02:17:50 +00002206 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2207 // This record indicates that the last instruction is at the same
2208 // location as the previous instruction with a location.
2209 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00002210
Chris Lattnera6245242010-04-03 02:17:50 +00002211 // Get the last instruction emitted.
2212 if (CurBB && !CurBB->empty())
2213 I = &CurBB->back();
2214 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2215 !FunctionBBs[CurBBNo-1]->empty())
2216 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00002217
Chris Lattnera6245242010-04-03 02:17:50 +00002218 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2219 I->setDebugLoc(LastLoc);
2220 I = 0;
2221 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002222
Chris Lattner4f6bab92011-06-17 18:17:37 +00002223 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002224 I = 0; // Get the last instruction emitted.
2225 if (CurBB && !CurBB->empty())
2226 I = &CurBB->back();
2227 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2228 !FunctionBBs[CurBBNo-1]->empty())
2229 I = &FunctionBBs[CurBBNo-1]->back();
2230 if (I == 0 || Record.size() < 4)
2231 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002232
Chris Lattnera6245242010-04-03 02:17:50 +00002233 unsigned Line = Record[0], Col = Record[1];
2234 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00002235
Chris Lattnera6245242010-04-03 02:17:50 +00002236 MDNode *Scope = 0, *IA = 0;
2237 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2238 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2239 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2240 I->setDebugLoc(LastLoc);
2241 I = 0;
2242 continue;
2243 }
2244
Chris Lattnerabfbf852007-05-06 00:21:25 +00002245 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2246 unsigned OpNum = 0;
2247 Value *LHS, *RHS;
2248 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002249 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002250 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002251 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002252
Dan Gohman1224c382009-07-20 21:19:07 +00002253 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002254 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002255 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002256 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002257 if (OpNum < Record.size()) {
2258 if (Opc == Instruction::Add ||
2259 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002260 Opc == Instruction::Mul ||
2261 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002262 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002263 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002264 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002265 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002266 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002267 Opc == Instruction::UDiv ||
2268 Opc == Instruction::LShr ||
2269 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002270 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002271 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002272 } else if (isa<FPMathOperator>(I)) {
2273 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002274 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2275 FMF.setUnsafeAlgebra();
2276 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2277 FMF.setNoNaNs();
2278 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2279 FMF.setNoInfs();
2280 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2281 FMF.setNoSignedZeros();
2282 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2283 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002284 if (FMF.any())
2285 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002286 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002287
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002288 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002289 break;
2290 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002291 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2292 unsigned OpNum = 0;
2293 Value *Op;
2294 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2295 OpNum+2 != Record.size())
2296 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002297
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002298 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002299 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2300 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002301 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002302 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002303 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002304 break;
2305 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002306 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002307 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002308 unsigned OpNum = 0;
2309 Value *BasePtr;
2310 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002311 return Error("Invalid GEP record");
2312
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002313 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002314 while (OpNum != Record.size()) {
2315 Value *Op;
2316 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002317 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002318 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002319 }
2320
Jay Foada9203102011-07-25 09:48:08 +00002321 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002322 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002323 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002324 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002325 break;
2326 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002327
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002328 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2329 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002330 unsigned OpNum = 0;
2331 Value *Agg;
2332 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2333 return Error("Invalid EXTRACTVAL record");
2334
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002335 SmallVector<unsigned, 4> EXTRACTVALIdx;
2336 for (unsigned RecSize = Record.size();
2337 OpNum != RecSize; ++OpNum) {
2338 uint64_t Index = Record[OpNum];
2339 if ((unsigned)Index != Index)
2340 return Error("Invalid EXTRACTVAL index");
2341 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002342 }
2343
Jay Foadfc6d3a42011-07-13 10:26:04 +00002344 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002345 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002346 break;
2347 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002348
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002349 case bitc::FUNC_CODE_INST_INSERTVAL: {
2350 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002351 unsigned OpNum = 0;
2352 Value *Agg;
2353 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2354 return Error("Invalid INSERTVAL record");
2355 Value *Val;
2356 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2357 return Error("Invalid INSERTVAL record");
2358
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002359 SmallVector<unsigned, 4> INSERTVALIdx;
2360 for (unsigned RecSize = Record.size();
2361 OpNum != RecSize; ++OpNum) {
2362 uint64_t Index = Record[OpNum];
2363 if ((unsigned)Index != Index)
2364 return Error("Invalid INSERTVAL index");
2365 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002366 }
2367
Jay Foadfc6d3a42011-07-13 10:26:04 +00002368 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002369 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002370 break;
2371 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002372
Chris Lattnerabfbf852007-05-06 00:21:25 +00002373 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002374 // obsolete form of select
2375 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002376 unsigned OpNum = 0;
2377 Value *TrueVal, *FalseVal, *Cond;
2378 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002379 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2380 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002381 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002382
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002383 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002384 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002385 break;
2386 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002387
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002388 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2389 // new form of select
2390 // handles select i1 or select [N x i1]
2391 unsigned OpNum = 0;
2392 Value *TrueVal, *FalseVal, *Cond;
2393 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002394 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002395 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2396 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002397
2398 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002399 if (VectorType* vector_type =
2400 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002401 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002402 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002403 return Error("Invalid SELECT condition type");
2404 } else {
2405 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002406 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002407 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002408 }
2409
Gabor Greif051a9502008-04-06 20:25:17 +00002410 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002411 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002412 break;
2413 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002414
Chris Lattner01ff65f2007-05-02 05:16:49 +00002415 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002416 unsigned OpNum = 0;
2417 Value *Vec, *Idx;
2418 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002419 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002420 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002421 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002422 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002423 break;
2424 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002425
Chris Lattner01ff65f2007-05-02 05:16:49 +00002426 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002427 unsigned OpNum = 0;
2428 Value *Vec, *Elt, *Idx;
2429 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002430 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002431 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002432 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002433 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002434 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002435 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002436 break;
2437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002438
Chris Lattnerabfbf852007-05-06 00:21:25 +00002439 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2440 unsigned OpNum = 0;
2441 Value *Vec1, *Vec2, *Mask;
2442 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002443 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002444 return Error("Invalid SHUFFLEVEC record");
2445
Mon P Wangaeb06d22008-11-10 04:46:22 +00002446 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002447 return Error("Invalid SHUFFLEVEC record");
2448 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002449 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002450 break;
2451 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002452
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002453 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2454 // Old form of ICmp/FCmp returning bool
2455 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2456 // both legal on vectors but had different behaviour.
2457 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2458 // FCmp/ICmp returning bool or vector of bool
2459
Chris Lattner7337ab92007-05-06 00:00:00 +00002460 unsigned OpNum = 0;
2461 Value *LHS, *RHS;
2462 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002463 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002464 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002465 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002466
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002467 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002468 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002469 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002470 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002471 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002472 break;
2473 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002474
Chris Lattner231cbcb2007-05-02 04:27:25 +00002475 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002476 {
2477 unsigned Size = Record.size();
2478 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002479 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002480 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002481 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002482 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002483
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002484 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002485 Value *Op = NULL;
2486 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2487 return Error("Invalid RET record");
2488 if (OpNum != Record.size())
2489 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002490
Chris Lattner96a74c52011-06-17 18:09:11 +00002491 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002492 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002493 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002494 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002495 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002496 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002497 return Error("Invalid BR record");
2498 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2499 if (TrueDest == 0)
2500 return Error("Invalid BR record");
2501
Devang Patele8e02132009-09-18 19:26:43 +00002502 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002503 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002504 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002505 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002506 else {
2507 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002508 Value *Cond = getValue(Record, 2, NextValueNo,
2509 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002510 if (FalseDest == 0 || Cond == 0)
2511 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002512 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002513 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002514 }
2515 break;
2516 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002517 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002518 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002519 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002520 // "New" SwitchInst format with case ranges. The changes to write this
2521 // format were reverted but we still recognize bitcode that uses it.
2522 // Hopefully someday we will have support for case ranges and can use
2523 // this format again.
Michael Ilseman407a6162012-11-15 22:34:00 +00002524
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002525 Type *OpTy = getTypeByID(Record[1]);
2526 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2527
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002528 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002529 BasicBlock *Default = getBasicBlock(Record[3]);
2530 if (OpTy == 0 || Cond == 0 || Default == 0)
2531 return Error("Invalid SWITCH record");
2532
2533 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002534
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002535 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2536 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002537
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002538 unsigned CurIdx = 5;
2539 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002540 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002541 unsigned NumItems = Record[CurIdx++];
2542 for (unsigned ci = 0; ci != NumItems; ++ci) {
2543 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002544
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002545 APInt Low;
2546 unsigned ActiveWords = 1;
2547 if (ValueBitWidth > 64)
2548 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002549 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2550 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002551 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002552
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002553 if (!isSingleNumber) {
2554 ActiveWords = 1;
2555 if (ValueBitWidth > 64)
2556 ActiveWords = Record[CurIdx++];
2557 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002558 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2559 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002560 CurIdx += ActiveWords;
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002561
2562 // FIXME: It is not clear whether values in the range should be
2563 // compared as signed or unsigned values. The partially
2564 // implemented changes that used this format in the past used
2565 // unsigned comparisons.
2566 for ( ; Low.ule(High); ++Low)
2567 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002568 } else
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002569 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002570 }
2571 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002572 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2573 cve = CaseVals.end(); cvi != cve; ++cvi)
2574 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002575 }
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002576 I = SI;
2577 break;
2578 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002579
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002580 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002581
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002582 if (Record.size() < 3 || (Record.size() & 1) == 0)
2583 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002584 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002585 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002586 BasicBlock *Default = getBasicBlock(Record[2]);
2587 if (OpTy == 0 || Cond == 0 || Default == 0)
2588 return Error("Invalid SWITCH record");
2589 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002590 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002591 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002592 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002593 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002594 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2595 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2596 if (CaseVal == 0 || DestBB == 0) {
2597 delete SI;
2598 return Error("Invalid SWITCH record!");
2599 }
2600 SI->addCase(CaseVal, DestBB);
2601 }
2602 I = SI;
2603 break;
2604 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002605 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002606 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002607 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002608 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002609 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002610 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002611 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002612 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002613 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002614 InstructionList.push_back(IBI);
2615 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2616 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2617 IBI->addDestination(DestBB);
2618 } else {
2619 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002620 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002621 }
2622 }
2623 I = IBI;
2624 break;
2625 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002626
Duncan Sandsdc024672007-11-27 13:23:08 +00002627 case bitc::FUNC_CODE_INST_INVOKE: {
2628 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002629 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002630 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002631 unsigned CCInfo = Record[1];
2632 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2633 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002634
Chris Lattnera9bb7132007-05-08 05:38:01 +00002635 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002636 Value *Callee;
2637 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002638 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002639
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002640 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2641 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002642 dyn_cast<FunctionType>(CalleeTy->getElementType());
2643
2644 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002645 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2646 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002647 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002648
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002649 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002650 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002651 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2652 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002653 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002654 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002655
Chris Lattner7337ab92007-05-06 00:00:00 +00002656 if (!FTy->isVarArg()) {
2657 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002658 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002659 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002660 // Read type/value pairs for varargs params.
2661 while (OpNum != Record.size()) {
2662 Value *Op;
2663 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2664 return Error("Invalid INVOKE record");
2665 Ops.push_back(Op);
2666 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002667 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002668
Jay Foada3efbb12011-07-15 08:37:34 +00002669 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002670 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002671 cast<InvokeInst>(I)->setCallingConv(
2672 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002673 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002674 break;
2675 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002676 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2677 unsigned Idx = 0;
2678 Value *Val = 0;
2679 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2680 return Error("Invalid RESUME record");
2681 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002682 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002683 break;
2684 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002685 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002686 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002687 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002688 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002689 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002690 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002691 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002692 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002693 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002694
Jay Foad3ecfc862011-03-30 11:28:46 +00002695 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002696 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002697
Chris Lattner15e6d172007-05-04 19:11:41 +00002698 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002699 Value *V;
2700 // With the new function encoding, it is possible that operands have
2701 // negative IDs (for forward references). Use a signed VBR
2702 // representation to keep the encoding small.
2703 if (UseRelativeIDs)
2704 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2705 else
2706 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002707 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002708 if (!V || !BB) return Error("Invalid PHI record");
2709 PN->addIncoming(V, BB);
2710 }
2711 I = PN;
2712 break;
2713 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002714
Bill Wendlinge6e88262011-08-12 20:24:12 +00002715 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2716 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2717 unsigned Idx = 0;
2718 if (Record.size() < 4)
2719 return Error("Invalid LANDINGPAD record");
2720 Type *Ty = getTypeByID(Record[Idx++]);
2721 if (!Ty) return Error("Invalid LANDINGPAD record");
2722 Value *PersFn = 0;
2723 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2724 return Error("Invalid LANDINGPAD record");
2725
2726 bool IsCleanup = !!Record[Idx++];
2727 unsigned NumClauses = Record[Idx++];
2728 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2729 LP->setCleanup(IsCleanup);
2730 for (unsigned J = 0; J != NumClauses; ++J) {
2731 LandingPadInst::ClauseType CT =
2732 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2733 Value *Val;
2734
2735 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2736 delete LP;
2737 return Error("Invalid LANDINGPAD record");
2738 }
2739
2740 assert((CT != LandingPadInst::Catch ||
2741 !isa<ArrayType>(Val->getType())) &&
2742 "Catch clause has a invalid type!");
2743 assert((CT != LandingPadInst::Filter ||
2744 isa<ArrayType>(Val->getType())) &&
2745 "Filter clause has invalid type!");
2746 LP->addClause(Val);
2747 }
2748
2749 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002750 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002751 break;
2752 }
2753
Chris Lattner96a74c52011-06-17 18:09:11 +00002754 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2755 if (Record.size() != 4)
2756 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002757 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002758 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002759 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002760 Value *Size = getFnValueByID(Record[2], OpTy);
2761 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002762 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002763 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002764 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002765 break;
2766 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002767 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002768 unsigned OpNum = 0;
2769 Value *Op;
2770 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2771 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002772 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002773
Chris Lattner7337ab92007-05-06 00:00:00 +00002774 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002775 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002776 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002777 }
Eli Friedman21006d42011-08-09 23:02:53 +00002778 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2779 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2780 unsigned OpNum = 0;
2781 Value *Op;
2782 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2783 OpNum+4 != Record.size())
2784 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002785
Eli Friedman21006d42011-08-09 23:02:53 +00002786
2787 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2788 if (Ordering == NotAtomic || Ordering == Release ||
2789 Ordering == AcquireRelease)
2790 return Error("Invalid LOADATOMIC record");
2791 if (Ordering != NotAtomic && Record[OpNum] == 0)
2792 return Error("Invalid LOADATOMIC record");
2793 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2794
2795 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2796 Ordering, SynchScope);
2797 InstructionList.push_back(I);
2798 break;
2799 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002800 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002801 unsigned OpNum = 0;
2802 Value *Val, *Ptr;
2803 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002804 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002805 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2806 OpNum+2 != Record.size())
2807 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002808
Christopher Lambfe63fb92007-12-11 08:59:05 +00002809 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002810 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002811 break;
2812 }
Eli Friedman21006d42011-08-09 23:02:53 +00002813 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2814 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2815 unsigned OpNum = 0;
2816 Value *Val, *Ptr;
2817 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002818 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002819 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2820 OpNum+4 != Record.size())
2821 return Error("Invalid STOREATOMIC record");
2822
2823 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002824 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002825 Ordering == AcquireRelease)
2826 return Error("Invalid STOREATOMIC record");
2827 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2828 if (Ordering != NotAtomic && Record[OpNum] == 0)
2829 return Error("Invalid STOREATOMIC record");
2830
2831 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2832 Ordering, SynchScope);
2833 InstructionList.push_back(I);
2834 break;
2835 }
Eli Friedmanff030482011-07-28 21:48:00 +00002836 case bitc::FUNC_CODE_INST_CMPXCHG: {
2837 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2838 unsigned OpNum = 0;
2839 Value *Ptr, *Cmp, *New;
2840 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002841 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002842 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002843 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002844 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2845 OpNum+3 != Record.size())
2846 return Error("Invalid CMPXCHG record");
2847 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002848 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002849 return Error("Invalid CMPXCHG record");
2850 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2851 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2852 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2853 InstructionList.push_back(I);
2854 break;
2855 }
2856 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2857 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2858 unsigned OpNum = 0;
2859 Value *Ptr, *Val;
2860 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002861 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002862 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2863 OpNum+4 != Record.size())
2864 return Error("Invalid ATOMICRMW record");
2865 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2866 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2867 Operation > AtomicRMWInst::LAST_BINOP)
2868 return Error("Invalid ATOMICRMW record");
2869 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002870 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002871 return Error("Invalid ATOMICRMW record");
2872 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2873 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2874 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2875 InstructionList.push_back(I);
2876 break;
2877 }
Eli Friedman47f35132011-07-25 23:16:38 +00002878 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2879 if (2 != Record.size())
2880 return Error("Invalid FENCE record");
2881 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2882 if (Ordering == NotAtomic || Ordering == Unordered ||
2883 Ordering == Monotonic)
2884 return Error("Invalid FENCE record");
2885 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2886 I = new FenceInst(Context, Ordering, SynchScope);
2887 InstructionList.push_back(I);
2888 break;
2889 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002890 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002891 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2892 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002893 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002894
Bill Wendling99faa3b2012-12-07 23:16:57 +00002895 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002896 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002897
Chris Lattnera9bb7132007-05-08 05:38:01 +00002898 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002899 Value *Callee;
2900 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2901 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002902
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002903 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2904 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002905 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002906 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002907 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002908
Chris Lattner0579f7f2007-05-03 22:04:19 +00002909 SmallVector<Value*, 16> Args;
2910 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002911 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002912 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002913 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002914 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002915 Args.push_back(getValue(Record, OpNum, NextValueNo,
2916 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002917 if (Args.back() == 0) return Error("Invalid CALL record");
2918 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002919
Chris Lattner0579f7f2007-05-03 22:04:19 +00002920 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002921 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002922 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002923 return Error("Invalid CALL record");
2924 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002925 while (OpNum != Record.size()) {
2926 Value *Op;
2927 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2928 return Error("Invalid CALL record");
2929 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002930 }
2931 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002932
Jay Foada3efbb12011-07-15 08:37:34 +00002933 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002934 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002935 cast<CallInst>(I)->setCallingConv(
2936 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002937 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002938 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002939 break;
2940 }
2941 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2942 if (Record.size() < 3)
2943 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002944 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002945 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002946 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002947 if (!OpTy || !Op || !ResTy)
2948 return Error("Invalid VAARG record");
2949 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002950 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002951 break;
2952 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002953 }
2954
2955 // Add instruction to end of current BB. If there is no current BB, reject
2956 // this file.
2957 if (CurBB == 0) {
2958 delete I;
2959 return Error("Invalid instruction with no BB");
2960 }
2961 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002962
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002963 // If this was a terminator instruction, move to the next block.
2964 if (isa<TerminatorInst>(I)) {
2965 ++CurBBNo;
2966 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2967 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002968
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002969 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002970 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002971 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002972 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002973
Chris Lattner5a4251c2013-01-20 02:13:19 +00002974OutOfRecordLoop:
Joe Abbeyacb61942013-02-06 22:14:06 +00002975
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002976 // Check the function list for unresolved values.
2977 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2978 if (A->getParent() == 0) {
2979 // We found at least one unresolved value. Nuke them all to avoid leaks.
2980 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002981 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002982 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002983 delete A;
2984 }
2985 }
Chris Lattner35a04702007-05-04 03:50:29 +00002986 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002987 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002988 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002989
Dan Gohman064ff3e2010-08-25 20:23:38 +00002990 // FIXME: Check for unresolved forward-declared metadata references
2991 // and clean up leaks.
2992
Chris Lattner50b136d2009-10-28 05:53:48 +00002993 // See if anything took the address of blocks in this function. If so,
2994 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002995 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2996 BlockAddrFwdRefs.find(F);
2997 if (BAFRI != BlockAddrFwdRefs.end()) {
2998 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2999 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3000 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00003001 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00003002 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00003003
Chris Lattner50b136d2009-10-28 05:53:48 +00003004 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00003005 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00003006 FwdRef->eraseFromParent();
3007 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003008
Chris Lattner50b136d2009-10-28 05:53:48 +00003009 BlockAddrFwdRefs.erase(BAFRI);
3010 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003011
Chris Lattner980e5aa2007-05-01 05:52:21 +00003012 // Trim the value list down to the size it was before we parsed this function.
3013 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00003014 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00003015 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00003016 return false;
3017}
3018
Derek Schuff2ea93872012-02-06 22:30:29 +00003019/// FindFunctionInStream - Find the function body in the bitcode stream
3020bool BitcodeReader::FindFunctionInStream(Function *F,
3021 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3022 while (DeferredFunctionInfoIterator->second == 0) {
3023 if (Stream.AtEndOfStream())
3024 return Error("Could not find Function in stream");
3025 // ParseModule will parse the next body in the stream and set its
3026 // position in the DeferredFunctionInfo map.
3027 if (ParseModule(true)) return true;
3028 }
3029 return false;
3030}
3031
Chris Lattnerb348bb82007-05-18 04:02:46 +00003032//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003033// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00003034//===----------------------------------------------------------------------===//
3035
3036
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003037bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3038 if (const Function *F = dyn_cast<Function>(GV)) {
3039 return F->isDeclaration() &&
3040 DeferredFunctionInfo.count(const_cast<Function*>(F));
3041 }
3042 return false;
3043}
Daniel Dunbara279bc32009-09-20 02:20:51 +00003044
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003045bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
3046 Function *F = dyn_cast<Function>(GV);
3047 // If it's not a function or is already material, ignore the request.
3048 if (!F || !F->isMaterializable()) return false;
3049
3050 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00003051 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00003052 // If its position is recorded as 0, its body is somewhere in the stream
3053 // but we haven't seen it yet.
3054 if (DFII->second == 0)
3055 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003056
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003057 // Move the bit stream to the saved position of the deferred function body.
3058 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003059
Chris Lattnerb348bb82007-05-18 04:02:46 +00003060 if (ParseFunctionBody(F)) {
3061 if (ErrInfo) *ErrInfo = ErrorString;
3062 return true;
3063 }
Chandler Carruth69940402007-08-04 01:51:18 +00003064
3065 // Upgrade any old intrinsic calls in the function.
3066 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3067 E = UpgradedIntrinsics.end(); I != E; ++I) {
3068 if (I->first != I->second) {
3069 for (Value::use_iterator UI = I->first->use_begin(),
3070 UE = I->first->use_end(); UI != UE; ) {
3071 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3072 UpgradeIntrinsicCall(CI, I->second);
3073 }
3074 }
3075 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003076
Chris Lattnerb348bb82007-05-18 04:02:46 +00003077 return false;
3078}
3079
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003080bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3081 const Function *F = dyn_cast<Function>(GV);
3082 if (!F || F->isDeclaration())
3083 return false;
3084 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3085}
3086
3087void BitcodeReader::Dematerialize(GlobalValue *GV) {
3088 Function *F = dyn_cast<Function>(GV);
3089 // If this function isn't dematerializable, this is a noop.
3090 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00003091 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003092
Chris Lattnerb348bb82007-05-18 04:02:46 +00003093 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003094
Chris Lattnerb348bb82007-05-18 04:02:46 +00003095 // Just forget the function body, we can remat it later.
3096 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00003097}
3098
3099
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003100bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
3101 assert(M == TheModule &&
3102 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00003103 // Iterate over the module, deserializing any functions that are still on
3104 // disk.
3105 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3106 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003107 if (F->isMaterializable() &&
3108 Materialize(F, ErrInfo))
3109 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00003110
Derek Schuff0ffe6982012-02-29 00:07:09 +00003111 // At this point, if there are any function bodies, the current bit is
3112 // pointing to the END_BLOCK record after them. Now make sure the rest
3113 // of the bits in the module have been read.
3114 if (NextUnreadBit)
3115 ParseModule(true);
3116
Daniel Dunbara279bc32009-09-20 02:20:51 +00003117 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3118 // delete the old functions to clean up. We can't do this unless the entire
3119 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00003120 // with calls to the old function.
3121 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3122 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3123 if (I->first != I->second) {
3124 for (Value::use_iterator UI = I->first->use_begin(),
3125 UE = I->first->use_end(); UI != UE; ) {
3126 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3127 UpgradeIntrinsicCall(CI, I->second);
3128 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00003129 if (!I->first->use_empty())
3130 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00003131 I->first->eraseFromParent();
3132 }
3133 }
3134 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00003135
Manman Ren804f0342013-09-28 00:22:27 +00003136 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3137 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3138
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003139 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003140}
3141
Derek Schuff2ea93872012-02-06 22:30:29 +00003142bool BitcodeReader::InitStream() {
3143 if (LazyStreamer) return InitLazyStream();
3144 return InitStreamFromBuffer();
3145}
3146
3147bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00003148 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00003149 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3150
3151 if (Buffer->getBufferSize() & 3) {
3152 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3153 return Error("Invalid bitcode signature");
3154 else
3155 return Error("Bitcode stream should be a multiple of 4 bytes in length");
3156 }
3157
3158 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3159 // The magic number is 0x0B17C0DE stored in little endian.
3160 if (isBitcodeWrapper(BufPtr, BufEnd))
3161 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3162 return Error("Invalid bitcode wrapper header");
3163
3164 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3165 Stream.init(*StreamFile);
3166
3167 return false;
3168}
3169
3170bool BitcodeReader::InitLazyStream() {
3171 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3172 // see it.
3173 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3174 StreamFile.reset(new BitstreamReader(Bytes));
3175 Stream.init(*StreamFile);
3176
3177 unsigned char buf[16];
Benjamin Kramer49a6a8d2013-05-24 10:54:58 +00003178 if (Bytes->readBytes(0, 16, buf) == -1)
Derek Schuff2ea93872012-02-06 22:30:29 +00003179 return Error("Bitcode stream must be at least 16 bytes in length");
3180
3181 if (!isBitcode(buf, buf + 16))
3182 return Error("Invalid bitcode signature");
3183
3184 if (isBitcodeWrapper(buf, buf + 4)) {
3185 const unsigned char *bitcodeStart = buf;
3186 const unsigned char *bitcodeEnd = buf + 16;
3187 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3188 Bytes->dropLeadingBytes(bitcodeStart - buf);
3189 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3190 }
3191 return false;
3192}
Chris Lattner48f84872007-05-01 04:59:48 +00003193
Chris Lattnerc453f762007-04-29 07:54:31 +00003194//===----------------------------------------------------------------------===//
3195// External interface
3196//===----------------------------------------------------------------------===//
3197
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003198/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00003199///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003200Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3201 LLVMContext& Context,
3202 std::string *ErrMsg) {
3203 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00003204 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003205 M->setMaterializer(R);
3206 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00003207 if (ErrMsg)
3208 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003209
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003210 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00003211 return 0;
3212 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003213 // Have the BitcodeReader dtor delete 'Buffer'.
3214 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00003215
3216 R->materializeForwardReferencedFunctions();
3217
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003218 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00003219}
3220
Derek Schuff2ea93872012-02-06 22:30:29 +00003221
3222Module *llvm::getStreamedBitcodeModule(const std::string &name,
3223 DataStreamer *streamer,
3224 LLVMContext &Context,
3225 std::string *ErrMsg) {
3226 Module *M = new Module(name, Context);
3227 BitcodeReader *R = new BitcodeReader(streamer, Context);
3228 M->setMaterializer(R);
3229 if (R->ParseBitcodeInto(M)) {
3230 if (ErrMsg)
3231 *ErrMsg = R->getErrorString();
3232 delete M; // Also deletes R.
3233 return 0;
3234 }
3235 R->setBufferOwned(false); // no buffer to delete
3236 return M;
3237}
3238
Chris Lattnerc453f762007-04-29 07:54:31 +00003239/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3240/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003241Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00003242 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003243 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3244 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003245
3246 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3247 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003248 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003249
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003250 // Read in the entire module, and destroy the BitcodeReader.
3251 if (M->MaterializeAllPermanently(ErrMsg)) {
3252 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003253 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003254 }
Bill Wendling34711742010-10-06 01:22:42 +00003255
Chad Rosiercbbb0962011-12-07 21:44:12 +00003256 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3257 // written. We must defer until the Module has been fully materialized.
3258
Chris Lattnerc453f762007-04-29 07:54:31 +00003259 return M;
3260}
Bill Wendling34711742010-10-06 01:22:42 +00003261
3262std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3263 LLVMContext& Context,
3264 std::string *ErrMsg) {
3265 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3266 // Don't let the BitcodeReader dtor delete 'Buffer'.
3267 R->setBufferOwned(false);
3268
3269 std::string Triple("");
3270 if (R->ParseTriple(Triple))
3271 if (ErrMsg)
3272 *ErrMsg = R->getErrorString();
3273
3274 delete R;
3275 return Triple;
3276}