blob: 3fca4ab8e0ddb0d2a3a15930fb98b69bbfde0afc [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:
626 std::string Buf;
627 raw_string_ostream fmt(Buf);
628 fmt << "Unknown attribute kind (" << Code << ")";
629 fmt.flush();
630 return Error(Buf.c_str());
631 }
632}
633
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000634bool BitcodeReader::ParseAttributeGroupBlock() {
635 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
636 return Error("Malformed block record");
637
638 if (!MAttributeGroups.empty())
639 return Error("Multiple PARAMATTR_GROUP blocks found!");
640
641 SmallVector<uint64_t, 64> Record;
642
643 // Read all the records.
644 while (1) {
645 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
646
647 switch (Entry.Kind) {
648 case BitstreamEntry::SubBlock: // Handled for us already.
649 case BitstreamEntry::Error:
650 return Error("Error at end of PARAMATTR_GROUP block");
651 case BitstreamEntry::EndBlock:
652 return false;
653 case BitstreamEntry::Record:
654 // The interesting case.
655 break;
656 }
657
658 // Read a record.
659 Record.clear();
660 switch (Stream.readRecord(Entry.ID, Record)) {
661 default: // Default behavior: ignore.
662 break;
663 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
664 if (Record.size() < 3)
665 return Error("Invalid ENTRY record");
666
Bill Wendling04ef4be2013-02-11 22:32:29 +0000667 uint64_t GrpID = Record[0];
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000668 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
669
670 AttrBuilder B;
671 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
672 if (Record[i] == 0) { // Enum attribute
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000673 Attribute::AttrKind Kind;
674 if (ParseAttrKind(Record[++i], &Kind))
675 return true;
676
677 B.addAttribute(Kind);
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000678 } else if (Record[i] == 1) { // Align attribute
Tobias Grossere7bc5bb2013-07-26 04:16:55 +0000679 Attribute::AttrKind Kind;
680 if (ParseAttrKind(Record[++i], &Kind))
681 return true;
682 if (Kind == Attribute::Alignment)
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000683 B.addAlignmentAttr(Record[++i]);
684 else
685 B.addStackAlignmentAttr(Record[++i]);
686 } else { // String attribute
Bill Wendling04ef4be2013-02-11 22:32:29 +0000687 assert((Record[i] == 3 || Record[i] == 4) &&
688 "Invalid attribute group entry");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000689 bool HasValue = (Record[i++] == 4);
690 SmallString<64> KindStr;
691 SmallString<64> ValStr;
692
693 while (Record[i] != 0 && i != e)
694 KindStr += Record[i++];
Bill Wendling04ef4be2013-02-11 22:32:29 +0000695 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000696
697 if (HasValue) {
698 // Has a value associated with it.
Bill Wendling04ef4be2013-02-11 22:32:29 +0000699 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000700 while (Record[i] != 0 && i != e)
701 ValStr += Record[i++];
Bill Wendling04ef4be2013-02-11 22:32:29 +0000702 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000703 }
704
705 B.addAttribute(KindStr.str(), ValStr.str());
706 }
707 }
708
Bill Wendling04ef4be2013-02-11 22:32:29 +0000709 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000710 break;
711 }
712 }
713 }
714}
715
Chris Lattner86697142007-05-01 05:01:34 +0000716bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000717 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000718 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000719
Chris Lattner1afcace2011-07-09 17:41:24 +0000720 return ParseTypeTableBody();
721}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000722
Chris Lattner1afcace2011-07-09 17:41:24 +0000723bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000724 if (!TypeList.empty())
725 return Error("Multiple TYPE_BLOCKs found!");
726
727 SmallVector<uint64_t, 64> Record;
728 unsigned NumRecords = 0;
729
Chris Lattner1afcace2011-07-09 17:41:24 +0000730 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000731
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000732 // Read all the records for this type table.
733 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000734 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000735
Chris Lattner5a4251c2013-01-20 02:13:19 +0000736 switch (Entry.Kind) {
737 case BitstreamEntry::SubBlock: // Handled for us already.
738 case BitstreamEntry::Error:
739 Error("Error in the type table block");
740 return true;
741 case BitstreamEntry::EndBlock:
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000742 if (NumRecords != TypeList.size())
743 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000744 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000745 case BitstreamEntry::Record:
746 // The interesting case.
747 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000748 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000749
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000750 // Read a record.
751 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000752 Type *ResultTy = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000753 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000754 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000755 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
756 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
757 // type list. This allows us to reserve space.
758 if (Record.size() < 1)
759 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000760 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000761 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000762 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000763 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000764 break;
Dan Gohmance163392011-12-17 00:04:22 +0000765 case bitc::TYPE_CODE_HALF: // HALF
766 ResultTy = Type::getHalfTy(Context);
767 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000768 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000769 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000770 break;
771 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000772 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000773 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000774 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000775 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000776 break;
777 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000778 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000779 break;
780 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000781 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000782 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000783 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000784 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000785 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000786 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000787 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000788 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000789 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
790 ResultTy = Type::getX86_MMXTy(Context);
791 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000792 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
793 if (Record.size() < 1)
794 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000795
Owen Anderson1d0be152009-08-13 21:58:54 +0000796 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000797 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000798 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000799 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000800 if (Record.size() < 1)
801 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000802 unsigned AddressSpace = 0;
803 if (Record.size() == 2)
804 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000805 ResultTy = getTypeByID(Record[0]);
806 if (ResultTy == 0) return Error("invalid element type in pointer type");
807 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000808 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000809 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000810 case bitc::TYPE_CODE_FUNCTION_OLD: {
811 // FIXME: attrid is dead, remove it in LLVM 4.0
812 // FUNCTION: [vararg, attrid, retty, paramty x N]
813 if (Record.size() < 3)
814 return Error("Invalid FUNCTION type record");
815 SmallVector<Type*, 8> ArgTys;
816 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
817 if (Type *T = getTypeByID(Record[i]))
818 ArgTys.push_back(T);
819 else
820 break;
821 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000822
Nuno Lopesee8100d2012-05-23 15:19:39 +0000823 ResultTy = getTypeByID(Record[2]);
824 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
825 return Error("invalid type in function type");
826
827 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
828 break;
829 }
Chad Rosiercde54642011-11-03 00:14:01 +0000830 case bitc::TYPE_CODE_FUNCTION: {
831 // FUNCTION: [vararg, retty, paramty x N]
832 if (Record.size() < 2)
833 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000834 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000835 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
836 if (Type *T = getTypeByID(Record[i]))
837 ArgTys.push_back(T);
838 else
839 break;
840 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000841
Chad Rosiercde54642011-11-03 00:14:01 +0000842 ResultTy = getTypeByID(Record[1]);
843 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
844 return Error("invalid type in function type");
845
846 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
847 break;
848 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000849 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000850 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000851 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000852 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000853 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
854 if (Type *T = getTypeByID(Record[i]))
855 EltTys.push_back(T);
856 else
857 break;
858 }
859 if (EltTys.size() != Record.size()-1)
860 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000861 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000862 break;
863 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000864 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
865 if (ConvertToString(Record, 0, TypeName))
866 return Error("Invalid STRUCT_NAME record");
867 continue;
868
869 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
870 if (Record.size() < 1)
871 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000872
Chris Lattner1afcace2011-07-09 17:41:24 +0000873 if (NumRecords >= TypeList.size())
874 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000875
Chris Lattner1afcace2011-07-09 17:41:24 +0000876 // Check to see if this was forward referenced, if so fill in the temp.
877 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
878 if (Res) {
879 Res->setName(TypeName);
880 TypeList[NumRecords] = 0;
881 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000882 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000883 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000884
Chris Lattner1afcace2011-07-09 17:41:24 +0000885 SmallVector<Type*, 8> EltTys;
886 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
887 if (Type *T = getTypeByID(Record[i]))
888 EltTys.push_back(T);
889 else
890 break;
891 }
892 if (EltTys.size() != Record.size()-1)
893 return Error("invalid STRUCT type record");
894 Res->setBody(EltTys, Record[0]);
895 ResultTy = Res;
896 break;
897 }
898 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
899 if (Record.size() != 1)
900 return Error("Invalid OPAQUE type record");
901
902 if (NumRecords >= TypeList.size())
903 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000904
Chris Lattner1afcace2011-07-09 17:41:24 +0000905 // Check to see if this was forward referenced, if so fill in the temp.
906 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
907 if (Res) {
908 Res->setName(TypeName);
909 TypeList[NumRecords] = 0;
910 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000911 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000912 TypeName.clear();
913 ResultTy = Res;
914 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000915 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000916 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
917 if (Record.size() < 2)
918 return Error("Invalid ARRAY type record");
919 if ((ResultTy = getTypeByID(Record[1])))
920 ResultTy = ArrayType::get(ResultTy, Record[0]);
921 else
922 return Error("Invalid ARRAY type element");
923 break;
924 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
925 if (Record.size() < 2)
926 return Error("Invalid VECTOR type record");
927 if ((ResultTy = getTypeByID(Record[1])))
928 ResultTy = VectorType::get(ResultTy, Record[0]);
929 else
930 return Error("Invalid ARRAY type element");
931 break;
932 }
933
934 if (NumRecords >= TypeList.size())
935 return Error("invalid TYPE table");
936 assert(ResultTy && "Didn't read a type?");
937 assert(TypeList[NumRecords] == 0 && "Already read type?");
938 TypeList[NumRecords++] = ResultTy;
939 }
940}
941
Chris Lattner86697142007-05-01 05:01:34 +0000942bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000943 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000944 return Error("Malformed block record");
945
946 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000947
Chris Lattner0b2482a2007-04-23 21:26:05 +0000948 // Read all the records for this value table.
949 SmallString<128> ValueName;
950 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000951 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000952
Chris Lattner5a4251c2013-01-20 02:13:19 +0000953 switch (Entry.Kind) {
954 case BitstreamEntry::SubBlock: // Handled for us already.
955 case BitstreamEntry::Error:
956 return Error("malformed value symbol table block");
957 case BitstreamEntry::EndBlock:
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000958 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000959 case BitstreamEntry::Record:
960 // The interesting case.
961 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000962 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000963
Chris Lattner0b2482a2007-04-23 21:26:05 +0000964 // Read a record.
965 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000966 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000967 default: // Default behavior: unknown type.
968 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000969 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000970 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000971 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000972 unsigned ValueID = Record[0];
973 if (ValueID >= ValueList.size())
974 return Error("Invalid Value ID in VST_ENTRY record");
975 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000976
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000977 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000978 ValueName.clear();
979 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000980 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000981 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000982 if (ConvertToString(Record, 1, ValueName))
983 return Error("Invalid VST_BBENTRY record");
984 BasicBlock *BB = getBasicBlock(Record[0]);
985 if (BB == 0)
986 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000987
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000988 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000989 ValueName.clear();
990 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000991 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000992 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000993 }
994}
995
Devang Patele54abc92009-07-22 17:43:22 +0000996bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000997 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000998
999 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1000 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001001
Devang Patele54abc92009-07-22 17:43:22 +00001002 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001003
Devang Patele54abc92009-07-22 17:43:22 +00001004 // Read all the records.
1005 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001006 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001007
Chris Lattner5a4251c2013-01-20 02:13:19 +00001008 switch (Entry.Kind) {
1009 case BitstreamEntry::SubBlock: // Handled for us already.
1010 case BitstreamEntry::Error:
1011 Error("malformed metadata block");
1012 return true;
1013 case BitstreamEntry::EndBlock:
Devang Patele54abc92009-07-22 17:43:22 +00001014 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001015 case BitstreamEntry::Record:
1016 // The interesting case.
1017 break;
Devang Patele54abc92009-07-22 17:43:22 +00001018 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001019
Victor Hernandez24e64df2010-01-10 07:14:18 +00001020 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +00001021 // Read a record.
1022 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001023 unsigned Code = Stream.readRecord(Entry.ID, Record);
Dan Gohman9b10dfb2010-09-13 18:00:48 +00001024 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +00001025 default: // Default behavior: ignore.
1026 break;
Devang Patelaa993142009-07-29 22:34:41 +00001027 case bitc::METADATA_NAME: {
Chris Lattner1ca114a2013-01-20 02:54:05 +00001028 // Read name of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001029 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +00001030 Record.clear();
1031 Code = Stream.ReadCode();
1032
Chris Lattner9d61dd92011-06-17 17:50:30 +00001033 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001034 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001035 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +00001036
1037 // Read named metadata elements.
1038 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +00001039 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +00001040 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +00001041 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1042 if (MD == 0)
1043 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +00001044 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +00001045 }
Devang Patelaa993142009-07-29 22:34:41 +00001046 break;
1047 }
Chris Lattner9d61dd92011-06-17 17:50:30 +00001048 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +00001049 IsFunctionLocal = true;
1050 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +00001051 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +00001052 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +00001053 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001054
Devang Patel104cf9e2009-07-23 01:07:34 +00001055 unsigned Size = Record.size();
1056 SmallVector<Value*, 8> Elts;
1057 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001058 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001059 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001060 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +00001061 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +00001062 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +00001063 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1064 else
1065 Elts.push_back(NULL);
1066 }
Jay Foadec9186b2011-04-21 19:59:31 +00001067 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +00001068 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +00001069 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +00001070 break;
1071 }
Devang Patele54abc92009-07-22 17:43:22 +00001072 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001073 SmallString<8> String(Record.begin(), Record.end());
1074 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +00001075 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +00001076 break;
1077 }
Devang Patele8e02132009-09-18 19:26:43 +00001078 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001079 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001080 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001081
Devang Patela2148402009-09-28 21:14:55 +00001082 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001083 SmallString<8> Name(Record.begin()+1, Record.end());
1084
Chris Lattner08113472009-12-29 09:01:33 +00001085 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +00001086 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1087 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +00001088 break;
1089 }
Devang Patele54abc92009-07-22 17:43:22 +00001090 }
1091 }
1092}
1093
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001094/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +00001095/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001096uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +00001097 if ((V & 1) == 0)
1098 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001099 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +00001100 return -(V >> 1);
1101 // There is no such thing as -0 with integers. "-0" really means MININT.
1102 return 1ULL << 63;
1103}
1104
Chris Lattner07d98b42007-04-26 02:46:40 +00001105/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1106/// values and aliases that we can.
1107bool BitcodeReader::ResolveGlobalAndAliasInits() {
1108 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1109 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001110 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001111
Chris Lattner07d98b42007-04-26 02:46:40 +00001112 GlobalInitWorklist.swap(GlobalInits);
1113 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001114 FunctionPrefixWorklist.swap(FunctionPrefixes);
Chris Lattner07d98b42007-04-26 02:46:40 +00001115
1116 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +00001117 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +00001118 if (ValID >= ValueList.size()) {
1119 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +00001120 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +00001121 } else {
1122 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1123 GlobalInitWorklist.back().first->setInitializer(C);
1124 else
1125 return Error("Global variable initializer is not a constant!");
1126 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001127 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001128 }
1129
1130 while (!AliasInitWorklist.empty()) {
1131 unsigned ValID = AliasInitWorklist.back().second;
1132 if (ValID >= ValueList.size()) {
1133 AliasInits.push_back(AliasInitWorklist.back());
1134 } else {
1135 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +00001136 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +00001137 else
1138 return Error("Alias initializer is not a constant!");
1139 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001140 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001141 }
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001142
1143 while (!FunctionPrefixWorklist.empty()) {
1144 unsigned ValID = FunctionPrefixWorklist.back().second;
1145 if (ValID >= ValueList.size()) {
1146 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1147 } else {
1148 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1149 FunctionPrefixWorklist.back().first->setPrefixData(C);
1150 else
1151 return Error("Function prefix is not a constant!");
1152 }
1153 FunctionPrefixWorklist.pop_back();
1154 }
1155
Chris Lattner07d98b42007-04-26 02:46:40 +00001156 return false;
1157}
1158
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001159static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1160 SmallVector<uint64_t, 8> Words(Vals.size());
1161 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001162 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001163
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001164 return APInt(TypeBits, Words);
1165}
1166
Chris Lattner86697142007-05-01 05:01:34 +00001167bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001168 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +00001169 return Error("Malformed block record");
1170
1171 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001172
Chris Lattnere16504e2007-04-24 03:30:34 +00001173 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001174 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +00001175 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +00001176 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001177 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001178
Chris Lattner5a4251c2013-01-20 02:13:19 +00001179 switch (Entry.Kind) {
1180 case BitstreamEntry::SubBlock: // Handled for us already.
1181 case BitstreamEntry::Error:
1182 return Error("malformed block record in AST file");
1183 case BitstreamEntry::EndBlock:
1184 if (NextCstNo != ValueList.size())
1185 return Error("Invalid constant reference!");
Joe Abbeyacb61942013-02-06 22:14:06 +00001186
Chris Lattner5a4251c2013-01-20 02:13:19 +00001187 // Once all the constants have been read, go through and resolve forward
1188 // references.
1189 ValueList.ResolveConstantForwardRefs();
1190 return false;
1191 case BitstreamEntry::Record:
1192 // The interesting case.
Chris Lattnerea693df2008-08-21 02:34:16 +00001193 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001194 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001195
Chris Lattnere16504e2007-04-24 03:30:34 +00001196 // Read a record.
1197 Record.clear();
1198 Value *V = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001199 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00001200 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001201 default: // Default behavior: unknown constant
1202 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001203 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001204 break;
1205 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1206 if (Record.empty())
1207 return Error("Malformed CST_SETTYPE record");
1208 if (Record[0] >= TypeList.size())
1209 return Error("Invalid Type ID in CST_SETTYPE record");
1210 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001211 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001212 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001213 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001214 break;
1215 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001216 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001217 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001218 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001219 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001220 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001221 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001222 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001223
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001224 APInt VInt = ReadWideAPInt(Record,
1225 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001226 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +00001227
Chris Lattner0eef0802007-04-24 04:04:35 +00001228 break;
1229 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001230 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001231 if (Record.empty())
1232 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001233 if (CurTy->isHalfTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001234 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1235 APInt(16, (uint16_t)Record[0])));
Dan Gohmance163392011-12-17 00:04:22 +00001236 else if (CurTy->isFloatTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001237 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1238 APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001239 else if (CurTy->isDoubleTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001240 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1241 APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001242 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001243 // Bits are not stored the same way as a normal i80 APInt, compensate.
1244 uint64_t Rearrange[2];
1245 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1246 Rearrange[1] = Record[0] >> 48;
Tim Northover0a29cb02013-01-22 09:46:31 +00001247 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1248 APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001249 } else if (CurTy->isFP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001250 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1251 APInt(128, Record)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001252 else if (CurTy->isPPC_FP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001253 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1254 APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001255 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001256 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001257 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001258 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001259
Chris Lattner15e6d172007-05-04 19:11:41 +00001260 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1261 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001262 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001263
Chris Lattner15e6d172007-05-04 19:11:41 +00001264 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001265 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001266
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001267 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001268 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001269 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001270 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001271 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001272 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1273 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001274 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001275 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001276 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001277 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1278 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001279 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001280 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001281 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001282 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001283 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001284 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001285 break;
1286 }
Chris Lattner2237f842012-02-05 02:41:35 +00001287 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001288 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1289 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001290 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001291
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001292 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001293 V = ConstantDataArray::getString(Context, Elts,
1294 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001295 break;
1296 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001297 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1298 if (Record.empty())
1299 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001300
Chris Lattnerd408f062012-01-30 00:51:16 +00001301 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1302 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001303
Chris Lattnerd408f062012-01-30 00:51:16 +00001304 if (EltTy->isIntegerTy(8)) {
1305 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1306 if (isa<VectorType>(CurTy))
1307 V = ConstantDataVector::get(Context, Elts);
1308 else
1309 V = ConstantDataArray::get(Context, Elts);
1310 } else if (EltTy->isIntegerTy(16)) {
1311 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1312 if (isa<VectorType>(CurTy))
1313 V = ConstantDataVector::get(Context, Elts);
1314 else
1315 V = ConstantDataArray::get(Context, Elts);
1316 } else if (EltTy->isIntegerTy(32)) {
1317 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1318 if (isa<VectorType>(CurTy))
1319 V = ConstantDataVector::get(Context, Elts);
1320 else
1321 V = ConstantDataArray::get(Context, Elts);
1322 } else if (EltTy->isIntegerTy(64)) {
1323 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1324 if (isa<VectorType>(CurTy))
1325 V = ConstantDataVector::get(Context, Elts);
1326 else
1327 V = ConstantDataArray::get(Context, Elts);
1328 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001329 SmallVector<float, 16> Elts(Size);
1330 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001331 if (isa<VectorType>(CurTy))
1332 V = ConstantDataVector::get(Context, Elts);
1333 else
1334 V = ConstantDataArray::get(Context, Elts);
1335 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001336 SmallVector<double, 16> Elts(Size);
1337 std::transform(Record.begin(), Record.end(), Elts.begin(),
1338 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001339 if (isa<VectorType>(CurTy))
1340 V = ConstantDataVector::get(Context, Elts);
1341 else
1342 V = ConstantDataArray::get(Context, Elts);
1343 } else {
1344 return Error("Unknown element type in CE_DATA");
1345 }
1346 break;
1347 }
1348
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001349 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1350 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1351 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001352 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001353 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001354 } else {
1355 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1356 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001357 unsigned Flags = 0;
1358 if (Record.size() >= 4) {
1359 if (Opc == Instruction::Add ||
1360 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001361 Opc == Instruction::Mul ||
1362 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001363 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1364 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1365 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1366 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001367 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001368 Opc == Instruction::UDiv ||
1369 Opc == Instruction::LShr ||
1370 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001371 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001372 Flags |= SDivOperator::IsExact;
1373 }
1374 }
1375 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001376 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001377 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001378 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001379 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1380 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1381 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001382 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001383 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001384 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001385 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001386 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001387 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001388 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001389 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001390 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001391 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001392 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001393 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001394 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001395 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001396 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001397 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001398 if (!ElTy) return Error("Invalid CE_GEP record");
1399 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1400 }
Jay Foaddab3d292011-07-21 14:31:17 +00001401 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001402 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1403 BitCode ==
1404 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001405 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001406 }
Joe Abbey405b6502013-09-12 22:02:31 +00001407 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001408 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbey405b6502013-09-12 22:02:31 +00001409
1410 Type *SelectorTy = Type::getInt1Ty(Context);
1411
1412 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1413 // vector. Otherwise, it must be a single bit.
1414 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1415 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1416 VTy->getNumElements());
1417
1418 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1419 SelectorTy),
1420 ValueList.getConstantFwdRef(Record[1],CurTy),
1421 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001422 break;
Joe Abbey405b6502013-09-12 22:02:31 +00001423 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001424 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1425 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001426 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001427 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1428 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1429 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001430 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001431 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001432 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001433 break;
1434 }
1435 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001436 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001437 if (Record.size() < 3 || OpTy == 0)
1438 return Error("Invalid CE_INSERTELT record");
1439 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1440 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1441 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001442 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001443 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001444 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001445 break;
1446 }
1447 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001448 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001449 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001450 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001451 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1452 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001453 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001454 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001455 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001456 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001457 break;
1458 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001459 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001460 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1461 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001462 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001463 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1464 return Error("Invalid CE_SHUFVEC_EX record");
1465 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1466 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001467 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001468 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001469 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001470 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001471 break;
1472 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001473 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1474 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001475 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001476 if (OpTy == 0) return Error("Invalid CE_CMP record");
1477 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1478 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1479
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001480 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001481 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001482 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001483 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001484 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001485 }
Chad Rosier581600b2012-09-05 19:00:49 +00001486 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001487 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001488 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001489 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1490 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001491 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001492 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001493 unsigned AsmStrSize = Record[1];
1494 if (2+AsmStrSize >= Record.size())
1495 return Error("Invalid INLINEASM record");
1496 unsigned ConstStrSize = Record[2+AsmStrSize];
1497 if (3+AsmStrSize+ConstStrSize > Record.size())
1498 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001499
Chris Lattner2bce93a2007-05-06 01:58:20 +00001500 for (unsigned i = 0; i != AsmStrSize; ++i)
1501 AsmStr += (char)Record[2+i];
1502 for (unsigned i = 0; i != ConstStrSize; ++i)
1503 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001504 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001505 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001506 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001507 break;
1508 }
Chad Rosier581600b2012-09-05 19:00:49 +00001509 // This version adds support for the asm dialect keywords (e.g.,
1510 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001511 case bitc::CST_CODE_INLINEASM: {
1512 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1513 std::string AsmStr, ConstrStr;
1514 bool HasSideEffects = Record[0] & 1;
1515 bool IsAlignStack = (Record[0] >> 1) & 1;
1516 unsigned AsmDialect = Record[0] >> 2;
1517 unsigned AsmStrSize = Record[1];
1518 if (2+AsmStrSize >= Record.size())
1519 return Error("Invalid INLINEASM record");
1520 unsigned ConstStrSize = Record[2+AsmStrSize];
1521 if (3+AsmStrSize+ConstStrSize > Record.size())
1522 return Error("Invalid INLINEASM record");
1523
1524 for (unsigned i = 0; i != AsmStrSize; ++i)
1525 AsmStr += (char)Record[2+i];
1526 for (unsigned i = 0; i != ConstStrSize; ++i)
1527 ConstrStr += (char)Record[3+AsmStrSize+i];
1528 PointerType *PTy = cast<PointerType>(CurTy);
1529 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1530 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001531 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001532 break;
1533 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001534 case bitc::CST_CODE_BLOCKADDRESS:{
1535 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001536 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001537 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1538 Function *Fn =
1539 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1540 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001541
1542 // If the function is already parsed we can insert the block address right
1543 // away.
1544 if (!Fn->empty()) {
1545 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1546 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1547 if (BBI == BBE)
1548 return Error("Invalid blockaddress block #");
1549 ++BBI;
1550 }
1551 V = BlockAddress::get(Fn, BBI);
1552 } else {
1553 // Otherwise insert a placeholder and remember it so it can be inserted
1554 // when the function is parsed.
1555 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1556 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001557 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001558 0, "");
1559 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1560 V = FwdRef;
1561 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001562 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001563 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001564 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001565
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001566 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001567 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001568 }
1569}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001570
Chad Rosiercbbb0962011-12-07 21:44:12 +00001571bool BitcodeReader::ParseUseLists() {
1572 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1573 return Error("Malformed block record");
1574
1575 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001576
Chad Rosiercbbb0962011-12-07 21:44:12 +00001577 // Read all the records.
1578 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001579 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001580
Chris Lattner5a4251c2013-01-20 02:13:19 +00001581 switch (Entry.Kind) {
1582 case BitstreamEntry::SubBlock: // Handled for us already.
1583 case BitstreamEntry::Error:
1584 return Error("malformed use list block");
1585 case BitstreamEntry::EndBlock:
Chad Rosiercbbb0962011-12-07 21:44:12 +00001586 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001587 case BitstreamEntry::Record:
1588 // The interesting case.
1589 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001590 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001591
Chad Rosiercbbb0962011-12-07 21:44:12 +00001592 // Read a use list record.
1593 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001594 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosiercbbb0962011-12-07 21:44:12 +00001595 default: // Default behavior: unknown type.
1596 break;
1597 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1598 unsigned RecordLength = Record.size();
1599 if (RecordLength < 1)
1600 return Error ("Invalid UseList reader!");
1601 UseListRecords.push_back(Record);
1602 break;
1603 }
1604 }
1605 }
1606}
1607
Chris Lattner980e5aa2007-05-01 05:52:21 +00001608/// RememberAndSkipFunctionBody - When we see the block for a function body,
1609/// remember where it is and then skip it. This lets us lazily deserialize the
1610/// functions.
1611bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001612 // Get the function we are talking about.
1613 if (FunctionsWithBodies.empty())
1614 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001615
Chris Lattner48f84872007-05-01 04:59:48 +00001616 Function *Fn = FunctionsWithBodies.back();
1617 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001618
Chris Lattner48f84872007-05-01 04:59:48 +00001619 // Save the current stream state.
1620 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001621 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Chris Lattner48f84872007-05-01 04:59:48 +00001623 // Skip over the function block for now.
1624 if (Stream.SkipBlock())
1625 return Error("Malformed block record");
1626 return false;
1627}
1628
Derek Schuff2ea93872012-02-06 22:30:29 +00001629bool BitcodeReader::GlobalCleanup() {
1630 // Patch the initializers for globals and aliases up.
1631 ResolveGlobalAndAliasInits();
1632 if (!GlobalInits.empty() || !AliasInits.empty())
1633 return Error("Malformed global initializer set");
1634
1635 // Look for intrinsic functions which need to be upgraded at some point
1636 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1637 FI != FE; ++FI) {
1638 Function *NewFn;
1639 if (UpgradeIntrinsicFunction(FI, NewFn))
1640 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1641 }
1642
1643 // Look for global variables which need to be renamed.
1644 for (Module::global_iterator
1645 GI = TheModule->global_begin(), GE = TheModule->global_end();
1646 GI != GE; ++GI)
1647 UpgradeGlobalVariable(GI);
1648 // Force deallocation of memory for these vectors to favor the client that
1649 // want lazy deserialization.
1650 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1651 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1652 return false;
1653}
1654
1655bool BitcodeReader::ParseModule(bool Resume) {
1656 if (Resume)
1657 Stream.JumpToBit(NextUnreadBit);
1658 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001659 return Error("Malformed block record");
1660
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001661 SmallVector<uint64_t, 64> Record;
1662 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001663 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001664
1665 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001666 while (1) {
1667 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00001668
Chris Lattner5a4251c2013-01-20 02:13:19 +00001669 switch (Entry.Kind) {
1670 case BitstreamEntry::Error:
1671 Error("malformed module block");
1672 return true;
1673 case BitstreamEntry::EndBlock:
Derek Schuff2ea93872012-02-06 22:30:29 +00001674 return GlobalCleanup();
Joe Abbeyacb61942013-02-06 22:14:06 +00001675
Chris Lattner5a4251c2013-01-20 02:13:19 +00001676 case BitstreamEntry::SubBlock:
1677 switch (Entry.ID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001678 default: // Skip unknown content.
1679 if (Stream.SkipBlock())
1680 return Error("Malformed block record");
1681 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001682 case bitc::BLOCKINFO_BLOCK_ID:
1683 if (Stream.ReadBlockInfoBlock())
1684 return Error("Malformed BlockInfoBlock");
1685 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001686 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001687 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001688 return true;
1689 break;
Bill Wendlingc3ba0a82013-02-10 23:24:25 +00001690 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1691 if (ParseAttributeGroupBlock())
1692 return true;
1693 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001694 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001695 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001696 return true;
1697 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001698 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001699 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001700 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001701 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001702 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001703 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001704 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001705 return true;
1706 break;
Devang Patele54abc92009-07-22 17:43:22 +00001707 case bitc::METADATA_BLOCK_ID:
1708 if (ParseMetadata())
1709 return true;
1710 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001711 case bitc::FUNCTION_BLOCK_ID:
1712 // If this is the first function body we've seen, reverse the
1713 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001714 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001715 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001716 if (GlobalCleanup())
1717 return true;
1718 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001719 }
Joe Abbeyacb61942013-02-06 22:14:06 +00001720
Chris Lattner980e5aa2007-05-01 05:52:21 +00001721 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001722 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001723 // For streaming bitcode, suspend parsing when we reach the function
1724 // bodies. Subsequent materialization calls will resume it when
1725 // necessary. For streaming, the function bodies must be at the end of
1726 // the bitcode. If the bitcode file is old, the symbol table will be
1727 // at the end instead and will not have been seen yet. In this case,
1728 // just finish the parse now.
1729 if (LazyStreamer && SeenValueSymbolTable) {
1730 NextUnreadBit = Stream.GetCurrentBitNo();
1731 return false;
1732 }
Chris Lattner48f84872007-05-01 04:59:48 +00001733 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001734 case bitc::USELIST_BLOCK_ID:
1735 if (ParseUseLists())
1736 return true;
1737 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001738 }
1739 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00001740
Chris Lattner5a4251c2013-01-20 02:13:19 +00001741 case BitstreamEntry::Record:
1742 // The interesting case.
1743 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001744 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001745
Daniel Dunbara279bc32009-09-20 02:20:51 +00001746
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001747 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001748 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001749 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001750 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001751 if (Record.size() < 1)
1752 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001753 // Only version #0 and #1 are supported so far.
1754 unsigned module_version = Record[0];
1755 switch (module_version) {
1756 default: return Error("Unknown bitstream version!");
1757 case 0:
1758 UseRelativeIDs = false;
1759 break;
1760 case 1:
1761 UseRelativeIDs = true;
1762 break;
1763 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001764 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001765 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001766 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001767 std::string S;
1768 if (ConvertToString(Record, 0, S))
1769 return Error("Invalid MODULE_CODE_TRIPLE record");
1770 TheModule->setTargetTriple(S);
1771 break;
1772 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001773 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001774 std::string S;
1775 if (ConvertToString(Record, 0, S))
1776 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1777 TheModule->setDataLayout(S);
1778 break;
1779 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001780 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001781 std::string S;
1782 if (ConvertToString(Record, 0, S))
1783 return Error("Invalid MODULE_CODE_ASM record");
1784 TheModule->setModuleInlineAsm(S);
1785 break;
1786 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001787 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1788 // FIXME: Remove in 4.0.
1789 std::string S;
1790 if (ConvertToString(Record, 0, S))
1791 return Error("Invalid MODULE_CODE_DEPLIB record");
1792 // Ignore value.
1793 break;
1794 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001795 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001796 std::string S;
1797 if (ConvertToString(Record, 0, S))
1798 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1799 SectionTable.push_back(S);
1800 break;
1801 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001802 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001803 std::string S;
1804 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001805 return Error("Invalid MODULE_CODE_GCNAME record");
1806 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001807 break;
1808 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001809 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001810 // linkage, alignment, section, visibility, threadlocal,
1811 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001812 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001813 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001814 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001815 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001816 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001817 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001818 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001819 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001820 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001821
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001822 bool isConstant = Record[1];
1823 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1824 unsigned Alignment = (1 << Record[4]) >> 1;
1825 std::string Section;
1826 if (Record[5]) {
1827 if (Record[5]-1 >= SectionTable.size())
1828 return Error("Invalid section ID");
1829 Section = SectionTable[Record[5]-1];
1830 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001831 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001832 if (Record.size() > 6)
1833 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001834
1835 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001836 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001837 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001838
Rafael Espindolabea46262011-01-08 16:42:36 +00001839 bool UnnamedAddr = false;
1840 if (Record.size() > 8)
1841 UnnamedAddr = Record[8];
1842
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001843 bool ExternallyInitialized = false;
1844 if (Record.size() > 9)
1845 ExternallyInitialized = Record[9];
1846
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001847 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001849 TLM, AddressSpace, ExternallyInitialized);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001850 NewGV->setAlignment(Alignment);
Shuxin Yang8e3851a2013-10-23 17:28:19 +00001851 if (Record.size() > 10)
1852 NewGV->setAddressMaybeTaken(Record[10]);
1853
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001854 if (!Section.empty())
1855 NewGV->setSection(Section);
1856 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001857 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001858
Chris Lattner0b2482a2007-04-23 21:26:05 +00001859 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001860
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001861 // Remember which value to use for the global initializer.
1862 if (unsigned InitID = Record[2])
1863 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001864 break;
1865 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001866 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001867 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001868 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001869 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001870 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001871 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001872 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001873 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001874 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001875 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001876 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1877 if (!FTy)
1878 return Error("Function not a pointer to function type!");
1879
Gabor Greif051a9502008-04-06 20:25:17 +00001880 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1881 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001882
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001883 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001884 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001885 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001886 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001887
Chris Lattnera9bb7132007-05-08 05:38:01 +00001888 Func->setAlignment((1 << Record[5]) >> 1);
1889 if (Record[6]) {
1890 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001891 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001892 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001893 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001894 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001895 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001896 if (Record[8]-1 > GCTable.size())
1897 return Error("Invalid GC ID");
1898 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001899 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001900 bool UnnamedAddr = false;
1901 if (Record.size() > 9)
1902 UnnamedAddr = Record[9];
1903 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne1e3037f2013-09-16 01:08:15 +00001904 if (Record.size() > 10 && Record[10] != 0)
1905 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
Chris Lattner0b2482a2007-04-23 21:26:05 +00001906 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001907
Chris Lattner48f84872007-05-01 04:59:48 +00001908 // If this is a function with a body, remember the prototype we are
1909 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001910 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001911 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001912 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1913 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001914 break;
1915 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001916 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001917 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001918 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001919 if (Record.size() < 3)
1920 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001921 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001922 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001923 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001924 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001925
Chris Lattner07d98b42007-04-26 02:46:40 +00001926 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1927 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001928 // Old bitcode files didn't have visibility field.
1929 if (Record.size() > 3)
1930 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001931 ValueList.push_back(NewGA);
1932 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1933 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001934 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001935 /// MODULE_CODE_PURGEVALS: [numvals]
1936 case bitc::MODULE_CODE_PURGEVALS:
1937 // Trim down the value list to the specified size.
1938 if (Record.size() < 1 || Record[0] > ValueList.size())
1939 return Error("Invalid MODULE_PURGEVALS record");
1940 ValueList.shrinkTo(Record[0]);
1941 break;
1942 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001943 Record.clear();
1944 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001945}
1946
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001947bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001948 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001949
Derek Schuff2ea93872012-02-06 22:30:29 +00001950 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001951
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001952 // Sniff for the signature.
1953 if (Stream.Read(8) != 'B' ||
1954 Stream.Read(8) != 'C' ||
1955 Stream.Read(4) != 0x0 ||
1956 Stream.Read(4) != 0xC ||
1957 Stream.Read(4) != 0xE ||
1958 Stream.Read(4) != 0xD)
1959 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001960
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001961 // We expect a number of well-defined blocks, though we don't necessarily
1962 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001963 while (1) {
1964 if (Stream.AtEndOfStream())
1965 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001966
Chris Lattner5a4251c2013-01-20 02:13:19 +00001967 BitstreamEntry Entry =
1968 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbeyacb61942013-02-06 22:14:06 +00001969
Chris Lattner5a4251c2013-01-20 02:13:19 +00001970 switch (Entry.Kind) {
1971 case BitstreamEntry::Error:
1972 Error("malformed module file");
1973 return true;
1974 case BitstreamEntry::EndBlock:
1975 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001976
Chris Lattner5a4251c2013-01-20 02:13:19 +00001977 case BitstreamEntry::SubBlock:
1978 switch (Entry.ID) {
1979 case bitc::BLOCKINFO_BLOCK_ID:
1980 if (Stream.ReadBlockInfoBlock())
1981 return Error("Malformed BlockInfoBlock");
1982 break;
1983 case bitc::MODULE_BLOCK_ID:
1984 // Reject multiple MODULE_BLOCK's in a single bitstream.
1985 if (TheModule)
1986 return Error("Multiple MODULE_BLOCKs in same stream");
1987 TheModule = M;
1988 if (ParseModule(false))
1989 return true;
1990 if (LazyStreamer) return false;
1991 break;
1992 default:
1993 if (Stream.SkipBlock())
1994 return Error("Malformed block record");
1995 break;
1996 }
1997 continue;
1998 case BitstreamEntry::Record:
1999 // There should be no records in the top-level of blocks.
Joe Abbeyacb61942013-02-06 22:14:06 +00002000
Chris Lattner5a4251c2013-01-20 02:13:19 +00002001 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosier6ff9aa22011-08-09 22:23:40 +00002002 // to the end of them. If this file size is a multiple of 4 but not 8, we
2003 // have to read and ignore these final 4 bytes :-(
Chris Lattner5a4251c2013-01-20 02:13:19 +00002004 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolac9687b32011-05-26 18:59:54 +00002005 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00002006 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00002007 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00002008
Chris Lattnercaee0dc2007-04-22 06:23:29 +00002009 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00002010 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00002011 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00002012}
Chris Lattnerc453f762007-04-29 07:54:31 +00002013
Bill Wendling34711742010-10-06 01:22:42 +00002014bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
2015 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2016 return Error("Malformed block record");
2017
2018 SmallVector<uint64_t, 64> Record;
2019
2020 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00002021 while (1) {
2022 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00002023
Chris Lattner5a4251c2013-01-20 02:13:19 +00002024 switch (Entry.Kind) {
2025 case BitstreamEntry::SubBlock: // Handled for us already.
2026 case BitstreamEntry::Error:
2027 return Error("malformed module block");
2028 case BitstreamEntry::EndBlock:
Bill Wendling34711742010-10-06 01:22:42 +00002029 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002030 case BitstreamEntry::Record:
2031 // The interesting case.
2032 break;
Bill Wendling34711742010-10-06 01:22:42 +00002033 }
2034
2035 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00002036 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling34711742010-10-06 01:22:42 +00002037 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00002038 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2039 std::string S;
2040 if (ConvertToString(Record, 0, S))
2041 return Error("Invalid MODULE_CODE_TRIPLE record");
2042 Triple = S;
2043 break;
2044 }
2045 }
2046 Record.clear();
2047 }
Bill Wendling34711742010-10-06 01:22:42 +00002048}
2049
2050bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00002051 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00002052
2053 // Sniff for the signature.
2054 if (Stream.Read(8) != 'B' ||
2055 Stream.Read(8) != 'C' ||
2056 Stream.Read(4) != 0x0 ||
2057 Stream.Read(4) != 0xC ||
2058 Stream.Read(4) != 0xE ||
2059 Stream.Read(4) != 0xD)
2060 return Error("Invalid bitcode signature");
2061
2062 // We expect a number of well-defined blocks, though we don't necessarily
2063 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00002064 while (1) {
2065 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00002066
Chris Lattner5a4251c2013-01-20 02:13:19 +00002067 switch (Entry.Kind) {
2068 case BitstreamEntry::Error:
2069 Error("malformed module file");
2070 return true;
2071 case BitstreamEntry::EndBlock:
2072 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00002073
Chris Lattner5a4251c2013-01-20 02:13:19 +00002074 case BitstreamEntry::SubBlock:
2075 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2076 return ParseModuleTriple(Triple);
Joe Abbeyacb61942013-02-06 22:14:06 +00002077
Chris Lattner5a4251c2013-01-20 02:13:19 +00002078 // Ignore other sub-blocks.
2079 if (Stream.SkipBlock()) {
2080 Error("malformed block record in AST file");
Bill Wendling34711742010-10-06 01:22:42 +00002081 return true;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002082 }
2083 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00002084
Chris Lattner5a4251c2013-01-20 02:13:19 +00002085 case BitstreamEntry::Record:
2086 Stream.skipRecord(Entry.ID);
2087 continue;
Bill Wendling34711742010-10-06 01:22:42 +00002088 }
2089 }
Bill Wendling34711742010-10-06 01:22:42 +00002090}
2091
Devang Patele8e02132009-09-18 19:26:43 +00002092/// ParseMetadataAttachment - Parse metadata attachments.
2093bool BitcodeReader::ParseMetadataAttachment() {
2094 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2095 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002096
Devang Patele8e02132009-09-18 19:26:43 +00002097 SmallVector<uint64_t, 64> Record;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002098 while (1) {
2099 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00002100
Chris Lattner5a4251c2013-01-20 02:13:19 +00002101 switch (Entry.Kind) {
2102 case BitstreamEntry::SubBlock: // Handled for us already.
2103 case BitstreamEntry::Error:
2104 return Error("malformed metadata block");
2105 case BitstreamEntry::EndBlock:
2106 return false;
2107 case BitstreamEntry::Record:
2108 // The interesting case.
Devang Patele8e02132009-09-18 19:26:43 +00002109 break;
2110 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00002111
Devang Patele8e02132009-09-18 19:26:43 +00002112 // Read a metadata attachment record.
2113 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00002114 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patele8e02132009-09-18 19:26:43 +00002115 default: // Default behavior: ignore.
2116 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00002117 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00002118 unsigned RecordLength = Record.size();
2119 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002120 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00002121 Instruction *Inst = InstructionList[Record[0]];
2122 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00002123 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00002124 DenseMap<unsigned, unsigned>::iterator I =
2125 MDKindMap.find(Kind);
2126 if (I == MDKindMap.end())
2127 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002128 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00002129 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren804f0342013-09-28 00:22:27 +00002130 if (I->second == LLVMContext::MD_tbaa)
2131 InstsWithTBAATag.push_back(Inst);
Devang Patele8e02132009-09-18 19:26:43 +00002132 }
2133 break;
2134 }
2135 }
2136 }
Devang Patele8e02132009-09-18 19:26:43 +00002137}
Chris Lattner48f84872007-05-01 04:59:48 +00002138
Chris Lattner980e5aa2007-05-01 05:52:21 +00002139/// ParseFunctionBody - Lazily parse the specified function body block.
2140bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00002141 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00002142 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002143
Nick Lewycky9a49f152010-02-25 08:30:17 +00002144 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002145 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00002146 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002147
Chris Lattner980e5aa2007-05-01 05:52:21 +00002148 // Add all the function arguments to the value table.
2149 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2150 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002151
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002152 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00002153 BasicBlock *CurBB = 0;
2154 unsigned CurBBNo = 0;
2155
Chris Lattnera6245242010-04-03 02:17:50 +00002156 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00002157
Chris Lattner980e5aa2007-05-01 05:52:21 +00002158 // Read all the records.
2159 SmallVector<uint64_t, 64> Record;
2160 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00002161 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00002162
Chris Lattner5a4251c2013-01-20 02:13:19 +00002163 switch (Entry.Kind) {
2164 case BitstreamEntry::Error:
2165 return Error("Bitcode error in function block");
2166 case BitstreamEntry::EndBlock:
2167 goto OutOfRecordLoop;
Joe Abbeyacb61942013-02-06 22:14:06 +00002168
Chris Lattner5a4251c2013-01-20 02:13:19 +00002169 case BitstreamEntry::SubBlock:
2170 switch (Entry.ID) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00002171 default: // Skip unknown content.
2172 if (Stream.SkipBlock())
2173 return Error("Malformed block record");
2174 break;
2175 case bitc::CONSTANTS_BLOCK_ID:
2176 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002177 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002178 break;
2179 case bitc::VALUE_SYMTAB_BLOCK_ID:
2180 if (ParseValueSymbolTable()) return true;
2181 break;
Devang Patele8e02132009-09-18 19:26:43 +00002182 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002183 if (ParseMetadataAttachment()) return true;
2184 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00002185 case bitc::METADATA_BLOCK_ID:
2186 if (ParseMetadata()) return true;
2187 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002188 }
2189 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00002190
Chris Lattner5a4251c2013-01-20 02:13:19 +00002191 case BitstreamEntry::Record:
2192 // The interesting case.
2193 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002194 }
Joe Abbeyacb61942013-02-06 22:14:06 +00002195
Chris Lattner980e5aa2007-05-01 05:52:21 +00002196 // Read a record.
2197 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002198 Instruction *I = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002199 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00002200 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002201 default: // Default behavior: reject
2202 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002203 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002204 if (Record.size() < 1 || Record[0] == 0)
2205 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002206 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00002207 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002208 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00002209 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002210 CurBB = FunctionBBs[0];
2211 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002212
Chris Lattnera6245242010-04-03 02:17:50 +00002213 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2214 // This record indicates that the last instruction is at the same
2215 // location as the previous instruction with a location.
2216 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00002217
Chris Lattnera6245242010-04-03 02:17:50 +00002218 // Get the last instruction emitted.
2219 if (CurBB && !CurBB->empty())
2220 I = &CurBB->back();
2221 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2222 !FunctionBBs[CurBBNo-1]->empty())
2223 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00002224
Chris Lattnera6245242010-04-03 02:17:50 +00002225 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2226 I->setDebugLoc(LastLoc);
2227 I = 0;
2228 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002229
Chris Lattner4f6bab92011-06-17 18:17:37 +00002230 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002231 I = 0; // Get the last instruction emitted.
2232 if (CurBB && !CurBB->empty())
2233 I = &CurBB->back();
2234 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2235 !FunctionBBs[CurBBNo-1]->empty())
2236 I = &FunctionBBs[CurBBNo-1]->back();
2237 if (I == 0 || Record.size() < 4)
2238 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002239
Chris Lattnera6245242010-04-03 02:17:50 +00002240 unsigned Line = Record[0], Col = Record[1];
2241 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00002242
Chris Lattnera6245242010-04-03 02:17:50 +00002243 MDNode *Scope = 0, *IA = 0;
2244 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2245 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2246 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2247 I->setDebugLoc(LastLoc);
2248 I = 0;
2249 continue;
2250 }
2251
Chris Lattnerabfbf852007-05-06 00:21:25 +00002252 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2253 unsigned OpNum = 0;
2254 Value *LHS, *RHS;
2255 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002256 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002257 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002258 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002259
Dan Gohman1224c382009-07-20 21:19:07 +00002260 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002261 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002262 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002263 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002264 if (OpNum < Record.size()) {
2265 if (Opc == Instruction::Add ||
2266 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002267 Opc == Instruction::Mul ||
2268 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002269 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002270 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002271 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002272 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002273 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002274 Opc == Instruction::UDiv ||
2275 Opc == Instruction::LShr ||
2276 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002277 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002278 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002279 } else if (isa<FPMathOperator>(I)) {
2280 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002281 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2282 FMF.setUnsafeAlgebra();
2283 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2284 FMF.setNoNaNs();
2285 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2286 FMF.setNoInfs();
2287 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2288 FMF.setNoSignedZeros();
2289 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2290 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002291 if (FMF.any())
2292 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002293 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002294
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002295 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002296 break;
2297 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002298 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2299 unsigned OpNum = 0;
2300 Value *Op;
2301 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2302 OpNum+2 != Record.size())
2303 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002304
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002305 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002306 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2307 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002308 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002309 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002310 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002311 break;
2312 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002313 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002314 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002315 unsigned OpNum = 0;
2316 Value *BasePtr;
2317 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002318 return Error("Invalid GEP record");
2319
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002320 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002321 while (OpNum != Record.size()) {
2322 Value *Op;
2323 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002324 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002325 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002326 }
2327
Jay Foada9203102011-07-25 09:48:08 +00002328 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002329 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002330 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002331 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002332 break;
2333 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002334
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002335 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2336 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002337 unsigned OpNum = 0;
2338 Value *Agg;
2339 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2340 return Error("Invalid EXTRACTVAL record");
2341
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002342 SmallVector<unsigned, 4> EXTRACTVALIdx;
2343 for (unsigned RecSize = Record.size();
2344 OpNum != RecSize; ++OpNum) {
2345 uint64_t Index = Record[OpNum];
2346 if ((unsigned)Index != Index)
2347 return Error("Invalid EXTRACTVAL index");
2348 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002349 }
2350
Jay Foadfc6d3a42011-07-13 10:26:04 +00002351 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002352 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002353 break;
2354 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002355
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002356 case bitc::FUNC_CODE_INST_INSERTVAL: {
2357 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002358 unsigned OpNum = 0;
2359 Value *Agg;
2360 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2361 return Error("Invalid INSERTVAL record");
2362 Value *Val;
2363 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2364 return Error("Invalid INSERTVAL record");
2365
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002366 SmallVector<unsigned, 4> INSERTVALIdx;
2367 for (unsigned RecSize = Record.size();
2368 OpNum != RecSize; ++OpNum) {
2369 uint64_t Index = Record[OpNum];
2370 if ((unsigned)Index != Index)
2371 return Error("Invalid INSERTVAL index");
2372 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002373 }
2374
Jay Foadfc6d3a42011-07-13 10:26:04 +00002375 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002376 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002377 break;
2378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002379
Chris Lattnerabfbf852007-05-06 00:21:25 +00002380 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002381 // obsolete form of select
2382 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002383 unsigned OpNum = 0;
2384 Value *TrueVal, *FalseVal, *Cond;
2385 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002386 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2387 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002388 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002389
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002390 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002391 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002392 break;
2393 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002394
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002395 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2396 // new form of select
2397 // handles select i1 or select [N x i1]
2398 unsigned OpNum = 0;
2399 Value *TrueVal, *FalseVal, *Cond;
2400 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002401 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002402 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2403 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002404
2405 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002406 if (VectorType* vector_type =
2407 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002408 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002409 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002410 return Error("Invalid SELECT condition type");
2411 } else {
2412 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002413 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002414 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002415 }
2416
Gabor Greif051a9502008-04-06 20:25:17 +00002417 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002418 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002419 break;
2420 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002421
Chris Lattner01ff65f2007-05-02 05:16:49 +00002422 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002423 unsigned OpNum = 0;
2424 Value *Vec, *Idx;
2425 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002426 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002427 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002428 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002429 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002430 break;
2431 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002432
Chris Lattner01ff65f2007-05-02 05:16:49 +00002433 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002434 unsigned OpNum = 0;
2435 Value *Vec, *Elt, *Idx;
2436 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002437 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002438 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002439 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002440 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002441 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002442 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002443 break;
2444 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002445
Chris Lattnerabfbf852007-05-06 00:21:25 +00002446 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2447 unsigned OpNum = 0;
2448 Value *Vec1, *Vec2, *Mask;
2449 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002450 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002451 return Error("Invalid SHUFFLEVEC record");
2452
Mon P Wangaeb06d22008-11-10 04:46:22 +00002453 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002454 return Error("Invalid SHUFFLEVEC record");
2455 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002456 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002457 break;
2458 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002459
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002460 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2461 // Old form of ICmp/FCmp returning bool
2462 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2463 // both legal on vectors but had different behaviour.
2464 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2465 // FCmp/ICmp returning bool or vector of bool
2466
Chris Lattner7337ab92007-05-06 00:00:00 +00002467 unsigned OpNum = 0;
2468 Value *LHS, *RHS;
2469 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002470 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002471 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002472 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002473
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002474 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002475 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002476 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002477 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002478 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002479 break;
2480 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002481
Chris Lattner231cbcb2007-05-02 04:27:25 +00002482 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002483 {
2484 unsigned Size = Record.size();
2485 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002486 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002487 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002488 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002489 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002490
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002491 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002492 Value *Op = NULL;
2493 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2494 return Error("Invalid RET record");
2495 if (OpNum != Record.size())
2496 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002497
Chris Lattner96a74c52011-06-17 18:09:11 +00002498 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002499 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002500 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002501 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002502 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002503 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002504 return Error("Invalid BR record");
2505 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2506 if (TrueDest == 0)
2507 return Error("Invalid BR record");
2508
Devang Patele8e02132009-09-18 19:26:43 +00002509 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002510 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002511 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002512 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002513 else {
2514 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002515 Value *Cond = getValue(Record, 2, NextValueNo,
2516 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002517 if (FalseDest == 0 || Cond == 0)
2518 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002519 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002520 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002521 }
2522 break;
2523 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002524 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002525 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002526 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002527 // "New" SwitchInst format with case ranges. The changes to write this
2528 // format were reverted but we still recognize bitcode that uses it.
2529 // Hopefully someday we will have support for case ranges and can use
2530 // this format again.
Michael Ilseman407a6162012-11-15 22:34:00 +00002531
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002532 Type *OpTy = getTypeByID(Record[1]);
2533 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2534
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002535 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002536 BasicBlock *Default = getBasicBlock(Record[3]);
2537 if (OpTy == 0 || Cond == 0 || Default == 0)
2538 return Error("Invalid SWITCH record");
2539
2540 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002541
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002542 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2543 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002544
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002545 unsigned CurIdx = 5;
2546 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002547 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002548 unsigned NumItems = Record[CurIdx++];
2549 for (unsigned ci = 0; ci != NumItems; ++ci) {
2550 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002551
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002552 APInt Low;
2553 unsigned ActiveWords = 1;
2554 if (ValueBitWidth > 64)
2555 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002556 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2557 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002558 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002559
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002560 if (!isSingleNumber) {
2561 ActiveWords = 1;
2562 if (ValueBitWidth > 64)
2563 ActiveWords = Record[CurIdx++];
2564 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002565 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2566 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002567 CurIdx += ActiveWords;
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002568
2569 // FIXME: It is not clear whether values in the range should be
2570 // compared as signed or unsigned values. The partially
2571 // implemented changes that used this format in the past used
2572 // unsigned comparisons.
2573 for ( ; Low.ule(High); ++Low)
2574 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002575 } else
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002576 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002577 }
2578 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsondb3a9e62013-09-09 19:14:35 +00002579 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2580 cve = CaseVals.end(); cvi != cve; ++cvi)
2581 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002582 }
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002583 I = SI;
2584 break;
2585 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002586
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002587 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002588
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002589 if (Record.size() < 3 || (Record.size() & 1) == 0)
2590 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002591 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002592 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002593 BasicBlock *Default = getBasicBlock(Record[2]);
2594 if (OpTy == 0 || Cond == 0 || Default == 0)
2595 return Error("Invalid SWITCH record");
2596 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002597 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002598 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002599 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002600 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002601 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2602 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2603 if (CaseVal == 0 || DestBB == 0) {
2604 delete SI;
2605 return Error("Invalid SWITCH record!");
2606 }
2607 SI->addCase(CaseVal, DestBB);
2608 }
2609 I = SI;
2610 break;
2611 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002612 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002613 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002614 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002615 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002616 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002617 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002618 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002619 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002620 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002621 InstructionList.push_back(IBI);
2622 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2623 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2624 IBI->addDestination(DestBB);
2625 } else {
2626 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002627 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002628 }
2629 }
2630 I = IBI;
2631 break;
2632 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002633
Duncan Sandsdc024672007-11-27 13:23:08 +00002634 case bitc::FUNC_CODE_INST_INVOKE: {
2635 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002636 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002637 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002638 unsigned CCInfo = Record[1];
2639 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2640 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002641
Chris Lattnera9bb7132007-05-08 05:38:01 +00002642 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002643 Value *Callee;
2644 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002645 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002646
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002647 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2648 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002649 dyn_cast<FunctionType>(CalleeTy->getElementType());
2650
2651 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002652 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2653 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002654 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002655
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002656 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002657 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002658 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2659 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002660 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002661 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002662
Chris Lattner7337ab92007-05-06 00:00:00 +00002663 if (!FTy->isVarArg()) {
2664 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002665 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002666 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002667 // Read type/value pairs for varargs params.
2668 while (OpNum != Record.size()) {
2669 Value *Op;
2670 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2671 return Error("Invalid INVOKE record");
2672 Ops.push_back(Op);
2673 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002674 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002675
Jay Foada3efbb12011-07-15 08:37:34 +00002676 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002677 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002678 cast<InvokeInst>(I)->setCallingConv(
2679 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002680 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002681 break;
2682 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002683 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2684 unsigned Idx = 0;
2685 Value *Val = 0;
2686 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2687 return Error("Invalid RESUME record");
2688 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002689 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002690 break;
2691 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002692 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002693 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002694 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002695 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002696 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002697 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002698 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002699 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002700 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002701
Jay Foad3ecfc862011-03-30 11:28:46 +00002702 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002703 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002704
Chris Lattner15e6d172007-05-04 19:11:41 +00002705 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002706 Value *V;
2707 // With the new function encoding, it is possible that operands have
2708 // negative IDs (for forward references). Use a signed VBR
2709 // representation to keep the encoding small.
2710 if (UseRelativeIDs)
2711 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2712 else
2713 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002714 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002715 if (!V || !BB) return Error("Invalid PHI record");
2716 PN->addIncoming(V, BB);
2717 }
2718 I = PN;
2719 break;
2720 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002721
Bill Wendlinge6e88262011-08-12 20:24:12 +00002722 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2723 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2724 unsigned Idx = 0;
2725 if (Record.size() < 4)
2726 return Error("Invalid LANDINGPAD record");
2727 Type *Ty = getTypeByID(Record[Idx++]);
2728 if (!Ty) return Error("Invalid LANDINGPAD record");
2729 Value *PersFn = 0;
2730 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2731 return Error("Invalid LANDINGPAD record");
2732
2733 bool IsCleanup = !!Record[Idx++];
2734 unsigned NumClauses = Record[Idx++];
2735 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2736 LP->setCleanup(IsCleanup);
2737 for (unsigned J = 0; J != NumClauses; ++J) {
2738 LandingPadInst::ClauseType CT =
2739 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2740 Value *Val;
2741
2742 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2743 delete LP;
2744 return Error("Invalid LANDINGPAD record");
2745 }
2746
2747 assert((CT != LandingPadInst::Catch ||
2748 !isa<ArrayType>(Val->getType())) &&
2749 "Catch clause has a invalid type!");
2750 assert((CT != LandingPadInst::Filter ||
2751 isa<ArrayType>(Val->getType())) &&
2752 "Filter clause has invalid type!");
2753 LP->addClause(Val);
2754 }
2755
2756 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002757 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002758 break;
2759 }
2760
Chris Lattner96a74c52011-06-17 18:09:11 +00002761 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2762 if (Record.size() != 4)
2763 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002764 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002765 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002766 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002767 Value *Size = getFnValueByID(Record[2], OpTy);
2768 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002769 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002770 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002771 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002772 break;
2773 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002774 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002775 unsigned OpNum = 0;
2776 Value *Op;
2777 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2778 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002779 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002780
Chris Lattner7337ab92007-05-06 00:00:00 +00002781 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002782 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002783 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002784 }
Eli Friedman21006d42011-08-09 23:02:53 +00002785 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2786 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2787 unsigned OpNum = 0;
2788 Value *Op;
2789 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2790 OpNum+4 != Record.size())
2791 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002792
Eli Friedman21006d42011-08-09 23:02:53 +00002793
2794 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2795 if (Ordering == NotAtomic || Ordering == Release ||
2796 Ordering == AcquireRelease)
2797 return Error("Invalid LOADATOMIC record");
2798 if (Ordering != NotAtomic && Record[OpNum] == 0)
2799 return Error("Invalid LOADATOMIC record");
2800 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2801
2802 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2803 Ordering, SynchScope);
2804 InstructionList.push_back(I);
2805 break;
2806 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002807 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002808 unsigned OpNum = 0;
2809 Value *Val, *Ptr;
2810 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002811 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002812 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2813 OpNum+2 != Record.size())
2814 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002815
Christopher Lambfe63fb92007-12-11 08:59:05 +00002816 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002817 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002818 break;
2819 }
Eli Friedman21006d42011-08-09 23:02:53 +00002820 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2821 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2822 unsigned OpNum = 0;
2823 Value *Val, *Ptr;
2824 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002825 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002826 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2827 OpNum+4 != Record.size())
2828 return Error("Invalid STOREATOMIC record");
2829
2830 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002831 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002832 Ordering == AcquireRelease)
2833 return Error("Invalid STOREATOMIC record");
2834 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2835 if (Ordering != NotAtomic && Record[OpNum] == 0)
2836 return Error("Invalid STOREATOMIC record");
2837
2838 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2839 Ordering, SynchScope);
2840 InstructionList.push_back(I);
2841 break;
2842 }
Eli Friedmanff030482011-07-28 21:48:00 +00002843 case bitc::FUNC_CODE_INST_CMPXCHG: {
2844 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2845 unsigned OpNum = 0;
2846 Value *Ptr, *Cmp, *New;
2847 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002848 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002849 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002850 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002851 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2852 OpNum+3 != Record.size())
2853 return Error("Invalid CMPXCHG record");
2854 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002855 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002856 return Error("Invalid CMPXCHG record");
2857 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2858 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2859 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2860 InstructionList.push_back(I);
2861 break;
2862 }
2863 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2864 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2865 unsigned OpNum = 0;
2866 Value *Ptr, *Val;
2867 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002868 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002869 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2870 OpNum+4 != Record.size())
2871 return Error("Invalid ATOMICRMW record");
2872 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2873 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2874 Operation > AtomicRMWInst::LAST_BINOP)
2875 return Error("Invalid ATOMICRMW record");
2876 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002877 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002878 return Error("Invalid ATOMICRMW record");
2879 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2880 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2881 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2882 InstructionList.push_back(I);
2883 break;
2884 }
Eli Friedman47f35132011-07-25 23:16:38 +00002885 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2886 if (2 != Record.size())
2887 return Error("Invalid FENCE record");
2888 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2889 if (Ordering == NotAtomic || Ordering == Unordered ||
2890 Ordering == Monotonic)
2891 return Error("Invalid FENCE record");
2892 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2893 I = new FenceInst(Context, Ordering, SynchScope);
2894 InstructionList.push_back(I);
2895 break;
2896 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002897 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002898 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2899 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002900 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002901
Bill Wendling99faa3b2012-12-07 23:16:57 +00002902 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002903 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002904
Chris Lattnera9bb7132007-05-08 05:38:01 +00002905 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002906 Value *Callee;
2907 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2908 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002909
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002910 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2911 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002912 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002913 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002914 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002915
Chris Lattner0579f7f2007-05-03 22:04:19 +00002916 SmallVector<Value*, 16> Args;
2917 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002918 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002919 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002920 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002921 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002922 Args.push_back(getValue(Record, OpNum, NextValueNo,
2923 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002924 if (Args.back() == 0) return Error("Invalid CALL record");
2925 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002926
Chris Lattner0579f7f2007-05-03 22:04:19 +00002927 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002928 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002929 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002930 return Error("Invalid CALL record");
2931 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002932 while (OpNum != Record.size()) {
2933 Value *Op;
2934 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2935 return Error("Invalid CALL record");
2936 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002937 }
2938 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002939
Jay Foada3efbb12011-07-15 08:37:34 +00002940 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002941 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002942 cast<CallInst>(I)->setCallingConv(
2943 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002944 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002945 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002946 break;
2947 }
2948 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2949 if (Record.size() < 3)
2950 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002951 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002952 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002953 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002954 if (!OpTy || !Op || !ResTy)
2955 return Error("Invalid VAARG record");
2956 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002957 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002958 break;
2959 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002960 }
2961
2962 // Add instruction to end of current BB. If there is no current BB, reject
2963 // this file.
2964 if (CurBB == 0) {
2965 delete I;
2966 return Error("Invalid instruction with no BB");
2967 }
2968 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002969
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002970 // If this was a terminator instruction, move to the next block.
2971 if (isa<TerminatorInst>(I)) {
2972 ++CurBBNo;
2973 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2974 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002975
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002976 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002977 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002978 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002979 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002980
Chris Lattner5a4251c2013-01-20 02:13:19 +00002981OutOfRecordLoop:
Joe Abbeyacb61942013-02-06 22:14:06 +00002982
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002983 // Check the function list for unresolved values.
2984 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2985 if (A->getParent() == 0) {
2986 // We found at least one unresolved value. Nuke them all to avoid leaks.
2987 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002988 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002989 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002990 delete A;
2991 }
2992 }
Chris Lattner35a04702007-05-04 03:50:29 +00002993 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002994 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002995 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002996
Dan Gohman064ff3e2010-08-25 20:23:38 +00002997 // FIXME: Check for unresolved forward-declared metadata references
2998 // and clean up leaks.
2999
Chris Lattner50b136d2009-10-28 05:53:48 +00003000 // See if anything took the address of blocks in this function. If so,
3001 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00003002 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3003 BlockAddrFwdRefs.find(F);
3004 if (BAFRI != BlockAddrFwdRefs.end()) {
3005 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3006 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3007 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00003008 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00003009 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00003010
Chris Lattner50b136d2009-10-28 05:53:48 +00003011 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00003012 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00003013 FwdRef->eraseFromParent();
3014 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003015
Chris Lattner50b136d2009-10-28 05:53:48 +00003016 BlockAddrFwdRefs.erase(BAFRI);
3017 }
Michael Ilseman407a6162012-11-15 22:34:00 +00003018
Chris Lattner980e5aa2007-05-01 05:52:21 +00003019 // Trim the value list down to the size it was before we parsed this function.
3020 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00003021 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00003022 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00003023 return false;
3024}
3025
Derek Schuff2ea93872012-02-06 22:30:29 +00003026/// FindFunctionInStream - Find the function body in the bitcode stream
3027bool BitcodeReader::FindFunctionInStream(Function *F,
3028 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3029 while (DeferredFunctionInfoIterator->second == 0) {
3030 if (Stream.AtEndOfStream())
3031 return Error("Could not find Function in stream");
3032 // ParseModule will parse the next body in the stream and set its
3033 // position in the DeferredFunctionInfo map.
3034 if (ParseModule(true)) return true;
3035 }
3036 return false;
3037}
3038
Chris Lattnerb348bb82007-05-18 04:02:46 +00003039//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003040// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00003041//===----------------------------------------------------------------------===//
3042
3043
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003044bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3045 if (const Function *F = dyn_cast<Function>(GV)) {
3046 return F->isDeclaration() &&
3047 DeferredFunctionInfo.count(const_cast<Function*>(F));
3048 }
3049 return false;
3050}
Daniel Dunbara279bc32009-09-20 02:20:51 +00003051
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003052bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
3053 Function *F = dyn_cast<Function>(GV);
3054 // If it's not a function or is already material, ignore the request.
3055 if (!F || !F->isMaterializable()) return false;
3056
3057 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00003058 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00003059 // If its position is recorded as 0, its body is somewhere in the stream
3060 // but we haven't seen it yet.
3061 if (DFII->second == 0)
3062 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003063
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003064 // Move the bit stream to the saved position of the deferred function body.
3065 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003066
Chris Lattnerb348bb82007-05-18 04:02:46 +00003067 if (ParseFunctionBody(F)) {
3068 if (ErrInfo) *ErrInfo = ErrorString;
3069 return true;
3070 }
Chandler Carruth69940402007-08-04 01:51:18 +00003071
3072 // Upgrade any old intrinsic calls in the function.
3073 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3074 E = UpgradedIntrinsics.end(); I != E; ++I) {
3075 if (I->first != I->second) {
3076 for (Value::use_iterator UI = I->first->use_begin(),
3077 UE = I->first->use_end(); UI != UE; ) {
3078 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3079 UpgradeIntrinsicCall(CI, I->second);
3080 }
3081 }
3082 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00003083
Chris Lattnerb348bb82007-05-18 04:02:46 +00003084 return false;
3085}
3086
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003087bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3088 const Function *F = dyn_cast<Function>(GV);
3089 if (!F || F->isDeclaration())
3090 return false;
3091 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3092}
3093
3094void BitcodeReader::Dematerialize(GlobalValue *GV) {
3095 Function *F = dyn_cast<Function>(GV);
3096 // If this function isn't dematerializable, this is a noop.
3097 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00003098 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00003099
Chris Lattnerb348bb82007-05-18 04:02:46 +00003100 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00003101
Chris Lattnerb348bb82007-05-18 04:02:46 +00003102 // Just forget the function body, we can remat it later.
3103 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00003104}
3105
3106
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003107bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
3108 assert(M == TheModule &&
3109 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00003110 // Iterate over the module, deserializing any functions that are still on
3111 // disk.
3112 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3113 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003114 if (F->isMaterializable() &&
3115 Materialize(F, ErrInfo))
3116 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00003117
Derek Schuff0ffe6982012-02-29 00:07:09 +00003118 // At this point, if there are any function bodies, the current bit is
3119 // pointing to the END_BLOCK record after them. Now make sure the rest
3120 // of the bits in the module have been read.
3121 if (NextUnreadBit)
3122 ParseModule(true);
3123
Daniel Dunbara279bc32009-09-20 02:20:51 +00003124 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3125 // delete the old functions to clean up. We can't do this unless the entire
3126 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00003127 // with calls to the old function.
3128 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3129 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3130 if (I->first != I->second) {
3131 for (Value::use_iterator UI = I->first->use_begin(),
3132 UE = I->first->use_end(); UI != UE; ) {
3133 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3134 UpgradeIntrinsicCall(CI, I->second);
3135 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00003136 if (!I->first->use_empty())
3137 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00003138 I->first->eraseFromParent();
3139 }
3140 }
3141 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00003142
Manman Ren804f0342013-09-28 00:22:27 +00003143 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3144 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3145
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003146 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003147}
3148
Derek Schuff2ea93872012-02-06 22:30:29 +00003149bool BitcodeReader::InitStream() {
3150 if (LazyStreamer) return InitLazyStream();
3151 return InitStreamFromBuffer();
3152}
3153
3154bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00003155 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00003156 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3157
3158 if (Buffer->getBufferSize() & 3) {
3159 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3160 return Error("Invalid bitcode signature");
3161 else
3162 return Error("Bitcode stream should be a multiple of 4 bytes in length");
3163 }
3164
3165 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3166 // The magic number is 0x0B17C0DE stored in little endian.
3167 if (isBitcodeWrapper(BufPtr, BufEnd))
3168 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3169 return Error("Invalid bitcode wrapper header");
3170
3171 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3172 Stream.init(*StreamFile);
3173
3174 return false;
3175}
3176
3177bool BitcodeReader::InitLazyStream() {
3178 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3179 // see it.
3180 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3181 StreamFile.reset(new BitstreamReader(Bytes));
3182 Stream.init(*StreamFile);
3183
3184 unsigned char buf[16];
Benjamin Kramer49a6a8d2013-05-24 10:54:58 +00003185 if (Bytes->readBytes(0, 16, buf) == -1)
Derek Schuff2ea93872012-02-06 22:30:29 +00003186 return Error("Bitcode stream must be at least 16 bytes in length");
3187
3188 if (!isBitcode(buf, buf + 16))
3189 return Error("Invalid bitcode signature");
3190
3191 if (isBitcodeWrapper(buf, buf + 4)) {
3192 const unsigned char *bitcodeStart = buf;
3193 const unsigned char *bitcodeEnd = buf + 16;
3194 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3195 Bytes->dropLeadingBytes(bitcodeStart - buf);
3196 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3197 }
3198 return false;
3199}
Chris Lattner48f84872007-05-01 04:59:48 +00003200
Chris Lattnerc453f762007-04-29 07:54:31 +00003201//===----------------------------------------------------------------------===//
3202// External interface
3203//===----------------------------------------------------------------------===//
3204
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003205/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00003206///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003207Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3208 LLVMContext& Context,
3209 std::string *ErrMsg) {
3210 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00003211 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003212 M->setMaterializer(R);
3213 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00003214 if (ErrMsg)
3215 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003216
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003217 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00003218 return 0;
3219 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003220 // Have the BitcodeReader dtor delete 'Buffer'.
3221 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00003222
3223 R->materializeForwardReferencedFunctions();
3224
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003225 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00003226}
3227
Derek Schuff2ea93872012-02-06 22:30:29 +00003228
3229Module *llvm::getStreamedBitcodeModule(const std::string &name,
3230 DataStreamer *streamer,
3231 LLVMContext &Context,
3232 std::string *ErrMsg) {
3233 Module *M = new Module(name, Context);
3234 BitcodeReader *R = new BitcodeReader(streamer, Context);
3235 M->setMaterializer(R);
3236 if (R->ParseBitcodeInto(M)) {
3237 if (ErrMsg)
3238 *ErrMsg = R->getErrorString();
3239 delete M; // Also deletes R.
3240 return 0;
3241 }
3242 R->setBufferOwned(false); // no buffer to delete
3243 return M;
3244}
3245
Chris Lattnerc453f762007-04-29 07:54:31 +00003246/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3247/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003248Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00003249 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003250 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3251 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003252
3253 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3254 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003255 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003256
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003257 // Read in the entire module, and destroy the BitcodeReader.
3258 if (M->MaterializeAllPermanently(ErrMsg)) {
3259 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003260 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003261 }
Bill Wendling34711742010-10-06 01:22:42 +00003262
Chad Rosiercbbb0962011-12-07 21:44:12 +00003263 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3264 // written. We must defer until the Module has been fully materialized.
3265
Chris Lattnerc453f762007-04-29 07:54:31 +00003266 return M;
3267}
Bill Wendling34711742010-10-06 01:22:42 +00003268
3269std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3270 LLVMContext& Context,
3271 std::string *ErrMsg) {
3272 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3273 // Don't let the BitcodeReader dtor delete 'Buffer'.
3274 R->setBufferOwned(false);
3275
3276 std::string Triple("");
3277 if (R->ParseTriple(Triple))
3278 if (ErrMsg)
3279 *ErrMsg = R->getErrorString();
3280
3281 delete R;
3282 return Triple;
3283}