blob: 99542ec8becabef947118541b9fc03aea8f387a4 [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//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Devang Patele4b27562009-08-28 23:24:31 +000019#include "llvm/IntrinsicInst.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000021#include "llvm/Operator.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000024#include "llvm/ADT/SmallVector.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000025#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000026#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000027#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000028#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000029using namespace llvm;
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
Devang Patel19c87462008-09-26 22:53:05 +000046 std::vector<AttrListPtr>().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();
Chris Lattnerc453f762007-04-29 07:54:31 +000051}
52
Chris Lattner48c85b82007-05-04 03:30:17 +000053//===----------------------------------------------------------------------===//
54// Helper functions to implement forward reference resolution, etc.
55//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000056
Chris Lattnercaee0dc2007-04-22 06:23:29 +000057/// ConvertToString - Convert a string from a record into an std::string, return
58/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000059template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000060static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000061 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000062 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000064
Chris Lattner15e6d172007-05-04 19:11:41 +000065 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
66 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000067 return false;
68}
69
70static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
71 switch (Val) {
72 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000073 case 0: return GlobalValue::ExternalLinkage;
74 case 1: return GlobalValue::WeakAnyLinkage;
75 case 2: return GlobalValue::AppendingLinkage;
76 case 3: return GlobalValue::InternalLinkage;
77 case 4: return GlobalValue::LinkOnceAnyLinkage;
78 case 5: return GlobalValue::DLLImportLinkage;
79 case 6: return GlobalValue::DLLExportLinkage;
80 case 7: return GlobalValue::ExternalWeakLinkage;
81 case 8: return GlobalValue::CommonLinkage;
82 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000083 case 10: return GlobalValue::WeakODRLinkage;
84 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000085 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000086 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000087 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling55ae5152010-08-20 22:05:50 +000088 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000089 }
90}
91
92static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
93 switch (Val) {
94 default: // Map unknown visibilities to default.
95 case 0: return GlobalValue::DefaultVisibility;
96 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000097 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000098 }
99}
100
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000101static int GetDecodedCastOpcode(unsigned Val) {
102 switch (Val) {
103 default: return -1;
104 case bitc::CAST_TRUNC : return Instruction::Trunc;
105 case bitc::CAST_ZEXT : return Instruction::ZExt;
106 case bitc::CAST_SEXT : return Instruction::SExt;
107 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
108 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
109 case bitc::CAST_UITOFP : return Instruction::UIToFP;
110 case bitc::CAST_SITOFP : return Instruction::SIToFP;
111 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
112 case bitc::CAST_FPEXT : return Instruction::FPExt;
113 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
114 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
115 case bitc::CAST_BITCAST : return Instruction::BitCast;
116 }
117}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000118static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000119 switch (Val) {
120 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000121 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000122 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000123 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000124 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000125 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000126 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000127 case bitc::BINOP_UDIV: return Instruction::UDiv;
128 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000129 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000130 case bitc::BINOP_UREM: return Instruction::URem;
131 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000132 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000133 case bitc::BINOP_SHL: return Instruction::Shl;
134 case bitc::BINOP_LSHR: return Instruction::LShr;
135 case bitc::BINOP_ASHR: return Instruction::AShr;
136 case bitc::BINOP_AND: return Instruction::And;
137 case bitc::BINOP_OR: return Instruction::Or;
138 case bitc::BINOP_XOR: return Instruction::Xor;
139 }
140}
141
Eli Friedmanff030482011-07-28 21:48:00 +0000142static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
143 switch (Val) {
144 default: return AtomicRMWInst::BAD_BINOP;
145 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
146 case bitc::RMW_ADD: return AtomicRMWInst::Add;
147 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
148 case bitc::RMW_AND: return AtomicRMWInst::And;
149 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
150 case bitc::RMW_OR: return AtomicRMWInst::Or;
151 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
152 case bitc::RMW_MAX: return AtomicRMWInst::Max;
153 case bitc::RMW_MIN: return AtomicRMWInst::Min;
154 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
155 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
156 }
157}
158
Eli Friedman47f35132011-07-25 23:16:38 +0000159static AtomicOrdering GetDecodedOrdering(unsigned Val) {
160 switch (Val) {
161 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
162 case bitc::ORDERING_UNORDERED: return Unordered;
163 case bitc::ORDERING_MONOTONIC: return Monotonic;
164 case bitc::ORDERING_ACQUIRE: return Acquire;
165 case bitc::ORDERING_RELEASE: return Release;
166 case bitc::ORDERING_ACQREL: return AcquireRelease;
167 default: // Map unknown orderings to sequentially-consistent.
168 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
169 }
170}
171
172static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
173 switch (Val) {
174 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
175 default: // Map unknown scopes to cross-thread.
176 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
177 }
178}
179
Gabor Greifefe65362008-05-10 08:32:32 +0000180namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000181namespace {
182 /// @brief A class for maintaining the slot number definition
183 /// as a placeholder for the actual definition for forward constants defs.
184 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000185 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000186 public:
187 // allocate space for exactly one operand
188 void *operator new(size_t s) {
189 return User::operator new(s, 1);
190 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000191 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000192 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000193 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000194 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000195
Chris Lattnerea693df2008-08-21 02:34:16 +0000196 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000197 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000198 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000199 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000200 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
201 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000202
203
Gabor Greifefe65362008-05-10 08:32:32 +0000204 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000205 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000206 };
207}
208
Chris Lattner46e77402009-03-31 22:55:09 +0000209// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000210template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000211struct OperandTraits<ConstantPlaceHolder> :
212 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000213};
Gabor Greifefe65362008-05-10 08:32:32 +0000214}
215
Chris Lattner46e77402009-03-31 22:55:09 +0000216
217void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
218 if (Idx == size()) {
219 push_back(V);
220 return;
221 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000222
Chris Lattner46e77402009-03-31 22:55:09 +0000223 if (Idx >= size())
224 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000225
Chris Lattner46e77402009-03-31 22:55:09 +0000226 WeakVH &OldV = ValuePtrs[Idx];
227 if (OldV == 0) {
228 OldV = V;
229 return;
230 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000231
Chris Lattner46e77402009-03-31 22:55:09 +0000232 // Handle constants and non-constants (e.g. instrs) differently for
233 // efficiency.
234 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
235 ResolveConstants.push_back(std::make_pair(PHC, Idx));
236 OldV = V;
237 } else {
238 // If there was a forward reference to this value, replace it.
239 Value *PrevVal = OldV;
240 OldV->replaceAllUsesWith(V);
241 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000242 }
243}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000244
Gabor Greifefe65362008-05-10 08:32:32 +0000245
Chris Lattner522b7b12007-04-24 05:48:56 +0000246Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000247 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000248 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000249 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000250
Chris Lattner46e77402009-03-31 22:55:09 +0000251 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000252 assert(Ty == V->getType() && "Type mismatch in constant table!");
253 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000254 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000255
256 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000257 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000258 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000259 return C;
260}
261
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000262Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000263 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000264 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000265
Chris Lattner46e77402009-03-31 22:55:09 +0000266 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000267 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
268 return V;
269 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000270
Chris Lattner01ff65f2007-05-02 05:16:49 +0000271 // No type specified, must be invalid reference.
272 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000273
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000274 // Create and return a placeholder, which will later be RAUW'd.
275 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000276 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000277 return V;
278}
279
Chris Lattnerea693df2008-08-21 02:34:16 +0000280/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
281/// resolves any forward references. The idea behind this is that we sometimes
282/// get constants (such as large arrays) which reference *many* forward ref
283/// constants. Replacing each of these causes a lot of thrashing when
284/// building/reuniquing the constant. Instead of doing this, we look at all the
285/// uses and rewrite all the place holders at once for any constant that uses
286/// a placeholder.
287void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000288 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000289 // binary search.
290 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000291
Chris Lattnerea693df2008-08-21 02:34:16 +0000292 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000293
Chris Lattnerea693df2008-08-21 02:34:16 +0000294 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000295 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000296 Constant *Placeholder = ResolveConstants.back().first;
297 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000298
Chris Lattnerea693df2008-08-21 02:34:16 +0000299 // Loop over all users of the placeholder, updating them to reference the
300 // new value. If they reference more than one placeholder, update them all
301 // at once.
302 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000303 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000304 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 // If the using object isn't uniqued, just update the operands. This
307 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000308 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000309 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000310 continue;
311 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000312
Chris Lattnerea693df2008-08-21 02:34:16 +0000313 // Otherwise, we have a constant that uses the placeholder. Replace that
314 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000315 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000316 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
317 I != E; ++I) {
318 Value *NewOp;
319 if (!isa<ConstantPlaceHolder>(*I)) {
320 // Not a placeholder reference.
321 NewOp = *I;
322 } else if (*I == Placeholder) {
323 // Common case is that it just references this one placeholder.
324 NewOp = RealVal;
325 } else {
326 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000327 ResolveConstantsTy::iterator It =
328 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000329 std::pair<Constant*, unsigned>(cast<Constant>(*I),
330 0));
331 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000332 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000333 }
334
335 NewOps.push_back(cast<Constant>(NewOp));
336 }
337
338 // Make the new constant.
339 Constant *NewC;
340 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000341 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000342 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000343 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000344 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000345 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000346 } else {
347 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000348 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000349 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000350
Chris Lattnerea693df2008-08-21 02:34:16 +0000351 UserC->replaceAllUsesWith(NewC);
352 UserC->destroyConstant();
353 NewOps.clear();
354 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000355
Nick Lewyckycb337992009-05-10 20:57:05 +0000356 // Update all ValueHandles, they should be the only users at this point.
357 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000358 delete Placeholder;
359 }
360}
361
Devang Pateld5ac4042009-08-04 06:00:18 +0000362void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
363 if (Idx == size()) {
364 push_back(V);
365 return;
366 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Devang Pateld5ac4042009-08-04 06:00:18 +0000368 if (Idx >= size())
369 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000370
Devang Pateld5ac4042009-08-04 06:00:18 +0000371 WeakVH &OldV = MDValuePtrs[Idx];
372 if (OldV == 0) {
373 OldV = V;
374 return;
375 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000376
Devang Pateld5ac4042009-08-04 06:00:18 +0000377 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000378 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000379 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000380 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000381 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
382 // value for Idx.
383 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000384}
385
386Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
387 if (Idx >= size())
388 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000389
Devang Pateld5ac4042009-08-04 06:00:18 +0000390 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000391 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000392 return V;
393 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000394
Devang Pateld5ac4042009-08-04 06:00:18 +0000395 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000396 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000397 MDValuePtrs[Idx] = V;
398 return V;
399}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000400
Chris Lattner1afcace2011-07-09 17:41:24 +0000401Type *BitcodeReader::getTypeByID(unsigned ID) {
402 // The type table size is always specified correctly.
403 if (ID >= TypeList.size())
404 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000405
Chris Lattner1afcace2011-07-09 17:41:24 +0000406 if (Type *Ty = TypeList[ID])
407 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000408
Chris Lattner1afcace2011-07-09 17:41:24 +0000409 // If we have a forward reference, the only possible case is when it is to a
410 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000411 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000412}
413
Chris Lattner1afcace2011-07-09 17:41:24 +0000414
Chris Lattner48c85b82007-05-04 03:30:17 +0000415//===----------------------------------------------------------------------===//
416// Functions for parsing blocks from the bitcode file
417//===----------------------------------------------------------------------===//
418
Devang Patel05988662008-09-25 21:00:45 +0000419bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000420 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000421 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000422
Devang Patel19c87462008-09-26 22:53:05 +0000423 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000424 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000425
Chris Lattner48c85b82007-05-04 03:30:17 +0000426 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000427
Devang Patel05988662008-09-25 21:00:45 +0000428 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000429
Chris Lattner48c85b82007-05-04 03:30:17 +0000430 // Read all the records.
431 while (1) {
432 unsigned Code = Stream.ReadCode();
433 if (Code == bitc::END_BLOCK) {
434 if (Stream.ReadBlockEnd())
435 return Error("Error at end of PARAMATTR block");
436 return false;
437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000438
Chris Lattner48c85b82007-05-04 03:30:17 +0000439 if (Code == bitc::ENTER_SUBBLOCK) {
440 // No known subblocks, always skip them.
441 Stream.ReadSubBlockID();
442 if (Stream.SkipBlock())
443 return Error("Malformed block record");
444 continue;
445 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000446
Chris Lattner48c85b82007-05-04 03:30:17 +0000447 if (Code == bitc::DEFINE_ABBREV) {
448 Stream.ReadAbbrevRecord();
449 continue;
450 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000451
Chris Lattner48c85b82007-05-04 03:30:17 +0000452 // Read a record.
453 Record.clear();
454 switch (Stream.ReadRecord(Code, Record)) {
455 default: // Default behavior: ignore.
456 break;
457 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
458 if (Record.size() & 1)
459 return Error("Invalid ENTRY record");
460
Chris Lattner9a6cb152008-10-05 18:22:09 +0000461 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000462 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000463 // to index ~0. Index 0 is used for return value attributes but used to be
464 // used for function attributes.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000465 Attributes RetAttribute;
466 Attributes FnAttribute;
Chris Lattner48c85b82007-05-04 03:30:17 +0000467 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000468 // FIXME: remove in LLVM 3.0
469 // The alignment is stored as a 16-bit raw value from bits 31--16.
470 // We shift the bits above 31 down by 11 bits.
471
472 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
473 if (Alignment && !isPowerOf2_32(Alignment))
474 return Error("Alignment is not a power of two.");
475
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000476 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000477 if (Alignment)
478 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000479 ReconstitutedAttr |=
480 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000481
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000482 Record[i+1] = ReconstitutedAttr.Raw();
Devang Patel19c87462008-09-26 22:53:05 +0000483 if (Record[i] == 0)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000484 RetAttribute = ReconstitutedAttr;
Devang Patel19c87462008-09-26 22:53:05 +0000485 else if (Record[i] == ~0U)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000486 FnAttribute = ReconstitutedAttr;
Devang Patel19c87462008-09-26 22:53:05 +0000487 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000488
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000489 Attributes OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
Chris Lattner9a6cb152008-10-05 18:22:09 +0000490 Attribute::ReadOnly|Attribute::ReadNone);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000491
Chris Lattner9a6cb152008-10-05 18:22:09 +0000492 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000493 (RetAttribute & OldRetAttrs)) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000494 if (FnAttribute == Attribute::None) { // add a slot so they get added.
495 Record.push_back(~0U);
496 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000497 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000498
Chris Lattner9a6cb152008-10-05 18:22:09 +0000499 FnAttribute |= RetAttribute & OldRetAttrs;
500 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000501 }
Chris Lattner461edd92008-03-12 02:25:52 +0000502
Devang Patel19c87462008-09-26 22:53:05 +0000503 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000504 if (Record[i] == 0) {
505 if (RetAttribute != Attribute::None)
506 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
507 } else if (Record[i] == ~0U) {
508 if (FnAttribute != Attribute::None)
509 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000510 } else if (Attributes(Record[i+1]) != Attribute::None)
511 Attrs.push_back(AttributeWithIndex::get(Record[i],
512 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000513 }
Devang Patel19c87462008-09-26 22:53:05 +0000514
515 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000516 Attrs.clear();
517 break;
518 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000519 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000520 }
521}
522
Chris Lattner86697142007-05-01 05:01:34 +0000523bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000524 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000525 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000526
Chris Lattner1afcace2011-07-09 17:41:24 +0000527 return ParseTypeTableBody();
528}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000529
Chris Lattner1afcace2011-07-09 17:41:24 +0000530bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000531 if (!TypeList.empty())
532 return Error("Multiple TYPE_BLOCKs found!");
533
534 SmallVector<uint64_t, 64> Record;
535 unsigned NumRecords = 0;
536
Chris Lattner1afcace2011-07-09 17:41:24 +0000537 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000538
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000539 // Read all the records for this type table.
540 while (1) {
541 unsigned Code = Stream.ReadCode();
542 if (Code == bitc::END_BLOCK) {
543 if (NumRecords != TypeList.size())
544 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000545 if (Stream.ReadBlockEnd())
546 return Error("Error at end of type table block");
547 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000548 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000549
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000550 if (Code == bitc::ENTER_SUBBLOCK) {
551 // No known subblocks, always skip them.
552 Stream.ReadSubBlockID();
553 if (Stream.SkipBlock())
554 return Error("Malformed block record");
555 continue;
556 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000557
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000558 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000559 Stream.ReadAbbrevRecord();
560 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000561 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000562
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000563 // Read a record.
564 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000565 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000566 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000567 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000568 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
569 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
570 // type list. This allows us to reserve space.
571 if (Record.size() < 1)
572 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000573 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000574 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000575 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000576 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000577 break;
Dan Gohmance163392011-12-17 00:04:22 +0000578 case bitc::TYPE_CODE_HALF: // HALF
579 ResultTy = Type::getHalfTy(Context);
580 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000581 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000582 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 break;
584 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000585 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000586 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000587 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000588 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000589 break;
590 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000591 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000592 break;
593 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000594 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000595 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000596 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000597 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000598 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000599 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000600 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000601 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000602 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
603 ResultTy = Type::getX86_MMXTy(Context);
604 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000605 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
606 if (Record.size() < 1)
607 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000608
Owen Anderson1d0be152009-08-13 21:58:54 +0000609 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000610 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000611 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000612 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000613 if (Record.size() < 1)
614 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000615 unsigned AddressSpace = 0;
616 if (Record.size() == 2)
617 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000618 ResultTy = getTypeByID(Record[0]);
619 if (ResultTy == 0) return Error("invalid element type in pointer type");
620 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000621 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000622 }
Chad Rosiercde54642011-11-03 00:14:01 +0000623 case bitc::TYPE_CODE_FUNCTION: {
624 // FUNCTION: [vararg, retty, paramty x N]
625 if (Record.size() < 2)
626 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000627 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000628 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
629 if (Type *T = getTypeByID(Record[i]))
630 ArgTys.push_back(T);
631 else
632 break;
633 }
634
635 ResultTy = getTypeByID(Record[1]);
636 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
637 return Error("invalid type in function type");
638
639 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
640 break;
641 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000642 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000643 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000644 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000645 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000646 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
647 if (Type *T = getTypeByID(Record[i]))
648 EltTys.push_back(T);
649 else
650 break;
651 }
652 if (EltTys.size() != Record.size()-1)
653 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000654 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000655 break;
656 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000657 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
658 if (ConvertToString(Record, 0, TypeName))
659 return Error("Invalid STRUCT_NAME record");
660 continue;
661
662 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
663 if (Record.size() < 1)
664 return Error("Invalid STRUCT type record");
665
666 if (NumRecords >= TypeList.size())
667 return Error("invalid TYPE table");
668
669 // Check to see if this was forward referenced, if so fill in the temp.
670 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
671 if (Res) {
672 Res->setName(TypeName);
673 TypeList[NumRecords] = 0;
674 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000675 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000676 TypeName.clear();
677
678 SmallVector<Type*, 8> EltTys;
679 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
680 if (Type *T = getTypeByID(Record[i]))
681 EltTys.push_back(T);
682 else
683 break;
684 }
685 if (EltTys.size() != Record.size()-1)
686 return Error("invalid STRUCT type record");
687 Res->setBody(EltTys, Record[0]);
688 ResultTy = Res;
689 break;
690 }
691 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
692 if (Record.size() != 1)
693 return Error("Invalid OPAQUE type record");
694
695 if (NumRecords >= TypeList.size())
696 return Error("invalid TYPE table");
697
698 // Check to see if this was forward referenced, if so fill in the temp.
699 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
700 if (Res) {
701 Res->setName(TypeName);
702 TypeList[NumRecords] = 0;
703 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000704 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000705 TypeName.clear();
706 ResultTy = Res;
707 break;
708 }
709 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
710 if (Record.size() < 2)
711 return Error("Invalid ARRAY type record");
712 if ((ResultTy = getTypeByID(Record[1])))
713 ResultTy = ArrayType::get(ResultTy, Record[0]);
714 else
715 return Error("Invalid ARRAY type element");
716 break;
717 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
718 if (Record.size() < 2)
719 return Error("Invalid VECTOR type record");
720 if ((ResultTy = getTypeByID(Record[1])))
721 ResultTy = VectorType::get(ResultTy, Record[0]);
722 else
723 return Error("Invalid ARRAY type element");
724 break;
725 }
726
727 if (NumRecords >= TypeList.size())
728 return Error("invalid TYPE table");
729 assert(ResultTy && "Didn't read a type?");
730 assert(TypeList[NumRecords] == 0 && "Already read type?");
731 TypeList[NumRecords++] = ResultTy;
732 }
733}
734
Chris Lattner86697142007-05-01 05:01:34 +0000735bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000736 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000737 return Error("Malformed block record");
738
739 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000740
Chris Lattner0b2482a2007-04-23 21:26:05 +0000741 // Read all the records for this value table.
742 SmallString<128> ValueName;
743 while (1) {
744 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000745 if (Code == bitc::END_BLOCK) {
746 if (Stream.ReadBlockEnd())
747 return Error("Error at end of value symbol table block");
748 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000749 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000750 if (Code == bitc::ENTER_SUBBLOCK) {
751 // No known subblocks, always skip them.
752 Stream.ReadSubBlockID();
753 if (Stream.SkipBlock())
754 return Error("Malformed block record");
755 continue;
756 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattner0b2482a2007-04-23 21:26:05 +0000758 if (Code == bitc::DEFINE_ABBREV) {
759 Stream.ReadAbbrevRecord();
760 continue;
761 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000762
Chris Lattner0b2482a2007-04-23 21:26:05 +0000763 // Read a record.
764 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000765 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000766 default: // Default behavior: unknown type.
767 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000768 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000769 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000770 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000771 unsigned ValueID = Record[0];
772 if (ValueID >= ValueList.size())
773 return Error("Invalid Value ID in VST_ENTRY record");
774 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000775
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000776 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000777 ValueName.clear();
778 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000779 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000780 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000781 if (ConvertToString(Record, 1, ValueName))
782 return Error("Invalid VST_BBENTRY record");
783 BasicBlock *BB = getBasicBlock(Record[0]);
784 if (BB == 0)
785 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000786
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000787 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000788 ValueName.clear();
789 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000790 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000791 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000792 }
793}
794
Devang Patele54abc92009-07-22 17:43:22 +0000795bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000796 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000797
798 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
799 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000800
Devang Patele54abc92009-07-22 17:43:22 +0000801 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000802
Devang Patele54abc92009-07-22 17:43:22 +0000803 // Read all the records.
804 while (1) {
805 unsigned Code = Stream.ReadCode();
806 if (Code == bitc::END_BLOCK) {
807 if (Stream.ReadBlockEnd())
808 return Error("Error at end of PARAMATTR block");
809 return false;
810 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000811
Devang Patele54abc92009-07-22 17:43:22 +0000812 if (Code == bitc::ENTER_SUBBLOCK) {
813 // No known subblocks, always skip them.
814 Stream.ReadSubBlockID();
815 if (Stream.SkipBlock())
816 return Error("Malformed block record");
817 continue;
818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000819
Devang Patele54abc92009-07-22 17:43:22 +0000820 if (Code == bitc::DEFINE_ABBREV) {
821 Stream.ReadAbbrevRecord();
822 continue;
823 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000824
Victor Hernandez24e64df2010-01-10 07:14:18 +0000825 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000826 // Read a record.
827 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000828 Code = Stream.ReadRecord(Code, Record);
829 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000830 default: // Default behavior: ignore.
831 break;
Devang Patelaa993142009-07-29 22:34:41 +0000832 case bitc::METADATA_NAME: {
833 // Read named of the named metadata.
834 unsigned NameLength = Record.size();
835 SmallString<8> Name;
836 Name.resize(NameLength);
837 for (unsigned i = 0; i != NameLength; ++i)
838 Name[i] = Record[i];
839 Record.clear();
840 Code = Stream.ReadCode();
841
Chris Lattner9d61dd92011-06-17 17:50:30 +0000842 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000843 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000844 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000845
846 // Read named metadata elements.
847 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000848 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000849 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000850 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
851 if (MD == 0)
852 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000853 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000854 }
Devang Patelaa993142009-07-29 22:34:41 +0000855 break;
856 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000857 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000858 IsFunctionLocal = true;
859 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000860 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000861 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000862 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000863
Devang Patel104cf9e2009-07-23 01:07:34 +0000864 unsigned Size = Record.size();
865 SmallVector<Value*, 8> Elts;
866 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000867 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000868 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000869 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000870 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000871 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000872 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
873 else
874 Elts.push_back(NULL);
875 }
Jay Foadec9186b2011-04-21 19:59:31 +0000876 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000877 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000878 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000879 break;
880 }
Devang Patele54abc92009-07-22 17:43:22 +0000881 case bitc::METADATA_STRING: {
882 unsigned MDStringLength = Record.size();
883 SmallString<8> String;
884 String.resize(MDStringLength);
885 for (unsigned i = 0; i != MDStringLength; ++i)
886 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000887 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +0000888 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +0000889 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000890 break;
891 }
Devang Patele8e02132009-09-18 19:26:43 +0000892 case bitc::METADATA_KIND: {
893 unsigned RecordLength = Record.size();
894 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000895 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +0000896 SmallString<8> Name;
897 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +0000898 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +0000899 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000900 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +0000901
Chris Lattner08113472009-12-29 09:01:33 +0000902 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000903 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
904 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000905 break;
906 }
Devang Patele54abc92009-07-22 17:43:22 +0000907 }
908 }
909}
910
Chris Lattner0eef0802007-04-24 04:04:35 +0000911/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
912/// the LSB for dense VBR encoding.
913static uint64_t DecodeSignRotatedValue(uint64_t V) {
914 if ((V & 1) == 0)
915 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000916 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000917 return -(V >> 1);
918 // There is no such thing as -0 with integers. "-0" really means MININT.
919 return 1ULL << 63;
920}
921
Chris Lattner07d98b42007-04-26 02:46:40 +0000922/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
923/// values and aliases that we can.
924bool BitcodeReader::ResolveGlobalAndAliasInits() {
925 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
926 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000927
Chris Lattner07d98b42007-04-26 02:46:40 +0000928 GlobalInitWorklist.swap(GlobalInits);
929 AliasInitWorklist.swap(AliasInits);
930
931 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000932 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000933 if (ValID >= ValueList.size()) {
934 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000935 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000936 } else {
937 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
938 GlobalInitWorklist.back().first->setInitializer(C);
939 else
940 return Error("Global variable initializer is not a constant!");
941 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000942 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000943 }
944
945 while (!AliasInitWorklist.empty()) {
946 unsigned ValID = AliasInitWorklist.back().second;
947 if (ValID >= ValueList.size()) {
948 AliasInits.push_back(AliasInitWorklist.back());
949 } else {
950 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000951 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000952 else
953 return Error("Alias initializer is not a constant!");
954 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000955 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000956 }
957 return false;
958}
959
Chris Lattner86697142007-05-01 05:01:34 +0000960bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000961 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000962 return Error("Malformed block record");
963
964 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000965
Chris Lattnere16504e2007-04-24 03:30:34 +0000966 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000967 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000968 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000969 while (1) {
970 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000971 if (Code == bitc::END_BLOCK)
972 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000973
Chris Lattnere16504e2007-04-24 03:30:34 +0000974 if (Code == bitc::ENTER_SUBBLOCK) {
975 // No known subblocks, always skip them.
976 Stream.ReadSubBlockID();
977 if (Stream.SkipBlock())
978 return Error("Malformed block record");
979 continue;
980 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000981
Chris Lattnere16504e2007-04-24 03:30:34 +0000982 if (Code == bitc::DEFINE_ABBREV) {
983 Stream.ReadAbbrevRecord();
984 continue;
985 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000986
Chris Lattnere16504e2007-04-24 03:30:34 +0000987 // Read a record.
988 Record.clear();
989 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000990 unsigned BitCode = Stream.ReadRecord(Code, Record);
991 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000992 default: // Default behavior: unknown constant
993 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000994 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000995 break;
996 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
997 if (Record.empty())
998 return Error("Malformed CST_SETTYPE record");
999 if (Record[0] >= TypeList.size())
1000 return Error("Invalid Type ID in CST_SETTYPE record");
1001 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001002 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001003 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001004 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001005 break;
1006 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001007 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001008 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +00001009 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001010 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001011 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001012 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001013 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001014
Chris Lattner15e6d172007-05-04 19:11:41 +00001015 unsigned NumWords = Record.size();
Stepan Dyatkovskiy1f983832012-05-08 08:33:21 +00001016 SmallVector<uint64_t, 8> Words;
1017 Words.resize(NumWords);
1018 for (unsigned i = 0; i != NumWords; ++i)
1019 Words[i] = DecodeSignRotatedValue(Record[i]);
1020 V = ConstantInt::get(Context,
1021 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
1022 Words));
Chris Lattner0eef0802007-04-24 04:04:35 +00001023 break;
1024 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001025 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001026 if (Record.empty())
1027 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001028 if (CurTy->isHalfTy())
1029 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1030 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001031 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001032 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001033 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001034 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001035 // Bits are not stored the same way as a normal i80 APInt, compensate.
1036 uint64_t Rearrange[2];
1037 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1038 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001039 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001040 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001041 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001042 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001043 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001044 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001045 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001046 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001047 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001048
Chris Lattner15e6d172007-05-04 19:11:41 +00001049 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1050 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001051 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001052
Chris Lattner15e6d172007-05-04 19:11:41 +00001053 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001054 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001055
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001056 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001057 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001058 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001059 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001060 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001061 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1062 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001063 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001064 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001065 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001066 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1067 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001068 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001069 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001070 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001071 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001072 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001073 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001074 break;
1075 }
Chris Lattner2237f842012-02-05 02:41:35 +00001076 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001077 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1078 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001079 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001080
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001081 unsigned Size = Record.size();
Chris Lattner2237f842012-02-05 02:41:35 +00001082 SmallString<16> Elts;
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001083 for (unsigned i = 0; i != Size; ++i)
Chris Lattner2237f842012-02-05 02:41:35 +00001084 Elts.push_back(Record[i]);
1085 V = ConstantDataArray::getString(Context, Elts,
1086 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001087 break;
1088 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001089 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1090 if (Record.empty())
1091 return Error("Invalid CST_DATA record");
1092
1093 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1094 unsigned Size = Record.size();
1095
1096 if (EltTy->isIntegerTy(8)) {
1097 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1098 if (isa<VectorType>(CurTy))
1099 V = ConstantDataVector::get(Context, Elts);
1100 else
1101 V = ConstantDataArray::get(Context, Elts);
1102 } else if (EltTy->isIntegerTy(16)) {
1103 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1104 if (isa<VectorType>(CurTy))
1105 V = ConstantDataVector::get(Context, Elts);
1106 else
1107 V = ConstantDataArray::get(Context, Elts);
1108 } else if (EltTy->isIntegerTy(32)) {
1109 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1110 if (isa<VectorType>(CurTy))
1111 V = ConstantDataVector::get(Context, Elts);
1112 else
1113 V = ConstantDataArray::get(Context, Elts);
1114 } else if (EltTy->isIntegerTy(64)) {
1115 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1116 if (isa<VectorType>(CurTy))
1117 V = ConstantDataVector::get(Context, Elts);
1118 else
1119 V = ConstantDataArray::get(Context, Elts);
1120 } else if (EltTy->isFloatTy()) {
1121 SmallVector<float, 16> Elts;
1122 for (unsigned i = 0; i != Size; ++i) {
1123 union { uint32_t I; float F; };
1124 I = Record[i];
1125 Elts.push_back(F);
1126 }
1127 if (isa<VectorType>(CurTy))
1128 V = ConstantDataVector::get(Context, Elts);
1129 else
1130 V = ConstantDataArray::get(Context, Elts);
1131 } else if (EltTy->isDoubleTy()) {
1132 SmallVector<double, 16> Elts;
1133 for (unsigned i = 0; i != Size; ++i) {
1134 union { uint64_t I; double F; };
1135 I = Record[i];
1136 Elts.push_back(F);
1137 }
1138 if (isa<VectorType>(CurTy))
1139 V = ConstantDataVector::get(Context, Elts);
1140 else
1141 V = ConstantDataArray::get(Context, Elts);
1142 } else {
1143 return Error("Unknown element type in CE_DATA");
1144 }
1145 break;
1146 }
1147
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001148 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1149 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1150 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001151 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001152 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001153 } else {
1154 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1155 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001156 unsigned Flags = 0;
1157 if (Record.size() >= 4) {
1158 if (Opc == Instruction::Add ||
1159 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001160 Opc == Instruction::Mul ||
1161 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001162 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1163 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1164 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1165 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001166 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001167 Opc == Instruction::UDiv ||
1168 Opc == Instruction::LShr ||
1169 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001170 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001171 Flags |= SDivOperator::IsExact;
1172 }
1173 }
1174 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001175 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001176 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001177 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001178 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1179 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1180 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001181 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001182 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001183 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001184 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001185 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001186 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001187 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001188 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001189 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001190 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001191 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001192 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001193 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001194 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001195 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001196 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001197 if (!ElTy) return Error("Invalid CE_GEP record");
1198 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1199 }
Jay Foaddab3d292011-07-21 14:31:17 +00001200 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001201 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1202 BitCode ==
1203 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001204 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001205 }
1206 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1207 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001208 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001209 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001210 ValueList.getConstantFwdRef(Record[1],CurTy),
1211 ValueList.getConstantFwdRef(Record[2],CurTy));
1212 break;
1213 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1214 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001215 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001216 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1217 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1218 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001219 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001220 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001221 break;
1222 }
1223 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001224 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001225 if (Record.size() < 3 || OpTy == 0)
1226 return Error("Invalid CE_INSERTELT record");
1227 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1228 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1229 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001230 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001231 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001232 break;
1233 }
1234 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001235 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001236 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001237 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001238 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1239 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001240 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001241 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001242 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001243 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001244 break;
1245 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001246 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001247 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1248 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001249 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001250 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1251 return Error("Invalid CE_SHUFVEC_EX record");
1252 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1253 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001254 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001255 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001256 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001257 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001258 break;
1259 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001260 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1261 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001262 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001263 if (OpTy == 0) return Error("Invalid CE_CMP record");
1264 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1265 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1266
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001267 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001268 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001269 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001270 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001271 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001272 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001273 case bitc::CST_CODE_INLINEASM: {
1274 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1275 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001276 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001277 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001278 unsigned AsmStrSize = Record[1];
1279 if (2+AsmStrSize >= Record.size())
1280 return Error("Invalid INLINEASM record");
1281 unsigned ConstStrSize = Record[2+AsmStrSize];
1282 if (3+AsmStrSize+ConstStrSize > Record.size())
1283 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001284
Chris Lattner2bce93a2007-05-06 01:58:20 +00001285 for (unsigned i = 0; i != AsmStrSize; ++i)
1286 AsmStr += (char)Record[2+i];
1287 for (unsigned i = 0; i != ConstStrSize; ++i)
1288 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001289 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001290 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001291 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001292 break;
1293 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001294 case bitc::CST_CODE_BLOCKADDRESS:{
1295 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001296 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001297 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1298 Function *Fn =
1299 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1300 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1301
1302 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1303 Type::getInt8Ty(Context),
1304 false, GlobalValue::InternalLinkage,
1305 0, "");
1306 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1307 V = FwdRef;
1308 break;
1309 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001310 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001311
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001312 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001313 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001314 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001315
Chris Lattnerea693df2008-08-21 02:34:16 +00001316 if (NextCstNo != ValueList.size())
1317 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001318
Chris Lattnerea693df2008-08-21 02:34:16 +00001319 if (Stream.ReadBlockEnd())
1320 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001321
Chris Lattnerea693df2008-08-21 02:34:16 +00001322 // Once all the constants have been read, go through and resolve forward
1323 // references.
1324 ValueList.ResolveConstantForwardRefs();
1325 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001326}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001327
Chad Rosiercbbb0962011-12-07 21:44:12 +00001328bool BitcodeReader::ParseUseLists() {
1329 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1330 return Error("Malformed block record");
1331
1332 SmallVector<uint64_t, 64> Record;
1333
1334 // Read all the records.
1335 while (1) {
1336 unsigned Code = Stream.ReadCode();
1337 if (Code == bitc::END_BLOCK) {
1338 if (Stream.ReadBlockEnd())
1339 return Error("Error at end of use-list table block");
1340 return false;
1341 }
1342
1343 if (Code == bitc::ENTER_SUBBLOCK) {
1344 // No known subblocks, always skip them.
1345 Stream.ReadSubBlockID();
1346 if (Stream.SkipBlock())
1347 return Error("Malformed block record");
1348 continue;
1349 }
1350
1351 if (Code == bitc::DEFINE_ABBREV) {
1352 Stream.ReadAbbrevRecord();
1353 continue;
1354 }
1355
1356 // Read a use list record.
1357 Record.clear();
1358 switch (Stream.ReadRecord(Code, Record)) {
1359 default: // Default behavior: unknown type.
1360 break;
1361 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1362 unsigned RecordLength = Record.size();
1363 if (RecordLength < 1)
1364 return Error ("Invalid UseList reader!");
1365 UseListRecords.push_back(Record);
1366 break;
1367 }
1368 }
1369 }
1370}
1371
Chris Lattner980e5aa2007-05-01 05:52:21 +00001372/// RememberAndSkipFunctionBody - When we see the block for a function body,
1373/// remember where it is and then skip it. This lets us lazily deserialize the
1374/// functions.
1375bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001376 // Get the function we are talking about.
1377 if (FunctionsWithBodies.empty())
1378 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001379
Chris Lattner48f84872007-05-01 04:59:48 +00001380 Function *Fn = FunctionsWithBodies.back();
1381 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001382
Chris Lattner48f84872007-05-01 04:59:48 +00001383 // Save the current stream state.
1384 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001385 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001386
Chris Lattner48f84872007-05-01 04:59:48 +00001387 // Skip over the function block for now.
1388 if (Stream.SkipBlock())
1389 return Error("Malformed block record");
1390 return false;
1391}
1392
Derek Schuff2ea93872012-02-06 22:30:29 +00001393bool BitcodeReader::GlobalCleanup() {
1394 // Patch the initializers for globals and aliases up.
1395 ResolveGlobalAndAliasInits();
1396 if (!GlobalInits.empty() || !AliasInits.empty())
1397 return Error("Malformed global initializer set");
1398
1399 // Look for intrinsic functions which need to be upgraded at some point
1400 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1401 FI != FE; ++FI) {
1402 Function *NewFn;
1403 if (UpgradeIntrinsicFunction(FI, NewFn))
1404 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1405 }
1406
1407 // Look for global variables which need to be renamed.
1408 for (Module::global_iterator
1409 GI = TheModule->global_begin(), GE = TheModule->global_end();
1410 GI != GE; ++GI)
1411 UpgradeGlobalVariable(GI);
1412 // Force deallocation of memory for these vectors to favor the client that
1413 // want lazy deserialization.
1414 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1415 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1416 return false;
1417}
1418
1419bool BitcodeReader::ParseModule(bool Resume) {
1420 if (Resume)
1421 Stream.JumpToBit(NextUnreadBit);
1422 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001423 return Error("Malformed block record");
1424
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001425 SmallVector<uint64_t, 64> Record;
1426 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001427 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001428
1429 // Read all the records for this module.
1430 while (!Stream.AtEndOfStream()) {
1431 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001432 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001433 if (Stream.ReadBlockEnd())
1434 return Error("Error at end of module block");
1435
Derek Schuff2ea93872012-02-06 22:30:29 +00001436 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001438
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001439 if (Code == bitc::ENTER_SUBBLOCK) {
1440 switch (Stream.ReadSubBlockID()) {
1441 default: // Skip unknown content.
1442 if (Stream.SkipBlock())
1443 return Error("Malformed block record");
1444 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001445 case bitc::BLOCKINFO_BLOCK_ID:
1446 if (Stream.ReadBlockInfoBlock())
1447 return Error("Malformed BlockInfoBlock");
1448 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001449 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001450 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001451 return true;
1452 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001453 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001454 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001455 return true;
1456 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001457 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001458 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001459 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001460 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001461 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001462 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001463 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001464 return true;
1465 break;
Devang Patele54abc92009-07-22 17:43:22 +00001466 case bitc::METADATA_BLOCK_ID:
1467 if (ParseMetadata())
1468 return true;
1469 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001470 case bitc::FUNCTION_BLOCK_ID:
1471 // If this is the first function body we've seen, reverse the
1472 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001473 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001474 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001475 if (GlobalCleanup())
1476 return true;
1477 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001478 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001479
Chris Lattner980e5aa2007-05-01 05:52:21 +00001480 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001481 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001482 // For streaming bitcode, suspend parsing when we reach the function
1483 // bodies. Subsequent materialization calls will resume it when
1484 // necessary. For streaming, the function bodies must be at the end of
1485 // the bitcode. If the bitcode file is old, the symbol table will be
1486 // at the end instead and will not have been seen yet. In this case,
1487 // just finish the parse now.
1488 if (LazyStreamer && SeenValueSymbolTable) {
1489 NextUnreadBit = Stream.GetCurrentBitNo();
1490 return false;
1491 }
Chris Lattner48f84872007-05-01 04:59:48 +00001492 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001493 case bitc::USELIST_BLOCK_ID:
1494 if (ParseUseLists())
1495 return true;
1496 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001497 }
1498 continue;
1499 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001500
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001501 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001502 Stream.ReadAbbrevRecord();
1503 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001504 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001505
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001506 // Read a record.
1507 switch (Stream.ReadRecord(Code, Record)) {
1508 default: break; // Default behavior, ignore unknown content.
1509 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1510 if (Record.size() < 1)
1511 return Error("Malformed MODULE_CODE_VERSION");
1512 // Only version #0 is supported so far.
1513 if (Record[0] != 0)
1514 return Error("Unknown bitstream version!");
1515 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001516 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001517 std::string S;
1518 if (ConvertToString(Record, 0, S))
1519 return Error("Invalid MODULE_CODE_TRIPLE record");
1520 TheModule->setTargetTriple(S);
1521 break;
1522 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001523 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001524 std::string S;
1525 if (ConvertToString(Record, 0, S))
1526 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1527 TheModule->setDataLayout(S);
1528 break;
1529 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001530 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001531 std::string S;
1532 if (ConvertToString(Record, 0, S))
1533 return Error("Invalid MODULE_CODE_ASM record");
1534 TheModule->setModuleInlineAsm(S);
1535 break;
1536 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001537 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001538 std::string S;
1539 if (ConvertToString(Record, 0, S))
1540 return Error("Invalid MODULE_CODE_DEPLIB record");
1541 TheModule->addLibrary(S);
1542 break;
1543 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001544 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001545 std::string S;
1546 if (ConvertToString(Record, 0, S))
1547 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1548 SectionTable.push_back(S);
1549 break;
1550 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001551 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001552 std::string S;
1553 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001554 return Error("Invalid MODULE_CODE_GCNAME record");
1555 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001556 break;
1557 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001558 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001559 // linkage, alignment, section, visibility, threadlocal,
1560 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001561 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001562 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001563 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001564 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001565 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001566 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001567 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001568 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001569 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001570
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001571 bool isConstant = Record[1];
1572 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1573 unsigned Alignment = (1 << Record[4]) >> 1;
1574 std::string Section;
1575 if (Record[5]) {
1576 if (Record[5]-1 >= SectionTable.size())
1577 return Error("Invalid section ID");
1578 Section = SectionTable[Record[5]-1];
1579 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001580 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001581 if (Record.size() > 6)
1582 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001583 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001584 if (Record.size() > 7)
1585 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001586
Rafael Espindolabea46262011-01-08 16:42:36 +00001587 bool UnnamedAddr = false;
1588 if (Record.size() > 8)
1589 UnnamedAddr = Record[8];
1590
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001591 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001592 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001593 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594 NewGV->setAlignment(Alignment);
1595 if (!Section.empty())
1596 NewGV->setSection(Section);
1597 NewGV->setVisibility(Visibility);
1598 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001599 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001600
Chris Lattner0b2482a2007-04-23 21:26:05 +00001601 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001602
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001603 // Remember which value to use for the global initializer.
1604 if (unsigned InitID = Record[2])
1605 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001606 break;
1607 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001608 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001609 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001610 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001611 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001612 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001613 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001614 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001615 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001616 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001617 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001618 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1619 if (!FTy)
1620 return Error("Function not a pointer to function type!");
1621
Gabor Greif051a9502008-04-06 20:25:17 +00001622 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1623 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001624
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001625 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001626 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001627 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001628 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Chris Lattnera9bb7132007-05-08 05:38:01 +00001630 Func->setAlignment((1 << Record[5]) >> 1);
1631 if (Record[6]) {
1632 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001633 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001634 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001635 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001636 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001637 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001638 if (Record[8]-1 > GCTable.size())
1639 return Error("Invalid GC ID");
1640 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001641 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001642 bool UnnamedAddr = false;
1643 if (Record.size() > 9)
1644 UnnamedAddr = Record[9];
1645 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001646 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001647
Chris Lattner48f84872007-05-01 04:59:48 +00001648 // If this is a function with a body, remember the prototype we are
1649 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001650 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001651 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001652 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1653 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001654 break;
1655 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001656 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001657 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001658 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001659 if (Record.size() < 3)
1660 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001661 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001662 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001663 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001664 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001665
Chris Lattner07d98b42007-04-26 02:46:40 +00001666 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1667 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001668 // Old bitcode files didn't have visibility field.
1669 if (Record.size() > 3)
1670 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001671 ValueList.push_back(NewGA);
1672 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1673 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001674 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001675 /// MODULE_CODE_PURGEVALS: [numvals]
1676 case bitc::MODULE_CODE_PURGEVALS:
1677 // Trim down the value list to the specified size.
1678 if (Record.size() < 1 || Record[0] > ValueList.size())
1679 return Error("Invalid MODULE_PURGEVALS record");
1680 ValueList.shrinkTo(Record[0]);
1681 break;
1682 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001683 Record.clear();
1684 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001685
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001686 return Error("Premature end of bitstream");
1687}
1688
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001689bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001690 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001691
Derek Schuff2ea93872012-02-06 22:30:29 +00001692 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001693
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001694 // Sniff for the signature.
1695 if (Stream.Read(8) != 'B' ||
1696 Stream.Read(8) != 'C' ||
1697 Stream.Read(4) != 0x0 ||
1698 Stream.Read(4) != 0xC ||
1699 Stream.Read(4) != 0xE ||
1700 Stream.Read(4) != 0xD)
1701 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001702
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001703 // We expect a number of well-defined blocks, though we don't necessarily
1704 // need to understand them all.
1705 while (!Stream.AtEndOfStream()) {
1706 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001707
Rafael Espindolac9687b32011-05-26 18:59:54 +00001708 if (Code != bitc::ENTER_SUBBLOCK) {
1709
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001710 // The ranlib in xcode 4 will align archive members by appending newlines
1711 // to the end of them. If this file size is a multiple of 4 but not 8, we
1712 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001713 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1714 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1715 Stream.AtEndOfStream())
1716 return false;
1717
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001718 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001719 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001721 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001722
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001723 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001724 switch (BlockID) {
1725 case bitc::BLOCKINFO_BLOCK_ID:
1726 if (Stream.ReadBlockInfoBlock())
1727 return Error("Malformed BlockInfoBlock");
1728 break;
1729 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001730 // Reject multiple MODULE_BLOCK's in a single bitstream.
1731 if (TheModule)
1732 return Error("Multiple MODULE_BLOCKs in same stream");
1733 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001734 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001735 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001736 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001737 break;
1738 default:
1739 if (Stream.SkipBlock())
1740 return Error("Malformed block record");
1741 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001742 }
1743 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001744
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001745 return false;
1746}
Chris Lattnerc453f762007-04-29 07:54:31 +00001747
Bill Wendling34711742010-10-06 01:22:42 +00001748bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1749 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1750 return Error("Malformed block record");
1751
1752 SmallVector<uint64_t, 64> Record;
1753
1754 // Read all the records for this module.
1755 while (!Stream.AtEndOfStream()) {
1756 unsigned Code = Stream.ReadCode();
1757 if (Code == bitc::END_BLOCK) {
1758 if (Stream.ReadBlockEnd())
1759 return Error("Error at end of module block");
1760
1761 return false;
1762 }
1763
1764 if (Code == bitc::ENTER_SUBBLOCK) {
1765 switch (Stream.ReadSubBlockID()) {
1766 default: // Skip unknown content.
1767 if (Stream.SkipBlock())
1768 return Error("Malformed block record");
1769 break;
1770 }
1771 continue;
1772 }
1773
1774 if (Code == bitc::DEFINE_ABBREV) {
1775 Stream.ReadAbbrevRecord();
1776 continue;
1777 }
1778
1779 // Read a record.
1780 switch (Stream.ReadRecord(Code, Record)) {
1781 default: break; // Default behavior, ignore unknown content.
1782 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1783 if (Record.size() < 1)
1784 return Error("Malformed MODULE_CODE_VERSION");
1785 // Only version #0 is supported so far.
1786 if (Record[0] != 0)
1787 return Error("Unknown bitstream version!");
1788 break;
1789 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1790 std::string S;
1791 if (ConvertToString(Record, 0, S))
1792 return Error("Invalid MODULE_CODE_TRIPLE record");
1793 Triple = S;
1794 break;
1795 }
1796 }
1797 Record.clear();
1798 }
1799
1800 return Error("Premature end of bitstream");
1801}
1802
1803bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001804 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001805
1806 // Sniff for the signature.
1807 if (Stream.Read(8) != 'B' ||
1808 Stream.Read(8) != 'C' ||
1809 Stream.Read(4) != 0x0 ||
1810 Stream.Read(4) != 0xC ||
1811 Stream.Read(4) != 0xE ||
1812 Stream.Read(4) != 0xD)
1813 return Error("Invalid bitcode signature");
1814
1815 // We expect a number of well-defined blocks, though we don't necessarily
1816 // need to understand them all.
1817 while (!Stream.AtEndOfStream()) {
1818 unsigned Code = Stream.ReadCode();
1819
1820 if (Code != bitc::ENTER_SUBBLOCK)
1821 return Error("Invalid record at top-level");
1822
1823 unsigned BlockID = Stream.ReadSubBlockID();
1824
1825 // We only know the MODULE subblock ID.
1826 switch (BlockID) {
1827 case bitc::MODULE_BLOCK_ID:
1828 if (ParseModuleTriple(Triple))
1829 return true;
1830 break;
1831 default:
1832 if (Stream.SkipBlock())
1833 return Error("Malformed block record");
1834 break;
1835 }
1836 }
1837
1838 return false;
1839}
1840
Devang Patele8e02132009-09-18 19:26:43 +00001841/// ParseMetadataAttachment - Parse metadata attachments.
1842bool BitcodeReader::ParseMetadataAttachment() {
1843 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1844 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001845
Devang Patele8e02132009-09-18 19:26:43 +00001846 SmallVector<uint64_t, 64> Record;
1847 while(1) {
1848 unsigned Code = Stream.ReadCode();
1849 if (Code == bitc::END_BLOCK) {
1850 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001851 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001852 break;
1853 }
1854 if (Code == bitc::DEFINE_ABBREV) {
1855 Stream.ReadAbbrevRecord();
1856 continue;
1857 }
1858 // Read a metadata attachment record.
1859 Record.clear();
1860 switch (Stream.ReadRecord(Code, Record)) {
1861 default: // Default behavior: ignore.
1862 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001863 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001864 unsigned RecordLength = Record.size();
1865 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001867 Instruction *Inst = InstructionList[Record[0]];
1868 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001869 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001870 DenseMap<unsigned, unsigned>::iterator I =
1871 MDKindMap.find(Kind);
1872 if (I == MDKindMap.end())
1873 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001874 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001875 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001876 }
1877 break;
1878 }
1879 }
1880 }
1881 return false;
1882}
Chris Lattner48f84872007-05-01 04:59:48 +00001883
Chris Lattner980e5aa2007-05-01 05:52:21 +00001884/// ParseFunctionBody - Lazily parse the specified function body block.
1885bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001886 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001887 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001888
Nick Lewycky9a49f152010-02-25 08:30:17 +00001889 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001890 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001891 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001892
Chris Lattner980e5aa2007-05-01 05:52:21 +00001893 // Add all the function arguments to the value table.
1894 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1895 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001896
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001897 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001898 BasicBlock *CurBB = 0;
1899 unsigned CurBBNo = 0;
1900
Chris Lattnera6245242010-04-03 02:17:50 +00001901 DebugLoc LastLoc;
1902
Chris Lattner980e5aa2007-05-01 05:52:21 +00001903 // Read all the records.
1904 SmallVector<uint64_t, 64> Record;
1905 while (1) {
1906 unsigned Code = Stream.ReadCode();
1907 if (Code == bitc::END_BLOCK) {
1908 if (Stream.ReadBlockEnd())
1909 return Error("Error at end of function block");
1910 break;
1911 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912
Chris Lattner980e5aa2007-05-01 05:52:21 +00001913 if (Code == bitc::ENTER_SUBBLOCK) {
1914 switch (Stream.ReadSubBlockID()) {
1915 default: // Skip unknown content.
1916 if (Stream.SkipBlock())
1917 return Error("Malformed block record");
1918 break;
1919 case bitc::CONSTANTS_BLOCK_ID:
1920 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001921 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001922 break;
1923 case bitc::VALUE_SYMTAB_BLOCK_ID:
1924 if (ParseValueSymbolTable()) return true;
1925 break;
Devang Patele8e02132009-09-18 19:26:43 +00001926 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001927 if (ParseMetadataAttachment()) return true;
1928 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001929 case bitc::METADATA_BLOCK_ID:
1930 if (ParseMetadata()) return true;
1931 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001932 }
1933 continue;
1934 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001935
Chris Lattner980e5aa2007-05-01 05:52:21 +00001936 if (Code == bitc::DEFINE_ABBREV) {
1937 Stream.ReadAbbrevRecord();
1938 continue;
1939 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001940
Chris Lattner980e5aa2007-05-01 05:52:21 +00001941 // Read a record.
1942 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001943 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001944 unsigned BitCode = Stream.ReadRecord(Code, Record);
1945 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001946 default: // Default behavior: reject
1947 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001948 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001949 if (Record.size() < 1 || Record[0] == 0)
1950 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001951 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001952 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001953 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001954 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001955 CurBB = FunctionBBs[0];
1956 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001957
1958 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1959 // This record indicates that the last instruction is at the same
1960 // location as the previous instruction with a location.
1961 I = 0;
1962
1963 // Get the last instruction emitted.
1964 if (CurBB && !CurBB->empty())
1965 I = &CurBB->back();
1966 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1967 !FunctionBBs[CurBBNo-1]->empty())
1968 I = &FunctionBBs[CurBBNo-1]->back();
1969
1970 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1971 I->setDebugLoc(LastLoc);
1972 I = 0;
1973 continue;
1974
Chris Lattner4f6bab92011-06-17 18:17:37 +00001975 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001976 I = 0; // Get the last instruction emitted.
1977 if (CurBB && !CurBB->empty())
1978 I = &CurBB->back();
1979 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1980 !FunctionBBs[CurBBNo-1]->empty())
1981 I = &FunctionBBs[CurBBNo-1]->back();
1982 if (I == 0 || Record.size() < 4)
1983 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1984
1985 unsigned Line = Record[0], Col = Record[1];
1986 unsigned ScopeID = Record[2], IAID = Record[3];
1987
1988 MDNode *Scope = 0, *IA = 0;
1989 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1990 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1991 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1992 I->setDebugLoc(LastLoc);
1993 I = 0;
1994 continue;
1995 }
1996
Chris Lattnerabfbf852007-05-06 00:21:25 +00001997 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1998 unsigned OpNum = 0;
1999 Value *LHS, *RHS;
2000 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2001 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002002 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002003 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002004
Dan Gohman1224c382009-07-20 21:19:07 +00002005 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002006 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002007 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002008 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002009 if (OpNum < Record.size()) {
2010 if (Opc == Instruction::Add ||
2011 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002012 Opc == Instruction::Mul ||
2013 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002014 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002015 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002016 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002017 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002018 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002019 Opc == Instruction::UDiv ||
2020 Opc == Instruction::LShr ||
2021 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002022 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002023 cast<BinaryOperator>(I)->setIsExact(true);
2024 }
2025 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002026 break;
2027 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002028 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2029 unsigned OpNum = 0;
2030 Value *Op;
2031 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2032 OpNum+2 != Record.size())
2033 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002034
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002035 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002036 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2037 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002038 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002039 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002040 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002041 break;
2042 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002043 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002044 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002045 unsigned OpNum = 0;
2046 Value *BasePtr;
2047 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002048 return Error("Invalid GEP record");
2049
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002050 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002051 while (OpNum != Record.size()) {
2052 Value *Op;
2053 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002054 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002055 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002056 }
2057
Jay Foada9203102011-07-25 09:48:08 +00002058 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002059 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002060 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002061 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002062 break;
2063 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002064
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002065 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2066 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002067 unsigned OpNum = 0;
2068 Value *Agg;
2069 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2070 return Error("Invalid EXTRACTVAL record");
2071
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002072 SmallVector<unsigned, 4> EXTRACTVALIdx;
2073 for (unsigned RecSize = Record.size();
2074 OpNum != RecSize; ++OpNum) {
2075 uint64_t Index = Record[OpNum];
2076 if ((unsigned)Index != Index)
2077 return Error("Invalid EXTRACTVAL index");
2078 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002079 }
2080
Jay Foadfc6d3a42011-07-13 10:26:04 +00002081 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002082 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002083 break;
2084 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002085
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002086 case bitc::FUNC_CODE_INST_INSERTVAL: {
2087 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002088 unsigned OpNum = 0;
2089 Value *Agg;
2090 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2091 return Error("Invalid INSERTVAL record");
2092 Value *Val;
2093 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2094 return Error("Invalid INSERTVAL record");
2095
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002096 SmallVector<unsigned, 4> INSERTVALIdx;
2097 for (unsigned RecSize = Record.size();
2098 OpNum != RecSize; ++OpNum) {
2099 uint64_t Index = Record[OpNum];
2100 if ((unsigned)Index != Index)
2101 return Error("Invalid INSERTVAL index");
2102 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002103 }
2104
Jay Foadfc6d3a42011-07-13 10:26:04 +00002105 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002106 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002107 break;
2108 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002109
Chris Lattnerabfbf852007-05-06 00:21:25 +00002110 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002111 // obsolete form of select
2112 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002113 unsigned OpNum = 0;
2114 Value *TrueVal, *FalseVal, *Cond;
2115 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2116 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002117 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002118 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002119
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002120 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002121 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002122 break;
2123 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002124
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002125 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2126 // new form of select
2127 // handles select i1 or select [N x i1]
2128 unsigned OpNum = 0;
2129 Value *TrueVal, *FalseVal, *Cond;
2130 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2131 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2132 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2133 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002134
2135 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002136 if (VectorType* vector_type =
2137 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002138 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002139 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002140 return Error("Invalid SELECT condition type");
2141 } else {
2142 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002143 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002144 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002145 }
2146
Gabor Greif051a9502008-04-06 20:25:17 +00002147 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002148 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002149 break;
2150 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002151
Chris Lattner01ff65f2007-05-02 05:16:49 +00002152 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002153 unsigned OpNum = 0;
2154 Value *Vec, *Idx;
2155 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002156 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002157 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002158 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002159 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002160 break;
2161 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002162
Chris Lattner01ff65f2007-05-02 05:16:49 +00002163 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002164 unsigned OpNum = 0;
2165 Value *Vec, *Elt, *Idx;
2166 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002167 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002168 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002169 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002170 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002171 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002172 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002173 break;
2174 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002175
Chris Lattnerabfbf852007-05-06 00:21:25 +00002176 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2177 unsigned OpNum = 0;
2178 Value *Vec1, *Vec2, *Mask;
2179 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2180 getValue(Record, OpNum, Vec1->getType(), Vec2))
2181 return Error("Invalid SHUFFLEVEC record");
2182
Mon P Wangaeb06d22008-11-10 04:46:22 +00002183 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002184 return Error("Invalid SHUFFLEVEC record");
2185 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002186 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002187 break;
2188 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002189
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002190 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2191 // Old form of ICmp/FCmp returning bool
2192 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2193 // both legal on vectors but had different behaviour.
2194 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2195 // FCmp/ICmp returning bool or vector of bool
2196
Chris Lattner7337ab92007-05-06 00:00:00 +00002197 unsigned OpNum = 0;
2198 Value *LHS, *RHS;
2199 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2200 getValue(Record, OpNum, LHS->getType(), RHS) ||
2201 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002202 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002203
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002204 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002205 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002206 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002207 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002208 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002209 break;
2210 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002211
Chris Lattner231cbcb2007-05-02 04:27:25 +00002212 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002213 {
2214 unsigned Size = Record.size();
2215 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002216 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002217 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002218 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002219 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002220
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002221 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002222 Value *Op = NULL;
2223 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2224 return Error("Invalid RET record");
2225 if (OpNum != Record.size())
2226 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002227
Chris Lattner96a74c52011-06-17 18:09:11 +00002228 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002229 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002230 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002231 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002232 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002233 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002234 return Error("Invalid BR record");
2235 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2236 if (TrueDest == 0)
2237 return Error("Invalid BR record");
2238
Devang Patele8e02132009-09-18 19:26:43 +00002239 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002240 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002241 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002242 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002243 else {
2244 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002245 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002246 if (FalseDest == 0 || Cond == 0)
2247 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002248 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002249 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002250 }
2251 break;
2252 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002253 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002254 if (Record.size() < 3 || (Record.size() & 1) == 0)
2255 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002256 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002257 Value *Cond = getFnValueByID(Record[1], OpTy);
2258 BasicBlock *Default = getBasicBlock(Record[2]);
2259 if (OpTy == 0 || Cond == 0 || Default == 0)
2260 return Error("Invalid SWITCH record");
2261 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002262 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002263 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002264 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002265 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002266 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2267 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2268 if (CaseVal == 0 || DestBB == 0) {
2269 delete SI;
2270 return Error("Invalid SWITCH record!");
2271 }
2272 SI->addCase(CaseVal, DestBB);
2273 }
2274 I = SI;
2275 break;
2276 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002277 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002278 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002279 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002280 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002281 Value *Address = getFnValueByID(Record[1], OpTy);
2282 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002283 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002284 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002285 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002286 InstructionList.push_back(IBI);
2287 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2288 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2289 IBI->addDestination(DestBB);
2290 } else {
2291 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002292 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002293 }
2294 }
2295 I = IBI;
2296 break;
2297 }
2298
Duncan Sandsdc024672007-11-27 13:23:08 +00002299 case bitc::FUNC_CODE_INST_INVOKE: {
2300 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002301 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002302 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002303 unsigned CCInfo = Record[1];
2304 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2305 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002306
Chris Lattnera9bb7132007-05-08 05:38:01 +00002307 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002308 Value *Callee;
2309 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002310 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002311
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002312 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2313 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002314 dyn_cast<FunctionType>(CalleeTy->getElementType());
2315
2316 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002317 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2318 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002319 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002320
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002321 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002322 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2323 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2324 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002325 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002326
Chris Lattner7337ab92007-05-06 00:00:00 +00002327 if (!FTy->isVarArg()) {
2328 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002329 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002330 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002331 // Read type/value pairs for varargs params.
2332 while (OpNum != Record.size()) {
2333 Value *Op;
2334 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2335 return Error("Invalid INVOKE record");
2336 Ops.push_back(Op);
2337 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002338 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002339
Jay Foada3efbb12011-07-15 08:37:34 +00002340 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002341 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002342 cast<InvokeInst>(I)->setCallingConv(
2343 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002344 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002345 break;
2346 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002347 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2348 unsigned Idx = 0;
2349 Value *Val = 0;
2350 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2351 return Error("Invalid RESUME record");
2352 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002353 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002354 break;
2355 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002356 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002357 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002358 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002359 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002360 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002361 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002362 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002363 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002364 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002365
Jay Foad3ecfc862011-03-30 11:28:46 +00002366 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002367 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002368
Chris Lattner15e6d172007-05-04 19:11:41 +00002369 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2370 Value *V = getFnValueByID(Record[1+i], Ty);
2371 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002372 if (!V || !BB) return Error("Invalid PHI record");
2373 PN->addIncoming(V, BB);
2374 }
2375 I = PN;
2376 break;
2377 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002378
Bill Wendlinge6e88262011-08-12 20:24:12 +00002379 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2380 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2381 unsigned Idx = 0;
2382 if (Record.size() < 4)
2383 return Error("Invalid LANDINGPAD record");
2384 Type *Ty = getTypeByID(Record[Idx++]);
2385 if (!Ty) return Error("Invalid LANDINGPAD record");
2386 Value *PersFn = 0;
2387 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2388 return Error("Invalid LANDINGPAD record");
2389
2390 bool IsCleanup = !!Record[Idx++];
2391 unsigned NumClauses = Record[Idx++];
2392 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2393 LP->setCleanup(IsCleanup);
2394 for (unsigned J = 0; J != NumClauses; ++J) {
2395 LandingPadInst::ClauseType CT =
2396 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2397 Value *Val;
2398
2399 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2400 delete LP;
2401 return Error("Invalid LANDINGPAD record");
2402 }
2403
2404 assert((CT != LandingPadInst::Catch ||
2405 !isa<ArrayType>(Val->getType())) &&
2406 "Catch clause has a invalid type!");
2407 assert((CT != LandingPadInst::Filter ||
2408 isa<ArrayType>(Val->getType())) &&
2409 "Filter clause has invalid type!");
2410 LP->addClause(Val);
2411 }
2412
2413 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002414 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002415 break;
2416 }
2417
Chris Lattner96a74c52011-06-17 18:09:11 +00002418 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2419 if (Record.size() != 4)
2420 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002421 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002422 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002423 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002424 Value *Size = getFnValueByID(Record[2], OpTy);
2425 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002426 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002427 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002428 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002429 break;
2430 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002431 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002432 unsigned OpNum = 0;
2433 Value *Op;
2434 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2435 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002436 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002437
Chris Lattner7337ab92007-05-06 00:00:00 +00002438 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002439 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002440 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002441 }
Eli Friedman21006d42011-08-09 23:02:53 +00002442 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2443 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2444 unsigned OpNum = 0;
2445 Value *Op;
2446 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2447 OpNum+4 != Record.size())
2448 return Error("Invalid LOADATOMIC record");
2449
2450
2451 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2452 if (Ordering == NotAtomic || Ordering == Release ||
2453 Ordering == AcquireRelease)
2454 return Error("Invalid LOADATOMIC record");
2455 if (Ordering != NotAtomic && Record[OpNum] == 0)
2456 return Error("Invalid LOADATOMIC record");
2457 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2458
2459 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2460 Ordering, SynchScope);
2461 InstructionList.push_back(I);
2462 break;
2463 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002464 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002465 unsigned OpNum = 0;
2466 Value *Val, *Ptr;
2467 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002468 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002469 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2470 OpNum+2 != Record.size())
2471 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002472
Christopher Lambfe63fb92007-12-11 08:59:05 +00002473 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002474 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002475 break;
2476 }
Eli Friedman21006d42011-08-09 23:02:53 +00002477 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2478 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2479 unsigned OpNum = 0;
2480 Value *Val, *Ptr;
2481 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2482 getValue(Record, OpNum,
2483 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2484 OpNum+4 != Record.size())
2485 return Error("Invalid STOREATOMIC record");
2486
2487 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002488 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002489 Ordering == AcquireRelease)
2490 return Error("Invalid STOREATOMIC record");
2491 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2492 if (Ordering != NotAtomic && Record[OpNum] == 0)
2493 return Error("Invalid STOREATOMIC record");
2494
2495 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2496 Ordering, SynchScope);
2497 InstructionList.push_back(I);
2498 break;
2499 }
Eli Friedmanff030482011-07-28 21:48:00 +00002500 case bitc::FUNC_CODE_INST_CMPXCHG: {
2501 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2502 unsigned OpNum = 0;
2503 Value *Ptr, *Cmp, *New;
2504 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2505 getValue(Record, OpNum,
2506 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2507 getValue(Record, OpNum,
2508 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2509 OpNum+3 != Record.size())
2510 return Error("Invalid CMPXCHG record");
2511 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002512 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002513 return Error("Invalid CMPXCHG record");
2514 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2515 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2516 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2517 InstructionList.push_back(I);
2518 break;
2519 }
2520 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2521 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2522 unsigned OpNum = 0;
2523 Value *Ptr, *Val;
2524 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2525 getValue(Record, OpNum,
2526 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2527 OpNum+4 != Record.size())
2528 return Error("Invalid ATOMICRMW record");
2529 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2530 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2531 Operation > AtomicRMWInst::LAST_BINOP)
2532 return Error("Invalid ATOMICRMW record");
2533 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002534 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002535 return Error("Invalid ATOMICRMW record");
2536 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2537 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2538 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2539 InstructionList.push_back(I);
2540 break;
2541 }
Eli Friedman47f35132011-07-25 23:16:38 +00002542 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2543 if (2 != Record.size())
2544 return Error("Invalid FENCE record");
2545 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2546 if (Ordering == NotAtomic || Ordering == Unordered ||
2547 Ordering == Monotonic)
2548 return Error("Invalid FENCE record");
2549 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2550 I = new FenceInst(Context, Ordering, SynchScope);
2551 InstructionList.push_back(I);
2552 break;
2553 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002554 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002555 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2556 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002557 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002558
Devang Patel05988662008-09-25 21:00:45 +00002559 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002560 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002561
Chris Lattnera9bb7132007-05-08 05:38:01 +00002562 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002563 Value *Callee;
2564 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2565 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002566
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002567 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2568 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002569 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002570 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002571 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002572
Chris Lattner0579f7f2007-05-03 22:04:19 +00002573 SmallVector<Value*, 16> Args;
2574 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002575 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002576 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002577 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002578 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002579 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002580 if (Args.back() == 0) return Error("Invalid CALL record");
2581 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002582
Chris Lattner0579f7f2007-05-03 22:04:19 +00002583 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002584 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002585 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002586 return Error("Invalid CALL record");
2587 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002588 while (OpNum != Record.size()) {
2589 Value *Op;
2590 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2591 return Error("Invalid CALL record");
2592 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002593 }
2594 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002595
Jay Foada3efbb12011-07-15 08:37:34 +00002596 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002597 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002598 cast<CallInst>(I)->setCallingConv(
2599 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002600 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002601 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002602 break;
2603 }
2604 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2605 if (Record.size() < 3)
2606 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002607 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002608 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002609 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002610 if (!OpTy || !Op || !ResTy)
2611 return Error("Invalid VAARG record");
2612 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002613 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002614 break;
2615 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002616 }
2617
2618 // Add instruction to end of current BB. If there is no current BB, reject
2619 // this file.
2620 if (CurBB == 0) {
2621 delete I;
2622 return Error("Invalid instruction with no BB");
2623 }
2624 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002625
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002626 // If this was a terminator instruction, move to the next block.
2627 if (isa<TerminatorInst>(I)) {
2628 ++CurBBNo;
2629 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2630 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002631
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002632 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002633 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002634 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002635 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002636
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002637 // Check the function list for unresolved values.
2638 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2639 if (A->getParent() == 0) {
2640 // We found at least one unresolved value. Nuke them all to avoid leaks.
2641 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002642 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002643 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002644 delete A;
2645 }
2646 }
Chris Lattner35a04702007-05-04 03:50:29 +00002647 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002648 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002649 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002650
Dan Gohman064ff3e2010-08-25 20:23:38 +00002651 // FIXME: Check for unresolved forward-declared metadata references
2652 // and clean up leaks.
2653
Chris Lattner50b136d2009-10-28 05:53:48 +00002654 // See if anything took the address of blocks in this function. If so,
2655 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002656 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2657 BlockAddrFwdRefs.find(F);
2658 if (BAFRI != BlockAddrFwdRefs.end()) {
2659 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2660 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2661 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002662 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002663 return Error("Invalid blockaddress block #");
2664
2665 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002666 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002667 FwdRef->eraseFromParent();
2668 }
2669
2670 BlockAddrFwdRefs.erase(BAFRI);
2671 }
2672
Chris Lattner980e5aa2007-05-01 05:52:21 +00002673 // Trim the value list down to the size it was before we parsed this function.
2674 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002675 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002676 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002677 return false;
2678}
2679
Derek Schuff2ea93872012-02-06 22:30:29 +00002680/// FindFunctionInStream - Find the function body in the bitcode stream
2681bool BitcodeReader::FindFunctionInStream(Function *F,
2682 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2683 while (DeferredFunctionInfoIterator->second == 0) {
2684 if (Stream.AtEndOfStream())
2685 return Error("Could not find Function in stream");
2686 // ParseModule will parse the next body in the stream and set its
2687 // position in the DeferredFunctionInfo map.
2688 if (ParseModule(true)) return true;
2689 }
2690 return false;
2691}
2692
Chris Lattnerb348bb82007-05-18 04:02:46 +00002693//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002694// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002695//===----------------------------------------------------------------------===//
2696
2697
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002698bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2699 if (const Function *F = dyn_cast<Function>(GV)) {
2700 return F->isDeclaration() &&
2701 DeferredFunctionInfo.count(const_cast<Function*>(F));
2702 }
2703 return false;
2704}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002705
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002706bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2707 Function *F = dyn_cast<Function>(GV);
2708 // If it's not a function or is already material, ignore the request.
2709 if (!F || !F->isMaterializable()) return false;
2710
2711 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002712 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002713 // If its position is recorded as 0, its body is somewhere in the stream
2714 // but we haven't seen it yet.
2715 if (DFII->second == 0)
2716 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002717
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002718 // Move the bit stream to the saved position of the deferred function body.
2719 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002720
Chris Lattnerb348bb82007-05-18 04:02:46 +00002721 if (ParseFunctionBody(F)) {
2722 if (ErrInfo) *ErrInfo = ErrorString;
2723 return true;
2724 }
Chandler Carruth69940402007-08-04 01:51:18 +00002725
2726 // Upgrade any old intrinsic calls in the function.
2727 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2728 E = UpgradedIntrinsics.end(); I != E; ++I) {
2729 if (I->first != I->second) {
2730 for (Value::use_iterator UI = I->first->use_begin(),
2731 UE = I->first->use_end(); UI != UE; ) {
2732 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2733 UpgradeIntrinsicCall(CI, I->second);
2734 }
2735 }
2736 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002737
Chris Lattnerb348bb82007-05-18 04:02:46 +00002738 return false;
2739}
2740
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002741bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2742 const Function *F = dyn_cast<Function>(GV);
2743 if (!F || F->isDeclaration())
2744 return false;
2745 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2746}
2747
2748void BitcodeReader::Dematerialize(GlobalValue *GV) {
2749 Function *F = dyn_cast<Function>(GV);
2750 // If this function isn't dematerializable, this is a noop.
2751 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002752 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002753
Chris Lattnerb348bb82007-05-18 04:02:46 +00002754 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002755
Chris Lattnerb348bb82007-05-18 04:02:46 +00002756 // Just forget the function body, we can remat it later.
2757 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002758}
2759
2760
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002761bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2762 assert(M == TheModule &&
2763 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002764 // Iterate over the module, deserializing any functions that are still on
2765 // disk.
2766 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2767 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002768 if (F->isMaterializable() &&
2769 Materialize(F, ErrInfo))
2770 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002771
Derek Schuff0ffe6982012-02-29 00:07:09 +00002772 // At this point, if there are any function bodies, the current bit is
2773 // pointing to the END_BLOCK record after them. Now make sure the rest
2774 // of the bits in the module have been read.
2775 if (NextUnreadBit)
2776 ParseModule(true);
2777
Daniel Dunbara279bc32009-09-20 02:20:51 +00002778 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2779 // delete the old functions to clean up. We can't do this unless the entire
2780 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002781 // with calls to the old function.
2782 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2783 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2784 if (I->first != I->second) {
2785 for (Value::use_iterator UI = I->first->use_begin(),
2786 UE = I->first->use_end(); UI != UE; ) {
2787 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2788 UpgradeIntrinsicCall(CI, I->second);
2789 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002790 if (!I->first->use_empty())
2791 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002792 I->first->eraseFromParent();
2793 }
2794 }
2795 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002796
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002797 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002798}
2799
Derek Schuff2ea93872012-02-06 22:30:29 +00002800bool BitcodeReader::InitStream() {
2801 if (LazyStreamer) return InitLazyStream();
2802 return InitStreamFromBuffer();
2803}
2804
2805bool BitcodeReader::InitStreamFromBuffer() {
2806 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2807 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2808
2809 if (Buffer->getBufferSize() & 3) {
2810 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2811 return Error("Invalid bitcode signature");
2812 else
2813 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2814 }
2815
2816 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2817 // The magic number is 0x0B17C0DE stored in little endian.
2818 if (isBitcodeWrapper(BufPtr, BufEnd))
2819 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2820 return Error("Invalid bitcode wrapper header");
2821
2822 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2823 Stream.init(*StreamFile);
2824
2825 return false;
2826}
2827
2828bool BitcodeReader::InitLazyStream() {
2829 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2830 // see it.
2831 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2832 StreamFile.reset(new BitstreamReader(Bytes));
2833 Stream.init(*StreamFile);
2834
2835 unsigned char buf[16];
2836 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2837 return Error("Bitcode stream must be at least 16 bytes in length");
2838
2839 if (!isBitcode(buf, buf + 16))
2840 return Error("Invalid bitcode signature");
2841
2842 if (isBitcodeWrapper(buf, buf + 4)) {
2843 const unsigned char *bitcodeStart = buf;
2844 const unsigned char *bitcodeEnd = buf + 16;
2845 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2846 Bytes->dropLeadingBytes(bitcodeStart - buf);
2847 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2848 }
2849 return false;
2850}
Chris Lattner48f84872007-05-01 04:59:48 +00002851
Chris Lattnerc453f762007-04-29 07:54:31 +00002852//===----------------------------------------------------------------------===//
2853// External interface
2854//===----------------------------------------------------------------------===//
2855
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002856/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002857///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002858Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2859 LLVMContext& Context,
2860 std::string *ErrMsg) {
2861 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002862 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002863 M->setMaterializer(R);
2864 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002865 if (ErrMsg)
2866 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002867
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002868 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002869 return 0;
2870 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002871 // Have the BitcodeReader dtor delete 'Buffer'.
2872 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002873
2874 R->materializeForwardReferencedFunctions();
2875
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002876 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002877}
2878
Derek Schuff2ea93872012-02-06 22:30:29 +00002879
2880Module *llvm::getStreamedBitcodeModule(const std::string &name,
2881 DataStreamer *streamer,
2882 LLVMContext &Context,
2883 std::string *ErrMsg) {
2884 Module *M = new Module(name, Context);
2885 BitcodeReader *R = new BitcodeReader(streamer, Context);
2886 M->setMaterializer(R);
2887 if (R->ParseBitcodeInto(M)) {
2888 if (ErrMsg)
2889 *ErrMsg = R->getErrorString();
2890 delete M; // Also deletes R.
2891 return 0;
2892 }
2893 R->setBufferOwned(false); // no buffer to delete
2894 return M;
2895}
2896
Chris Lattnerc453f762007-04-29 07:54:31 +00002897/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2898/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002899Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002900 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002901 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2902 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002903
2904 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2905 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002906 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002907
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002908 // Read in the entire module, and destroy the BitcodeReader.
2909 if (M->MaterializeAllPermanently(ErrMsg)) {
2910 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002911 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002912 }
Bill Wendling34711742010-10-06 01:22:42 +00002913
Chad Rosiercbbb0962011-12-07 21:44:12 +00002914 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2915 // written. We must defer until the Module has been fully materialized.
2916
Chris Lattnerc453f762007-04-29 07:54:31 +00002917 return M;
2918}
Bill Wendling34711742010-10-06 01:22:42 +00002919
2920std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2921 LLVMContext& Context,
2922 std::string *ErrMsg) {
2923 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2924 // Don't let the BitcodeReader dtor delete 'Buffer'.
2925 R->setBufferOwned(false);
2926
2927 std::string Triple("");
2928 if (R->ParseTriple(Triple))
2929 if (ErrMsg)
2930 *ErrMsg = R->getErrorString();
2931
2932 delete R;
2933 return Triple;
2934}