blob: cf827c5d4b08d89012514153d89881ac3813e10b [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnercaee0dc2007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
Chris Lattnercaee0dc2007-04-22 06:23:29 +00009
Chris Lattnerc453f762007-04-29 07:54:31 +000010#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000011#include "BitcodeReader.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000012#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/AutoUpgrade.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000015#include "llvm/IR/Constants.h"
16#include "llvm/IR/DerivedTypes.h"
17#include "llvm/IR/InlineAsm.h"
18#include "llvm/IR/IntrinsicInst.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/OperandTraits.h"
21#include "llvm/IR/Operator.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000022#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000023#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000024#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000025using namespace llvm;
26
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000027enum {
28 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
29};
30
Rafael Espindola47f79bb2012-01-02 07:49:53 +000031void BitcodeReader::materializeForwardReferencedFunctions() {
32 while (!BlockAddrFwdRefs.empty()) {
33 Function *F = BlockAddrFwdRefs.begin()->first;
34 F->Materialize();
35 }
36}
37
Chris Lattnerb348bb82007-05-18 04:02:46 +000038void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000039 if (BufferOwned)
40 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000041 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000042 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000043 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000044 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000045
Bill Wendling99faa3b2012-12-07 23:16:57 +000046 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 std::vector<BasicBlock*>().swap(FunctionBBs);
48 std::vector<Function*>().swap(FunctionsWithBodies);
49 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000050 MDKindMap.clear();
Benjamin Kramer122f5e52012-09-21 14:34:31 +000051
52 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
Chris Lattnerc453f762007-04-29 07:54:31 +000053}
54
Chris Lattner48c85b82007-05-04 03:30:17 +000055//===----------------------------------------------------------------------===//
56// Helper functions to implement forward reference resolution, etc.
57//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000058
Chris Lattnercaee0dc2007-04-22 06:23:29 +000059/// ConvertToString - Convert a string from a record into an std::string, return
60/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000061template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000062static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000063 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000064 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000065 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000066
Chris Lattner15e6d172007-05-04 19:11:41 +000067 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
68 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000069 return false;
70}
71
72static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
73 switch (Val) {
74 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000075 case 0: return GlobalValue::ExternalLinkage;
76 case 1: return GlobalValue::WeakAnyLinkage;
77 case 2: return GlobalValue::AppendingLinkage;
78 case 3: return GlobalValue::InternalLinkage;
79 case 4: return GlobalValue::LinkOnceAnyLinkage;
80 case 5: return GlobalValue::DLLImportLinkage;
81 case 6: return GlobalValue::DLLExportLinkage;
82 case 7: return GlobalValue::ExternalWeakLinkage;
83 case 8: return GlobalValue::CommonLinkage;
84 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000085 case 10: return GlobalValue::WeakODRLinkage;
86 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000087 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000088 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000089 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000090 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000091 }
92}
93
94static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
95 switch (Val) {
96 default: // Map unknown visibilities to default.
97 case 0: return GlobalValue::DefaultVisibility;
98 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000099 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000100 }
101}
102
Hans Wennborgce718ff2012-06-23 11:37:03 +0000103static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
104 switch (Val) {
105 case 0: return GlobalVariable::NotThreadLocal;
106 default: // Map unknown non-zero value to general dynamic.
107 case 1: return GlobalVariable::GeneralDynamicTLSModel;
108 case 2: return GlobalVariable::LocalDynamicTLSModel;
109 case 3: return GlobalVariable::InitialExecTLSModel;
110 case 4: return GlobalVariable::LocalExecTLSModel;
111 }
112}
113
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000114static int GetDecodedCastOpcode(unsigned Val) {
115 switch (Val) {
116 default: return -1;
117 case bitc::CAST_TRUNC : return Instruction::Trunc;
118 case bitc::CAST_ZEXT : return Instruction::ZExt;
119 case bitc::CAST_SEXT : return Instruction::SExt;
120 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
121 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
122 case bitc::CAST_UITOFP : return Instruction::UIToFP;
123 case bitc::CAST_SITOFP : return Instruction::SIToFP;
124 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
125 case bitc::CAST_FPEXT : return Instruction::FPExt;
126 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
127 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
128 case bitc::CAST_BITCAST : return Instruction::BitCast;
129 }
130}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000131static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000132 switch (Val) {
133 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000134 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000135 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000136 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000137 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000138 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000139 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000140 case bitc::BINOP_UDIV: return Instruction::UDiv;
141 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000142 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000143 case bitc::BINOP_UREM: return Instruction::URem;
144 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000145 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000146 case bitc::BINOP_SHL: return Instruction::Shl;
147 case bitc::BINOP_LSHR: return Instruction::LShr;
148 case bitc::BINOP_ASHR: return Instruction::AShr;
149 case bitc::BINOP_AND: return Instruction::And;
150 case bitc::BINOP_OR: return Instruction::Or;
151 case bitc::BINOP_XOR: return Instruction::Xor;
152 }
153}
154
Eli Friedmanff030482011-07-28 21:48:00 +0000155static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
156 switch (Val) {
157 default: return AtomicRMWInst::BAD_BINOP;
158 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
159 case bitc::RMW_ADD: return AtomicRMWInst::Add;
160 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
161 case bitc::RMW_AND: return AtomicRMWInst::And;
162 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
163 case bitc::RMW_OR: return AtomicRMWInst::Or;
164 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
165 case bitc::RMW_MAX: return AtomicRMWInst::Max;
166 case bitc::RMW_MIN: return AtomicRMWInst::Min;
167 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
168 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
169 }
170}
171
Eli Friedman47f35132011-07-25 23:16:38 +0000172static AtomicOrdering GetDecodedOrdering(unsigned Val) {
173 switch (Val) {
174 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
175 case bitc::ORDERING_UNORDERED: return Unordered;
176 case bitc::ORDERING_MONOTONIC: return Monotonic;
177 case bitc::ORDERING_ACQUIRE: return Acquire;
178 case bitc::ORDERING_RELEASE: return Release;
179 case bitc::ORDERING_ACQREL: return AcquireRelease;
180 default: // Map unknown orderings to sequentially-consistent.
181 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
182 }
183}
184
185static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
186 switch (Val) {
187 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
188 default: // Map unknown scopes to cross-thread.
189 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
190 }
191}
192
Gabor Greifefe65362008-05-10 08:32:32 +0000193namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000194namespace {
195 /// @brief A class for maintaining the slot number definition
196 /// as a placeholder for the actual definition for forward constants defs.
197 class ConstantPlaceHolder : public ConstantExpr {
Craig Topper86a1c322012-09-15 17:09:36 +0000198 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greif051a9502008-04-06 20:25:17 +0000199 public:
200 // allocate space for exactly one operand
201 void *operator new(size_t s) {
202 return User::operator new(s, 1);
203 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000204 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000205 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000206 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000207 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000208
Chris Lattnerea693df2008-08-21 02:34:16 +0000209 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattnerea693df2008-08-21 02:34:16 +0000210 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000211 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000212 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000214
215
Gabor Greifefe65362008-05-10 08:32:32 +0000216 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000217 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000218 };
219}
220
Chris Lattner46e77402009-03-31 22:55:09 +0000221// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000222template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000223struct OperandTraits<ConstantPlaceHolder> :
224 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000225};
Gabor Greifefe65362008-05-10 08:32:32 +0000226}
227
Chris Lattner46e77402009-03-31 22:55:09 +0000228
229void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
230 if (Idx == size()) {
231 push_back(V);
232 return;
233 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000234
Chris Lattner46e77402009-03-31 22:55:09 +0000235 if (Idx >= size())
236 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000237
Chris Lattner46e77402009-03-31 22:55:09 +0000238 WeakVH &OldV = ValuePtrs[Idx];
239 if (OldV == 0) {
240 OldV = V;
241 return;
242 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000243
Chris Lattner46e77402009-03-31 22:55:09 +0000244 // Handle constants and non-constants (e.g. instrs) differently for
245 // efficiency.
246 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
247 ResolveConstants.push_back(std::make_pair(PHC, Idx));
248 OldV = V;
249 } else {
250 // If there was a forward reference to this value, replace it.
251 Value *PrevVal = OldV;
252 OldV->replaceAllUsesWith(V);
253 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000254 }
255}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000256
Gabor Greifefe65362008-05-10 08:32:32 +0000257
Chris Lattner522b7b12007-04-24 05:48:56 +0000258Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000259 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000260 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000261 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000262
Chris Lattner46e77402009-03-31 22:55:09 +0000263 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000264 assert(Ty == V->getType() && "Type mismatch in constant table!");
265 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000266 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000267
268 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000269 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000270 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000271 return C;
272}
273
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000274Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000275 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000276 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000277
Chris Lattner46e77402009-03-31 22:55:09 +0000278 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000279 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
280 return V;
281 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000282
Chris Lattner01ff65f2007-05-02 05:16:49 +0000283 // No type specified, must be invalid reference.
284 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000285
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000286 // Create and return a placeholder, which will later be RAUW'd.
287 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000288 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000289 return V;
290}
291
Chris Lattnerea693df2008-08-21 02:34:16 +0000292/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
293/// resolves any forward references. The idea behind this is that we sometimes
294/// get constants (such as large arrays) which reference *many* forward ref
295/// constants. Replacing each of these causes a lot of thrashing when
296/// building/reuniquing the constant. Instead of doing this, we look at all the
297/// uses and rewrite all the place holders at once for any constant that uses
298/// a placeholder.
299void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000300 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000301 // binary search.
302 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000303
Chris Lattnerea693df2008-08-21 02:34:16 +0000304 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000307 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000308 Constant *Placeholder = ResolveConstants.back().first;
309 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000310
Chris Lattnerea693df2008-08-21 02:34:16 +0000311 // Loop over all users of the placeholder, updating them to reference the
312 // new value. If they reference more than one placeholder, update them all
313 // at once.
314 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000315 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000316 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000317
Chris Lattnerea693df2008-08-21 02:34:16 +0000318 // If the using object isn't uniqued, just update the operands. This
319 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000320 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000321 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000322 continue;
323 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000324
Chris Lattnerea693df2008-08-21 02:34:16 +0000325 // Otherwise, we have a constant that uses the placeholder. Replace that
326 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000327 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000328 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
329 I != E; ++I) {
330 Value *NewOp;
331 if (!isa<ConstantPlaceHolder>(*I)) {
332 // Not a placeholder reference.
333 NewOp = *I;
334 } else if (*I == Placeholder) {
335 // Common case is that it just references this one placeholder.
336 NewOp = RealVal;
337 } else {
338 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339 ResolveConstantsTy::iterator It =
340 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000341 std::pair<Constant*, unsigned>(cast<Constant>(*I),
342 0));
343 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000344 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000345 }
346
347 NewOps.push_back(cast<Constant>(NewOp));
348 }
349
350 // Make the new constant.
351 Constant *NewC;
352 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000353 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000354 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000355 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000356 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000357 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000358 } else {
359 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000360 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000361 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerea693df2008-08-21 02:34:16 +0000363 UserC->replaceAllUsesWith(NewC);
364 UserC->destroyConstant();
365 NewOps.clear();
366 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Nick Lewyckycb337992009-05-10 20:57:05 +0000368 // Update all ValueHandles, they should be the only users at this point.
369 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000370 delete Placeholder;
371 }
372}
373
Devang Pateld5ac4042009-08-04 06:00:18 +0000374void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
375 if (Idx == size()) {
376 push_back(V);
377 return;
378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Devang Pateld5ac4042009-08-04 06:00:18 +0000380 if (Idx >= size())
381 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000382
Devang Pateld5ac4042009-08-04 06:00:18 +0000383 WeakVH &OldV = MDValuePtrs[Idx];
384 if (OldV == 0) {
385 OldV = V;
386 return;
387 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Devang Pateld5ac4042009-08-04 06:00:18 +0000389 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000390 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000391 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000392 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000393 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
394 // value for Idx.
395 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000396}
397
398Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
399 if (Idx >= size())
400 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000401
Devang Pateld5ac4042009-08-04 06:00:18 +0000402 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000403 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000404 return V;
405 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000406
Devang Pateld5ac4042009-08-04 06:00:18 +0000407 // Create and return a placeholder, which will later be RAUW'd.
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000408 Value *V = MDNode::getTemporary(Context, None);
Devang Pateld5ac4042009-08-04 06:00:18 +0000409 MDValuePtrs[Idx] = V;
410 return V;
411}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413Type *BitcodeReader::getTypeByID(unsigned ID) {
414 // The type table size is always specified correctly.
415 if (ID >= TypeList.size())
416 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000417
Chris Lattner1afcace2011-07-09 17:41:24 +0000418 if (Type *Ty = TypeList[ID])
419 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000420
Chris Lattner1afcace2011-07-09 17:41:24 +0000421 // If we have a forward reference, the only possible case is when it is to a
422 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000423 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000424}
425
Chris Lattner1afcace2011-07-09 17:41:24 +0000426
Chris Lattner48c85b82007-05-04 03:30:17 +0000427//===----------------------------------------------------------------------===//
428// Functions for parsing blocks from the bitcode file
429//===----------------------------------------------------------------------===//
430
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000431
432/// \brief This fills an AttrBuilder object with the LLVM attributes that have
433/// been decoded from the given integer. This function must stay in sync with
434/// 'encodeLLVMAttributesForBitcode'.
435static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
436 uint64_t EncodedAttrs) {
437 // FIXME: Remove in 4.0.
438
439 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
440 // the bits above 31 down by 11 bits.
441 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
442 assert((!Alignment || isPowerOf2_32(Alignment)) &&
443 "Alignment must be a power of two.");
444
445 if (Alignment)
446 B.addAlignmentAttr(Alignment);
Kostya Serebryanyab39afa2013-02-11 08:13:54 +0000447 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000448 (EncodedAttrs & 0xffff));
449}
450
Devang Patel05988662008-09-25 21:00:45 +0000451bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000452 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000453 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000454
Devang Patel19c87462008-09-26 22:53:05 +0000455 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000456 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000457
Chris Lattner48c85b82007-05-04 03:30:17 +0000458 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000459
Bill Wendling0c2f0ff2013-01-27 00:36:48 +0000460 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000461
Chris Lattner48c85b82007-05-04 03:30:17 +0000462 // Read all the records.
463 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000464 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000465
Chris Lattner5a4251c2013-01-20 02:13:19 +0000466 switch (Entry.Kind) {
467 case BitstreamEntry::SubBlock: // Handled for us already.
468 case BitstreamEntry::Error:
469 return Error("Error at end of PARAMATTR block");
470 case BitstreamEntry::EndBlock:
Chris Lattner48c85b82007-05-04 03:30:17 +0000471 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000472 case BitstreamEntry::Record:
473 // The interesting case.
474 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000475 }
Joe Abbeyacb61942013-02-06 22:14:06 +0000476
Chris Lattner48c85b82007-05-04 03:30:17 +0000477 // Read a record.
478 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000479 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner48c85b82007-05-04 03:30:17 +0000480 default: // Default behavior: ignore.
481 break;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000482 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
483 // FIXME: Remove in 4.0.
Chris Lattner48c85b82007-05-04 03:30:17 +0000484 if (Record.size() & 1)
485 return Error("Invalid ENTRY record");
486
Chris Lattner48c85b82007-05-04 03:30:17 +0000487 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling8232ece2013-01-29 01:43:29 +0000488 AttrBuilder B;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000489 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling8232ece2013-01-29 01:43:29 +0000490 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patel19c87462008-09-26 22:53:05 +0000491 }
Devang Patel19c87462008-09-26 22:53:05 +0000492
Bill Wendling99faa3b2012-12-07 23:16:57 +0000493 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000494 Attrs.clear();
495 break;
496 }
Bill Wendling48fbcfe2013-02-12 08:13:50 +0000497 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
498 for (unsigned i = 0, e = Record.size(); i != e; ++i)
499 Attrs.push_back(MAttributeGroups[Record[i]]);
500
501 MAttributes.push_back(AttributeSet::get(Context, Attrs));
502 Attrs.clear();
503 break;
504 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000505 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000506 }
507}
508
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000509bool BitcodeReader::ParseAttributeGroupBlock() {
510 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
511 return Error("Malformed block record");
512
513 if (!MAttributeGroups.empty())
514 return Error("Multiple PARAMATTR_GROUP blocks found!");
515
516 SmallVector<uint64_t, 64> Record;
517
518 // Read all the records.
519 while (1) {
520 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
521
522 switch (Entry.Kind) {
523 case BitstreamEntry::SubBlock: // Handled for us already.
524 case BitstreamEntry::Error:
525 return Error("Error at end of PARAMATTR_GROUP block");
526 case BitstreamEntry::EndBlock:
527 return false;
528 case BitstreamEntry::Record:
529 // The interesting case.
530 break;
531 }
532
533 // Read a record.
534 Record.clear();
535 switch (Stream.readRecord(Entry.ID, Record)) {
536 default: // Default behavior: ignore.
537 break;
538 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
539 if (Record.size() < 3)
540 return Error("Invalid ENTRY record");
541
Bill Wendling04ef4be2013-02-11 22:32:29 +0000542 uint64_t GrpID = Record[0];
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000543 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
544
545 AttrBuilder B;
546 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
547 if (Record[i] == 0) { // Enum attribute
548 B.addAttribute(Attribute::AttrKind(Record[++i]));
549 } else if (Record[i] == 1) { // Align attribute
550 if (Attribute::AttrKind(Record[++i]) == Attribute::Alignment)
551 B.addAlignmentAttr(Record[++i]);
552 else
553 B.addStackAlignmentAttr(Record[++i]);
554 } else { // String attribute
Bill Wendling04ef4be2013-02-11 22:32:29 +0000555 assert((Record[i] == 3 || Record[i] == 4) &&
556 "Invalid attribute group entry");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000557 bool HasValue = (Record[i++] == 4);
558 SmallString<64> KindStr;
559 SmallString<64> ValStr;
560
561 while (Record[i] != 0 && i != e)
562 KindStr += Record[i++];
Bill Wendling04ef4be2013-02-11 22:32:29 +0000563 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000564
565 if (HasValue) {
566 // Has a value associated with it.
Bill Wendling04ef4be2013-02-11 22:32:29 +0000567 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000568 while (Record[i] != 0 && i != e)
569 ValStr += Record[i++];
Bill Wendling04ef4be2013-02-11 22:32:29 +0000570 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000571 }
572
573 B.addAttribute(KindStr.str(), ValStr.str());
574 }
575 }
576
Bill Wendling04ef4be2013-02-11 22:32:29 +0000577 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000578 break;
579 }
580 }
581 }
582}
583
Chris Lattner86697142007-05-01 05:01:34 +0000584bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000585 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000586 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000587
Chris Lattner1afcace2011-07-09 17:41:24 +0000588 return ParseTypeTableBody();
589}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000590
Chris Lattner1afcace2011-07-09 17:41:24 +0000591bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000592 if (!TypeList.empty())
593 return Error("Multiple TYPE_BLOCKs found!");
594
595 SmallVector<uint64_t, 64> Record;
596 unsigned NumRecords = 0;
597
Chris Lattner1afcace2011-07-09 17:41:24 +0000598 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000599
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000600 // Read all the records for this type table.
601 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000602 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000603
Chris Lattner5a4251c2013-01-20 02:13:19 +0000604 switch (Entry.Kind) {
605 case BitstreamEntry::SubBlock: // Handled for us already.
606 case BitstreamEntry::Error:
607 Error("Error in the type table block");
608 return true;
609 case BitstreamEntry::EndBlock:
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000610 if (NumRecords != TypeList.size())
611 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000612 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000613 case BitstreamEntry::Record:
614 // The interesting case.
615 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000616 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000617
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000618 // Read a record.
619 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000620 Type *ResultTy = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000621 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000622 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000623 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
624 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
625 // type list. This allows us to reserve space.
626 if (Record.size() < 1)
627 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000628 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000629 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000630 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000631 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000632 break;
Dan Gohmance163392011-12-17 00:04:22 +0000633 case bitc::TYPE_CODE_HALF: // HALF
634 ResultTy = Type::getHalfTy(Context);
635 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000636 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000637 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000638 break;
639 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000640 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000641 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000642 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000643 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000644 break;
645 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000646 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000647 break;
648 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000649 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000650 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000651 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000652 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000653 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000654 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000655 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000656 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000657 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
658 ResultTy = Type::getX86_MMXTy(Context);
659 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000660 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
661 if (Record.size() < 1)
662 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000663
Owen Anderson1d0be152009-08-13 21:58:54 +0000664 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000665 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000666 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000667 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000668 if (Record.size() < 1)
669 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000670 unsigned AddressSpace = 0;
671 if (Record.size() == 2)
672 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000673 ResultTy = getTypeByID(Record[0]);
674 if (ResultTy == 0) return Error("invalid element type in pointer type");
675 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000676 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000677 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000678 case bitc::TYPE_CODE_FUNCTION_OLD: {
679 // FIXME: attrid is dead, remove it in LLVM 4.0
680 // FUNCTION: [vararg, attrid, retty, paramty x N]
681 if (Record.size() < 3)
682 return Error("Invalid FUNCTION type record");
683 SmallVector<Type*, 8> ArgTys;
684 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
685 if (Type *T = getTypeByID(Record[i]))
686 ArgTys.push_back(T);
687 else
688 break;
689 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000690
Nuno Lopesee8100d2012-05-23 15:19:39 +0000691 ResultTy = getTypeByID(Record[2]);
692 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
693 return Error("invalid type in function type");
694
695 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
696 break;
697 }
Chad Rosiercde54642011-11-03 00:14:01 +0000698 case bitc::TYPE_CODE_FUNCTION: {
699 // FUNCTION: [vararg, retty, paramty x N]
700 if (Record.size() < 2)
701 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000702 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000703 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
704 if (Type *T = getTypeByID(Record[i]))
705 ArgTys.push_back(T);
706 else
707 break;
708 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000709
Chad Rosiercde54642011-11-03 00:14:01 +0000710 ResultTy = getTypeByID(Record[1]);
711 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
712 return Error("invalid type in function type");
713
714 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
715 break;
716 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000717 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000718 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000719 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000720 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000721 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
722 if (Type *T = getTypeByID(Record[i]))
723 EltTys.push_back(T);
724 else
725 break;
726 }
727 if (EltTys.size() != Record.size()-1)
728 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000729 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000730 break;
731 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000732 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
733 if (ConvertToString(Record, 0, TypeName))
734 return Error("Invalid STRUCT_NAME record");
735 continue;
736
737 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
738 if (Record.size() < 1)
739 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000740
Chris Lattner1afcace2011-07-09 17:41:24 +0000741 if (NumRecords >= TypeList.size())
742 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000743
Chris Lattner1afcace2011-07-09 17:41:24 +0000744 // Check to see if this was forward referenced, if so fill in the temp.
745 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
746 if (Res) {
747 Res->setName(TypeName);
748 TypeList[NumRecords] = 0;
749 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000750 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000751 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000752
Chris Lattner1afcace2011-07-09 17:41:24 +0000753 SmallVector<Type*, 8> EltTys;
754 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
755 if (Type *T = getTypeByID(Record[i]))
756 EltTys.push_back(T);
757 else
758 break;
759 }
760 if (EltTys.size() != Record.size()-1)
761 return Error("invalid STRUCT type record");
762 Res->setBody(EltTys, Record[0]);
763 ResultTy = Res;
764 break;
765 }
766 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
767 if (Record.size() != 1)
768 return Error("Invalid OPAQUE type record");
769
770 if (NumRecords >= TypeList.size())
771 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000772
Chris Lattner1afcace2011-07-09 17:41:24 +0000773 // Check to see if this was forward referenced, if so fill in the temp.
774 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
775 if (Res) {
776 Res->setName(TypeName);
777 TypeList[NumRecords] = 0;
778 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000779 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000780 TypeName.clear();
781 ResultTy = Res;
782 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000783 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000784 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
785 if (Record.size() < 2)
786 return Error("Invalid ARRAY type record");
787 if ((ResultTy = getTypeByID(Record[1])))
788 ResultTy = ArrayType::get(ResultTy, Record[0]);
789 else
790 return Error("Invalid ARRAY type element");
791 break;
792 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
793 if (Record.size() < 2)
794 return Error("Invalid VECTOR type record");
795 if ((ResultTy = getTypeByID(Record[1])))
796 ResultTy = VectorType::get(ResultTy, Record[0]);
797 else
798 return Error("Invalid ARRAY type element");
799 break;
800 }
801
802 if (NumRecords >= TypeList.size())
803 return Error("invalid TYPE table");
804 assert(ResultTy && "Didn't read a type?");
805 assert(TypeList[NumRecords] == 0 && "Already read type?");
806 TypeList[NumRecords++] = ResultTy;
807 }
808}
809
Chris Lattner86697142007-05-01 05:01:34 +0000810bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000811 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000812 return Error("Malformed block record");
813
814 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000815
Chris Lattner0b2482a2007-04-23 21:26:05 +0000816 // Read all the records for this value table.
817 SmallString<128> ValueName;
818 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000819 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000820
Chris Lattner5a4251c2013-01-20 02:13:19 +0000821 switch (Entry.Kind) {
822 case BitstreamEntry::SubBlock: // Handled for us already.
823 case BitstreamEntry::Error:
824 return Error("malformed value symbol table block");
825 case BitstreamEntry::EndBlock:
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000826 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000827 case BitstreamEntry::Record:
828 // The interesting case.
829 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000830 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000831
Chris Lattner0b2482a2007-04-23 21:26:05 +0000832 // Read a record.
833 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000834 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000835 default: // Default behavior: unknown type.
836 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000837 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000838 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000839 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000840 unsigned ValueID = Record[0];
841 if (ValueID >= ValueList.size())
842 return Error("Invalid Value ID in VST_ENTRY record");
843 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000844
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000845 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000846 ValueName.clear();
847 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000848 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000849 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000850 if (ConvertToString(Record, 1, ValueName))
851 return Error("Invalid VST_BBENTRY record");
852 BasicBlock *BB = getBasicBlock(Record[0]);
853 if (BB == 0)
854 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000855
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000856 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000857 ValueName.clear();
858 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000859 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000860 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000861 }
862}
863
Devang Patele54abc92009-07-22 17:43:22 +0000864bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000865 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000866
867 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
868 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000869
Devang Patele54abc92009-07-22 17:43:22 +0000870 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000871
Devang Patele54abc92009-07-22 17:43:22 +0000872 // Read all the records.
873 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000874 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000875
Chris Lattner5a4251c2013-01-20 02:13:19 +0000876 switch (Entry.Kind) {
877 case BitstreamEntry::SubBlock: // Handled for us already.
878 case BitstreamEntry::Error:
879 Error("malformed metadata block");
880 return true;
881 case BitstreamEntry::EndBlock:
Devang Patele54abc92009-07-22 17:43:22 +0000882 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000883 case BitstreamEntry::Record:
884 // The interesting case.
885 break;
Devang Patele54abc92009-07-22 17:43:22 +0000886 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000887
Victor Hernandez24e64df2010-01-10 07:14:18 +0000888 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000889 // Read a record.
890 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000891 unsigned Code = Stream.readRecord(Entry.ID, Record);
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000892 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000893 default: // Default behavior: ignore.
894 break;
Devang Patelaa993142009-07-29 22:34:41 +0000895 case bitc::METADATA_NAME: {
Chris Lattner1ca114a2013-01-20 02:54:05 +0000896 // Read name of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000897 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000898 Record.clear();
899 Code = Stream.ReadCode();
900
Chris Lattner9d61dd92011-06-17 17:50:30 +0000901 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner5a4251c2013-01-20 02:13:19 +0000902 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000903 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000904
905 // Read named metadata elements.
906 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000907 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000908 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000909 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
910 if (MD == 0)
911 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000912 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000913 }
Devang Patelaa993142009-07-29 22:34:41 +0000914 break;
915 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000916 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000917 IsFunctionLocal = true;
918 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000919 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000920 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000921 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000922
Devang Patel104cf9e2009-07-23 01:07:34 +0000923 unsigned Size = Record.size();
924 SmallVector<Value*, 8> Elts;
925 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000926 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000927 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000928 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000929 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000930 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000931 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
932 else
933 Elts.push_back(NULL);
934 }
Jay Foadec9186b2011-04-21 19:59:31 +0000935 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000936 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000937 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000938 break;
939 }
Devang Patele54abc92009-07-22 17:43:22 +0000940 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000941 SmallString<8> String(Record.begin(), Record.end());
942 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000943 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000944 break;
945 }
Devang Patele8e02132009-09-18 19:26:43 +0000946 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000947 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000948 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000949
Devang Patela2148402009-09-28 21:14:55 +0000950 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000951 SmallString<8> Name(Record.begin()+1, Record.end());
952
Chris Lattner08113472009-12-29 09:01:33 +0000953 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000954 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
955 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000956 break;
957 }
Devang Patele54abc92009-07-22 17:43:22 +0000958 }
959 }
960}
961
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000962/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +0000963/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000964uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +0000965 if ((V & 1) == 0)
966 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000967 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000968 return -(V >> 1);
969 // There is no such thing as -0 with integers. "-0" really means MININT.
970 return 1ULL << 63;
971}
972
Chris Lattner07d98b42007-04-26 02:46:40 +0000973/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
974/// values and aliases that we can.
975bool BitcodeReader::ResolveGlobalAndAliasInits() {
976 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
977 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000978
Chris Lattner07d98b42007-04-26 02:46:40 +0000979 GlobalInitWorklist.swap(GlobalInits);
980 AliasInitWorklist.swap(AliasInits);
981
982 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000983 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000984 if (ValID >= ValueList.size()) {
985 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000986 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000987 } else {
988 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
989 GlobalInitWorklist.back().first->setInitializer(C);
990 else
991 return Error("Global variable initializer is not a constant!");
992 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000993 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000994 }
995
996 while (!AliasInitWorklist.empty()) {
997 unsigned ValID = AliasInitWorklist.back().second;
998 if (ValID >= ValueList.size()) {
999 AliasInits.push_back(AliasInitWorklist.back());
1000 } else {
1001 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +00001002 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +00001003 else
1004 return Error("Alias initializer is not a constant!");
1005 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001006 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001007 }
1008 return false;
1009}
1010
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001011static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1012 SmallVector<uint64_t, 8> Words(Vals.size());
1013 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001014 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001015
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001016 return APInt(TypeBits, Words);
1017}
1018
Chris Lattner86697142007-05-01 05:01:34 +00001019bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001020 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +00001021 return Error("Malformed block record");
1022
1023 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001024
Chris Lattnere16504e2007-04-24 03:30:34 +00001025 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001026 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +00001027 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +00001028 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001029 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001030
Chris Lattner5a4251c2013-01-20 02:13:19 +00001031 switch (Entry.Kind) {
1032 case BitstreamEntry::SubBlock: // Handled for us already.
1033 case BitstreamEntry::Error:
1034 return Error("malformed block record in AST file");
1035 case BitstreamEntry::EndBlock:
1036 if (NextCstNo != ValueList.size())
1037 return Error("Invalid constant reference!");
Joe Abbeyacb61942013-02-06 22:14:06 +00001038
Chris Lattner5a4251c2013-01-20 02:13:19 +00001039 // Once all the constants have been read, go through and resolve forward
1040 // references.
1041 ValueList.ResolveConstantForwardRefs();
1042 return false;
1043 case BitstreamEntry::Record:
1044 // The interesting case.
Chris Lattnerea693df2008-08-21 02:34:16 +00001045 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001046 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001047
Chris Lattnere16504e2007-04-24 03:30:34 +00001048 // Read a record.
1049 Record.clear();
1050 Value *V = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001051 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00001052 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001053 default: // Default behavior: unknown constant
1054 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001055 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001056 break;
1057 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1058 if (Record.empty())
1059 return Error("Malformed CST_SETTYPE record");
1060 if (Record[0] >= TypeList.size())
1061 return Error("Invalid Type ID in CST_SETTYPE record");
1062 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001063 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001064 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001065 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001066 break;
1067 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001068 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001069 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001070 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001071 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001072 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001073 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001074 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001075
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001076 APInt VInt = ReadWideAPInt(Record,
1077 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001078 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +00001079
Chris Lattner0eef0802007-04-24 04:04:35 +00001080 break;
1081 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001082 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001083 if (Record.empty())
1084 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001085 if (CurTy->isHalfTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001086 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1087 APInt(16, (uint16_t)Record[0])));
Dan Gohmance163392011-12-17 00:04:22 +00001088 else if (CurTy->isFloatTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001089 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1090 APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001091 else if (CurTy->isDoubleTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001092 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1093 APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001094 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001095 // Bits are not stored the same way as a normal i80 APInt, compensate.
1096 uint64_t Rearrange[2];
1097 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1098 Rearrange[1] = Record[0] >> 48;
Tim Northover0a29cb02013-01-22 09:46:31 +00001099 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1100 APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001101 } else if (CurTy->isFP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001102 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1103 APInt(128, Record)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001104 else if (CurTy->isPPC_FP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001105 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1106 APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001107 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001108 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001109 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001110 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001111
Chris Lattner15e6d172007-05-04 19:11:41 +00001112 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1113 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001114 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115
Chris Lattner15e6d172007-05-04 19:11:41 +00001116 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001117 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001118
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001119 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001120 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001121 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001122 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001123 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001124 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1125 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001126 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001127 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001128 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001129 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1130 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001131 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001132 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001133 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001134 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001135 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001136 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001137 break;
1138 }
Chris Lattner2237f842012-02-05 02:41:35 +00001139 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001140 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1141 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001142 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001143
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001144 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001145 V = ConstantDataArray::getString(Context, Elts,
1146 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001147 break;
1148 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001149 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1150 if (Record.empty())
1151 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001152
Chris Lattnerd408f062012-01-30 00:51:16 +00001153 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1154 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001155
Chris Lattnerd408f062012-01-30 00:51:16 +00001156 if (EltTy->isIntegerTy(8)) {
1157 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1158 if (isa<VectorType>(CurTy))
1159 V = ConstantDataVector::get(Context, Elts);
1160 else
1161 V = ConstantDataArray::get(Context, Elts);
1162 } else if (EltTy->isIntegerTy(16)) {
1163 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1164 if (isa<VectorType>(CurTy))
1165 V = ConstantDataVector::get(Context, Elts);
1166 else
1167 V = ConstantDataArray::get(Context, Elts);
1168 } else if (EltTy->isIntegerTy(32)) {
1169 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1170 if (isa<VectorType>(CurTy))
1171 V = ConstantDataVector::get(Context, Elts);
1172 else
1173 V = ConstantDataArray::get(Context, Elts);
1174 } else if (EltTy->isIntegerTy(64)) {
1175 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1176 if (isa<VectorType>(CurTy))
1177 V = ConstantDataVector::get(Context, Elts);
1178 else
1179 V = ConstantDataArray::get(Context, Elts);
1180 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001181 SmallVector<float, 16> Elts(Size);
1182 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001183 if (isa<VectorType>(CurTy))
1184 V = ConstantDataVector::get(Context, Elts);
1185 else
1186 V = ConstantDataArray::get(Context, Elts);
1187 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001188 SmallVector<double, 16> Elts(Size);
1189 std::transform(Record.begin(), Record.end(), Elts.begin(),
1190 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001191 if (isa<VectorType>(CurTy))
1192 V = ConstantDataVector::get(Context, Elts);
1193 else
1194 V = ConstantDataArray::get(Context, Elts);
1195 } else {
1196 return Error("Unknown element type in CE_DATA");
1197 }
1198 break;
1199 }
1200
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001201 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1202 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1203 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001204 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001205 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001206 } else {
1207 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1208 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001209 unsigned Flags = 0;
1210 if (Record.size() >= 4) {
1211 if (Opc == Instruction::Add ||
1212 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001213 Opc == Instruction::Mul ||
1214 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001215 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1216 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1217 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1218 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001219 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001220 Opc == Instruction::UDiv ||
1221 Opc == Instruction::LShr ||
1222 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001223 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001224 Flags |= SDivOperator::IsExact;
1225 }
1226 }
1227 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001228 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001229 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001230 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001231 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1232 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1233 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001234 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001235 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001236 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001237 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001238 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001239 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001240 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001241 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001242 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001243 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001244 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001245 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001246 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001247 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001248 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001249 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001250 if (!ElTy) return Error("Invalid CE_GEP record");
1251 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1252 }
Jay Foaddab3d292011-07-21 14:31:17 +00001253 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001254 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1255 BitCode ==
1256 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001257 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001258 }
1259 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1260 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbeye46b14a2012-11-19 19:22:55 +00001261 V = ConstantExpr::getSelect(
1262 ValueList.getConstantFwdRef(Record[0],
1263 Type::getInt1Ty(Context)),
1264 ValueList.getConstantFwdRef(Record[1],CurTy),
1265 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001266 break;
1267 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1268 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001269 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001270 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1271 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1272 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001273 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001274 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001275 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001276 break;
1277 }
1278 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001279 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001280 if (Record.size() < 3 || OpTy == 0)
1281 return Error("Invalid CE_INSERTELT record");
1282 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1283 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1284 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001285 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001286 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001287 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001288 break;
1289 }
1290 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001291 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001292 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001293 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001294 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1295 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001296 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001297 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001298 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001299 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001300 break;
1301 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001302 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001303 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1304 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001305 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001306 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1307 return Error("Invalid CE_SHUFVEC_EX record");
1308 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1309 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001310 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001311 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001312 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001313 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001314 break;
1315 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001316 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1317 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001318 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001319 if (OpTy == 0) return Error("Invalid CE_CMP record");
1320 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1321 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1322
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001323 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001324 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001325 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001326 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001327 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001328 }
Chad Rosier581600b2012-09-05 19:00:49 +00001329 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001330 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001331 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001332 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1333 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001334 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001335 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001336 unsigned AsmStrSize = Record[1];
1337 if (2+AsmStrSize >= Record.size())
1338 return Error("Invalid INLINEASM record");
1339 unsigned ConstStrSize = Record[2+AsmStrSize];
1340 if (3+AsmStrSize+ConstStrSize > Record.size())
1341 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001342
Chris Lattner2bce93a2007-05-06 01:58:20 +00001343 for (unsigned i = 0; i != AsmStrSize; ++i)
1344 AsmStr += (char)Record[2+i];
1345 for (unsigned i = 0; i != ConstStrSize; ++i)
1346 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001347 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001348 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001349 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001350 break;
1351 }
Chad Rosier581600b2012-09-05 19:00:49 +00001352 // This version adds support for the asm dialect keywords (e.g.,
1353 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001354 case bitc::CST_CODE_INLINEASM: {
1355 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1356 std::string AsmStr, ConstrStr;
1357 bool HasSideEffects = Record[0] & 1;
1358 bool IsAlignStack = (Record[0] >> 1) & 1;
1359 unsigned AsmDialect = Record[0] >> 2;
1360 unsigned AsmStrSize = Record[1];
1361 if (2+AsmStrSize >= Record.size())
1362 return Error("Invalid INLINEASM record");
1363 unsigned ConstStrSize = Record[2+AsmStrSize];
1364 if (3+AsmStrSize+ConstStrSize > Record.size())
1365 return Error("Invalid INLINEASM record");
1366
1367 for (unsigned i = 0; i != AsmStrSize; ++i)
1368 AsmStr += (char)Record[2+i];
1369 for (unsigned i = 0; i != ConstStrSize; ++i)
1370 ConstrStr += (char)Record[3+AsmStrSize+i];
1371 PointerType *PTy = cast<PointerType>(CurTy);
1372 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1373 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001374 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001375 break;
1376 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001377 case bitc::CST_CODE_BLOCKADDRESS:{
1378 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001379 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001380 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1381 Function *Fn =
1382 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1383 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001384
1385 // If the function is already parsed we can insert the block address right
1386 // away.
1387 if (!Fn->empty()) {
1388 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1389 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1390 if (BBI == BBE)
1391 return Error("Invalid blockaddress block #");
1392 ++BBI;
1393 }
1394 V = BlockAddress::get(Fn, BBI);
1395 } else {
1396 // Otherwise insert a placeholder and remember it so it can be inserted
1397 // when the function is parsed.
1398 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1399 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001400 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001401 0, "");
1402 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1403 V = FwdRef;
1404 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001405 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001406 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001407 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001408
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001409 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001410 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001411 }
1412}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001413
Chad Rosiercbbb0962011-12-07 21:44:12 +00001414bool BitcodeReader::ParseUseLists() {
1415 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1416 return Error("Malformed block record");
1417
1418 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001419
Chad Rosiercbbb0962011-12-07 21:44:12 +00001420 // Read all the records.
1421 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001422 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001423
Chris Lattner5a4251c2013-01-20 02:13:19 +00001424 switch (Entry.Kind) {
1425 case BitstreamEntry::SubBlock: // Handled for us already.
1426 case BitstreamEntry::Error:
1427 return Error("malformed use list block");
1428 case BitstreamEntry::EndBlock:
Chad Rosiercbbb0962011-12-07 21:44:12 +00001429 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001430 case BitstreamEntry::Record:
1431 // The interesting case.
1432 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001433 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001434
Chad Rosiercbbb0962011-12-07 21:44:12 +00001435 // Read a use list record.
1436 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001437 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosiercbbb0962011-12-07 21:44:12 +00001438 default: // Default behavior: unknown type.
1439 break;
1440 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1441 unsigned RecordLength = Record.size();
1442 if (RecordLength < 1)
1443 return Error ("Invalid UseList reader!");
1444 UseListRecords.push_back(Record);
1445 break;
1446 }
1447 }
1448 }
1449}
1450
Chris Lattner980e5aa2007-05-01 05:52:21 +00001451/// RememberAndSkipFunctionBody - When we see the block for a function body,
1452/// remember where it is and then skip it. This lets us lazily deserialize the
1453/// functions.
1454bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001455 // Get the function we are talking about.
1456 if (FunctionsWithBodies.empty())
1457 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001458
Chris Lattner48f84872007-05-01 04:59:48 +00001459 Function *Fn = FunctionsWithBodies.back();
1460 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001461
Chris Lattner48f84872007-05-01 04:59:48 +00001462 // Save the current stream state.
1463 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001464 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001465
Chris Lattner48f84872007-05-01 04:59:48 +00001466 // Skip over the function block for now.
1467 if (Stream.SkipBlock())
1468 return Error("Malformed block record");
1469 return false;
1470}
1471
Derek Schuff2ea93872012-02-06 22:30:29 +00001472bool BitcodeReader::GlobalCleanup() {
1473 // Patch the initializers for globals and aliases up.
1474 ResolveGlobalAndAliasInits();
1475 if (!GlobalInits.empty() || !AliasInits.empty())
1476 return Error("Malformed global initializer set");
1477
1478 // Look for intrinsic functions which need to be upgraded at some point
1479 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1480 FI != FE; ++FI) {
1481 Function *NewFn;
1482 if (UpgradeIntrinsicFunction(FI, NewFn))
1483 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1484 }
1485
1486 // Look for global variables which need to be renamed.
1487 for (Module::global_iterator
1488 GI = TheModule->global_begin(), GE = TheModule->global_end();
1489 GI != GE; ++GI)
1490 UpgradeGlobalVariable(GI);
1491 // Force deallocation of memory for these vectors to favor the client that
1492 // want lazy deserialization.
1493 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1494 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1495 return false;
1496}
1497
1498bool BitcodeReader::ParseModule(bool Resume) {
1499 if (Resume)
1500 Stream.JumpToBit(NextUnreadBit);
1501 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001502 return Error("Malformed block record");
1503
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001504 SmallVector<uint64_t, 64> Record;
1505 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001506 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001507
1508 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001509 while (1) {
1510 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00001511
Chris Lattner5a4251c2013-01-20 02:13:19 +00001512 switch (Entry.Kind) {
1513 case BitstreamEntry::Error:
1514 Error("malformed module block");
1515 return true;
1516 case BitstreamEntry::EndBlock:
Derek Schuff2ea93872012-02-06 22:30:29 +00001517 return GlobalCleanup();
Joe Abbeyacb61942013-02-06 22:14:06 +00001518
Chris Lattner5a4251c2013-01-20 02:13:19 +00001519 case BitstreamEntry::SubBlock:
1520 switch (Entry.ID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001521 default: // Skip unknown content.
1522 if (Stream.SkipBlock())
1523 return Error("Malformed block record");
1524 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001525 case bitc::BLOCKINFO_BLOCK_ID:
1526 if (Stream.ReadBlockInfoBlock())
1527 return Error("Malformed BlockInfoBlock");
1528 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001529 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001530 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001531 return true;
1532 break;
Bill Wendlingc3ba0a82013-02-10 23:24:25 +00001533 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1534 if (ParseAttributeGroupBlock())
1535 return true;
1536 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001537 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001538 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001539 return true;
1540 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001541 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001542 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001543 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001544 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001545 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001546 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001547 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001548 return true;
1549 break;
Devang Patele54abc92009-07-22 17:43:22 +00001550 case bitc::METADATA_BLOCK_ID:
1551 if (ParseMetadata())
1552 return true;
1553 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001554 case bitc::FUNCTION_BLOCK_ID:
1555 // If this is the first function body we've seen, reverse the
1556 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001557 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001558 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001559 if (GlobalCleanup())
1560 return true;
1561 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001562 }
Joe Abbeyacb61942013-02-06 22:14:06 +00001563
Chris Lattner980e5aa2007-05-01 05:52:21 +00001564 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001565 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001566 // For streaming bitcode, suspend parsing when we reach the function
1567 // bodies. Subsequent materialization calls will resume it when
1568 // necessary. For streaming, the function bodies must be at the end of
1569 // the bitcode. If the bitcode file is old, the symbol table will be
1570 // at the end instead and will not have been seen yet. In this case,
1571 // just finish the parse now.
1572 if (LazyStreamer && SeenValueSymbolTable) {
1573 NextUnreadBit = Stream.GetCurrentBitNo();
1574 return false;
1575 }
Chris Lattner48f84872007-05-01 04:59:48 +00001576 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001577 case bitc::USELIST_BLOCK_ID:
1578 if (ParseUseLists())
1579 return true;
1580 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001581 }
1582 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00001583
Chris Lattner5a4251c2013-01-20 02:13:19 +00001584 case BitstreamEntry::Record:
1585 // The interesting case.
1586 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001587 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001588
Daniel Dunbara279bc32009-09-20 02:20:51 +00001589
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001590 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001591 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001592 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001593 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594 if (Record.size() < 1)
1595 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001596 // Only version #0 and #1 are supported so far.
1597 unsigned module_version = Record[0];
1598 switch (module_version) {
1599 default: return Error("Unknown bitstream version!");
1600 case 0:
1601 UseRelativeIDs = false;
1602 break;
1603 case 1:
1604 UseRelativeIDs = true;
1605 break;
1606 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001607 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001608 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001609 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001610 std::string S;
1611 if (ConvertToString(Record, 0, S))
1612 return Error("Invalid MODULE_CODE_TRIPLE record");
1613 TheModule->setTargetTriple(S);
1614 break;
1615 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001616 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001617 std::string S;
1618 if (ConvertToString(Record, 0, S))
1619 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1620 TheModule->setDataLayout(S);
1621 break;
1622 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001623 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001624 std::string S;
1625 if (ConvertToString(Record, 0, S))
1626 return Error("Invalid MODULE_CODE_ASM record");
1627 TheModule->setModuleInlineAsm(S);
1628 break;
1629 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001630 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1631 // FIXME: Remove in 4.0.
1632 std::string S;
1633 if (ConvertToString(Record, 0, S))
1634 return Error("Invalid MODULE_CODE_DEPLIB record");
1635 // Ignore value.
1636 break;
1637 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001638 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001639 std::string S;
1640 if (ConvertToString(Record, 0, S))
1641 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1642 SectionTable.push_back(S);
1643 break;
1644 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001645 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001646 std::string S;
1647 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001648 return Error("Invalid MODULE_CODE_GCNAME record");
1649 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001650 break;
1651 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001652 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001653 // linkage, alignment, section, visibility, threadlocal,
1654 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001655 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001656 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001657 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001658 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001659 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001660 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001661 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001662 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001663 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001664
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001665 bool isConstant = Record[1];
1666 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1667 unsigned Alignment = (1 << Record[4]) >> 1;
1668 std::string Section;
1669 if (Record[5]) {
1670 if (Record[5]-1 >= SectionTable.size())
1671 return Error("Invalid section ID");
1672 Section = SectionTable[Record[5]-1];
1673 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001674 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001675 if (Record.size() > 6)
1676 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001677
1678 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001679 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001680 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001681
Rafael Espindolabea46262011-01-08 16:42:36 +00001682 bool UnnamedAddr = false;
1683 if (Record.size() > 8)
1684 UnnamedAddr = Record[8];
1685
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001686 bool ExternallyInitialized = false;
1687 if (Record.size() > 9)
1688 ExternallyInitialized = Record[9];
1689
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001690 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001691 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001692 TLM, AddressSpace, ExternallyInitialized);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001693 NewGV->setAlignment(Alignment);
1694 if (!Section.empty())
1695 NewGV->setSection(Section);
1696 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001697 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001698
Chris Lattner0b2482a2007-04-23 21:26:05 +00001699 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001700
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001701 // Remember which value to use for the global initializer.
1702 if (unsigned InitID = Record[2])
1703 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001704 break;
1705 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001706 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001707 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001708 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001709 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001710 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001711 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001712 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001713 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001714 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001715 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001716 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1717 if (!FTy)
1718 return Error("Function not a pointer to function type!");
1719
Gabor Greif051a9502008-04-06 20:25:17 +00001720 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1721 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001722
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001723 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001724 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001725 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001726 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001727
Chris Lattnera9bb7132007-05-08 05:38:01 +00001728 Func->setAlignment((1 << Record[5]) >> 1);
1729 if (Record[6]) {
1730 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001731 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001732 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001733 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001734 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001735 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001736 if (Record[8]-1 > GCTable.size())
1737 return Error("Invalid GC ID");
1738 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001739 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001740 bool UnnamedAddr = false;
1741 if (Record.size() > 9)
1742 UnnamedAddr = Record[9];
1743 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001744 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001745
Chris Lattner48f84872007-05-01 04:59:48 +00001746 // If this is a function with a body, remember the prototype we are
1747 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001748 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001749 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001750 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1751 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001752 break;
1753 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001754 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001755 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001756 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001757 if (Record.size() < 3)
1758 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001759 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001760 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001761 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001762 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001763
Chris Lattner07d98b42007-04-26 02:46:40 +00001764 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1765 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001766 // Old bitcode files didn't have visibility field.
1767 if (Record.size() > 3)
1768 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001769 ValueList.push_back(NewGA);
1770 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1771 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001772 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001773 /// MODULE_CODE_PURGEVALS: [numvals]
1774 case bitc::MODULE_CODE_PURGEVALS:
1775 // Trim down the value list to the specified size.
1776 if (Record.size() < 1 || Record[0] > ValueList.size())
1777 return Error("Invalid MODULE_PURGEVALS record");
1778 ValueList.shrinkTo(Record[0]);
1779 break;
1780 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001781 Record.clear();
1782 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001783}
1784
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001785bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001786 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001787
Derek Schuff2ea93872012-02-06 22:30:29 +00001788 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001789
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001790 // Sniff for the signature.
1791 if (Stream.Read(8) != 'B' ||
1792 Stream.Read(8) != 'C' ||
1793 Stream.Read(4) != 0x0 ||
1794 Stream.Read(4) != 0xC ||
1795 Stream.Read(4) != 0xE ||
1796 Stream.Read(4) != 0xD)
1797 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001798
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001799 // We expect a number of well-defined blocks, though we don't necessarily
1800 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001801 while (1) {
1802 if (Stream.AtEndOfStream())
1803 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001804
Chris Lattner5a4251c2013-01-20 02:13:19 +00001805 BitstreamEntry Entry =
1806 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbeyacb61942013-02-06 22:14:06 +00001807
Chris Lattner5a4251c2013-01-20 02:13:19 +00001808 switch (Entry.Kind) {
1809 case BitstreamEntry::Error:
1810 Error("malformed module file");
1811 return true;
1812 case BitstreamEntry::EndBlock:
1813 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001814
Chris Lattner5a4251c2013-01-20 02:13:19 +00001815 case BitstreamEntry::SubBlock:
1816 switch (Entry.ID) {
1817 case bitc::BLOCKINFO_BLOCK_ID:
1818 if (Stream.ReadBlockInfoBlock())
1819 return Error("Malformed BlockInfoBlock");
1820 break;
1821 case bitc::MODULE_BLOCK_ID:
1822 // Reject multiple MODULE_BLOCK's in a single bitstream.
1823 if (TheModule)
1824 return Error("Multiple MODULE_BLOCKs in same stream");
1825 TheModule = M;
1826 if (ParseModule(false))
1827 return true;
1828 if (LazyStreamer) return false;
1829 break;
1830 default:
1831 if (Stream.SkipBlock())
1832 return Error("Malformed block record");
1833 break;
1834 }
1835 continue;
1836 case BitstreamEntry::Record:
1837 // There should be no records in the top-level of blocks.
Joe Abbeyacb61942013-02-06 22:14:06 +00001838
Chris Lattner5a4251c2013-01-20 02:13:19 +00001839 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001840 // to the end of them. If this file size is a multiple of 4 but not 8, we
1841 // have to read and ignore these final 4 bytes :-(
Chris Lattner5a4251c2013-01-20 02:13:19 +00001842 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolac9687b32011-05-26 18:59:54 +00001843 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001844 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001845 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001846
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001847 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001848 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001849 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001850}
Chris Lattnerc453f762007-04-29 07:54:31 +00001851
Bill Wendling34711742010-10-06 01:22:42 +00001852bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1853 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1854 return Error("Malformed block record");
1855
1856 SmallVector<uint64_t, 64> Record;
1857
1858 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001859 while (1) {
1860 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001861
Chris Lattner5a4251c2013-01-20 02:13:19 +00001862 switch (Entry.Kind) {
1863 case BitstreamEntry::SubBlock: // Handled for us already.
1864 case BitstreamEntry::Error:
1865 return Error("malformed module block");
1866 case BitstreamEntry::EndBlock:
Bill Wendling34711742010-10-06 01:22:42 +00001867 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001868 case BitstreamEntry::Record:
1869 // The interesting case.
1870 break;
Bill Wendling34711742010-10-06 01:22:42 +00001871 }
1872
1873 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001874 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling34711742010-10-06 01:22:42 +00001875 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00001876 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1877 std::string S;
1878 if (ConvertToString(Record, 0, S))
1879 return Error("Invalid MODULE_CODE_TRIPLE record");
1880 Triple = S;
1881 break;
1882 }
1883 }
1884 Record.clear();
1885 }
Bill Wendling34711742010-10-06 01:22:42 +00001886}
1887
1888bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001889 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001890
1891 // Sniff for the signature.
1892 if (Stream.Read(8) != 'B' ||
1893 Stream.Read(8) != 'C' ||
1894 Stream.Read(4) != 0x0 ||
1895 Stream.Read(4) != 0xC ||
1896 Stream.Read(4) != 0xE ||
1897 Stream.Read(4) != 0xD)
1898 return Error("Invalid bitcode signature");
1899
1900 // We expect a number of well-defined blocks, though we don't necessarily
1901 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001902 while (1) {
1903 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00001904
Chris Lattner5a4251c2013-01-20 02:13:19 +00001905 switch (Entry.Kind) {
1906 case BitstreamEntry::Error:
1907 Error("malformed module file");
1908 return true;
1909 case BitstreamEntry::EndBlock:
1910 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001911
Chris Lattner5a4251c2013-01-20 02:13:19 +00001912 case BitstreamEntry::SubBlock:
1913 if (Entry.ID == bitc::MODULE_BLOCK_ID)
1914 return ParseModuleTriple(Triple);
Joe Abbeyacb61942013-02-06 22:14:06 +00001915
Chris Lattner5a4251c2013-01-20 02:13:19 +00001916 // Ignore other sub-blocks.
1917 if (Stream.SkipBlock()) {
1918 Error("malformed block record in AST file");
Bill Wendling34711742010-10-06 01:22:42 +00001919 return true;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001920 }
1921 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00001922
Chris Lattner5a4251c2013-01-20 02:13:19 +00001923 case BitstreamEntry::Record:
1924 Stream.skipRecord(Entry.ID);
1925 continue;
Bill Wendling34711742010-10-06 01:22:42 +00001926 }
1927 }
Bill Wendling34711742010-10-06 01:22:42 +00001928}
1929
Devang Patele8e02132009-09-18 19:26:43 +00001930/// ParseMetadataAttachment - Parse metadata attachments.
1931bool BitcodeReader::ParseMetadataAttachment() {
1932 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1933 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001934
Devang Patele8e02132009-09-18 19:26:43 +00001935 SmallVector<uint64_t, 64> Record;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001936 while (1) {
1937 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001938
Chris Lattner5a4251c2013-01-20 02:13:19 +00001939 switch (Entry.Kind) {
1940 case BitstreamEntry::SubBlock: // Handled for us already.
1941 case BitstreamEntry::Error:
1942 return Error("malformed metadata block");
1943 case BitstreamEntry::EndBlock:
1944 return false;
1945 case BitstreamEntry::Record:
1946 // The interesting case.
Devang Patele8e02132009-09-18 19:26:43 +00001947 break;
1948 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001949
Devang Patele8e02132009-09-18 19:26:43 +00001950 // Read a metadata attachment record.
1951 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001952 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patele8e02132009-09-18 19:26:43 +00001953 default: // Default behavior: ignore.
1954 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001955 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001956 unsigned RecordLength = Record.size();
1957 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001958 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001959 Instruction *Inst = InstructionList[Record[0]];
1960 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001961 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001962 DenseMap<unsigned, unsigned>::iterator I =
1963 MDKindMap.find(Kind);
1964 if (I == MDKindMap.end())
1965 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001966 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001967 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001968 }
1969 break;
1970 }
1971 }
1972 }
Devang Patele8e02132009-09-18 19:26:43 +00001973}
Chris Lattner48f84872007-05-01 04:59:48 +00001974
Chris Lattner980e5aa2007-05-01 05:52:21 +00001975/// ParseFunctionBody - Lazily parse the specified function body block.
1976bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001977 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001978 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001979
Nick Lewycky9a49f152010-02-25 08:30:17 +00001980 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001981 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001982 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001983
Chris Lattner980e5aa2007-05-01 05:52:21 +00001984 // Add all the function arguments to the value table.
1985 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1986 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001987
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001988 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001989 BasicBlock *CurBB = 0;
1990 unsigned CurBBNo = 0;
1991
Chris Lattnera6245242010-04-03 02:17:50 +00001992 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00001993
Chris Lattner980e5aa2007-05-01 05:52:21 +00001994 // Read all the records.
1995 SmallVector<uint64_t, 64> Record;
1996 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001997 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00001998
Chris Lattner5a4251c2013-01-20 02:13:19 +00001999 switch (Entry.Kind) {
2000 case BitstreamEntry::Error:
2001 return Error("Bitcode error in function block");
2002 case BitstreamEntry::EndBlock:
2003 goto OutOfRecordLoop;
Joe Abbeyacb61942013-02-06 22:14:06 +00002004
Chris Lattner5a4251c2013-01-20 02:13:19 +00002005 case BitstreamEntry::SubBlock:
2006 switch (Entry.ID) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00002007 default: // Skip unknown content.
2008 if (Stream.SkipBlock())
2009 return Error("Malformed block record");
2010 break;
2011 case bitc::CONSTANTS_BLOCK_ID:
2012 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002013 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002014 break;
2015 case bitc::VALUE_SYMTAB_BLOCK_ID:
2016 if (ParseValueSymbolTable()) return true;
2017 break;
Devang Patele8e02132009-09-18 19:26:43 +00002018 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002019 if (ParseMetadataAttachment()) return true;
2020 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00002021 case bitc::METADATA_BLOCK_ID:
2022 if (ParseMetadata()) return true;
2023 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002024 }
2025 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00002026
Chris Lattner5a4251c2013-01-20 02:13:19 +00002027 case BitstreamEntry::Record:
2028 // The interesting case.
2029 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002030 }
Joe Abbeyacb61942013-02-06 22:14:06 +00002031
Chris Lattner980e5aa2007-05-01 05:52:21 +00002032 // Read a record.
2033 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002034 Instruction *I = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002035 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00002036 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002037 default: // Default behavior: reject
2038 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002039 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002040 if (Record.size() < 1 || Record[0] == 0)
2041 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002042 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00002043 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002044 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00002045 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002046 CurBB = FunctionBBs[0];
2047 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002048
Chris Lattnera6245242010-04-03 02:17:50 +00002049 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2050 // This record indicates that the last instruction is at the same
2051 // location as the previous instruction with a location.
2052 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00002053
Chris Lattnera6245242010-04-03 02:17:50 +00002054 // Get the last instruction emitted.
2055 if (CurBB && !CurBB->empty())
2056 I = &CurBB->back();
2057 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2058 !FunctionBBs[CurBBNo-1]->empty())
2059 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00002060
Chris Lattnera6245242010-04-03 02:17:50 +00002061 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2062 I->setDebugLoc(LastLoc);
2063 I = 0;
2064 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002065
Chris Lattner4f6bab92011-06-17 18:17:37 +00002066 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002067 I = 0; // Get the last instruction emitted.
2068 if (CurBB && !CurBB->empty())
2069 I = &CurBB->back();
2070 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2071 !FunctionBBs[CurBBNo-1]->empty())
2072 I = &FunctionBBs[CurBBNo-1]->back();
2073 if (I == 0 || Record.size() < 4)
2074 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002075
Chris Lattnera6245242010-04-03 02:17:50 +00002076 unsigned Line = Record[0], Col = Record[1];
2077 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00002078
Chris Lattnera6245242010-04-03 02:17:50 +00002079 MDNode *Scope = 0, *IA = 0;
2080 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2081 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2082 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2083 I->setDebugLoc(LastLoc);
2084 I = 0;
2085 continue;
2086 }
2087
Chris Lattnerabfbf852007-05-06 00:21:25 +00002088 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2089 unsigned OpNum = 0;
2090 Value *LHS, *RHS;
2091 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002092 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002093 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002094 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002095
Dan Gohman1224c382009-07-20 21:19:07 +00002096 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002097 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002098 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002099 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002100 if (OpNum < Record.size()) {
2101 if (Opc == Instruction::Add ||
2102 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002103 Opc == Instruction::Mul ||
2104 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002105 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002106 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002107 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002108 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002109 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002110 Opc == Instruction::UDiv ||
2111 Opc == Instruction::LShr ||
2112 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002113 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002114 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002115 } else if (isa<FPMathOperator>(I)) {
2116 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002117 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2118 FMF.setUnsafeAlgebra();
2119 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2120 FMF.setNoNaNs();
2121 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2122 FMF.setNoInfs();
2123 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2124 FMF.setNoSignedZeros();
2125 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2126 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002127 if (FMF.any())
2128 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002129 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002130
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002131 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002132 break;
2133 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002134 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2135 unsigned OpNum = 0;
2136 Value *Op;
2137 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2138 OpNum+2 != Record.size())
2139 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002140
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002141 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002142 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2143 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002144 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002145 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002146 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002147 break;
2148 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002149 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002150 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002151 unsigned OpNum = 0;
2152 Value *BasePtr;
2153 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002154 return Error("Invalid GEP record");
2155
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002156 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002157 while (OpNum != Record.size()) {
2158 Value *Op;
2159 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002160 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002161 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002162 }
2163
Jay Foada9203102011-07-25 09:48:08 +00002164 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002165 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002166 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002167 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002168 break;
2169 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002170
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002171 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2172 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002173 unsigned OpNum = 0;
2174 Value *Agg;
2175 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2176 return Error("Invalid EXTRACTVAL record");
2177
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002178 SmallVector<unsigned, 4> EXTRACTVALIdx;
2179 for (unsigned RecSize = Record.size();
2180 OpNum != RecSize; ++OpNum) {
2181 uint64_t Index = Record[OpNum];
2182 if ((unsigned)Index != Index)
2183 return Error("Invalid EXTRACTVAL index");
2184 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002185 }
2186
Jay Foadfc6d3a42011-07-13 10:26:04 +00002187 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002188 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002189 break;
2190 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002191
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002192 case bitc::FUNC_CODE_INST_INSERTVAL: {
2193 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002194 unsigned OpNum = 0;
2195 Value *Agg;
2196 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2197 return Error("Invalid INSERTVAL record");
2198 Value *Val;
2199 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2200 return Error("Invalid INSERTVAL record");
2201
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002202 SmallVector<unsigned, 4> INSERTVALIdx;
2203 for (unsigned RecSize = Record.size();
2204 OpNum != RecSize; ++OpNum) {
2205 uint64_t Index = Record[OpNum];
2206 if ((unsigned)Index != Index)
2207 return Error("Invalid INSERTVAL index");
2208 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002209 }
2210
Jay Foadfc6d3a42011-07-13 10:26:04 +00002211 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002212 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002213 break;
2214 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002215
Chris Lattnerabfbf852007-05-06 00:21:25 +00002216 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002217 // obsolete form of select
2218 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002219 unsigned OpNum = 0;
2220 Value *TrueVal, *FalseVal, *Cond;
2221 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002222 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2223 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002224 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002225
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002226 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002227 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002228 break;
2229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002230
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002231 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2232 // new form of select
2233 // handles select i1 or select [N x i1]
2234 unsigned OpNum = 0;
2235 Value *TrueVal, *FalseVal, *Cond;
2236 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002237 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002238 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2239 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002240
2241 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002242 if (VectorType* vector_type =
2243 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002244 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002245 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002246 return Error("Invalid SELECT condition type");
2247 } else {
2248 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002249 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002250 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002251 }
2252
Gabor Greif051a9502008-04-06 20:25:17 +00002253 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002254 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002255 break;
2256 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002257
Chris Lattner01ff65f2007-05-02 05:16:49 +00002258 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002259 unsigned OpNum = 0;
2260 Value *Vec, *Idx;
2261 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002262 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002263 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002264 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002265 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002266 break;
2267 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002268
Chris Lattner01ff65f2007-05-02 05:16:49 +00002269 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002270 unsigned OpNum = 0;
2271 Value *Vec, *Elt, *Idx;
2272 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002273 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002274 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002275 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002276 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002277 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002278 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002279 break;
2280 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002281
Chris Lattnerabfbf852007-05-06 00:21:25 +00002282 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2283 unsigned OpNum = 0;
2284 Value *Vec1, *Vec2, *Mask;
2285 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002286 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002287 return Error("Invalid SHUFFLEVEC record");
2288
Mon P Wangaeb06d22008-11-10 04:46:22 +00002289 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002290 return Error("Invalid SHUFFLEVEC record");
2291 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002292 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002293 break;
2294 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002295
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002296 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2297 // Old form of ICmp/FCmp returning bool
2298 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2299 // both legal on vectors but had different behaviour.
2300 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2301 // FCmp/ICmp returning bool or vector of bool
2302
Chris Lattner7337ab92007-05-06 00:00:00 +00002303 unsigned OpNum = 0;
2304 Value *LHS, *RHS;
2305 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002306 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002307 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002308 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002309
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002310 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002311 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002312 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002313 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002314 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002315 break;
2316 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002317
Chris Lattner231cbcb2007-05-02 04:27:25 +00002318 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002319 {
2320 unsigned Size = Record.size();
2321 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002322 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002323 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002324 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002325 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002326
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002327 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002328 Value *Op = NULL;
2329 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2330 return Error("Invalid RET record");
2331 if (OpNum != Record.size())
2332 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002333
Chris Lattner96a74c52011-06-17 18:09:11 +00002334 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002335 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002336 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002337 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002338 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002339 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002340 return Error("Invalid BR record");
2341 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2342 if (TrueDest == 0)
2343 return Error("Invalid BR record");
2344
Devang Patele8e02132009-09-18 19:26:43 +00002345 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002346 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002347 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002348 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002349 else {
2350 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002351 Value *Cond = getValue(Record, 2, NextValueNo,
2352 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002353 if (FalseDest == 0 || Cond == 0)
2354 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002355 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002356 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002357 }
2358 break;
2359 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002360 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002361 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002362 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2363 // New SwitchInst format with case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002364
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002365 Type *OpTy = getTypeByID(Record[1]);
2366 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2367
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002368 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002369 BasicBlock *Default = getBasicBlock(Record[3]);
2370 if (OpTy == 0 || Cond == 0 || Default == 0)
2371 return Error("Invalid SWITCH record");
2372
2373 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002374
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002375 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2376 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002377
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002378 unsigned CurIdx = 5;
2379 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002380 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002381 unsigned NumItems = Record[CurIdx++];
2382 for (unsigned ci = 0; ci != NumItems; ++ci) {
2383 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002384
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002385 APInt Low;
2386 unsigned ActiveWords = 1;
2387 if (ValueBitWidth > 64)
2388 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002389 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2390 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002391 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002392
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002393 if (!isSingleNumber) {
2394 ActiveWords = 1;
2395 if (ValueBitWidth > 64)
2396 ActiveWords = Record[CurIdx++];
2397 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002398 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2399 ValueBitWidth);
Michael Ilseman407a6162012-11-15 22:34:00 +00002400
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002401 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2402 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002403 CurIdx += ActiveWords;
2404 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002405 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002406 }
2407 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Michael Ilseman407a6162012-11-15 22:34:00 +00002408 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002409 SI->addCase(Case, DestBB);
2410 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002411 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002412 if (Hash != (Record[0] & 0xFFFF))
2413 return Error("Invalid SWITCH record");
2414 I = SI;
2415 break;
2416 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002417
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002418 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002419
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002420 if (Record.size() < 3 || (Record.size() & 1) == 0)
2421 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002422 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002423 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002424 BasicBlock *Default = getBasicBlock(Record[2]);
2425 if (OpTy == 0 || Cond == 0 || Default == 0)
2426 return Error("Invalid SWITCH record");
2427 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002428 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002429 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002430 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002431 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002432 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2433 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2434 if (CaseVal == 0 || DestBB == 0) {
2435 delete SI;
2436 return Error("Invalid SWITCH record!");
2437 }
2438 SI->addCase(CaseVal, DestBB);
2439 }
2440 I = SI;
2441 break;
2442 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002443 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002444 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002445 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002446 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002447 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002448 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002449 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002450 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002451 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002452 InstructionList.push_back(IBI);
2453 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2454 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2455 IBI->addDestination(DestBB);
2456 } else {
2457 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002458 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002459 }
2460 }
2461 I = IBI;
2462 break;
2463 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002464
Duncan Sandsdc024672007-11-27 13:23:08 +00002465 case bitc::FUNC_CODE_INST_INVOKE: {
2466 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002467 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002468 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002469 unsigned CCInfo = Record[1];
2470 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2471 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002472
Chris Lattnera9bb7132007-05-08 05:38:01 +00002473 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002474 Value *Callee;
2475 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002476 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002477
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002478 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2479 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002480 dyn_cast<FunctionType>(CalleeTy->getElementType());
2481
2482 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002483 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2484 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002485 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002486
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002487 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002488 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002489 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2490 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002491 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002492 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002493
Chris Lattner7337ab92007-05-06 00:00:00 +00002494 if (!FTy->isVarArg()) {
2495 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002496 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002497 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002498 // Read type/value pairs for varargs params.
2499 while (OpNum != Record.size()) {
2500 Value *Op;
2501 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2502 return Error("Invalid INVOKE record");
2503 Ops.push_back(Op);
2504 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002505 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002506
Jay Foada3efbb12011-07-15 08:37:34 +00002507 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002508 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002509 cast<InvokeInst>(I)->setCallingConv(
2510 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002511 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002512 break;
2513 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002514 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2515 unsigned Idx = 0;
2516 Value *Val = 0;
2517 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2518 return Error("Invalid RESUME record");
2519 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002520 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002521 break;
2522 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002523 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002524 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002525 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002526 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002527 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002528 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002529 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002530 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002531 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002532
Jay Foad3ecfc862011-03-30 11:28:46 +00002533 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002534 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002535
Chris Lattner15e6d172007-05-04 19:11:41 +00002536 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002537 Value *V;
2538 // With the new function encoding, it is possible that operands have
2539 // negative IDs (for forward references). Use a signed VBR
2540 // representation to keep the encoding small.
2541 if (UseRelativeIDs)
2542 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2543 else
2544 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002545 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002546 if (!V || !BB) return Error("Invalid PHI record");
2547 PN->addIncoming(V, BB);
2548 }
2549 I = PN;
2550 break;
2551 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002552
Bill Wendlinge6e88262011-08-12 20:24:12 +00002553 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2554 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2555 unsigned Idx = 0;
2556 if (Record.size() < 4)
2557 return Error("Invalid LANDINGPAD record");
2558 Type *Ty = getTypeByID(Record[Idx++]);
2559 if (!Ty) return Error("Invalid LANDINGPAD record");
2560 Value *PersFn = 0;
2561 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2562 return Error("Invalid LANDINGPAD record");
2563
2564 bool IsCleanup = !!Record[Idx++];
2565 unsigned NumClauses = Record[Idx++];
2566 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2567 LP->setCleanup(IsCleanup);
2568 for (unsigned J = 0; J != NumClauses; ++J) {
2569 LandingPadInst::ClauseType CT =
2570 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2571 Value *Val;
2572
2573 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2574 delete LP;
2575 return Error("Invalid LANDINGPAD record");
2576 }
2577
2578 assert((CT != LandingPadInst::Catch ||
2579 !isa<ArrayType>(Val->getType())) &&
2580 "Catch clause has a invalid type!");
2581 assert((CT != LandingPadInst::Filter ||
2582 isa<ArrayType>(Val->getType())) &&
2583 "Filter clause has invalid type!");
2584 LP->addClause(Val);
2585 }
2586
2587 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002588 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002589 break;
2590 }
2591
Chris Lattner96a74c52011-06-17 18:09:11 +00002592 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2593 if (Record.size() != 4)
2594 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002595 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002596 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002597 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002598 Value *Size = getFnValueByID(Record[2], OpTy);
2599 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002600 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002601 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002602 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002603 break;
2604 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002605 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002606 unsigned OpNum = 0;
2607 Value *Op;
2608 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2609 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002610 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002611
Chris Lattner7337ab92007-05-06 00:00:00 +00002612 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002613 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002614 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002615 }
Eli Friedman21006d42011-08-09 23:02:53 +00002616 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2617 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2618 unsigned OpNum = 0;
2619 Value *Op;
2620 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2621 OpNum+4 != Record.size())
2622 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002623
Eli Friedman21006d42011-08-09 23:02:53 +00002624
2625 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2626 if (Ordering == NotAtomic || Ordering == Release ||
2627 Ordering == AcquireRelease)
2628 return Error("Invalid LOADATOMIC record");
2629 if (Ordering != NotAtomic && Record[OpNum] == 0)
2630 return Error("Invalid LOADATOMIC record");
2631 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2632
2633 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2634 Ordering, SynchScope);
2635 InstructionList.push_back(I);
2636 break;
2637 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002638 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002639 unsigned OpNum = 0;
2640 Value *Val, *Ptr;
2641 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002642 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002643 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2644 OpNum+2 != Record.size())
2645 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002646
Christopher Lambfe63fb92007-12-11 08:59:05 +00002647 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002648 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002649 break;
2650 }
Eli Friedman21006d42011-08-09 23:02:53 +00002651 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2652 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2653 unsigned OpNum = 0;
2654 Value *Val, *Ptr;
2655 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002656 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002657 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2658 OpNum+4 != Record.size())
2659 return Error("Invalid STOREATOMIC record");
2660
2661 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002662 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002663 Ordering == AcquireRelease)
2664 return Error("Invalid STOREATOMIC record");
2665 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2666 if (Ordering != NotAtomic && Record[OpNum] == 0)
2667 return Error("Invalid STOREATOMIC record");
2668
2669 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2670 Ordering, SynchScope);
2671 InstructionList.push_back(I);
2672 break;
2673 }
Eli Friedmanff030482011-07-28 21:48:00 +00002674 case bitc::FUNC_CODE_INST_CMPXCHG: {
2675 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2676 unsigned OpNum = 0;
2677 Value *Ptr, *Cmp, *New;
2678 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002679 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002680 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002681 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002682 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2683 OpNum+3 != Record.size())
2684 return Error("Invalid CMPXCHG record");
2685 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002686 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002687 return Error("Invalid CMPXCHG record");
2688 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2689 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2690 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2691 InstructionList.push_back(I);
2692 break;
2693 }
2694 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2695 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2696 unsigned OpNum = 0;
2697 Value *Ptr, *Val;
2698 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002699 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002700 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2701 OpNum+4 != Record.size())
2702 return Error("Invalid ATOMICRMW record");
2703 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2704 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2705 Operation > AtomicRMWInst::LAST_BINOP)
2706 return Error("Invalid ATOMICRMW record");
2707 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002708 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002709 return Error("Invalid ATOMICRMW record");
2710 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2711 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2712 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2713 InstructionList.push_back(I);
2714 break;
2715 }
Eli Friedman47f35132011-07-25 23:16:38 +00002716 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2717 if (2 != Record.size())
2718 return Error("Invalid FENCE record");
2719 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2720 if (Ordering == NotAtomic || Ordering == Unordered ||
2721 Ordering == Monotonic)
2722 return Error("Invalid FENCE record");
2723 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2724 I = new FenceInst(Context, Ordering, SynchScope);
2725 InstructionList.push_back(I);
2726 break;
2727 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002728 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002729 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2730 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002731 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002732
Bill Wendling99faa3b2012-12-07 23:16:57 +00002733 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002734 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002735
Chris Lattnera9bb7132007-05-08 05:38:01 +00002736 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002737 Value *Callee;
2738 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2739 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002740
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002741 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2742 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002743 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002744 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002745 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002746
Chris Lattner0579f7f2007-05-03 22:04:19 +00002747 SmallVector<Value*, 16> Args;
2748 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002749 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002750 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002751 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002752 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002753 Args.push_back(getValue(Record, OpNum, NextValueNo,
2754 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002755 if (Args.back() == 0) return Error("Invalid CALL record");
2756 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002757
Chris Lattner0579f7f2007-05-03 22:04:19 +00002758 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002759 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002760 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002761 return Error("Invalid CALL record");
2762 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002763 while (OpNum != Record.size()) {
2764 Value *Op;
2765 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2766 return Error("Invalid CALL record");
2767 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002768 }
2769 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002770
Jay Foada3efbb12011-07-15 08:37:34 +00002771 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002772 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002773 cast<CallInst>(I)->setCallingConv(
2774 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002775 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002776 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002777 break;
2778 }
2779 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2780 if (Record.size() < 3)
2781 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002782 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002783 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002784 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002785 if (!OpTy || !Op || !ResTy)
2786 return Error("Invalid VAARG record");
2787 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002788 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002789 break;
2790 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002791 }
2792
2793 // Add instruction to end of current BB. If there is no current BB, reject
2794 // this file.
2795 if (CurBB == 0) {
2796 delete I;
2797 return Error("Invalid instruction with no BB");
2798 }
2799 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002800
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002801 // If this was a terminator instruction, move to the next block.
2802 if (isa<TerminatorInst>(I)) {
2803 ++CurBBNo;
2804 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002806
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002807 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002808 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002809 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002811
Chris Lattner5a4251c2013-01-20 02:13:19 +00002812OutOfRecordLoop:
Joe Abbeyacb61942013-02-06 22:14:06 +00002813
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002814 // Check the function list for unresolved values.
2815 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2816 if (A->getParent() == 0) {
2817 // We found at least one unresolved value. Nuke them all to avoid leaks.
2818 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002819 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002820 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002821 delete A;
2822 }
2823 }
Chris Lattner35a04702007-05-04 03:50:29 +00002824 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002825 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002826 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002827
Dan Gohman064ff3e2010-08-25 20:23:38 +00002828 // FIXME: Check for unresolved forward-declared metadata references
2829 // and clean up leaks.
2830
Chris Lattner50b136d2009-10-28 05:53:48 +00002831 // See if anything took the address of blocks in this function. If so,
2832 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002833 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2834 BlockAddrFwdRefs.find(F);
2835 if (BAFRI != BlockAddrFwdRefs.end()) {
2836 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2837 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2838 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002839 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002840 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00002841
Chris Lattner50b136d2009-10-28 05:53:48 +00002842 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002843 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002844 FwdRef->eraseFromParent();
2845 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002846
Chris Lattner50b136d2009-10-28 05:53:48 +00002847 BlockAddrFwdRefs.erase(BAFRI);
2848 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002849
Chris Lattner980e5aa2007-05-01 05:52:21 +00002850 // Trim the value list down to the size it was before we parsed this function.
2851 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002852 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002853 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002854 return false;
2855}
2856
Derek Schuff2ea93872012-02-06 22:30:29 +00002857/// FindFunctionInStream - Find the function body in the bitcode stream
2858bool BitcodeReader::FindFunctionInStream(Function *F,
2859 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2860 while (DeferredFunctionInfoIterator->second == 0) {
2861 if (Stream.AtEndOfStream())
2862 return Error("Could not find Function in stream");
2863 // ParseModule will parse the next body in the stream and set its
2864 // position in the DeferredFunctionInfo map.
2865 if (ParseModule(true)) return true;
2866 }
2867 return false;
2868}
2869
Chris Lattnerb348bb82007-05-18 04:02:46 +00002870//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002871// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002872//===----------------------------------------------------------------------===//
2873
2874
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002875bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2876 if (const Function *F = dyn_cast<Function>(GV)) {
2877 return F->isDeclaration() &&
2878 DeferredFunctionInfo.count(const_cast<Function*>(F));
2879 }
2880 return false;
2881}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002882
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002883bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2884 Function *F = dyn_cast<Function>(GV);
2885 // If it's not a function or is already material, ignore the request.
2886 if (!F || !F->isMaterializable()) return false;
2887
2888 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002889 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002890 // If its position is recorded as 0, its body is somewhere in the stream
2891 // but we haven't seen it yet.
2892 if (DFII->second == 0)
2893 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002894
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002895 // Move the bit stream to the saved position of the deferred function body.
2896 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002897
Chris Lattnerb348bb82007-05-18 04:02:46 +00002898 if (ParseFunctionBody(F)) {
2899 if (ErrInfo) *ErrInfo = ErrorString;
2900 return true;
2901 }
Chandler Carruth69940402007-08-04 01:51:18 +00002902
2903 // Upgrade any old intrinsic calls in the function.
2904 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2905 E = UpgradedIntrinsics.end(); I != E; ++I) {
2906 if (I->first != I->second) {
2907 for (Value::use_iterator UI = I->first->use_begin(),
2908 UE = I->first->use_end(); UI != UE; ) {
2909 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2910 UpgradeIntrinsicCall(CI, I->second);
2911 }
2912 }
2913 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002914
Chris Lattnerb348bb82007-05-18 04:02:46 +00002915 return false;
2916}
2917
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002918bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2919 const Function *F = dyn_cast<Function>(GV);
2920 if (!F || F->isDeclaration())
2921 return false;
2922 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2923}
2924
2925void BitcodeReader::Dematerialize(GlobalValue *GV) {
2926 Function *F = dyn_cast<Function>(GV);
2927 // If this function isn't dematerializable, this is a noop.
2928 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002929 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002930
Chris Lattnerb348bb82007-05-18 04:02:46 +00002931 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002932
Chris Lattnerb348bb82007-05-18 04:02:46 +00002933 // Just forget the function body, we can remat it later.
2934 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002935}
2936
2937
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002938bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2939 assert(M == TheModule &&
2940 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002941 // Iterate over the module, deserializing any functions that are still on
2942 // disk.
2943 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2944 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002945 if (F->isMaterializable() &&
2946 Materialize(F, ErrInfo))
2947 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002948
Derek Schuff0ffe6982012-02-29 00:07:09 +00002949 // At this point, if there are any function bodies, the current bit is
2950 // pointing to the END_BLOCK record after them. Now make sure the rest
2951 // of the bits in the module have been read.
2952 if (NextUnreadBit)
2953 ParseModule(true);
2954
Daniel Dunbara279bc32009-09-20 02:20:51 +00002955 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2956 // delete the old functions to clean up. We can't do this unless the entire
2957 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002958 // with calls to the old function.
2959 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2960 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2961 if (I->first != I->second) {
2962 for (Value::use_iterator UI = I->first->use_begin(),
2963 UE = I->first->use_end(); UI != UE; ) {
2964 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2965 UpgradeIntrinsicCall(CI, I->second);
2966 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002967 if (!I->first->use_empty())
2968 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002969 I->first->eraseFromParent();
2970 }
2971 }
2972 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002973
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002974 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002975}
2976
Derek Schuff2ea93872012-02-06 22:30:29 +00002977bool BitcodeReader::InitStream() {
2978 if (LazyStreamer) return InitLazyStream();
2979 return InitStreamFromBuffer();
2980}
2981
2982bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00002983 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00002984 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2985
2986 if (Buffer->getBufferSize() & 3) {
2987 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2988 return Error("Invalid bitcode signature");
2989 else
2990 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2991 }
2992
2993 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2994 // The magic number is 0x0B17C0DE stored in little endian.
2995 if (isBitcodeWrapper(BufPtr, BufEnd))
2996 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2997 return Error("Invalid bitcode wrapper header");
2998
2999 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3000 Stream.init(*StreamFile);
3001
3002 return false;
3003}
3004
3005bool BitcodeReader::InitLazyStream() {
3006 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3007 // see it.
3008 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3009 StreamFile.reset(new BitstreamReader(Bytes));
3010 Stream.init(*StreamFile);
3011
3012 unsigned char buf[16];
Benjamin Kramer49a6a8d2013-05-24 10:54:58 +00003013 if (Bytes->readBytes(0, 16, buf) == -1)
Derek Schuff2ea93872012-02-06 22:30:29 +00003014 return Error("Bitcode stream must be at least 16 bytes in length");
3015
3016 if (!isBitcode(buf, buf + 16))
3017 return Error("Invalid bitcode signature");
3018
3019 if (isBitcodeWrapper(buf, buf + 4)) {
3020 const unsigned char *bitcodeStart = buf;
3021 const unsigned char *bitcodeEnd = buf + 16;
3022 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3023 Bytes->dropLeadingBytes(bitcodeStart - buf);
3024 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3025 }
3026 return false;
3027}
Chris Lattner48f84872007-05-01 04:59:48 +00003028
Chris Lattnerc453f762007-04-29 07:54:31 +00003029//===----------------------------------------------------------------------===//
3030// External interface
3031//===----------------------------------------------------------------------===//
3032
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003033/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00003034///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003035Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3036 LLVMContext& Context,
3037 std::string *ErrMsg) {
3038 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00003039 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003040 M->setMaterializer(R);
3041 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00003042 if (ErrMsg)
3043 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003044
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003045 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00003046 return 0;
3047 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003048 // Have the BitcodeReader dtor delete 'Buffer'.
3049 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00003050
3051 R->materializeForwardReferencedFunctions();
3052
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003053 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00003054}
3055
Derek Schuff2ea93872012-02-06 22:30:29 +00003056
3057Module *llvm::getStreamedBitcodeModule(const std::string &name,
3058 DataStreamer *streamer,
3059 LLVMContext &Context,
3060 std::string *ErrMsg) {
3061 Module *M = new Module(name, Context);
3062 BitcodeReader *R = new BitcodeReader(streamer, Context);
3063 M->setMaterializer(R);
3064 if (R->ParseBitcodeInto(M)) {
3065 if (ErrMsg)
3066 *ErrMsg = R->getErrorString();
3067 delete M; // Also deletes R.
3068 return 0;
3069 }
3070 R->setBufferOwned(false); // no buffer to delete
3071 return M;
3072}
3073
Chris Lattnerc453f762007-04-29 07:54:31 +00003074/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3075/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003076Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00003077 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003078 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3079 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003080
3081 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3082 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003083 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003084
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003085 // Read in the entire module, and destroy the BitcodeReader.
3086 if (M->MaterializeAllPermanently(ErrMsg)) {
3087 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003088 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003089 }
Bill Wendling34711742010-10-06 01:22:42 +00003090
Chad Rosiercbbb0962011-12-07 21:44:12 +00003091 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3092 // written. We must defer until the Module has been fully materialized.
3093
Chris Lattnerc453f762007-04-29 07:54:31 +00003094 return M;
3095}
Bill Wendling34711742010-10-06 01:22:42 +00003096
3097std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3098 LLVMContext& Context,
3099 std::string *ErrMsg) {
3100 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3101 // Don't let the BitcodeReader dtor delete 'Buffer'.
3102 R->setBufferOwned(false);
3103
3104 std::string Triple("");
3105 if (R->ParseTriple(Triple))
3106 if (ErrMsg)
3107 *ErrMsg = R->getErrorString();
3108
3109 delete R;
3110 return Triple;
3111}