blob: 040f3438fe953d6ddf944c0d13c6ed7a36a486dc [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 Lattner48c85b82007-05-04 03:30:17 +0000461 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000462 // FIXME: remove in LLVM 3.0
463 // The alignment is stored as a 16-bit raw value from bits 31--16.
464 // We shift the bits above 31 down by 11 bits.
465
466 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
467 if (Alignment && !isPowerOf2_32(Alignment))
468 return Error("Alignment is not a power of two.");
469
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000470 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000471 if (Alignment)
472 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000473 ReconstitutedAttr |=
474 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000475
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000476 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000477 }
Chris Lattner461edd92008-03-12 02:25:52 +0000478
Devang Patel19c87462008-09-26 22:53:05 +0000479 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nuno Lopes006c7b92012-05-08 17:07:35 +0000480 if (Attributes(Record[i+1]) != Attribute::None)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000481 Attrs.push_back(AttributeWithIndex::get(Record[i],
482 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000483 }
Devang Patel19c87462008-09-26 22:53:05 +0000484
485 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000486 Attrs.clear();
487 break;
488 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000489 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000490 }
491}
492
Chris Lattner86697142007-05-01 05:01:34 +0000493bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000494 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000495 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000496
Chris Lattner1afcace2011-07-09 17:41:24 +0000497 return ParseTypeTableBody();
498}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000499
Chris Lattner1afcace2011-07-09 17:41:24 +0000500bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000501 if (!TypeList.empty())
502 return Error("Multiple TYPE_BLOCKs found!");
503
504 SmallVector<uint64_t, 64> Record;
505 unsigned NumRecords = 0;
506
Chris Lattner1afcace2011-07-09 17:41:24 +0000507 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000508
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000509 // Read all the records for this type table.
510 while (1) {
511 unsigned Code = Stream.ReadCode();
512 if (Code == bitc::END_BLOCK) {
513 if (NumRecords != TypeList.size())
514 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000515 if (Stream.ReadBlockEnd())
516 return Error("Error at end of type table block");
517 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000518 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000519
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000520 if (Code == bitc::ENTER_SUBBLOCK) {
521 // No known subblocks, always skip them.
522 Stream.ReadSubBlockID();
523 if (Stream.SkipBlock())
524 return Error("Malformed block record");
525 continue;
526 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000527
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000528 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000529 Stream.ReadAbbrevRecord();
530 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000531 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000532
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000533 // Read a record.
534 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000535 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000536 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000537 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000538 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
539 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
540 // type list. This allows us to reserve space.
541 if (Record.size() < 1)
542 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000543 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000544 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000545 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000546 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000547 break;
Dan Gohmance163392011-12-17 00:04:22 +0000548 case bitc::TYPE_CODE_HALF: // HALF
549 ResultTy = Type::getHalfTy(Context);
550 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000551 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000552 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000553 break;
554 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000555 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000556 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000557 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000558 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000559 break;
560 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000561 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000562 break;
563 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000564 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000565 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000566 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000567 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000568 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000569 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000570 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000571 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000572 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
573 ResultTy = Type::getX86_MMXTy(Context);
574 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000575 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
576 if (Record.size() < 1)
577 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000578
Owen Anderson1d0be152009-08-13 21:58:54 +0000579 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000580 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000581 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000582 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 if (Record.size() < 1)
584 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000585 unsigned AddressSpace = 0;
586 if (Record.size() == 2)
587 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000588 ResultTy = getTypeByID(Record[0]);
589 if (ResultTy == 0) return Error("invalid element type in pointer type");
590 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000591 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000592 }
Chad Rosiercde54642011-11-03 00:14:01 +0000593 case bitc::TYPE_CODE_FUNCTION: {
594 // FUNCTION: [vararg, retty, paramty x N]
595 if (Record.size() < 2)
596 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000597 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000598 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
599 if (Type *T = getTypeByID(Record[i]))
600 ArgTys.push_back(T);
601 else
602 break;
603 }
604
605 ResultTy = getTypeByID(Record[1]);
606 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
607 return Error("invalid type in function type");
608
609 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
610 break;
611 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000612 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000613 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000614 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000615 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000616 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
617 if (Type *T = getTypeByID(Record[i]))
618 EltTys.push_back(T);
619 else
620 break;
621 }
622 if (EltTys.size() != Record.size()-1)
623 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000624 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000625 break;
626 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000627 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
628 if (ConvertToString(Record, 0, TypeName))
629 return Error("Invalid STRUCT_NAME record");
630 continue;
631
632 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
633 if (Record.size() < 1)
634 return Error("Invalid STRUCT type record");
635
636 if (NumRecords >= TypeList.size())
637 return Error("invalid TYPE table");
638
639 // Check to see if this was forward referenced, if so fill in the temp.
640 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
641 if (Res) {
642 Res->setName(TypeName);
643 TypeList[NumRecords] = 0;
644 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000645 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000646 TypeName.clear();
647
648 SmallVector<Type*, 8> EltTys;
649 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
650 if (Type *T = getTypeByID(Record[i]))
651 EltTys.push_back(T);
652 else
653 break;
654 }
655 if (EltTys.size() != Record.size()-1)
656 return Error("invalid STRUCT type record");
657 Res->setBody(EltTys, Record[0]);
658 ResultTy = Res;
659 break;
660 }
661 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
662 if (Record.size() != 1)
663 return Error("Invalid OPAQUE type record");
664
665 if (NumRecords >= TypeList.size())
666 return Error("invalid TYPE table");
667
668 // Check to see if this was forward referenced, if so fill in the temp.
669 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
670 if (Res) {
671 Res->setName(TypeName);
672 TypeList[NumRecords] = 0;
673 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000674 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000675 TypeName.clear();
676 ResultTy = Res;
677 break;
678 }
679 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
680 if (Record.size() < 2)
681 return Error("Invalid ARRAY type record");
682 if ((ResultTy = getTypeByID(Record[1])))
683 ResultTy = ArrayType::get(ResultTy, Record[0]);
684 else
685 return Error("Invalid ARRAY type element");
686 break;
687 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
688 if (Record.size() < 2)
689 return Error("Invalid VECTOR type record");
690 if ((ResultTy = getTypeByID(Record[1])))
691 ResultTy = VectorType::get(ResultTy, Record[0]);
692 else
693 return Error("Invalid ARRAY type element");
694 break;
695 }
696
697 if (NumRecords >= TypeList.size())
698 return Error("invalid TYPE table");
699 assert(ResultTy && "Didn't read a type?");
700 assert(TypeList[NumRecords] == 0 && "Already read type?");
701 TypeList[NumRecords++] = ResultTy;
702 }
703}
704
Chris Lattner86697142007-05-01 05:01:34 +0000705bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000706 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000707 return Error("Malformed block record");
708
709 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000710
Chris Lattner0b2482a2007-04-23 21:26:05 +0000711 // Read all the records for this value table.
712 SmallString<128> ValueName;
713 while (1) {
714 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000715 if (Code == bitc::END_BLOCK) {
716 if (Stream.ReadBlockEnd())
717 return Error("Error at end of value symbol table block");
718 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000719 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000720 if (Code == bitc::ENTER_SUBBLOCK) {
721 // No known subblocks, always skip them.
722 Stream.ReadSubBlockID();
723 if (Stream.SkipBlock())
724 return Error("Malformed block record");
725 continue;
726 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000727
Chris Lattner0b2482a2007-04-23 21:26:05 +0000728 if (Code == bitc::DEFINE_ABBREV) {
729 Stream.ReadAbbrevRecord();
730 continue;
731 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000732
Chris Lattner0b2482a2007-04-23 21:26:05 +0000733 // Read a record.
734 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000735 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000736 default: // Default behavior: unknown type.
737 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000738 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000739 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000740 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000741 unsigned ValueID = Record[0];
742 if (ValueID >= ValueList.size())
743 return Error("Invalid Value ID in VST_ENTRY record");
744 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000745
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000746 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000747 ValueName.clear();
748 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000749 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000750 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000751 if (ConvertToString(Record, 1, ValueName))
752 return Error("Invalid VST_BBENTRY record");
753 BasicBlock *BB = getBasicBlock(Record[0]);
754 if (BB == 0)
755 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000756
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000757 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000758 ValueName.clear();
759 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000760 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000761 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000762 }
763}
764
Devang Patele54abc92009-07-22 17:43:22 +0000765bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000766 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000767
768 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
769 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000770
Devang Patele54abc92009-07-22 17:43:22 +0000771 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000772
Devang Patele54abc92009-07-22 17:43:22 +0000773 // Read all the records.
774 while (1) {
775 unsigned Code = Stream.ReadCode();
776 if (Code == bitc::END_BLOCK) {
777 if (Stream.ReadBlockEnd())
778 return Error("Error at end of PARAMATTR block");
779 return false;
780 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Devang Patele54abc92009-07-22 17:43:22 +0000782 if (Code == bitc::ENTER_SUBBLOCK) {
783 // No known subblocks, always skip them.
784 Stream.ReadSubBlockID();
785 if (Stream.SkipBlock())
786 return Error("Malformed block record");
787 continue;
788 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000789
Devang Patele54abc92009-07-22 17:43:22 +0000790 if (Code == bitc::DEFINE_ABBREV) {
791 Stream.ReadAbbrevRecord();
792 continue;
793 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Victor Hernandez24e64df2010-01-10 07:14:18 +0000795 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000796 // Read a record.
797 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000798 Code = Stream.ReadRecord(Code, Record);
799 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000800 default: // Default behavior: ignore.
801 break;
Devang Patelaa993142009-07-29 22:34:41 +0000802 case bitc::METADATA_NAME: {
803 // Read named of the named metadata.
804 unsigned NameLength = Record.size();
805 SmallString<8> Name;
806 Name.resize(NameLength);
807 for (unsigned i = 0; i != NameLength; ++i)
808 Name[i] = Record[i];
809 Record.clear();
810 Code = Stream.ReadCode();
811
Chris Lattner9d61dd92011-06-17 17:50:30 +0000812 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000813 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000814 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000815
816 // Read named metadata elements.
817 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000818 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000819 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000820 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
821 if (MD == 0)
822 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000823 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000824 }
Devang Patelaa993142009-07-29 22:34:41 +0000825 break;
826 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000827 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000828 IsFunctionLocal = true;
829 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000830 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000831 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000832 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000833
Devang Patel104cf9e2009-07-23 01:07:34 +0000834 unsigned Size = Record.size();
835 SmallVector<Value*, 8> Elts;
836 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000837 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000838 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000839 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000840 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000841 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000842 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
843 else
844 Elts.push_back(NULL);
845 }
Jay Foadec9186b2011-04-21 19:59:31 +0000846 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000847 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000848 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000849 break;
850 }
Devang Patele54abc92009-07-22 17:43:22 +0000851 case bitc::METADATA_STRING: {
852 unsigned MDStringLength = Record.size();
853 SmallString<8> String;
854 String.resize(MDStringLength);
855 for (unsigned i = 0; i != MDStringLength; ++i)
856 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000857 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +0000858 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +0000859 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000860 break;
861 }
Devang Patele8e02132009-09-18 19:26:43 +0000862 case bitc::METADATA_KIND: {
863 unsigned RecordLength = Record.size();
864 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000865 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +0000866 SmallString<8> Name;
867 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +0000868 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +0000869 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000870 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +0000871
Chris Lattner08113472009-12-29 09:01:33 +0000872 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000873 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
874 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000875 break;
876 }
Devang Patele54abc92009-07-22 17:43:22 +0000877 }
878 }
879}
880
Chris Lattner0eef0802007-04-24 04:04:35 +0000881/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
882/// the LSB for dense VBR encoding.
883static uint64_t DecodeSignRotatedValue(uint64_t V) {
884 if ((V & 1) == 0)
885 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000886 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000887 return -(V >> 1);
888 // There is no such thing as -0 with integers. "-0" really means MININT.
889 return 1ULL << 63;
890}
891
Chris Lattner07d98b42007-04-26 02:46:40 +0000892/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
893/// values and aliases that we can.
894bool BitcodeReader::ResolveGlobalAndAliasInits() {
895 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
896 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000897
Chris Lattner07d98b42007-04-26 02:46:40 +0000898 GlobalInitWorklist.swap(GlobalInits);
899 AliasInitWorklist.swap(AliasInits);
900
901 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000902 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000903 if (ValID >= ValueList.size()) {
904 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000905 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000906 } else {
907 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
908 GlobalInitWorklist.back().first->setInitializer(C);
909 else
910 return Error("Global variable initializer is not a constant!");
911 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000912 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000913 }
914
915 while (!AliasInitWorklist.empty()) {
916 unsigned ValID = AliasInitWorklist.back().second;
917 if (ValID >= ValueList.size()) {
918 AliasInits.push_back(AliasInitWorklist.back());
919 } else {
920 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000921 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000922 else
923 return Error("Alias initializer is not a constant!");
924 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000926 }
927 return false;
928}
929
Chris Lattner86697142007-05-01 05:01:34 +0000930bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000931 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000932 return Error("Malformed block record");
933
934 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000935
Chris Lattnere16504e2007-04-24 03:30:34 +0000936 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000937 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000938 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000939 while (1) {
940 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000941 if (Code == bitc::END_BLOCK)
942 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000943
Chris Lattnere16504e2007-04-24 03:30:34 +0000944 if (Code == bitc::ENTER_SUBBLOCK) {
945 // No known subblocks, always skip them.
946 Stream.ReadSubBlockID();
947 if (Stream.SkipBlock())
948 return Error("Malformed block record");
949 continue;
950 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000951
Chris Lattnere16504e2007-04-24 03:30:34 +0000952 if (Code == bitc::DEFINE_ABBREV) {
953 Stream.ReadAbbrevRecord();
954 continue;
955 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000956
Chris Lattnere16504e2007-04-24 03:30:34 +0000957 // Read a record.
958 Record.clear();
959 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000960 unsigned BitCode = Stream.ReadRecord(Code, Record);
961 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000962 default: // Default behavior: unknown constant
963 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000964 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000965 break;
966 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
967 if (Record.empty())
968 return Error("Malformed CST_SETTYPE record");
969 if (Record[0] >= TypeList.size())
970 return Error("Invalid Type ID in CST_SETTYPE record");
971 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000972 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000973 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000974 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000975 break;
976 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000977 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000978 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +0000979 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000980 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000981 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000982 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000983 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000984
Chris Lattner15e6d172007-05-04 19:11:41 +0000985 unsigned NumWords = Record.size();
Stepan Dyatkovskiy1f983832012-05-08 08:33:21 +0000986 SmallVector<uint64_t, 8> Words;
987 Words.resize(NumWords);
988 for (unsigned i = 0; i != NumWords; ++i)
989 Words[i] = DecodeSignRotatedValue(Record[i]);
990 V = ConstantInt::get(Context,
991 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
992 Words));
Chris Lattner0eef0802007-04-24 04:04:35 +0000993 break;
994 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000995 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000996 if (Record.empty())
997 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +0000998 if (CurTy->isHalfTy())
999 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1000 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001001 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001002 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001003 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001004 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001005 // Bits are not stored the same way as a normal i80 APInt, compensate.
1006 uint64_t Rearrange[2];
1007 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1008 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001009 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001010 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001011 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001012 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001013 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001014 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001015 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001016 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001017 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001018
Chris Lattner15e6d172007-05-04 19:11:41 +00001019 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1020 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001021 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001022
Chris Lattner15e6d172007-05-04 19:11:41 +00001023 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001024 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001025
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001026 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001027 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001028 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001029 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001030 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001031 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1032 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001033 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001034 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001035 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001036 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1037 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001038 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001039 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001040 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001041 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001042 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001043 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001044 break;
1045 }
Chris Lattner2237f842012-02-05 02:41:35 +00001046 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001047 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1048 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001049 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001050
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001051 unsigned Size = Record.size();
Chris Lattner2237f842012-02-05 02:41:35 +00001052 SmallString<16> Elts;
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001053 for (unsigned i = 0; i != Size; ++i)
Chris Lattner2237f842012-02-05 02:41:35 +00001054 Elts.push_back(Record[i]);
1055 V = ConstantDataArray::getString(Context, Elts,
1056 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001057 break;
1058 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001059 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1060 if (Record.empty())
1061 return Error("Invalid CST_DATA record");
1062
1063 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1064 unsigned Size = Record.size();
1065
1066 if (EltTy->isIntegerTy(8)) {
1067 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1068 if (isa<VectorType>(CurTy))
1069 V = ConstantDataVector::get(Context, Elts);
1070 else
1071 V = ConstantDataArray::get(Context, Elts);
1072 } else if (EltTy->isIntegerTy(16)) {
1073 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1074 if (isa<VectorType>(CurTy))
1075 V = ConstantDataVector::get(Context, Elts);
1076 else
1077 V = ConstantDataArray::get(Context, Elts);
1078 } else if (EltTy->isIntegerTy(32)) {
1079 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1080 if (isa<VectorType>(CurTy))
1081 V = ConstantDataVector::get(Context, Elts);
1082 else
1083 V = ConstantDataArray::get(Context, Elts);
1084 } else if (EltTy->isIntegerTy(64)) {
1085 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1086 if (isa<VectorType>(CurTy))
1087 V = ConstantDataVector::get(Context, Elts);
1088 else
1089 V = ConstantDataArray::get(Context, Elts);
1090 } else if (EltTy->isFloatTy()) {
1091 SmallVector<float, 16> Elts;
1092 for (unsigned i = 0; i != Size; ++i) {
1093 union { uint32_t I; float F; };
1094 I = Record[i];
1095 Elts.push_back(F);
1096 }
1097 if (isa<VectorType>(CurTy))
1098 V = ConstantDataVector::get(Context, Elts);
1099 else
1100 V = ConstantDataArray::get(Context, Elts);
1101 } else if (EltTy->isDoubleTy()) {
1102 SmallVector<double, 16> Elts;
1103 for (unsigned i = 0; i != Size; ++i) {
1104 union { uint64_t I; double F; };
1105 I = Record[i];
1106 Elts.push_back(F);
1107 }
1108 if (isa<VectorType>(CurTy))
1109 V = ConstantDataVector::get(Context, Elts);
1110 else
1111 V = ConstantDataArray::get(Context, Elts);
1112 } else {
1113 return Error("Unknown element type in CE_DATA");
1114 }
1115 break;
1116 }
1117
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001118 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1119 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1120 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001121 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001122 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001123 } else {
1124 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1125 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001126 unsigned Flags = 0;
1127 if (Record.size() >= 4) {
1128 if (Opc == Instruction::Add ||
1129 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001130 Opc == Instruction::Mul ||
1131 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001132 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1133 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1134 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1135 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001136 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001137 Opc == Instruction::UDiv ||
1138 Opc == Instruction::LShr ||
1139 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001140 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001141 Flags |= SDivOperator::IsExact;
1142 }
1143 }
1144 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001145 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001146 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001147 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001148 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1149 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1150 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001151 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001152 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001153 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001154 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001155 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001156 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001157 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001158 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001159 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001160 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001161 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001162 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001163 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001164 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001165 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001166 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001167 if (!ElTy) return Error("Invalid CE_GEP record");
1168 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1169 }
Jay Foaddab3d292011-07-21 14:31:17 +00001170 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001171 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1172 BitCode ==
1173 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001174 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001175 }
1176 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1177 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001178 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001179 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001180 ValueList.getConstantFwdRef(Record[1],CurTy),
1181 ValueList.getConstantFwdRef(Record[2],CurTy));
1182 break;
1183 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1184 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001185 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001186 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1187 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1188 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001189 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001190 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001191 break;
1192 }
1193 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001194 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001195 if (Record.size() < 3 || OpTy == 0)
1196 return Error("Invalid CE_INSERTELT record");
1197 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1198 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1199 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001200 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001201 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001202 break;
1203 }
1204 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001205 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001206 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001207 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001208 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1209 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001210 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001211 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001212 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001213 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001214 break;
1215 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001216 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001217 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1218 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001219 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001220 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1221 return Error("Invalid CE_SHUFVEC_EX record");
1222 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1223 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001224 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001225 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001226 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001227 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001228 break;
1229 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001230 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1231 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001232 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001233 if (OpTy == 0) return Error("Invalid CE_CMP record");
1234 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1235 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1236
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001237 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001238 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001239 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001240 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001241 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001242 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001243 case bitc::CST_CODE_INLINEASM: {
1244 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1245 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001246 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001247 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001248 unsigned AsmStrSize = Record[1];
1249 if (2+AsmStrSize >= Record.size())
1250 return Error("Invalid INLINEASM record");
1251 unsigned ConstStrSize = Record[2+AsmStrSize];
1252 if (3+AsmStrSize+ConstStrSize > Record.size())
1253 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001254
Chris Lattner2bce93a2007-05-06 01:58:20 +00001255 for (unsigned i = 0; i != AsmStrSize; ++i)
1256 AsmStr += (char)Record[2+i];
1257 for (unsigned i = 0; i != ConstStrSize; ++i)
1258 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001259 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001260 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001261 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001262 break;
1263 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001264 case bitc::CST_CODE_BLOCKADDRESS:{
1265 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001266 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001267 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1268 Function *Fn =
1269 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1270 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1271
1272 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1273 Type::getInt8Ty(Context),
1274 false, GlobalValue::InternalLinkage,
1275 0, "");
1276 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1277 V = FwdRef;
1278 break;
1279 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001280 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001281
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001282 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001283 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001284 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001285
Chris Lattnerea693df2008-08-21 02:34:16 +00001286 if (NextCstNo != ValueList.size())
1287 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001288
Chris Lattnerea693df2008-08-21 02:34:16 +00001289 if (Stream.ReadBlockEnd())
1290 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001291
Chris Lattnerea693df2008-08-21 02:34:16 +00001292 // Once all the constants have been read, go through and resolve forward
1293 // references.
1294 ValueList.ResolveConstantForwardRefs();
1295 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001296}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001297
Chad Rosiercbbb0962011-12-07 21:44:12 +00001298bool BitcodeReader::ParseUseLists() {
1299 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1300 return Error("Malformed block record");
1301
1302 SmallVector<uint64_t, 64> Record;
1303
1304 // Read all the records.
1305 while (1) {
1306 unsigned Code = Stream.ReadCode();
1307 if (Code == bitc::END_BLOCK) {
1308 if (Stream.ReadBlockEnd())
1309 return Error("Error at end of use-list table block");
1310 return false;
1311 }
1312
1313 if (Code == bitc::ENTER_SUBBLOCK) {
1314 // No known subblocks, always skip them.
1315 Stream.ReadSubBlockID();
1316 if (Stream.SkipBlock())
1317 return Error("Malformed block record");
1318 continue;
1319 }
1320
1321 if (Code == bitc::DEFINE_ABBREV) {
1322 Stream.ReadAbbrevRecord();
1323 continue;
1324 }
1325
1326 // Read a use list record.
1327 Record.clear();
1328 switch (Stream.ReadRecord(Code, Record)) {
1329 default: // Default behavior: unknown type.
1330 break;
1331 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1332 unsigned RecordLength = Record.size();
1333 if (RecordLength < 1)
1334 return Error ("Invalid UseList reader!");
1335 UseListRecords.push_back(Record);
1336 break;
1337 }
1338 }
1339 }
1340}
1341
Chris Lattner980e5aa2007-05-01 05:52:21 +00001342/// RememberAndSkipFunctionBody - When we see the block for a function body,
1343/// remember where it is and then skip it. This lets us lazily deserialize the
1344/// functions.
1345bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001346 // Get the function we are talking about.
1347 if (FunctionsWithBodies.empty())
1348 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001349
Chris Lattner48f84872007-05-01 04:59:48 +00001350 Function *Fn = FunctionsWithBodies.back();
1351 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001352
Chris Lattner48f84872007-05-01 04:59:48 +00001353 // Save the current stream state.
1354 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001355 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001356
Chris Lattner48f84872007-05-01 04:59:48 +00001357 // Skip over the function block for now.
1358 if (Stream.SkipBlock())
1359 return Error("Malformed block record");
1360 return false;
1361}
1362
Derek Schuff2ea93872012-02-06 22:30:29 +00001363bool BitcodeReader::GlobalCleanup() {
1364 // Patch the initializers for globals and aliases up.
1365 ResolveGlobalAndAliasInits();
1366 if (!GlobalInits.empty() || !AliasInits.empty())
1367 return Error("Malformed global initializer set");
1368
1369 // Look for intrinsic functions which need to be upgraded at some point
1370 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1371 FI != FE; ++FI) {
1372 Function *NewFn;
1373 if (UpgradeIntrinsicFunction(FI, NewFn))
1374 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1375 }
1376
1377 // Look for global variables which need to be renamed.
1378 for (Module::global_iterator
1379 GI = TheModule->global_begin(), GE = TheModule->global_end();
1380 GI != GE; ++GI)
1381 UpgradeGlobalVariable(GI);
1382 // Force deallocation of memory for these vectors to favor the client that
1383 // want lazy deserialization.
1384 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1385 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1386 return false;
1387}
1388
1389bool BitcodeReader::ParseModule(bool Resume) {
1390 if (Resume)
1391 Stream.JumpToBit(NextUnreadBit);
1392 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001393 return Error("Malformed block record");
1394
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001395 SmallVector<uint64_t, 64> Record;
1396 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001397 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001398
1399 // Read all the records for this module.
1400 while (!Stream.AtEndOfStream()) {
1401 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001402 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001403 if (Stream.ReadBlockEnd())
1404 return Error("Error at end of module block");
1405
Derek Schuff2ea93872012-02-06 22:30:29 +00001406 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001407 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001408
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001409 if (Code == bitc::ENTER_SUBBLOCK) {
1410 switch (Stream.ReadSubBlockID()) {
1411 default: // Skip unknown content.
1412 if (Stream.SkipBlock())
1413 return Error("Malformed block record");
1414 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001415 case bitc::BLOCKINFO_BLOCK_ID:
1416 if (Stream.ReadBlockInfoBlock())
1417 return Error("Malformed BlockInfoBlock");
1418 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001419 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001420 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001421 return true;
1422 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001423 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001424 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001425 return true;
1426 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001427 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001428 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001429 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001430 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001431 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001432 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001433 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001434 return true;
1435 break;
Devang Patele54abc92009-07-22 17:43:22 +00001436 case bitc::METADATA_BLOCK_ID:
1437 if (ParseMetadata())
1438 return true;
1439 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001440 case bitc::FUNCTION_BLOCK_ID:
1441 // If this is the first function body we've seen, reverse the
1442 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001443 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001444 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001445 if (GlobalCleanup())
1446 return true;
1447 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001448 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001449
Chris Lattner980e5aa2007-05-01 05:52:21 +00001450 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001451 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001452 // For streaming bitcode, suspend parsing when we reach the function
1453 // bodies. Subsequent materialization calls will resume it when
1454 // necessary. For streaming, the function bodies must be at the end of
1455 // the bitcode. If the bitcode file is old, the symbol table will be
1456 // at the end instead and will not have been seen yet. In this case,
1457 // just finish the parse now.
1458 if (LazyStreamer && SeenValueSymbolTable) {
1459 NextUnreadBit = Stream.GetCurrentBitNo();
1460 return false;
1461 }
Chris Lattner48f84872007-05-01 04:59:48 +00001462 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001463 case bitc::USELIST_BLOCK_ID:
1464 if (ParseUseLists())
1465 return true;
1466 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001467 }
1468 continue;
1469 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001470
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001471 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001472 Stream.ReadAbbrevRecord();
1473 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001474 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001475
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001476 // Read a record.
1477 switch (Stream.ReadRecord(Code, Record)) {
1478 default: break; // Default behavior, ignore unknown content.
1479 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1480 if (Record.size() < 1)
1481 return Error("Malformed MODULE_CODE_VERSION");
1482 // Only version #0 is supported so far.
1483 if (Record[0] != 0)
1484 return Error("Unknown bitstream version!");
1485 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001486 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001487 std::string S;
1488 if (ConvertToString(Record, 0, S))
1489 return Error("Invalid MODULE_CODE_TRIPLE record");
1490 TheModule->setTargetTriple(S);
1491 break;
1492 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001493 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001494 std::string S;
1495 if (ConvertToString(Record, 0, S))
1496 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1497 TheModule->setDataLayout(S);
1498 break;
1499 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001500 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001501 std::string S;
1502 if (ConvertToString(Record, 0, S))
1503 return Error("Invalid MODULE_CODE_ASM record");
1504 TheModule->setModuleInlineAsm(S);
1505 break;
1506 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001507 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001508 std::string S;
1509 if (ConvertToString(Record, 0, S))
1510 return Error("Invalid MODULE_CODE_DEPLIB record");
1511 TheModule->addLibrary(S);
1512 break;
1513 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001514 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001515 std::string S;
1516 if (ConvertToString(Record, 0, S))
1517 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1518 SectionTable.push_back(S);
1519 break;
1520 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001521 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001522 std::string S;
1523 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001524 return Error("Invalid MODULE_CODE_GCNAME record");
1525 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001526 break;
1527 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001528 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001529 // linkage, alignment, section, visibility, threadlocal,
1530 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001531 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001532 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001533 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001534 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001535 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001536 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001537 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001538 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001539 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001540
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001541 bool isConstant = Record[1];
1542 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1543 unsigned Alignment = (1 << Record[4]) >> 1;
1544 std::string Section;
1545 if (Record[5]) {
1546 if (Record[5]-1 >= SectionTable.size())
1547 return Error("Invalid section ID");
1548 Section = SectionTable[Record[5]-1];
1549 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001550 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001551 if (Record.size() > 6)
1552 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001553 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001554 if (Record.size() > 7)
1555 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001556
Rafael Espindolabea46262011-01-08 16:42:36 +00001557 bool UnnamedAddr = false;
1558 if (Record.size() > 8)
1559 UnnamedAddr = Record[8];
1560
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001561 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001562 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001563 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001564 NewGV->setAlignment(Alignment);
1565 if (!Section.empty())
1566 NewGV->setSection(Section);
1567 NewGV->setVisibility(Visibility);
1568 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001569 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001570
Chris Lattner0b2482a2007-04-23 21:26:05 +00001571 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001572
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001573 // Remember which value to use for the global initializer.
1574 if (unsigned InitID = Record[2])
1575 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001576 break;
1577 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001578 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001579 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001580 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001581 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001582 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001583 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001584 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001585 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001586 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001587 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001588 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1589 if (!FTy)
1590 return Error("Function not a pointer to function type!");
1591
Gabor Greif051a9502008-04-06 20:25:17 +00001592 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1593 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001595 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001596 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001597 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001598 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001599
Chris Lattnera9bb7132007-05-08 05:38:01 +00001600 Func->setAlignment((1 << Record[5]) >> 1);
1601 if (Record[6]) {
1602 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001603 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001604 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001605 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001606 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001607 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001608 if (Record[8]-1 > GCTable.size())
1609 return Error("Invalid GC ID");
1610 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001611 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001612 bool UnnamedAddr = false;
1613 if (Record.size() > 9)
1614 UnnamedAddr = Record[9];
1615 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001616 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001617
Chris Lattner48f84872007-05-01 04:59:48 +00001618 // If this is a function with a body, remember the prototype we are
1619 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001620 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001621 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001622 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1623 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001624 break;
1625 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001626 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001627 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001628 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001629 if (Record.size() < 3)
1630 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001631 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001632 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001633 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001634 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001635
Chris Lattner07d98b42007-04-26 02:46:40 +00001636 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1637 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001638 // Old bitcode files didn't have visibility field.
1639 if (Record.size() > 3)
1640 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001641 ValueList.push_back(NewGA);
1642 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1643 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001644 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001645 /// MODULE_CODE_PURGEVALS: [numvals]
1646 case bitc::MODULE_CODE_PURGEVALS:
1647 // Trim down the value list to the specified size.
1648 if (Record.size() < 1 || Record[0] > ValueList.size())
1649 return Error("Invalid MODULE_PURGEVALS record");
1650 ValueList.shrinkTo(Record[0]);
1651 break;
1652 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001653 Record.clear();
1654 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001655
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001656 return Error("Premature end of bitstream");
1657}
1658
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001659bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001660 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001661
Derek Schuff2ea93872012-02-06 22:30:29 +00001662 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001663
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001664 // Sniff for the signature.
1665 if (Stream.Read(8) != 'B' ||
1666 Stream.Read(8) != 'C' ||
1667 Stream.Read(4) != 0x0 ||
1668 Stream.Read(4) != 0xC ||
1669 Stream.Read(4) != 0xE ||
1670 Stream.Read(4) != 0xD)
1671 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001672
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001673 // We expect a number of well-defined blocks, though we don't necessarily
1674 // need to understand them all.
1675 while (!Stream.AtEndOfStream()) {
1676 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001677
Rafael Espindolac9687b32011-05-26 18:59:54 +00001678 if (Code != bitc::ENTER_SUBBLOCK) {
1679
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001680 // The ranlib in xcode 4 will align archive members by appending newlines
1681 // to the end of them. If this file size is a multiple of 4 but not 8, we
1682 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001683 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1684 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1685 Stream.AtEndOfStream())
1686 return false;
1687
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001688 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001689 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001690
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001691 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001692
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001693 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001694 switch (BlockID) {
1695 case bitc::BLOCKINFO_BLOCK_ID:
1696 if (Stream.ReadBlockInfoBlock())
1697 return Error("Malformed BlockInfoBlock");
1698 break;
1699 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001700 // Reject multiple MODULE_BLOCK's in a single bitstream.
1701 if (TheModule)
1702 return Error("Multiple MODULE_BLOCKs in same stream");
1703 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001704 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001705 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001706 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001707 break;
1708 default:
1709 if (Stream.SkipBlock())
1710 return Error("Malformed block record");
1711 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001712 }
1713 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001714
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001715 return false;
1716}
Chris Lattnerc453f762007-04-29 07:54:31 +00001717
Bill Wendling34711742010-10-06 01:22:42 +00001718bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1719 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1720 return Error("Malformed block record");
1721
1722 SmallVector<uint64_t, 64> Record;
1723
1724 // Read all the records for this module.
1725 while (!Stream.AtEndOfStream()) {
1726 unsigned Code = Stream.ReadCode();
1727 if (Code == bitc::END_BLOCK) {
1728 if (Stream.ReadBlockEnd())
1729 return Error("Error at end of module block");
1730
1731 return false;
1732 }
1733
1734 if (Code == bitc::ENTER_SUBBLOCK) {
1735 switch (Stream.ReadSubBlockID()) {
1736 default: // Skip unknown content.
1737 if (Stream.SkipBlock())
1738 return Error("Malformed block record");
1739 break;
1740 }
1741 continue;
1742 }
1743
1744 if (Code == bitc::DEFINE_ABBREV) {
1745 Stream.ReadAbbrevRecord();
1746 continue;
1747 }
1748
1749 // Read a record.
1750 switch (Stream.ReadRecord(Code, Record)) {
1751 default: break; // Default behavior, ignore unknown content.
1752 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1753 if (Record.size() < 1)
1754 return Error("Malformed MODULE_CODE_VERSION");
1755 // Only version #0 is supported so far.
1756 if (Record[0] != 0)
1757 return Error("Unknown bitstream version!");
1758 break;
1759 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1760 std::string S;
1761 if (ConvertToString(Record, 0, S))
1762 return Error("Invalid MODULE_CODE_TRIPLE record");
1763 Triple = S;
1764 break;
1765 }
1766 }
1767 Record.clear();
1768 }
1769
1770 return Error("Premature end of bitstream");
1771}
1772
1773bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001774 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001775
1776 // Sniff for the signature.
1777 if (Stream.Read(8) != 'B' ||
1778 Stream.Read(8) != 'C' ||
1779 Stream.Read(4) != 0x0 ||
1780 Stream.Read(4) != 0xC ||
1781 Stream.Read(4) != 0xE ||
1782 Stream.Read(4) != 0xD)
1783 return Error("Invalid bitcode signature");
1784
1785 // We expect a number of well-defined blocks, though we don't necessarily
1786 // need to understand them all.
1787 while (!Stream.AtEndOfStream()) {
1788 unsigned Code = Stream.ReadCode();
1789
1790 if (Code != bitc::ENTER_SUBBLOCK)
1791 return Error("Invalid record at top-level");
1792
1793 unsigned BlockID = Stream.ReadSubBlockID();
1794
1795 // We only know the MODULE subblock ID.
1796 switch (BlockID) {
1797 case bitc::MODULE_BLOCK_ID:
1798 if (ParseModuleTriple(Triple))
1799 return true;
1800 break;
1801 default:
1802 if (Stream.SkipBlock())
1803 return Error("Malformed block record");
1804 break;
1805 }
1806 }
1807
1808 return false;
1809}
1810
Devang Patele8e02132009-09-18 19:26:43 +00001811/// ParseMetadataAttachment - Parse metadata attachments.
1812bool BitcodeReader::ParseMetadataAttachment() {
1813 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1814 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001815
Devang Patele8e02132009-09-18 19:26:43 +00001816 SmallVector<uint64_t, 64> Record;
1817 while(1) {
1818 unsigned Code = Stream.ReadCode();
1819 if (Code == bitc::END_BLOCK) {
1820 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001821 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001822 break;
1823 }
1824 if (Code == bitc::DEFINE_ABBREV) {
1825 Stream.ReadAbbrevRecord();
1826 continue;
1827 }
1828 // Read a metadata attachment record.
1829 Record.clear();
1830 switch (Stream.ReadRecord(Code, Record)) {
1831 default: // Default behavior: ignore.
1832 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001833 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001834 unsigned RecordLength = Record.size();
1835 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001836 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001837 Instruction *Inst = InstructionList[Record[0]];
1838 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001839 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001840 DenseMap<unsigned, unsigned>::iterator I =
1841 MDKindMap.find(Kind);
1842 if (I == MDKindMap.end())
1843 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001844 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001845 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001846 }
1847 break;
1848 }
1849 }
1850 }
1851 return false;
1852}
Chris Lattner48f84872007-05-01 04:59:48 +00001853
Chris Lattner980e5aa2007-05-01 05:52:21 +00001854/// ParseFunctionBody - Lazily parse the specified function body block.
1855bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001856 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001857 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001858
Nick Lewycky9a49f152010-02-25 08:30:17 +00001859 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001860 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001861 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001862
Chris Lattner980e5aa2007-05-01 05:52:21 +00001863 // Add all the function arguments to the value table.
1864 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1865 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001866
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001867 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001868 BasicBlock *CurBB = 0;
1869 unsigned CurBBNo = 0;
1870
Chris Lattnera6245242010-04-03 02:17:50 +00001871 DebugLoc LastLoc;
1872
Chris Lattner980e5aa2007-05-01 05:52:21 +00001873 // Read all the records.
1874 SmallVector<uint64_t, 64> Record;
1875 while (1) {
1876 unsigned Code = Stream.ReadCode();
1877 if (Code == bitc::END_BLOCK) {
1878 if (Stream.ReadBlockEnd())
1879 return Error("Error at end of function block");
1880 break;
1881 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001882
Chris Lattner980e5aa2007-05-01 05:52:21 +00001883 if (Code == bitc::ENTER_SUBBLOCK) {
1884 switch (Stream.ReadSubBlockID()) {
1885 default: // Skip unknown content.
1886 if (Stream.SkipBlock())
1887 return Error("Malformed block record");
1888 break;
1889 case bitc::CONSTANTS_BLOCK_ID:
1890 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001891 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001892 break;
1893 case bitc::VALUE_SYMTAB_BLOCK_ID:
1894 if (ParseValueSymbolTable()) return true;
1895 break;
Devang Patele8e02132009-09-18 19:26:43 +00001896 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001897 if (ParseMetadataAttachment()) return true;
1898 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001899 case bitc::METADATA_BLOCK_ID:
1900 if (ParseMetadata()) return true;
1901 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001902 }
1903 continue;
1904 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001905
Chris Lattner980e5aa2007-05-01 05:52:21 +00001906 if (Code == bitc::DEFINE_ABBREV) {
1907 Stream.ReadAbbrevRecord();
1908 continue;
1909 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001910
Chris Lattner980e5aa2007-05-01 05:52:21 +00001911 // Read a record.
1912 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001913 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001914 unsigned BitCode = Stream.ReadRecord(Code, Record);
1915 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001916 default: // Default behavior: reject
1917 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001918 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001919 if (Record.size() < 1 || Record[0] == 0)
1920 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001921 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001922 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001923 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001924 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001925 CurBB = FunctionBBs[0];
1926 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001927
1928 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1929 // This record indicates that the last instruction is at the same
1930 // location as the previous instruction with a location.
1931 I = 0;
1932
1933 // Get the last instruction emitted.
1934 if (CurBB && !CurBB->empty())
1935 I = &CurBB->back();
1936 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1937 !FunctionBBs[CurBBNo-1]->empty())
1938 I = &FunctionBBs[CurBBNo-1]->back();
1939
1940 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1941 I->setDebugLoc(LastLoc);
1942 I = 0;
1943 continue;
1944
Chris Lattner4f6bab92011-06-17 18:17:37 +00001945 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001946 I = 0; // Get the last instruction emitted.
1947 if (CurBB && !CurBB->empty())
1948 I = &CurBB->back();
1949 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1950 !FunctionBBs[CurBBNo-1]->empty())
1951 I = &FunctionBBs[CurBBNo-1]->back();
1952 if (I == 0 || Record.size() < 4)
1953 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1954
1955 unsigned Line = Record[0], Col = Record[1];
1956 unsigned ScopeID = Record[2], IAID = Record[3];
1957
1958 MDNode *Scope = 0, *IA = 0;
1959 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1960 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1961 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1962 I->setDebugLoc(LastLoc);
1963 I = 0;
1964 continue;
1965 }
1966
Chris Lattnerabfbf852007-05-06 00:21:25 +00001967 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1968 unsigned OpNum = 0;
1969 Value *LHS, *RHS;
1970 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1971 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001972 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001973 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001974
Dan Gohman1224c382009-07-20 21:19:07 +00001975 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001976 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001977 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001978 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001979 if (OpNum < Record.size()) {
1980 if (Opc == Instruction::Add ||
1981 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001982 Opc == Instruction::Mul ||
1983 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00001984 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001985 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00001986 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001987 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00001988 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001989 Opc == Instruction::UDiv ||
1990 Opc == Instruction::LShr ||
1991 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001992 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001993 cast<BinaryOperator>(I)->setIsExact(true);
1994 }
1995 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001996 break;
1997 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001998 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1999 unsigned OpNum = 0;
2000 Value *Op;
2001 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2002 OpNum+2 != Record.size())
2003 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002004
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002005 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002006 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2007 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002008 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002009 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002010 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002011 break;
2012 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002013 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002014 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002015 unsigned OpNum = 0;
2016 Value *BasePtr;
2017 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002018 return Error("Invalid GEP record");
2019
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002020 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002021 while (OpNum != Record.size()) {
2022 Value *Op;
2023 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002024 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002025 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002026 }
2027
Jay Foada9203102011-07-25 09:48:08 +00002028 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002029 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002030 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002031 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002032 break;
2033 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002034
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002035 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2036 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002037 unsigned OpNum = 0;
2038 Value *Agg;
2039 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2040 return Error("Invalid EXTRACTVAL record");
2041
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002042 SmallVector<unsigned, 4> EXTRACTVALIdx;
2043 for (unsigned RecSize = Record.size();
2044 OpNum != RecSize; ++OpNum) {
2045 uint64_t Index = Record[OpNum];
2046 if ((unsigned)Index != Index)
2047 return Error("Invalid EXTRACTVAL index");
2048 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002049 }
2050
Jay Foadfc6d3a42011-07-13 10:26:04 +00002051 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002052 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002053 break;
2054 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002055
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002056 case bitc::FUNC_CODE_INST_INSERTVAL: {
2057 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002058 unsigned OpNum = 0;
2059 Value *Agg;
2060 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2061 return Error("Invalid INSERTVAL record");
2062 Value *Val;
2063 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2064 return Error("Invalid INSERTVAL record");
2065
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002066 SmallVector<unsigned, 4> INSERTVALIdx;
2067 for (unsigned RecSize = Record.size();
2068 OpNum != RecSize; ++OpNum) {
2069 uint64_t Index = Record[OpNum];
2070 if ((unsigned)Index != Index)
2071 return Error("Invalid INSERTVAL index");
2072 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002073 }
2074
Jay Foadfc6d3a42011-07-13 10:26:04 +00002075 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002076 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002077 break;
2078 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002079
Chris Lattnerabfbf852007-05-06 00:21:25 +00002080 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002081 // obsolete form of select
2082 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002083 unsigned OpNum = 0;
2084 Value *TrueVal, *FalseVal, *Cond;
2085 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2086 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002087 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002088 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002089
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002090 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002091 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002092 break;
2093 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002094
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002095 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2096 // new form of select
2097 // handles select i1 or select [N x i1]
2098 unsigned OpNum = 0;
2099 Value *TrueVal, *FalseVal, *Cond;
2100 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2101 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2102 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2103 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002104
2105 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002106 if (VectorType* vector_type =
2107 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002108 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002109 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002110 return Error("Invalid SELECT condition type");
2111 } else {
2112 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002113 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002114 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002115 }
2116
Gabor Greif051a9502008-04-06 20:25:17 +00002117 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002118 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002119 break;
2120 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002121
Chris Lattner01ff65f2007-05-02 05:16:49 +00002122 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002123 unsigned OpNum = 0;
2124 Value *Vec, *Idx;
2125 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002126 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002127 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002128 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002129 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002130 break;
2131 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002132
Chris Lattner01ff65f2007-05-02 05:16:49 +00002133 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002134 unsigned OpNum = 0;
2135 Value *Vec, *Elt, *Idx;
2136 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002137 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002138 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002139 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002140 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002141 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002142 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002143 break;
2144 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002145
Chris Lattnerabfbf852007-05-06 00:21:25 +00002146 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2147 unsigned OpNum = 0;
2148 Value *Vec1, *Vec2, *Mask;
2149 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2150 getValue(Record, OpNum, Vec1->getType(), Vec2))
2151 return Error("Invalid SHUFFLEVEC record");
2152
Mon P Wangaeb06d22008-11-10 04:46:22 +00002153 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002154 return Error("Invalid SHUFFLEVEC record");
2155 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002156 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002157 break;
2158 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002159
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002160 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2161 // Old form of ICmp/FCmp returning bool
2162 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2163 // both legal on vectors but had different behaviour.
2164 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2165 // FCmp/ICmp returning bool or vector of bool
2166
Chris Lattner7337ab92007-05-06 00:00:00 +00002167 unsigned OpNum = 0;
2168 Value *LHS, *RHS;
2169 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2170 getValue(Record, OpNum, LHS->getType(), RHS) ||
2171 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002172 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002173
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002174 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002175 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002176 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002177 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002178 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002179 break;
2180 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002181
Chris Lattner231cbcb2007-05-02 04:27:25 +00002182 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002183 {
2184 unsigned Size = Record.size();
2185 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002186 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002187 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002188 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002189 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002190
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002191 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002192 Value *Op = NULL;
2193 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2194 return Error("Invalid RET record");
2195 if (OpNum != Record.size())
2196 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002197
Chris Lattner96a74c52011-06-17 18:09:11 +00002198 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002199 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002200 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002201 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002202 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002203 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002204 return Error("Invalid BR record");
2205 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2206 if (TrueDest == 0)
2207 return Error("Invalid BR record");
2208
Devang Patele8e02132009-09-18 19:26:43 +00002209 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002210 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002211 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002212 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002213 else {
2214 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002215 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002216 if (FalseDest == 0 || Cond == 0)
2217 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002218 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002219 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002220 }
2221 break;
2222 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002223 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002224 if (Record.size() < 3 || (Record.size() & 1) == 0)
2225 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002226 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002227 Value *Cond = getFnValueByID(Record[1], OpTy);
2228 BasicBlock *Default = getBasicBlock(Record[2]);
2229 if (OpTy == 0 || Cond == 0 || Default == 0)
2230 return Error("Invalid SWITCH record");
2231 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002232 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002233 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002234 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002235 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002236 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2237 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2238 if (CaseVal == 0 || DestBB == 0) {
2239 delete SI;
2240 return Error("Invalid SWITCH record!");
2241 }
2242 SI->addCase(CaseVal, DestBB);
2243 }
2244 I = SI;
2245 break;
2246 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002247 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002248 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002249 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002250 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002251 Value *Address = getFnValueByID(Record[1], OpTy);
2252 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002253 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002254 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002255 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002256 InstructionList.push_back(IBI);
2257 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2258 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2259 IBI->addDestination(DestBB);
2260 } else {
2261 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002262 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002263 }
2264 }
2265 I = IBI;
2266 break;
2267 }
2268
Duncan Sandsdc024672007-11-27 13:23:08 +00002269 case bitc::FUNC_CODE_INST_INVOKE: {
2270 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002271 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002272 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002273 unsigned CCInfo = Record[1];
2274 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2275 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002276
Chris Lattnera9bb7132007-05-08 05:38:01 +00002277 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002278 Value *Callee;
2279 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002280 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002281
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002282 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2283 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002284 dyn_cast<FunctionType>(CalleeTy->getElementType());
2285
2286 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002287 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2288 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002289 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002290
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002291 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002292 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2293 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2294 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002295 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002296
Chris Lattner7337ab92007-05-06 00:00:00 +00002297 if (!FTy->isVarArg()) {
2298 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002299 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002300 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002301 // Read type/value pairs for varargs params.
2302 while (OpNum != Record.size()) {
2303 Value *Op;
2304 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2305 return Error("Invalid INVOKE record");
2306 Ops.push_back(Op);
2307 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002308 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002309
Jay Foada3efbb12011-07-15 08:37:34 +00002310 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002311 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002312 cast<InvokeInst>(I)->setCallingConv(
2313 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002314 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002315 break;
2316 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002317 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2318 unsigned Idx = 0;
2319 Value *Val = 0;
2320 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2321 return Error("Invalid RESUME record");
2322 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002323 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002324 break;
2325 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002326 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002327 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002328 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002329 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002330 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002331 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002332 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002333 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002334 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002335
Jay Foad3ecfc862011-03-30 11:28:46 +00002336 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002337 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002338
Chris Lattner15e6d172007-05-04 19:11:41 +00002339 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2340 Value *V = getFnValueByID(Record[1+i], Ty);
2341 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002342 if (!V || !BB) return Error("Invalid PHI record");
2343 PN->addIncoming(V, BB);
2344 }
2345 I = PN;
2346 break;
2347 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002348
Bill Wendlinge6e88262011-08-12 20:24:12 +00002349 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2350 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2351 unsigned Idx = 0;
2352 if (Record.size() < 4)
2353 return Error("Invalid LANDINGPAD record");
2354 Type *Ty = getTypeByID(Record[Idx++]);
2355 if (!Ty) return Error("Invalid LANDINGPAD record");
2356 Value *PersFn = 0;
2357 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2358 return Error("Invalid LANDINGPAD record");
2359
2360 bool IsCleanup = !!Record[Idx++];
2361 unsigned NumClauses = Record[Idx++];
2362 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2363 LP->setCleanup(IsCleanup);
2364 for (unsigned J = 0; J != NumClauses; ++J) {
2365 LandingPadInst::ClauseType CT =
2366 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2367 Value *Val;
2368
2369 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2370 delete LP;
2371 return Error("Invalid LANDINGPAD record");
2372 }
2373
2374 assert((CT != LandingPadInst::Catch ||
2375 !isa<ArrayType>(Val->getType())) &&
2376 "Catch clause has a invalid type!");
2377 assert((CT != LandingPadInst::Filter ||
2378 isa<ArrayType>(Val->getType())) &&
2379 "Filter clause has invalid type!");
2380 LP->addClause(Val);
2381 }
2382
2383 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002384 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002385 break;
2386 }
2387
Chris Lattner96a74c52011-06-17 18:09:11 +00002388 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2389 if (Record.size() != 4)
2390 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002391 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002392 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002393 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002394 Value *Size = getFnValueByID(Record[2], OpTy);
2395 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002396 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002397 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002398 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002399 break;
2400 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002401 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002402 unsigned OpNum = 0;
2403 Value *Op;
2404 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2405 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002406 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002407
Chris Lattner7337ab92007-05-06 00:00:00 +00002408 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002409 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002410 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002411 }
Eli Friedman21006d42011-08-09 23:02:53 +00002412 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2413 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2414 unsigned OpNum = 0;
2415 Value *Op;
2416 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2417 OpNum+4 != Record.size())
2418 return Error("Invalid LOADATOMIC record");
2419
2420
2421 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2422 if (Ordering == NotAtomic || Ordering == Release ||
2423 Ordering == AcquireRelease)
2424 return Error("Invalid LOADATOMIC record");
2425 if (Ordering != NotAtomic && Record[OpNum] == 0)
2426 return Error("Invalid LOADATOMIC record");
2427 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2428
2429 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2430 Ordering, SynchScope);
2431 InstructionList.push_back(I);
2432 break;
2433 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002434 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002435 unsigned OpNum = 0;
2436 Value *Val, *Ptr;
2437 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002438 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002439 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2440 OpNum+2 != Record.size())
2441 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002442
Christopher Lambfe63fb92007-12-11 08:59:05 +00002443 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002444 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002445 break;
2446 }
Eli Friedman21006d42011-08-09 23:02:53 +00002447 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2448 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2449 unsigned OpNum = 0;
2450 Value *Val, *Ptr;
2451 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2452 getValue(Record, OpNum,
2453 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2454 OpNum+4 != Record.size())
2455 return Error("Invalid STOREATOMIC record");
2456
2457 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002458 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002459 Ordering == AcquireRelease)
2460 return Error("Invalid STOREATOMIC record");
2461 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2462 if (Ordering != NotAtomic && Record[OpNum] == 0)
2463 return Error("Invalid STOREATOMIC record");
2464
2465 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2466 Ordering, SynchScope);
2467 InstructionList.push_back(I);
2468 break;
2469 }
Eli Friedmanff030482011-07-28 21:48:00 +00002470 case bitc::FUNC_CODE_INST_CMPXCHG: {
2471 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2472 unsigned OpNum = 0;
2473 Value *Ptr, *Cmp, *New;
2474 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2475 getValue(Record, OpNum,
2476 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2477 getValue(Record, OpNum,
2478 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2479 OpNum+3 != Record.size())
2480 return Error("Invalid CMPXCHG record");
2481 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002482 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002483 return Error("Invalid CMPXCHG record");
2484 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2485 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2486 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2487 InstructionList.push_back(I);
2488 break;
2489 }
2490 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2491 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2492 unsigned OpNum = 0;
2493 Value *Ptr, *Val;
2494 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2495 getValue(Record, OpNum,
2496 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2497 OpNum+4 != Record.size())
2498 return Error("Invalid ATOMICRMW record");
2499 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2500 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2501 Operation > AtomicRMWInst::LAST_BINOP)
2502 return Error("Invalid ATOMICRMW record");
2503 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002504 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002505 return Error("Invalid ATOMICRMW record");
2506 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2507 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2508 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2509 InstructionList.push_back(I);
2510 break;
2511 }
Eli Friedman47f35132011-07-25 23:16:38 +00002512 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2513 if (2 != Record.size())
2514 return Error("Invalid FENCE record");
2515 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2516 if (Ordering == NotAtomic || Ordering == Unordered ||
2517 Ordering == Monotonic)
2518 return Error("Invalid FENCE record");
2519 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2520 I = new FenceInst(Context, Ordering, SynchScope);
2521 InstructionList.push_back(I);
2522 break;
2523 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002524 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002525 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2526 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002527 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002528
Devang Patel05988662008-09-25 21:00:45 +00002529 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002530 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002531
Chris Lattnera9bb7132007-05-08 05:38:01 +00002532 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002533 Value *Callee;
2534 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2535 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002536
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002537 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2538 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002539 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002540 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002541 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002542
Chris Lattner0579f7f2007-05-03 22:04:19 +00002543 SmallVector<Value*, 16> Args;
2544 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002545 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002546 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002547 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002548 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002549 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002550 if (Args.back() == 0) return Error("Invalid CALL record");
2551 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002552
Chris Lattner0579f7f2007-05-03 22:04:19 +00002553 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002554 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002555 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002556 return Error("Invalid CALL record");
2557 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002558 while (OpNum != Record.size()) {
2559 Value *Op;
2560 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2561 return Error("Invalid CALL record");
2562 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002563 }
2564 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002565
Jay Foada3efbb12011-07-15 08:37:34 +00002566 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002567 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002568 cast<CallInst>(I)->setCallingConv(
2569 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002570 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002571 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002572 break;
2573 }
2574 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2575 if (Record.size() < 3)
2576 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002577 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002578 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002579 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002580 if (!OpTy || !Op || !ResTy)
2581 return Error("Invalid VAARG record");
2582 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002583 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002584 break;
2585 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002586 }
2587
2588 // Add instruction to end of current BB. If there is no current BB, reject
2589 // this file.
2590 if (CurBB == 0) {
2591 delete I;
2592 return Error("Invalid instruction with no BB");
2593 }
2594 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002595
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002596 // If this was a terminator instruction, move to the next block.
2597 if (isa<TerminatorInst>(I)) {
2598 ++CurBBNo;
2599 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2600 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002601
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002602 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002603 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002604 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002605 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002606
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002607 // Check the function list for unresolved values.
2608 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2609 if (A->getParent() == 0) {
2610 // We found at least one unresolved value. Nuke them all to avoid leaks.
2611 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002612 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002613 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002614 delete A;
2615 }
2616 }
Chris Lattner35a04702007-05-04 03:50:29 +00002617 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002618 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002619 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002620
Dan Gohman064ff3e2010-08-25 20:23:38 +00002621 // FIXME: Check for unresolved forward-declared metadata references
2622 // and clean up leaks.
2623
Chris Lattner50b136d2009-10-28 05:53:48 +00002624 // See if anything took the address of blocks in this function. If so,
2625 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002626 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2627 BlockAddrFwdRefs.find(F);
2628 if (BAFRI != BlockAddrFwdRefs.end()) {
2629 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2630 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2631 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002632 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002633 return Error("Invalid blockaddress block #");
2634
2635 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002636 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002637 FwdRef->eraseFromParent();
2638 }
2639
2640 BlockAddrFwdRefs.erase(BAFRI);
2641 }
2642
Chris Lattner980e5aa2007-05-01 05:52:21 +00002643 // Trim the value list down to the size it was before we parsed this function.
2644 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002645 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002646 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002647 return false;
2648}
2649
Derek Schuff2ea93872012-02-06 22:30:29 +00002650/// FindFunctionInStream - Find the function body in the bitcode stream
2651bool BitcodeReader::FindFunctionInStream(Function *F,
2652 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2653 while (DeferredFunctionInfoIterator->second == 0) {
2654 if (Stream.AtEndOfStream())
2655 return Error("Could not find Function in stream");
2656 // ParseModule will parse the next body in the stream and set its
2657 // position in the DeferredFunctionInfo map.
2658 if (ParseModule(true)) return true;
2659 }
2660 return false;
2661}
2662
Chris Lattnerb348bb82007-05-18 04:02:46 +00002663//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002664// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002665//===----------------------------------------------------------------------===//
2666
2667
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002668bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2669 if (const Function *F = dyn_cast<Function>(GV)) {
2670 return F->isDeclaration() &&
2671 DeferredFunctionInfo.count(const_cast<Function*>(F));
2672 }
2673 return false;
2674}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002675
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002676bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2677 Function *F = dyn_cast<Function>(GV);
2678 // If it's not a function or is already material, ignore the request.
2679 if (!F || !F->isMaterializable()) return false;
2680
2681 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002682 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002683 // If its position is recorded as 0, its body is somewhere in the stream
2684 // but we haven't seen it yet.
2685 if (DFII->second == 0)
2686 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002687
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002688 // Move the bit stream to the saved position of the deferred function body.
2689 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002690
Chris Lattnerb348bb82007-05-18 04:02:46 +00002691 if (ParseFunctionBody(F)) {
2692 if (ErrInfo) *ErrInfo = ErrorString;
2693 return true;
2694 }
Chandler Carruth69940402007-08-04 01:51:18 +00002695
2696 // Upgrade any old intrinsic calls in the function.
2697 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2698 E = UpgradedIntrinsics.end(); I != E; ++I) {
2699 if (I->first != I->second) {
2700 for (Value::use_iterator UI = I->first->use_begin(),
2701 UE = I->first->use_end(); UI != UE; ) {
2702 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2703 UpgradeIntrinsicCall(CI, I->second);
2704 }
2705 }
2706 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002707
Chris Lattnerb348bb82007-05-18 04:02:46 +00002708 return false;
2709}
2710
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002711bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2712 const Function *F = dyn_cast<Function>(GV);
2713 if (!F || F->isDeclaration())
2714 return false;
2715 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2716}
2717
2718void BitcodeReader::Dematerialize(GlobalValue *GV) {
2719 Function *F = dyn_cast<Function>(GV);
2720 // If this function isn't dematerializable, this is a noop.
2721 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002722 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002723
Chris Lattnerb348bb82007-05-18 04:02:46 +00002724 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002725
Chris Lattnerb348bb82007-05-18 04:02:46 +00002726 // Just forget the function body, we can remat it later.
2727 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002728}
2729
2730
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002731bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2732 assert(M == TheModule &&
2733 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002734 // Iterate over the module, deserializing any functions that are still on
2735 // disk.
2736 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2737 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002738 if (F->isMaterializable() &&
2739 Materialize(F, ErrInfo))
2740 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002741
Derek Schuff0ffe6982012-02-29 00:07:09 +00002742 // At this point, if there are any function bodies, the current bit is
2743 // pointing to the END_BLOCK record after them. Now make sure the rest
2744 // of the bits in the module have been read.
2745 if (NextUnreadBit)
2746 ParseModule(true);
2747
Daniel Dunbara279bc32009-09-20 02:20:51 +00002748 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2749 // delete the old functions to clean up. We can't do this unless the entire
2750 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002751 // with calls to the old function.
2752 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2753 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2754 if (I->first != I->second) {
2755 for (Value::use_iterator UI = I->first->use_begin(),
2756 UE = I->first->use_end(); UI != UE; ) {
2757 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2758 UpgradeIntrinsicCall(CI, I->second);
2759 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002760 if (!I->first->use_empty())
2761 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002762 I->first->eraseFromParent();
2763 }
2764 }
2765 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002766
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002767 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002768}
2769
Derek Schuff2ea93872012-02-06 22:30:29 +00002770bool BitcodeReader::InitStream() {
2771 if (LazyStreamer) return InitLazyStream();
2772 return InitStreamFromBuffer();
2773}
2774
2775bool BitcodeReader::InitStreamFromBuffer() {
2776 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2777 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2778
2779 if (Buffer->getBufferSize() & 3) {
2780 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2781 return Error("Invalid bitcode signature");
2782 else
2783 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2784 }
2785
2786 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2787 // The magic number is 0x0B17C0DE stored in little endian.
2788 if (isBitcodeWrapper(BufPtr, BufEnd))
2789 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2790 return Error("Invalid bitcode wrapper header");
2791
2792 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2793 Stream.init(*StreamFile);
2794
2795 return false;
2796}
2797
2798bool BitcodeReader::InitLazyStream() {
2799 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2800 // see it.
2801 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2802 StreamFile.reset(new BitstreamReader(Bytes));
2803 Stream.init(*StreamFile);
2804
2805 unsigned char buf[16];
2806 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2807 return Error("Bitcode stream must be at least 16 bytes in length");
2808
2809 if (!isBitcode(buf, buf + 16))
2810 return Error("Invalid bitcode signature");
2811
2812 if (isBitcodeWrapper(buf, buf + 4)) {
2813 const unsigned char *bitcodeStart = buf;
2814 const unsigned char *bitcodeEnd = buf + 16;
2815 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2816 Bytes->dropLeadingBytes(bitcodeStart - buf);
2817 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2818 }
2819 return false;
2820}
Chris Lattner48f84872007-05-01 04:59:48 +00002821
Chris Lattnerc453f762007-04-29 07:54:31 +00002822//===----------------------------------------------------------------------===//
2823// External interface
2824//===----------------------------------------------------------------------===//
2825
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002826/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002827///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002828Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2829 LLVMContext& Context,
2830 std::string *ErrMsg) {
2831 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002832 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002833 M->setMaterializer(R);
2834 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002835 if (ErrMsg)
2836 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002837
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002838 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002839 return 0;
2840 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002841 // Have the BitcodeReader dtor delete 'Buffer'.
2842 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002843
2844 R->materializeForwardReferencedFunctions();
2845
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002846 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002847}
2848
Derek Schuff2ea93872012-02-06 22:30:29 +00002849
2850Module *llvm::getStreamedBitcodeModule(const std::string &name,
2851 DataStreamer *streamer,
2852 LLVMContext &Context,
2853 std::string *ErrMsg) {
2854 Module *M = new Module(name, Context);
2855 BitcodeReader *R = new BitcodeReader(streamer, Context);
2856 M->setMaterializer(R);
2857 if (R->ParseBitcodeInto(M)) {
2858 if (ErrMsg)
2859 *ErrMsg = R->getErrorString();
2860 delete M; // Also deletes R.
2861 return 0;
2862 }
2863 R->setBufferOwned(false); // no buffer to delete
2864 return M;
2865}
2866
Chris Lattnerc453f762007-04-29 07:54:31 +00002867/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2868/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002869Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002870 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002871 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2872 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002873
2874 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2875 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002876 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002877
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002878 // Read in the entire module, and destroy the BitcodeReader.
2879 if (M->MaterializeAllPermanently(ErrMsg)) {
2880 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002881 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002882 }
Bill Wendling34711742010-10-06 01:22:42 +00002883
Chad Rosiercbbb0962011-12-07 21:44:12 +00002884 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2885 // written. We must defer until the Module has been fully materialized.
2886
Chris Lattnerc453f762007-04-29 07:54:31 +00002887 return M;
2888}
Bill Wendling34711742010-10-06 01:22:42 +00002889
2890std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2891 LLVMContext& Context,
2892 std::string *ErrMsg) {
2893 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2894 // Don't let the BitcodeReader dtor delete 'Buffer'.
2895 R->setBufferOwned(false);
2896
2897 std::string Triple("");
2898 if (R->ParseTriple(Triple))
2899 if (ErrMsg)
2900 *ErrMsg = R->getErrorString();
2901
2902 delete R;
2903 return Triple;
2904}