blob: 81fdbd29afb95ed9efc046dc137b32a9488e6339 [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"
Chris Lattnera7c49aa2007-05-01 07:01:57 +000019#include "llvm/Instructions.h"
Owen Anderson74a77812009-07-07 20:18:58 +000020#include "llvm/LLVMContext.h"
Devang Patel0a9f7b92009-07-28 21:49:47 +000021#include "llvm/Metadata.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000022#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000023#include "llvm/Operator.h"
Chandler Carruth69940402007-08-04 01:51:18 +000024#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000025#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000027#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000028#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000029#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000030using namespace llvm;
31
Chris Lattnerb348bb82007-05-18 04:02:46 +000032void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000033 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000034 Buffer = 0;
35 std::vector<PATypeHolder>().swap(TypeList);
36 ValueList.clear();
Chris Lattner461edd92008-03-12 02:25:52 +000037
Devang Patel19c87462008-09-26 22:53:05 +000038 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000039 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000042}
43
Chris Lattner48c85b82007-05-04 03:30:17 +000044//===----------------------------------------------------------------------===//
45// Helper functions to implement forward reference resolution, etc.
46//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000047
Chris Lattnercaee0dc2007-04-22 06:23:29 +000048/// ConvertToString - Convert a string from a record into an std::string, return
49/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000050template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000051static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000052 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000053 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000054 return true;
55
Chris Lattner15e6d172007-05-04 19:11:41 +000056 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
57 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000058 return false;
59}
60
61static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
62 switch (Val) {
63 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000064 case 0: return GlobalValue::ExternalLinkage;
65 case 1: return GlobalValue::WeakAnyLinkage;
66 case 2: return GlobalValue::AppendingLinkage;
67 case 3: return GlobalValue::InternalLinkage;
68 case 4: return GlobalValue::LinkOnceAnyLinkage;
69 case 5: return GlobalValue::DLLImportLinkage;
70 case 6: return GlobalValue::DLLExportLinkage;
71 case 7: return GlobalValue::ExternalWeakLinkage;
72 case 8: return GlobalValue::CommonLinkage;
73 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000074 case 10: return GlobalValue::WeakODRLinkage;
75 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000076 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000077 case 13: return GlobalValue::LinkerPrivateLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000078 }
79}
80
81static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
82 switch (Val) {
83 default: // Map unknown visibilities to default.
84 case 0: return GlobalValue::DefaultVisibility;
85 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000086 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000087 }
88}
89
Chris Lattnerf581c3b2007-04-24 07:07:11 +000090static int GetDecodedCastOpcode(unsigned Val) {
91 switch (Val) {
92 default: return -1;
93 case bitc::CAST_TRUNC : return Instruction::Trunc;
94 case bitc::CAST_ZEXT : return Instruction::ZExt;
95 case bitc::CAST_SEXT : return Instruction::SExt;
96 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
97 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
98 case bitc::CAST_UITOFP : return Instruction::UIToFP;
99 case bitc::CAST_SITOFP : return Instruction::SIToFP;
100 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
101 case bitc::CAST_FPEXT : return Instruction::FPExt;
102 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
103 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
104 case bitc::CAST_BITCAST : return Instruction::BitCast;
105 }
106}
107static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
108 switch (Val) {
109 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000110 case bitc::BINOP_ADD:
111 return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add;
112 case bitc::BINOP_SUB:
113 return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub;
114 case bitc::BINOP_MUL:
115 return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000116 case bitc::BINOP_UDIV: return Instruction::UDiv;
117 case bitc::BINOP_SDIV:
118 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
119 case bitc::BINOP_UREM: return Instruction::URem;
120 case bitc::BINOP_SREM:
121 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
122 case bitc::BINOP_SHL: return Instruction::Shl;
123 case bitc::BINOP_LSHR: return Instruction::LShr;
124 case bitc::BINOP_ASHR: return Instruction::AShr;
125 case bitc::BINOP_AND: return Instruction::And;
126 case bitc::BINOP_OR: return Instruction::Or;
127 case bitc::BINOP_XOR: return Instruction::Xor;
128 }
129}
130
Gabor Greifefe65362008-05-10 08:32:32 +0000131namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000132namespace {
133 /// @brief A class for maintaining the slot number definition
134 /// as a placeholder for the actual definition for forward constants defs.
135 class ConstantPlaceHolder : public ConstantExpr {
136 ConstantPlaceHolder(); // DO NOT IMPLEMENT
137 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000138 public:
139 // allocate space for exactly one operand
140 void *operator new(size_t s) {
141 return User::operator new(s, 1);
142 }
Owen Anderson74a77812009-07-07 20:18:58 +0000143 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000144 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000145 Op<0>() = UndefValue::get(Type::Int32Ty);
Chris Lattner522b7b12007-04-24 05:48:56 +0000146 }
Chris Lattnerea693df2008-08-21 02:34:16 +0000147
148 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
149 static inline bool classof(const ConstantPlaceHolder *) { return true; }
150 static bool classof(const Value *V) {
151 return isa<ConstantExpr>(V) &&
152 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
153 }
154
155
Gabor Greifefe65362008-05-10 08:32:32 +0000156 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000157 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000158 };
159}
160
Chris Lattner46e77402009-03-31 22:55:09 +0000161// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000162template <>
163struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
164};
Gabor Greifefe65362008-05-10 08:32:32 +0000165}
166
Chris Lattner46e77402009-03-31 22:55:09 +0000167
168void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
169 if (Idx == size()) {
170 push_back(V);
171 return;
172 }
173
174 if (Idx >= size())
175 resize(Idx+1);
176
177 WeakVH &OldV = ValuePtrs[Idx];
178 if (OldV == 0) {
179 OldV = V;
180 return;
181 }
182
183 // Handle constants and non-constants (e.g. instrs) differently for
184 // efficiency.
185 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
186 ResolveConstants.push_back(std::make_pair(PHC, Idx));
187 OldV = V;
188 } else {
189 // If there was a forward reference to this value, replace it.
190 Value *PrevVal = OldV;
191 OldV->replaceAllUsesWith(V);
192 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000193 }
194}
Chris Lattner46e77402009-03-31 22:55:09 +0000195
Gabor Greifefe65362008-05-10 08:32:32 +0000196
Chris Lattner522b7b12007-04-24 05:48:56 +0000197Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
198 const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000199 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000200 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000201
Chris Lattner46e77402009-03-31 22:55:09 +0000202 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000203 assert(Ty == V->getType() && "Type mismatch in constant table!");
204 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000205 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000206
207 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000208 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000209 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000210 return C;
211}
212
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000213Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000214 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000215 resize(Idx + 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000216
Chris Lattner46e77402009-03-31 22:55:09 +0000217 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000218 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
219 return V;
220 }
221
Chris Lattner01ff65f2007-05-02 05:16:49 +0000222 // No type specified, must be invalid reference.
223 if (Ty == 0) return 0;
224
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000225 // Create and return a placeholder, which will later be RAUW'd.
226 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000227 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000228 return V;
229}
230
Chris Lattnerea693df2008-08-21 02:34:16 +0000231/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
232/// resolves any forward references. The idea behind this is that we sometimes
233/// get constants (such as large arrays) which reference *many* forward ref
234/// constants. Replacing each of these causes a lot of thrashing when
235/// building/reuniquing the constant. Instead of doing this, we look at all the
236/// uses and rewrite all the place holders at once for any constant that uses
237/// a placeholder.
238void BitcodeReaderValueList::ResolveConstantForwardRefs() {
239 // Sort the values by-pointer so that they are efficient to look up with a
240 // binary search.
241 std::sort(ResolveConstants.begin(), ResolveConstants.end());
242
243 SmallVector<Constant*, 64> NewOps;
244
245 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000246 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000247 Constant *Placeholder = ResolveConstants.back().first;
248 ResolveConstants.pop_back();
249
250 // Loop over all users of the placeholder, updating them to reference the
251 // new value. If they reference more than one placeholder, update them all
252 // at once.
253 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000254 Value::use_iterator UI = Placeholder->use_begin();
255
Chris Lattnerea693df2008-08-21 02:34:16 +0000256 // If the using object isn't uniqued, just update the operands. This
257 // handles instructions and initializers for global variables.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000258 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
259 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000260 continue;
261 }
262
263 // Otherwise, we have a constant that uses the placeholder. Replace that
264 // constant with a new constant that has *all* placeholder uses updated.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000265 Constant *UserC = cast<Constant>(*UI);
Chris Lattnerea693df2008-08-21 02:34:16 +0000266 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
267 I != E; ++I) {
268 Value *NewOp;
269 if (!isa<ConstantPlaceHolder>(*I)) {
270 // Not a placeholder reference.
271 NewOp = *I;
272 } else if (*I == Placeholder) {
273 // Common case is that it just references this one placeholder.
274 NewOp = RealVal;
275 } else {
276 // Otherwise, look up the placeholder in ResolveConstants.
277 ResolveConstantsTy::iterator It =
278 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
279 std::pair<Constant*, unsigned>(cast<Constant>(*I),
280 0));
281 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000282 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000283 }
284
285 NewOps.push_back(cast<Constant>(NewOp));
286 }
287
288 // Make the new constant.
289 Constant *NewC;
290 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Owen Anderson1fd70962009-07-28 18:32:17 +0000291 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
Owen Anderson74a77812009-07-07 20:18:58 +0000292 NewOps.size());
Chris Lattnerea693df2008-08-21 02:34:16 +0000293 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Owen Anderson8fa33382009-07-27 22:29:26 +0000294 NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
Owen Anderson74a77812009-07-07 20:18:58 +0000295 UserCS->getType()->isPacked());
Chris Lattnerea693df2008-08-21 02:34:16 +0000296 } else if (isa<ConstantVector>(UserC)) {
Owen Andersonaf7ec972009-07-28 21:19:26 +0000297 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
Nick Lewyckycb337992009-05-10 20:57:05 +0000298 } else {
299 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Chris Lattnerea693df2008-08-21 02:34:16 +0000300 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
301 NewOps.size());
302 }
303
304 UserC->replaceAllUsesWith(NewC);
305 UserC->destroyConstant();
306 NewOps.clear();
307 }
308
Nick Lewyckycb337992009-05-10 20:57:05 +0000309 // Update all ValueHandles, they should be the only users at this point.
310 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000311 delete Placeholder;
312 }
313}
314
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000315
316const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
317 // If the TypeID is in range, return it.
318 if (ID < TypeList.size())
319 return TypeList[ID].get();
320 if (!isTypeTable) return 0;
321
322 // The type table allows forward references. Push as many Opaque types as
323 // needed to get up to ID.
324 while (TypeList.size() <= ID)
Owen Andersondebcb012009-07-29 22:17:13 +0000325 TypeList.push_back(OpaqueType::get());
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000326 return TypeList.back().get();
327}
328
Chris Lattner48c85b82007-05-04 03:30:17 +0000329//===----------------------------------------------------------------------===//
330// Functions for parsing blocks from the bitcode file
331//===----------------------------------------------------------------------===//
332
Devang Patel05988662008-09-25 21:00:45 +0000333bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000334 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000335 return Error("Malformed block record");
336
Devang Patel19c87462008-09-26 22:53:05 +0000337 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000338 return Error("Multiple PARAMATTR blocks found!");
339
340 SmallVector<uint64_t, 64> Record;
341
Devang Patel05988662008-09-25 21:00:45 +0000342 SmallVector<AttributeWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000343
344 // Read all the records.
345 while (1) {
346 unsigned Code = Stream.ReadCode();
347 if (Code == bitc::END_BLOCK) {
348 if (Stream.ReadBlockEnd())
349 return Error("Error at end of PARAMATTR block");
350 return false;
351 }
352
353 if (Code == bitc::ENTER_SUBBLOCK) {
354 // No known subblocks, always skip them.
355 Stream.ReadSubBlockID();
356 if (Stream.SkipBlock())
357 return Error("Malformed block record");
358 continue;
359 }
360
361 if (Code == bitc::DEFINE_ABBREV) {
362 Stream.ReadAbbrevRecord();
363 continue;
364 }
365
366 // Read a record.
367 Record.clear();
368 switch (Stream.ReadRecord(Code, Record)) {
369 default: // Default behavior: ignore.
370 break;
371 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
372 if (Record.size() & 1)
373 return Error("Invalid ENTRY record");
374
Chris Lattner9a6cb152008-10-05 18:22:09 +0000375 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000376 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000377 // to index ~0. Index 0 is used for return value attributes but used to be
378 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000379 Attributes RetAttribute = Attribute::None;
380 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000381 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000382 // FIXME: remove in LLVM 3.0
383 // The alignment is stored as a 16-bit raw value from bits 31--16.
384 // We shift the bits above 31 down by 11 bits.
385
386 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
387 if (Alignment && !isPowerOf2_32(Alignment))
388 return Error("Alignment is not a power of two.");
389
390 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
391 if (Alignment)
392 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
393 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
394 Record[i+1] = ReconstitutedAttr;
395
Devang Patel19c87462008-09-26 22:53:05 +0000396 if (Record[i] == 0)
397 RetAttribute = Record[i+1];
398 else if (Record[i] == ~0U)
399 FnAttribute = Record[i+1];
400 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000401
402 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
403 Attribute::ReadOnly|Attribute::ReadNone);
404
405 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
406 (RetAttribute & OldRetAttrs) != 0) {
407 if (FnAttribute == Attribute::None) { // add a slot so they get added.
408 Record.push_back(~0U);
409 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000410 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000411
412 FnAttribute |= RetAttribute & OldRetAttrs;
413 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000414 }
Chris Lattner461edd92008-03-12 02:25:52 +0000415
Devang Patel19c87462008-09-26 22:53:05 +0000416 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000417 if (Record[i] == 0) {
418 if (RetAttribute != Attribute::None)
419 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
420 } else if (Record[i] == ~0U) {
421 if (FnAttribute != Attribute::None)
422 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
423 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000424 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
425 }
Devang Patel19c87462008-09-26 22:53:05 +0000426
427 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000428 Attrs.clear();
429 break;
430 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000431 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000432 }
433}
434
435
Chris Lattner86697142007-05-01 05:01:34 +0000436bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000437 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000438 return Error("Malformed block record");
439
440 if (!TypeList.empty())
441 return Error("Multiple TYPE_BLOCKs found!");
442
443 SmallVector<uint64_t, 64> Record;
444 unsigned NumRecords = 0;
445
446 // Read all the records for this type table.
447 while (1) {
448 unsigned Code = Stream.ReadCode();
449 if (Code == bitc::END_BLOCK) {
450 if (NumRecords != TypeList.size())
451 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000452 if (Stream.ReadBlockEnd())
453 return Error("Error at end of type table block");
454 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000455 }
456
457 if (Code == bitc::ENTER_SUBBLOCK) {
458 // No known subblocks, always skip them.
459 Stream.ReadSubBlockID();
460 if (Stream.SkipBlock())
461 return Error("Malformed block record");
462 continue;
463 }
464
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000465 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000466 Stream.ReadAbbrevRecord();
467 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000468 }
469
470 // Read a record.
471 Record.clear();
472 const Type *ResultTy = 0;
473 switch (Stream.ReadRecord(Code, Record)) {
474 default: // Default behavior: unknown type.
475 ResultTy = 0;
476 break;
477 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
478 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
479 // type list. This allows us to reserve space.
480 if (Record.size() < 1)
481 return Error("Invalid TYPE_CODE_NUMENTRY record");
482 TypeList.reserve(Record[0]);
483 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000484 case bitc::TYPE_CODE_VOID: // VOID
485 ResultTy = Type::VoidTy;
486 break;
487 case bitc::TYPE_CODE_FLOAT: // FLOAT
488 ResultTy = Type::FloatTy;
489 break;
490 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
491 ResultTy = Type::DoubleTy;
492 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000493 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
494 ResultTy = Type::X86_FP80Ty;
495 break;
496 case bitc::TYPE_CODE_FP128: // FP128
497 ResultTy = Type::FP128Ty;
498 break;
499 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
500 ResultTy = Type::PPC_FP128Ty;
501 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000502 case bitc::TYPE_CODE_LABEL: // LABEL
503 ResultTy = Type::LabelTy;
504 break;
505 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
506 ResultTy = 0;
507 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000508 case bitc::TYPE_CODE_METADATA: // METADATA
509 ResultTy = Type::MetadataTy;
510 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000511 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
512 if (Record.size() < 1)
513 return Error("Invalid Integer type record");
514
Owen Andersondebcb012009-07-29 22:17:13 +0000515 ResultTy = IntegerType::get(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000516 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000517 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
518 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000519 if (Record.size() < 1)
520 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000521 unsigned AddressSpace = 0;
522 if (Record.size() == 2)
523 AddressSpace = Record[1];
Owen Andersondebcb012009-07-29 22:17:13 +0000524 ResultTy = PointerType::get(getTypeByID(Record[0], true),
Owen Anderson74a77812009-07-07 20:18:58 +0000525 AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000526 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000527 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000528 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000529 // FIXME: attrid is dead, remove it in LLVM 3.0
530 // FUNCTION: [vararg, attrid, retty, paramty x N]
531 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000532 return Error("Invalid FUNCTION type record");
533 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000534 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000535 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000536
Owen Andersondebcb012009-07-29 22:17:13 +0000537 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000538 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000539 break;
540 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000541 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000542 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000543 return Error("Invalid STRUCT type record");
544 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000545 for (unsigned i = 1, e = Record.size(); i != e; ++i)
546 EltTys.push_back(getTypeByID(Record[i], true));
Owen Andersondebcb012009-07-29 22:17:13 +0000547 ResultTy = StructType::get(EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000548 break;
549 }
550 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
551 if (Record.size() < 2)
552 return Error("Invalid ARRAY type record");
Owen Andersondebcb012009-07-29 22:17:13 +0000553 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000554 break;
555 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
556 if (Record.size() < 2)
557 return Error("Invalid VECTOR type record");
Owen Andersondebcb012009-07-29 22:17:13 +0000558 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000559 break;
560 }
561
562 if (NumRecords == TypeList.size()) {
563 // If this is a new type slot, just append it.
Owen Andersondebcb012009-07-29 22:17:13 +0000564 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000565 ++NumRecords;
566 } else if (ResultTy == 0) {
567 // Otherwise, this was forward referenced, so an opaque type was created,
568 // but the result type is actually just an opaque. Leave the one we
569 // created previously.
570 ++NumRecords;
571 } else {
572 // Otherwise, this was forward referenced, so an opaque type was created.
573 // Resolve the opaque type to the real type now.
574 assert(NumRecords < TypeList.size() && "Typelist imbalance");
575 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
576
577 // Don't directly push the new type on the Tab. Instead we want to replace
578 // the opaque type we previously inserted with the new concrete value. The
579 // refinement from the abstract (opaque) type to the new type causes all
580 // uses of the abstract type to use the concrete type (NewTy). This will
581 // also cause the opaque type to be deleted.
582 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
583
584 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000585 // value table... or with a preexisting type that was already in the
586 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000587 assert(TypeList[NumRecords-1].get() != OldTy &&
588 "refineAbstractType didn't work!");
589 }
590 }
591}
592
593
Chris Lattner86697142007-05-01 05:01:34 +0000594bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000595 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000596 return Error("Malformed block record");
597
598 SmallVector<uint64_t, 64> Record;
599
600 // Read all the records for this type table.
601 std::string TypeName;
602 while (1) {
603 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000604 if (Code == bitc::END_BLOCK) {
605 if (Stream.ReadBlockEnd())
606 return Error("Error at end of type symbol table block");
607 return false;
608 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000609
610 if (Code == bitc::ENTER_SUBBLOCK) {
611 // No known subblocks, always skip them.
612 Stream.ReadSubBlockID();
613 if (Stream.SkipBlock())
614 return Error("Malformed block record");
615 continue;
616 }
617
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000618 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000619 Stream.ReadAbbrevRecord();
620 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000621 }
622
623 // Read a record.
624 Record.clear();
625 switch (Stream.ReadRecord(Code, Record)) {
626 default: // Default behavior: unknown type.
627 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000628 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000629 if (ConvertToString(Record, 1, TypeName))
630 return Error("Invalid TST_ENTRY record");
631 unsigned TypeID = Record[0];
632 if (TypeID >= TypeList.size())
633 return Error("Invalid Type ID in TST_ENTRY record");
634
635 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
636 TypeName.clear();
637 break;
638 }
639 }
640}
641
Chris Lattner86697142007-05-01 05:01:34 +0000642bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000643 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000644 return Error("Malformed block record");
645
646 SmallVector<uint64_t, 64> Record;
647
648 // Read all the records for this value table.
649 SmallString<128> ValueName;
650 while (1) {
651 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000652 if (Code == bitc::END_BLOCK) {
653 if (Stream.ReadBlockEnd())
654 return Error("Error at end of value symbol table block");
655 return false;
656 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000657 if (Code == bitc::ENTER_SUBBLOCK) {
658 // No known subblocks, always skip them.
659 Stream.ReadSubBlockID();
660 if (Stream.SkipBlock())
661 return Error("Malformed block record");
662 continue;
663 }
664
665 if (Code == bitc::DEFINE_ABBREV) {
666 Stream.ReadAbbrevRecord();
667 continue;
668 }
669
670 // Read a record.
671 Record.clear();
672 switch (Stream.ReadRecord(Code, Record)) {
673 default: // Default behavior: unknown type.
674 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000675 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000676 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000677 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000678 unsigned ValueID = Record[0];
679 if (ValueID >= ValueList.size())
680 return Error("Invalid Value ID in VST_ENTRY record");
681 Value *V = ValueList[ValueID];
682
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000683 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000684 ValueName.clear();
685 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000686 }
687 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000688 if (ConvertToString(Record, 1, ValueName))
689 return Error("Invalid VST_BBENTRY record");
690 BasicBlock *BB = getBasicBlock(Record[0]);
691 if (BB == 0)
692 return Error("Invalid BB ID in VST_BBENTRY record");
693
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000694 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000695 ValueName.clear();
696 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000697 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000698 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000699 }
700}
701
Devang Patele54abc92009-07-22 17:43:22 +0000702bool BitcodeReader::ParseMetadata() {
703 unsigned NextValueNo = ValueList.size();
704
705 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
706 return Error("Malformed block record");
707
708 SmallVector<uint64_t, 64> Record;
709
710 // Read all the records.
711 while (1) {
712 unsigned Code = Stream.ReadCode();
713 if (Code == bitc::END_BLOCK) {
714 if (Stream.ReadBlockEnd())
715 return Error("Error at end of PARAMATTR block");
716 return false;
717 }
718
719 if (Code == bitc::ENTER_SUBBLOCK) {
720 // No known subblocks, always skip them.
721 Stream.ReadSubBlockID();
722 if (Stream.SkipBlock())
723 return Error("Malformed block record");
724 continue;
725 }
726
727 if (Code == bitc::DEFINE_ABBREV) {
728 Stream.ReadAbbrevRecord();
729 continue;
730 }
731
732 // Read a record.
733 Record.clear();
734 switch (Stream.ReadRecord(Code, Record)) {
735 default: // Default behavior: ignore.
736 break;
Devang Patelaa993142009-07-29 22:34:41 +0000737 case bitc::METADATA_NAME: {
738 // Read named of the named metadata.
739 unsigned NameLength = Record.size();
740 SmallString<8> Name;
741 Name.resize(NameLength);
742 for (unsigned i = 0; i != NameLength; ++i)
743 Name[i] = Record[i];
744 Record.clear();
745 Code = Stream.ReadCode();
746
747 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
748 if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
749 assert ( 0 && "Inavlid Named Metadata record");
750
751 // Read named metadata elements.
752 unsigned Size = Record.size();
753 SmallVector<MetadataBase*, 8> Elts;
754 for (unsigned i = 0; i != Size; ++i) {
755 Value *MD = ValueList.getValueFwdRef(Record[i], Type::MetadataTy);
756 if (MetadataBase *B = dyn_cast<MetadataBase>(MD))
757 Elts.push_back(B);
758 }
759 Value *V = NamedMDNode::Create(Name.c_str(), Elts.data(), Elts.size(),
760 TheModule);
761 ValueList.AssignValue(V, NextValueNo++);
762 break;
763 }
Devang Patel104cf9e2009-07-23 01:07:34 +0000764 case bitc::METADATA_NODE: {
765 if (Record.empty() || Record.size() % 2 == 1)
766 return Error("Invalid METADATA_NODE record");
767
768 unsigned Size = Record.size();
769 SmallVector<Value*, 8> Elts;
770 for (unsigned i = 0; i != Size; i += 2) {
771 const Type *Ty = getTypeByID(Record[i], false);
772 if (Ty != Type::VoidTy)
773 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
774 else
775 Elts.push_back(NULL);
776 }
Owen Anderson647e3012009-07-31 21:35:40 +0000777 Value *V = MDNode::get(Context, &Elts[0], Elts.size());
Devang Patel104cf9e2009-07-23 01:07:34 +0000778 ValueList.AssignValue(V, NextValueNo++);
779 break;
780 }
Devang Patele54abc92009-07-22 17:43:22 +0000781 case bitc::METADATA_STRING: {
782 unsigned MDStringLength = Record.size();
783 SmallString<8> String;
784 String.resize(MDStringLength);
785 for (unsigned i = 0; i != MDStringLength; ++i)
786 String[i] = Record[i];
Owen Anderson647e3012009-07-31 21:35:40 +0000787 Value *V = MDString::get(Context,
788 StringRef(String.data(), String.size()));
Devang Patele54abc92009-07-22 17:43:22 +0000789 ValueList.AssignValue(V, NextValueNo++);
790 break;
791 }
792 }
793 }
794}
795
Chris Lattner0eef0802007-04-24 04:04:35 +0000796/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
797/// the LSB for dense VBR encoding.
798static uint64_t DecodeSignRotatedValue(uint64_t V) {
799 if ((V & 1) == 0)
800 return V >> 1;
801 if (V != 1)
802 return -(V >> 1);
803 // There is no such thing as -0 with integers. "-0" really means MININT.
804 return 1ULL << 63;
805}
806
Chris Lattner07d98b42007-04-26 02:46:40 +0000807/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
808/// values and aliases that we can.
809bool BitcodeReader::ResolveGlobalAndAliasInits() {
810 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
811 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
812
813 GlobalInitWorklist.swap(GlobalInits);
814 AliasInitWorklist.swap(AliasInits);
815
816 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000817 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000818 if (ValID >= ValueList.size()) {
819 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000820 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000821 } else {
822 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
823 GlobalInitWorklist.back().first->setInitializer(C);
824 else
825 return Error("Global variable initializer is not a constant!");
826 }
827 GlobalInitWorklist.pop_back();
828 }
829
830 while (!AliasInitWorklist.empty()) {
831 unsigned ValID = AliasInitWorklist.back().second;
832 if (ValID >= ValueList.size()) {
833 AliasInits.push_back(AliasInitWorklist.back());
834 } else {
835 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000836 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000837 else
838 return Error("Alias initializer is not a constant!");
839 }
840 AliasInitWorklist.pop_back();
841 }
842 return false;
843}
844
Dan Gohman1224c382009-07-20 21:19:07 +0000845static void SetOptimizationFlags(Value *V, uint64_t Flags) {
846 if (OverflowingBinaryOperator *OBO =
847 dyn_cast<OverflowingBinaryOperator>(V)) {
848 if (Flags & (1 << bitc::OBO_NO_SIGNED_OVERFLOW))
849 OBO->setHasNoSignedOverflow(true);
850 if (Flags & (1 << bitc::OBO_NO_UNSIGNED_OVERFLOW))
851 OBO->setHasNoUnsignedOverflow(true);
852 } else if (SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
853 if (Flags & (1 << bitc::SDIV_EXACT))
854 Div->setIsExact(true);
855 }
856}
Chris Lattner07d98b42007-04-26 02:46:40 +0000857
Chris Lattner86697142007-05-01 05:01:34 +0000858bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000859 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000860 return Error("Malformed block record");
861
862 SmallVector<uint64_t, 64> Record;
863
864 // Read all the records for this value table.
865 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000866 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000867 while (1) {
868 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000869 if (Code == bitc::END_BLOCK)
870 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000871
872 if (Code == bitc::ENTER_SUBBLOCK) {
873 // No known subblocks, always skip them.
874 Stream.ReadSubBlockID();
875 if (Stream.SkipBlock())
876 return Error("Malformed block record");
877 continue;
878 }
879
880 if (Code == bitc::DEFINE_ABBREV) {
881 Stream.ReadAbbrevRecord();
882 continue;
883 }
884
885 // Read a record.
886 Record.clear();
887 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000888 unsigned BitCode = Stream.ReadRecord(Code, Record);
889 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000890 default: // Default behavior: unknown constant
891 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000892 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000893 break;
894 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
895 if (Record.empty())
896 return Error("Malformed CST_SETTYPE record");
897 if (Record[0] >= TypeList.size())
898 return Error("Invalid Type ID in CST_SETTYPE record");
899 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000900 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000901 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000902 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000903 break;
904 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000905 if (!isa<IntegerType>(CurTy) || Record.empty())
906 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +0000907 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000908 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000909 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
910 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000911 return Error("Invalid WIDE_INTEGER record");
912
Chris Lattner15e6d172007-05-04 19:11:41 +0000913 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000914 SmallVector<uint64_t, 8> Words;
915 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000916 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000917 Words[i] = DecodeSignRotatedValue(Record[i]);
Owen Andersoneed707b2009-07-24 23:12:02 +0000918 V = ConstantInt::get(Context,
919 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
920 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000921 break;
922 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000923 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000924 if (Record.empty())
925 return Error("Invalid FLOAT record");
926 if (CurTy == Type::FloatTy)
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000927 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000928 else if (CurTy == Type::DoubleTy)
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000929 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000930 else if (CurTy == Type::X86_FP80Ty) {
931 // Bits are not stored the same way as a normal i80 APInt, compensate.
932 uint64_t Rearrange[2];
933 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
934 Rearrange[1] = Record[0] >> 48;
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000935 V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000936 } else if (CurTy == Type::FP128Ty)
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000937 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000938 else if (CurTy == Type::PPC_FP128Ty)
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000939 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000940 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000941 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000942 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000943 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000944
Chris Lattner15e6d172007-05-04 19:11:41 +0000945 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
946 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000947 return Error("Invalid CST_AGGREGATE record");
948
Chris Lattner15e6d172007-05-04 19:11:41 +0000949 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000950 std::vector<Constant*> Elts;
951
952 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
953 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000954 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000955 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +0000956 V = ConstantStruct::get(STy, Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +0000957 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
958 const Type *EltTy = ATy->getElementType();
959 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000960 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +0000961 V = ConstantArray::get(ATy, Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +0000962 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
963 const Type *EltTy = VTy->getElementType();
964 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000965 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +0000966 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +0000967 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000968 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +0000969 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000970 break;
971 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000972 case bitc::CST_CODE_STRING: { // STRING: [values]
973 if (Record.empty())
974 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000975
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000976 const ArrayType *ATy = cast<ArrayType>(CurTy);
977 const Type *EltTy = ATy->getElementType();
978
979 unsigned Size = Record.size();
980 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000981 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +0000982 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Anderson1fd70962009-07-28 18:32:17 +0000983 V = ConstantArray::get(ATy, Elts);
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000984 break;
985 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000986 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
987 if (Record.empty())
988 return Error("Invalid CST_AGGREGATE record");
989
990 const ArrayType *ATy = cast<ArrayType>(CurTy);
991 const Type *EltTy = ATy->getElementType();
992
993 unsigned Size = Record.size();
994 std::vector<Constant*> Elts;
995 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +0000996 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Andersona7235ea2009-07-31 20:28:14 +0000997 Elts.push_back(Constant::getNullValue(EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +0000998 V = ConstantArray::get(ATy, Elts);
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000999 break;
1000 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001001 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1002 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1003 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001004 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001005 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001006 } else {
1007 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1008 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001009 V = ConstantExpr::get(Opc, LHS, RHS);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001010 }
Dan Gohman1224c382009-07-20 21:19:07 +00001011 if (Record.size() >= 4)
1012 SetOptimizationFlags(V, Record[3]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001013 break;
1014 }
1015 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1016 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1017 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001018 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001019 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001020 } else {
1021 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001022 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001023 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001024 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001025 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001026 break;
1027 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001028 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001029 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001030 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001031 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001032 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001033 const Type *ElTy = getTypeByID(Record[i]);
1034 if (!ElTy) return Error("Invalid CE_GEP record");
1035 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1036 }
Owen Andersonbaf3c402009-07-29 18:55:55 +00001037 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
Owen Anderson74a77812009-07-07 20:18:58 +00001038 Elts.size()-1);
Dan Gohmandd8004d2009-07-27 21:53:46 +00001039 if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1040 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001041 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001042 }
1043 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1044 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001045 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001046 Type::Int1Ty),
1047 ValueList.getConstantFwdRef(Record[1],CurTy),
1048 ValueList.getConstantFwdRef(Record[2],CurTy));
1049 break;
1050 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1051 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1052 const VectorType *OpTy =
1053 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1054 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1055 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerba120aa2009-02-03 02:11:28 +00001056 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001057 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001058 break;
1059 }
1060 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1061 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1062 if (Record.size() < 3 || OpTy == 0)
1063 return Error("Invalid CE_INSERTELT record");
1064 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1065 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1066 OpTy->getElementType());
1067 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001068 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001069 break;
1070 }
1071 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1072 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1073 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001074 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001075 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1076 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Andersondebcb012009-07-29 22:17:13 +00001077 const Type *ShufTy = VectorType::get(Type::Int32Ty,
Owen Anderson74a77812009-07-07 20:18:58 +00001078 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001079 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001080 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001081 break;
1082 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001083 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1084 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1085 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
1086 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1087 return Error("Invalid CE_SHUFVEC_EX record");
1088 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1089 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersondebcb012009-07-29 22:17:13 +00001090 const Type *ShufTy = VectorType::get(Type::Int32Ty,
Owen Anderson74a77812009-07-07 20:18:58 +00001091 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001092 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001093 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001094 break;
1095 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001096 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1097 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1098 const Type *OpTy = getTypeByID(Record[0]);
1099 if (OpTy == 0) return Error("Invalid CE_CMP record");
1100 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1101 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1102
1103 if (OpTy->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001104 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001105 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001106 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001107 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001108 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001109 case bitc::CST_CODE_INLINEASM: {
1110 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1111 std::string AsmStr, ConstrStr;
1112 bool HasSideEffects = Record[0];
1113 unsigned AsmStrSize = Record[1];
1114 if (2+AsmStrSize >= Record.size())
1115 return Error("Invalid INLINEASM record");
1116 unsigned ConstStrSize = Record[2+AsmStrSize];
1117 if (3+AsmStrSize+ConstStrSize > Record.size())
1118 return Error("Invalid INLINEASM record");
1119
1120 for (unsigned i = 0; i != AsmStrSize; ++i)
1121 AsmStr += (char)Record[2+i];
1122 for (unsigned i = 0; i != ConstStrSize; ++i)
1123 ConstrStr += (char)Record[3+AsmStrSize+i];
1124 const PointerType *PTy = cast<PointerType>(CurTy);
1125 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1126 AsmStr, ConstrStr, HasSideEffects);
1127 break;
1128 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001129 }
1130
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001131 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001132 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001133 }
Chris Lattnerea693df2008-08-21 02:34:16 +00001134
1135 if (NextCstNo != ValueList.size())
1136 return Error("Invalid constant reference!");
1137
1138 if (Stream.ReadBlockEnd())
1139 return Error("Error at end of constants block");
1140
1141 // Once all the constants have been read, go through and resolve forward
1142 // references.
1143 ValueList.ResolveConstantForwardRefs();
1144 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001145}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001146
Chris Lattner980e5aa2007-05-01 05:52:21 +00001147/// RememberAndSkipFunctionBody - When we see the block for a function body,
1148/// remember where it is and then skip it. This lets us lazily deserialize the
1149/// functions.
1150bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001151 // Get the function we are talking about.
1152 if (FunctionsWithBodies.empty())
1153 return Error("Insufficient function protos");
1154
1155 Function *Fn = FunctionsWithBodies.back();
1156 FunctionsWithBodies.pop_back();
1157
1158 // Save the current stream state.
1159 uint64_t CurBit = Stream.GetCurrentBitNo();
1160 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1161
1162 // Set the functions linkage to GhostLinkage so we know it is lazily
1163 // deserialized.
1164 Fn->setLinkage(GlobalValue::GhostLinkage);
1165
1166 // Skip over the function block for now.
1167 if (Stream.SkipBlock())
1168 return Error("Malformed block record");
1169 return false;
1170}
1171
Chris Lattner86697142007-05-01 05:01:34 +00001172bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001173 // Reject multiple MODULE_BLOCK's in a single bitstream.
1174 if (TheModule)
1175 return Error("Multiple MODULE_BLOCKs in same stream");
1176
Chris Lattnere17b6582007-05-05 00:17:00 +00001177 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001178 return Error("Malformed block record");
1179
1180 // Otherwise, create the module.
Owen Anderson8b477ed2009-07-01 16:58:40 +00001181 TheModule = new Module(ModuleID, Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001182
1183 SmallVector<uint64_t, 64> Record;
1184 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001185 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001186
1187 // Read all the records for this module.
1188 while (!Stream.AtEndOfStream()) {
1189 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001190 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001191 if (Stream.ReadBlockEnd())
1192 return Error("Error at end of module block");
1193
1194 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001195 ResolveGlobalAndAliasInits();
1196 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001197 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001198 if (!FunctionsWithBodies.empty())
1199 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001200
Chandler Carruth69940402007-08-04 01:51:18 +00001201 // Look for intrinsic functions which need to be upgraded at some point
1202 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1203 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001204 Function* NewFn;
1205 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001206 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1207 }
1208
Chris Lattner980e5aa2007-05-01 05:52:21 +00001209 // Force deallocation of memory for these vectors to favor the client that
1210 // want lazy deserialization.
1211 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1212 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1213 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001214 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001215 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001216
1217 if (Code == bitc::ENTER_SUBBLOCK) {
1218 switch (Stream.ReadSubBlockID()) {
1219 default: // Skip unknown content.
1220 if (Stream.SkipBlock())
1221 return Error("Malformed block record");
1222 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001223 case bitc::BLOCKINFO_BLOCK_ID:
1224 if (Stream.ReadBlockInfoBlock())
1225 return Error("Malformed BlockInfoBlock");
1226 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001227 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001228 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001229 return true;
1230 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001231 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001232 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001233 return true;
1234 break;
1235 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001236 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001237 return true;
1238 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001239 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001240 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001241 return true;
1242 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001243 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001244 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001245 return true;
1246 break;
Devang Patele54abc92009-07-22 17:43:22 +00001247 case bitc::METADATA_BLOCK_ID:
1248 if (ParseMetadata())
1249 return true;
1250 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001251 case bitc::FUNCTION_BLOCK_ID:
1252 // If this is the first function body we've seen, reverse the
1253 // FunctionsWithBodies list.
1254 if (!HasReversedFunctionsWithBodies) {
1255 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1256 HasReversedFunctionsWithBodies = true;
1257 }
1258
Chris Lattner980e5aa2007-05-01 05:52:21 +00001259 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001260 return true;
1261 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001262 }
1263 continue;
1264 }
1265
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001266 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001267 Stream.ReadAbbrevRecord();
1268 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001269 }
1270
1271 // Read a record.
1272 switch (Stream.ReadRecord(Code, Record)) {
1273 default: break; // Default behavior, ignore unknown content.
1274 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1275 if (Record.size() < 1)
1276 return Error("Malformed MODULE_CODE_VERSION");
1277 // Only version #0 is supported so far.
1278 if (Record[0] != 0)
1279 return Error("Unknown bitstream version!");
1280 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001281 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001282 std::string S;
1283 if (ConvertToString(Record, 0, S))
1284 return Error("Invalid MODULE_CODE_TRIPLE record");
1285 TheModule->setTargetTriple(S);
1286 break;
1287 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001288 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001289 std::string S;
1290 if (ConvertToString(Record, 0, S))
1291 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1292 TheModule->setDataLayout(S);
1293 break;
1294 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001295 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001296 std::string S;
1297 if (ConvertToString(Record, 0, S))
1298 return Error("Invalid MODULE_CODE_ASM record");
1299 TheModule->setModuleInlineAsm(S);
1300 break;
1301 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001302 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001303 std::string S;
1304 if (ConvertToString(Record, 0, S))
1305 return Error("Invalid MODULE_CODE_DEPLIB record");
1306 TheModule->addLibrary(S);
1307 break;
1308 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001309 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001310 std::string S;
1311 if (ConvertToString(Record, 0, S))
1312 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1313 SectionTable.push_back(S);
1314 break;
1315 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001316 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001317 std::string S;
1318 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001319 return Error("Invalid MODULE_CODE_GCNAME record");
1320 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001321 break;
1322 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001323 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001324 // linkage, alignment, section, visibility, threadlocal]
1325 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001326 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001327 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1328 const Type *Ty = getTypeByID(Record[0]);
1329 if (!isa<PointerType>(Ty))
1330 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001331 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001332 Ty = cast<PointerType>(Ty)->getElementType();
1333
1334 bool isConstant = Record[1];
1335 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1336 unsigned Alignment = (1 << Record[4]) >> 1;
1337 std::string Section;
1338 if (Record[5]) {
1339 if (Record[5]-1 >= SectionTable.size())
1340 return Error("Invalid section ID");
1341 Section = SectionTable[Record[5]-1];
1342 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001343 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001344 if (Record.size() > 6)
1345 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001346 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001347 if (Record.size() > 7)
1348 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001349
1350 GlobalVariable *NewGV =
Owen Andersone9b11b42009-07-08 19:03:57 +00001351 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001352 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001353 NewGV->setAlignment(Alignment);
1354 if (!Section.empty())
1355 NewGV->setSection(Section);
1356 NewGV->setVisibility(Visibility);
1357 NewGV->setThreadLocal(isThreadLocal);
1358
Chris Lattner0b2482a2007-04-23 21:26:05 +00001359 ValueList.push_back(NewGV);
1360
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001361 // Remember which value to use for the global initializer.
1362 if (unsigned InitID = Record[2])
1363 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001364 break;
1365 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001366 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001367 // alignment, section, visibility, gc]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001368 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001369 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001370 return Error("Invalid MODULE_CODE_FUNCTION record");
1371 const Type *Ty = getTypeByID(Record[0]);
1372 if (!isa<PointerType>(Ty))
1373 return Error("Function not a pointer type!");
1374 const FunctionType *FTy =
1375 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1376 if (!FTy)
1377 return Error("Function not a pointer to function type!");
1378
Gabor Greif051a9502008-04-06 20:25:17 +00001379 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1380 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001381
1382 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001383 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001384 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001385 Func->setAttributes(getAttributes(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001386
1387 Func->setAlignment((1 << Record[5]) >> 1);
1388 if (Record[6]) {
1389 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001390 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001391 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001392 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001393 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001394 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001395 if (Record[8]-1 > GCTable.size())
1396 return Error("Invalid GC ID");
1397 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001398 }
Chris Lattner0b2482a2007-04-23 21:26:05 +00001399 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001400
1401 // If this is a function with a body, remember the prototype we are
1402 // creating now, so that we can match up the body with them later.
1403 if (!isProto)
1404 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001405 break;
1406 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001407 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001408 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001409 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001410 if (Record.size() < 3)
1411 return Error("Invalid MODULE_ALIAS record");
1412 const Type *Ty = getTypeByID(Record[0]);
1413 if (!isa<PointerType>(Ty))
1414 return Error("Function not a pointer type!");
1415
1416 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1417 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001418 // Old bitcode files didn't have visibility field.
1419 if (Record.size() > 3)
1420 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001421 ValueList.push_back(NewGA);
1422 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1423 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001424 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001425 /// MODULE_CODE_PURGEVALS: [numvals]
1426 case bitc::MODULE_CODE_PURGEVALS:
1427 // Trim down the value list to the specified size.
1428 if (Record.size() < 1 || Record[0] > ValueList.size())
1429 return Error("Invalid MODULE_PURGEVALS record");
1430 ValueList.shrinkTo(Record[0]);
1431 break;
1432 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001433 Record.clear();
1434 }
1435
1436 return Error("Premature end of bitstream");
1437}
1438
Chris Lattnerc453f762007-04-29 07:54:31 +00001439bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001440 TheModule = 0;
1441
Chris Lattnerc453f762007-04-29 07:54:31 +00001442 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001443 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1444
Chris Lattnerc453f762007-04-29 07:54:31 +00001445 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001446 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1447
1448 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1449 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnere2a466b2009-04-06 20:54:32 +00001450 if (isBitcodeWrapper(BufPtr, BufEnd))
1451 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner6fa6a322008-07-09 05:14:23 +00001452 return Error("Invalid bitcode wrapper header");
1453
Chris Lattner962dde32009-04-26 20:59:02 +00001454 StreamFile.init(BufPtr, BufEnd);
1455 Stream.init(StreamFile);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001456
1457 // Sniff for the signature.
1458 if (Stream.Read(8) != 'B' ||
1459 Stream.Read(8) != 'C' ||
1460 Stream.Read(4) != 0x0 ||
1461 Stream.Read(4) != 0xC ||
1462 Stream.Read(4) != 0xE ||
1463 Stream.Read(4) != 0xD)
1464 return Error("Invalid bitcode signature");
1465
1466 // We expect a number of well-defined blocks, though we don't necessarily
1467 // need to understand them all.
1468 while (!Stream.AtEndOfStream()) {
1469 unsigned Code = Stream.ReadCode();
1470
1471 if (Code != bitc::ENTER_SUBBLOCK)
1472 return Error("Invalid record at top-level");
1473
1474 unsigned BlockID = Stream.ReadSubBlockID();
1475
1476 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001477 switch (BlockID) {
1478 case bitc::BLOCKINFO_BLOCK_ID:
1479 if (Stream.ReadBlockInfoBlock())
1480 return Error("Malformed BlockInfoBlock");
1481 break;
1482 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001483 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001484 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001485 break;
1486 default:
1487 if (Stream.SkipBlock())
1488 return Error("Malformed block record");
1489 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001490 }
1491 }
1492
1493 return false;
1494}
Chris Lattnerc453f762007-04-29 07:54:31 +00001495
Chris Lattner48f84872007-05-01 04:59:48 +00001496
Chris Lattner980e5aa2007-05-01 05:52:21 +00001497/// ParseFunctionBody - Lazily parse the specified function body block.
1498bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001499 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001500 return Error("Malformed block record");
1501
1502 unsigned ModuleValueListSize = ValueList.size();
1503
1504 // Add all the function arguments to the value table.
1505 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1506 ValueList.push_back(I);
1507
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001508 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001509 BasicBlock *CurBB = 0;
1510 unsigned CurBBNo = 0;
1511
Chris Lattner980e5aa2007-05-01 05:52:21 +00001512 // Read all the records.
1513 SmallVector<uint64_t, 64> Record;
1514 while (1) {
1515 unsigned Code = Stream.ReadCode();
1516 if (Code == bitc::END_BLOCK) {
1517 if (Stream.ReadBlockEnd())
1518 return Error("Error at end of function block");
1519 break;
1520 }
1521
1522 if (Code == bitc::ENTER_SUBBLOCK) {
1523 switch (Stream.ReadSubBlockID()) {
1524 default: // Skip unknown content.
1525 if (Stream.SkipBlock())
1526 return Error("Malformed block record");
1527 break;
1528 case bitc::CONSTANTS_BLOCK_ID:
1529 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001530 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001531 break;
1532 case bitc::VALUE_SYMTAB_BLOCK_ID:
1533 if (ParseValueSymbolTable()) return true;
1534 break;
1535 }
1536 continue;
1537 }
1538
1539 if (Code == bitc::DEFINE_ABBREV) {
1540 Stream.ReadAbbrevRecord();
1541 continue;
1542 }
1543
1544 // Read a record.
1545 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001546 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001547 unsigned BitCode = Stream.ReadRecord(Code, Record);
1548 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001549 default: // Default behavior: reject
1550 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001551 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001552 if (Record.size() < 1 || Record[0] == 0)
1553 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001554 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001555 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001556 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001557 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001558 CurBB = FunctionBBs[0];
1559 continue;
1560
Chris Lattnerabfbf852007-05-06 00:21:25 +00001561 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1562 unsigned OpNum = 0;
1563 Value *LHS, *RHS;
1564 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1565 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001566 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001567 return Error("Invalid BINOP record");
1568
Dan Gohman1224c382009-07-20 21:19:07 +00001569 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001570 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001571 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohman1224c382009-07-20 21:19:07 +00001572 if (OpNum < Record.size())
1573 SetOptimizationFlags(I, Record[3]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001574 break;
1575 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001576 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1577 unsigned OpNum = 0;
1578 Value *Op;
1579 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1580 OpNum+2 != Record.size())
1581 return Error("Invalid CAST record");
1582
1583 const Type *ResTy = getTypeByID(Record[OpNum]);
1584 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1585 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001586 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001587 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Chris Lattner231cbcb2007-05-02 04:27:25 +00001588 break;
1589 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001590 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00001591 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001592 unsigned OpNum = 0;
1593 Value *BasePtr;
1594 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001595 return Error("Invalid GEP record");
1596
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001597 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001598 while (OpNum != Record.size()) {
1599 Value *Op;
1600 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001601 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001602 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001603 }
1604
Gabor Greif051a9502008-04-06 20:25:17 +00001605 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Dan Gohmandd8004d2009-07-27 21:53:46 +00001606 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1607 cast<GEPOperator>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001608 break;
1609 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001610
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001611 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1612 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001613 unsigned OpNum = 0;
1614 Value *Agg;
1615 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1616 return Error("Invalid EXTRACTVAL record");
1617
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001618 SmallVector<unsigned, 4> EXTRACTVALIdx;
1619 for (unsigned RecSize = Record.size();
1620 OpNum != RecSize; ++OpNum) {
1621 uint64_t Index = Record[OpNum];
1622 if ((unsigned)Index != Index)
1623 return Error("Invalid EXTRACTVAL index");
1624 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001625 }
1626
1627 I = ExtractValueInst::Create(Agg,
1628 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1629 break;
1630 }
1631
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001632 case bitc::FUNC_CODE_INST_INSERTVAL: {
1633 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001634 unsigned OpNum = 0;
1635 Value *Agg;
1636 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1637 return Error("Invalid INSERTVAL record");
1638 Value *Val;
1639 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1640 return Error("Invalid INSERTVAL record");
1641
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001642 SmallVector<unsigned, 4> INSERTVALIdx;
1643 for (unsigned RecSize = Record.size();
1644 OpNum != RecSize; ++OpNum) {
1645 uint64_t Index = Record[OpNum];
1646 if ((unsigned)Index != Index)
1647 return Error("Invalid INSERTVAL index");
1648 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001649 }
1650
1651 I = InsertValueInst::Create(Agg, Val,
1652 INSERTVALIdx.begin(), INSERTVALIdx.end());
1653 break;
1654 }
1655
Chris Lattnerabfbf852007-05-06 00:21:25 +00001656 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001657 // obsolete form of select
1658 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00001659 unsigned OpNum = 0;
1660 Value *TrueVal, *FalseVal, *Cond;
1661 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1662 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Dan Gohmanbe919402008-09-09 02:08:49 +00001663 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001664 return Error("Invalid SELECT record");
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001665
1666 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1667 break;
1668 }
1669
1670 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1671 // new form of select
1672 // handles select i1 or select [N x i1]
1673 unsigned OpNum = 0;
1674 Value *TrueVal, *FalseVal, *Cond;
1675 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1676 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1677 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1678 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00001679
1680 // select condition can be either i1 or [N x i1]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001681 if (const VectorType* vector_type =
1682 dyn_cast<const VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00001683 // expect <n x i1>
1684 if (vector_type->getElementType() != Type::Int1Ty)
1685 return Error("Invalid SELECT condition type");
1686 } else {
1687 // expect i1
1688 if (Cond->getType() != Type::Int1Ty)
1689 return Error("Invalid SELECT condition type");
1690 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001691
Gabor Greif051a9502008-04-06 20:25:17 +00001692 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001693 break;
1694 }
1695
1696 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001697 unsigned OpNum = 0;
1698 Value *Vec, *Idx;
1699 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1700 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001701 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00001702 I = ExtractElementInst::Create(Vec, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001703 break;
1704 }
1705
1706 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001707 unsigned OpNum = 0;
1708 Value *Vec, *Elt, *Idx;
1709 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1710 getValue(Record, OpNum,
1711 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1712 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001713 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001714 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001715 break;
1716 }
1717
Chris Lattnerabfbf852007-05-06 00:21:25 +00001718 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1719 unsigned OpNum = 0;
1720 Value *Vec1, *Vec2, *Mask;
1721 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1722 getValue(Record, OpNum, Vec1->getType(), Vec2))
1723 return Error("Invalid SHUFFLEVEC record");
1724
Mon P Wangaeb06d22008-11-10 04:46:22 +00001725 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001726 return Error("Invalid SHUFFLEVEC record");
1727 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1728 break;
1729 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001730
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001731 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
1732 // Old form of ICmp/FCmp returning bool
1733 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1734 // both legal on vectors but had different behaviour.
1735 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1736 // FCmp/ICmp returning bool or vector of bool
1737
Chris Lattner7337ab92007-05-06 00:00:00 +00001738 unsigned OpNum = 0;
1739 Value *LHS, *RHS;
1740 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1741 getValue(Record, OpNum, LHS->getType(), RHS) ||
1742 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001743 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001744
Dan Gohmanf72fb672008-09-09 01:02:47 +00001745 if (LHS->getType()->isFPOrFPVector())
Owen Anderson333c4002009-07-09 23:48:35 +00001746 I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001747 else
Owen Anderson333c4002009-07-09 23:48:35 +00001748 I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Dan Gohmanf72fb672008-09-09 01:02:47 +00001749 break;
1750 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001751
Devang Patel197be3d2008-02-22 02:49:49 +00001752 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1753 if (Record.size() != 2)
1754 return Error("Invalid GETRESULT record");
1755 unsigned OpNum = 0;
1756 Value *Op;
1757 getValueTypePair(Record, OpNum, NextValueNo, Op);
1758 unsigned Index = Record[1];
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001759 I = ExtractValueInst::Create(Op, Index);
Devang Patel197be3d2008-02-22 02:49:49 +00001760 break;
1761 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001762
Chris Lattner231cbcb2007-05-02 04:27:25 +00001763 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001764 {
1765 unsigned Size = Record.size();
1766 if (Size == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00001767 I = ReturnInst::Create();
Devang Pateld9d99ff2008-02-26 01:29:32 +00001768 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001769 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00001770
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001771 unsigned OpNum = 0;
1772 SmallVector<Value *,4> Vs;
1773 do {
1774 Value *Op = NULL;
1775 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1776 return Error("Invalid RET record");
1777 Vs.push_back(Op);
1778 } while(OpNum != Record.size());
1779
1780 const Type *ReturnType = F->getReturnType();
1781 if (Vs.size() > 1 ||
1782 (isa<StructType>(ReturnType) &&
1783 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001784 Value *RV = UndefValue::get(ReturnType);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001785 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1786 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1787 CurBB->getInstList().push_back(I);
1788 ValueList.AssignValue(I, NextValueNo++);
1789 RV = I;
1790 }
1791 I = ReturnInst::Create(RV);
Devang Pateld9d99ff2008-02-26 01:29:32 +00001792 break;
1793 }
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001794
1795 I = ReturnInst::Create(Vs[0]);
1796 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00001797 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001798 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001799 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001800 return Error("Invalid BR record");
1801 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1802 if (TrueDest == 0)
1803 return Error("Invalid BR record");
1804
1805 if (Record.size() == 1)
Gabor Greif051a9502008-04-06 20:25:17 +00001806 I = BranchInst::Create(TrueDest);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001807 else {
1808 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1809 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1810 if (FalseDest == 0 || Cond == 0)
1811 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001812 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001813 }
1814 break;
1815 }
1816 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1817 if (Record.size() < 3 || (Record.size() & 1) == 0)
1818 return Error("Invalid SWITCH record");
1819 const Type *OpTy = getTypeByID(Record[0]);
1820 Value *Cond = getFnValueByID(Record[1], OpTy);
1821 BasicBlock *Default = getBasicBlock(Record[2]);
1822 if (OpTy == 0 || Cond == 0 || Default == 0)
1823 return Error("Invalid SWITCH record");
1824 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001825 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001826 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1827 ConstantInt *CaseVal =
1828 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1829 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1830 if (CaseVal == 0 || DestBB == 0) {
1831 delete SI;
1832 return Error("Invalid SWITCH record!");
1833 }
1834 SI->addCase(CaseVal, DestBB);
1835 }
1836 I = SI;
1837 break;
1838 }
1839
Duncan Sandsdc024672007-11-27 13:23:08 +00001840 case bitc::FUNC_CODE_INST_INVOKE: {
1841 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001842 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00001843 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001844 unsigned CCInfo = Record[1];
1845 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1846 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001847
Chris Lattnera9bb7132007-05-08 05:38:01 +00001848 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001849 Value *Callee;
1850 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001851 return Error("Invalid INVOKE record");
1852
Chris Lattner7337ab92007-05-06 00:00:00 +00001853 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1854 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001855 dyn_cast<FunctionType>(CalleeTy->getElementType());
1856
1857 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001858 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1859 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001860 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001861
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001862 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001863 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1864 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1865 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001866 }
1867
Chris Lattner7337ab92007-05-06 00:00:00 +00001868 if (!FTy->isVarArg()) {
1869 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001870 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001871 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001872 // Read type/value pairs for varargs params.
1873 while (OpNum != Record.size()) {
1874 Value *Op;
1875 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1876 return Error("Invalid INVOKE record");
1877 Ops.push_back(Op);
1878 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001879 }
1880
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001881 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1882 Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001883 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Devang Patel05988662008-09-25 21:00:45 +00001884 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001885 break;
1886 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001887 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1888 I = new UnwindInst();
1889 break;
1890 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1891 I = new UnreachableInst();
1892 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001893 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001894 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001895 return Error("Invalid PHI record");
1896 const Type *Ty = getTypeByID(Record[0]);
1897 if (!Ty) return Error("Invalid PHI record");
1898
Gabor Greif051a9502008-04-06 20:25:17 +00001899 PHINode *PN = PHINode::Create(Ty);
Chris Lattner86941612008-04-13 00:14:42 +00001900 PN->reserveOperandSpace((Record.size()-1)/2);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001901
Chris Lattner15e6d172007-05-04 19:11:41 +00001902 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1903 Value *V = getFnValueByID(Record[1+i], Ty);
1904 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001905 if (!V || !BB) return Error("Invalid PHI record");
1906 PN->addIncoming(V, BB);
1907 }
1908 I = PN;
1909 break;
1910 }
1911
1912 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1913 if (Record.size() < 3)
1914 return Error("Invalid MALLOC record");
1915 const PointerType *Ty =
1916 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1917 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1918 unsigned Align = Record[2];
1919 if (!Ty || !Size) return Error("Invalid MALLOC record");
Owen Anderson50dead02009-07-15 23:53:25 +00001920 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001921 break;
1922 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001923 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1924 unsigned OpNum = 0;
1925 Value *Op;
1926 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1927 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001928 return Error("Invalid FREE record");
1929 I = new FreeInst(Op);
1930 break;
1931 }
1932 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1933 if (Record.size() < 3)
1934 return Error("Invalid ALLOCA record");
1935 const PointerType *Ty =
1936 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1937 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1938 unsigned Align = Record[2];
1939 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00001940 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001941 break;
1942 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001943 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001944 unsigned OpNum = 0;
1945 Value *Op;
1946 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1947 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001948 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001949
1950 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001951 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001952 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001953 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1954 unsigned OpNum = 0;
1955 Value *Val, *Ptr;
1956 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1957 getValue(Record, OpNum,
1958 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1959 OpNum+2 != Record.size())
1960 return Error("Invalid STORE record");
1961
1962 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1963 break;
1964 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001965 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001966 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001967 unsigned OpNum = 0;
1968 Value *Val, *Ptr;
1969 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Owen Anderson74a77812009-07-07 20:18:58 +00001970 getValue(Record, OpNum,
Owen Andersondebcb012009-07-29 22:17:13 +00001971 PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001972 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001973 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001974
1975 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001976 break;
1977 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001978 case bitc::FUNC_CODE_INST_CALL: {
1979 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1980 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001981 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001982
Devang Patel05988662008-09-25 21:00:45 +00001983 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001984 unsigned CCInfo = Record[1];
1985
1986 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001987 Value *Callee;
1988 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1989 return Error("Invalid CALL record");
1990
1991 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001992 const FunctionType *FTy = 0;
1993 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001994 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001995 return Error("Invalid CALL record");
1996
1997 SmallVector<Value*, 16> Args;
1998 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001999 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002000 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2001 Args.push_back(getBasicBlock(Record[OpNum]));
2002 else
2003 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002004 if (Args.back() == 0) return Error("Invalid CALL record");
2005 }
2006
Chris Lattner0579f7f2007-05-03 22:04:19 +00002007 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002008 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002009 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002010 return Error("Invalid CALL record");
2011 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002012 while (OpNum != Record.size()) {
2013 Value *Op;
2014 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2015 return Error("Invalid CALL record");
2016 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002017 }
2018 }
2019
Gabor Greif051a9502008-04-06 20:25:17 +00002020 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00002021 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
2022 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002023 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002024 break;
2025 }
2026 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2027 if (Record.size() < 3)
2028 return Error("Invalid VAARG record");
2029 const Type *OpTy = getTypeByID(Record[0]);
2030 Value *Op = getFnValueByID(Record[1], OpTy);
2031 const Type *ResTy = getTypeByID(Record[2]);
2032 if (!OpTy || !Op || !ResTy)
2033 return Error("Invalid VAARG record");
2034 I = new VAArgInst(Op, ResTy);
2035 break;
2036 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002037 }
2038
2039 // Add instruction to end of current BB. If there is no current BB, reject
2040 // this file.
2041 if (CurBB == 0) {
2042 delete I;
2043 return Error("Invalid instruction with no BB");
2044 }
2045 CurBB->getInstList().push_back(I);
2046
2047 // If this was a terminator instruction, move to the next block.
2048 if (isa<TerminatorInst>(I)) {
2049 ++CurBBNo;
2050 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2051 }
2052
2053 // Non-void values get registered in the value table for future use.
2054 if (I && I->getType() != Type::VoidTy)
2055 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002056 }
2057
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002058 // Check the function list for unresolved values.
2059 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2060 if (A->getParent() == 0) {
2061 // We found at least one unresolved value. Nuke them all to avoid leaks.
2062 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2063 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002064 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002065 delete A;
2066 }
2067 }
Chris Lattner35a04702007-05-04 03:50:29 +00002068 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002069 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002070 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002071
2072 // Trim the value list down to the size it was before we parsed this function.
2073 ValueList.shrinkTo(ModuleValueListSize);
2074 std::vector<BasicBlock*>().swap(FunctionBBs);
2075
Chris Lattner48f84872007-05-01 04:59:48 +00002076 return false;
2077}
2078
Chris Lattnerb348bb82007-05-18 04:02:46 +00002079//===----------------------------------------------------------------------===//
2080// ModuleProvider implementation
2081//===----------------------------------------------------------------------===//
2082
2083
2084bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2085 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00002086 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002087
2088 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2089 DeferredFunctionInfo.find(F);
2090 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2091
2092 // Move the bit stream to the saved position of the deferred function body and
2093 // restore the real linkage type for the function.
2094 Stream.JumpToBit(DFII->second.first);
2095 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2096
2097 if (ParseFunctionBody(F)) {
2098 if (ErrInfo) *ErrInfo = ErrorString;
2099 return true;
2100 }
Chandler Carruth69940402007-08-04 01:51:18 +00002101
2102 // Upgrade any old intrinsic calls in the function.
2103 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2104 E = UpgradedIntrinsics.end(); I != E; ++I) {
2105 if (I->first != I->second) {
2106 for (Value::use_iterator UI = I->first->use_begin(),
2107 UE = I->first->use_end(); UI != UE; ) {
2108 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2109 UpgradeIntrinsicCall(CI, I->second);
2110 }
2111 }
2112 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00002113
2114 return false;
2115}
2116
2117void BitcodeReader::dematerializeFunction(Function *F) {
2118 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00002119 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00002120 return;
2121
2122 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2123
2124 // Just forget the function body, we can remat it later.
2125 F->deleteBody();
2126 F->setLinkage(GlobalValue::GhostLinkage);
2127}
2128
2129
2130Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
Chris Lattner714fa952009-06-16 05:15:21 +00002131 // Iterate over the module, deserializing any functions that are still on
2132 // disk.
2133 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2134 F != E; ++F)
Gabor Greifa99be512007-07-05 17:07:56 +00002135 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00002136 materializeFunction(F, ErrInfo))
2137 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00002138
2139 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2140 // delete the old functions to clean up. We can't do this unless the entire
2141 // module is materialized because there could always be another function body
2142 // with calls to the old function.
2143 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2144 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2145 if (I->first != I->second) {
2146 for (Value::use_iterator UI = I->first->use_begin(),
2147 UE = I->first->use_end(); UI != UE; ) {
2148 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2149 UpgradeIntrinsicCall(CI, I->second);
2150 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002151 if (!I->first->use_empty())
2152 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002153 I->first->eraseFromParent();
2154 }
2155 }
2156 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2157
Chris Lattnerb348bb82007-05-18 04:02:46 +00002158 return TheModule;
2159}
2160
2161
2162/// This method is provided by the parent ModuleProvde class and overriden
2163/// here. It simply releases the module from its provided and frees up our
2164/// state.
2165/// @brief Release our hold on the generated module
2166Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2167 // Since we're losing control of this Module, we must hand it back complete
2168 Module *M = ModuleProvider::releaseModule(ErrInfo);
2169 FreeState();
2170 return M;
2171}
2172
Chris Lattner48f84872007-05-01 04:59:48 +00002173
Chris Lattnerc453f762007-04-29 07:54:31 +00002174//===----------------------------------------------------------------------===//
2175// External interface
2176//===----------------------------------------------------------------------===//
2177
2178/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2179///
2180ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
Owen Anderson4434ed42009-07-01 23:13:44 +00002181 LLVMContext& Context,
Chris Lattnerc453f762007-04-29 07:54:31 +00002182 std::string *ErrMsg) {
Owen Anderson8b477ed2009-07-01 16:58:40 +00002183 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Chris Lattnerc453f762007-04-29 07:54:31 +00002184 if (R->ParseBitcode()) {
2185 if (ErrMsg)
2186 *ErrMsg = R->getErrorString();
2187
2188 // Don't let the BitcodeReader dtor delete 'Buffer'.
2189 R->releaseMemoryBuffer();
2190 delete R;
2191 return 0;
2192 }
2193 return R;
2194}
2195
2196/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2197/// If an error occurs, return null and fill in *ErrMsg if non-null.
Owen Anderson4434ed42009-07-01 23:13:44 +00002198Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002199 std::string *ErrMsg){
Chris Lattnerc453f762007-04-29 07:54:31 +00002200 BitcodeReader *R;
Owen Anderson8b477ed2009-07-01 16:58:40 +00002201 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
2202 ErrMsg));
Chris Lattnerc453f762007-04-29 07:54:31 +00002203 if (!R) return 0;
2204
Chris Lattnerb348bb82007-05-18 04:02:46 +00002205 // Read in the entire module.
2206 Module *M = R->materializeModule(ErrMsg);
2207
2208 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2209 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00002210 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002211
2212 // If there was no error, tell ModuleProvider not to delete it when its dtor
2213 // is run.
2214 if (M)
2215 M = R->releaseModule(ErrMsg);
Chris Lattner714fa952009-06-16 05:15:21 +00002216
Chris Lattnerc453f762007-04-29 07:54:31 +00002217 delete R;
2218 return M;
2219}