blob: 69eadd9ee41fb0248c3bd6030c17564780931d6b [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"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Chandler Carruth69940402007-08-04 01:51:18 +000021#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000022#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000023#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000025#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000026#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000027using namespace llvm;
28
Chris Lattnerb348bb82007-05-18 04:02:46 +000029void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000030 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000031 Buffer = 0;
32 std::vector<PATypeHolder>().swap(TypeList);
33 ValueList.clear();
Chris Lattner461edd92008-03-12 02:25:52 +000034
Devang Patel19c87462008-09-26 22:53:05 +000035 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000036 std::vector<BasicBlock*>().swap(FunctionBBs);
37 std::vector<Function*>().swap(FunctionsWithBodies);
38 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000039}
40
Chris Lattner48c85b82007-05-04 03:30:17 +000041//===----------------------------------------------------------------------===//
42// Helper functions to implement forward reference resolution, etc.
43//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000044
Chris Lattnercaee0dc2007-04-22 06:23:29 +000045/// ConvertToString - Convert a string from a record into an std::string, return
46/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000047template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000048static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000049 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000050 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000051 return true;
52
Chris Lattner15e6d172007-05-04 19:11:41 +000053 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
54 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000055 return false;
56}
57
58static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
59 switch (Val) {
60 default: // Map unknown/new linkages to external
61 case 0: return GlobalValue::ExternalLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000062 case 1: return GlobalValue::WeakAnyLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063 case 2: return GlobalValue::AppendingLinkage;
64 case 3: return GlobalValue::InternalLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000065 case 4: return GlobalValue::LinkOnceAnyLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000066 case 5: return GlobalValue::DLLImportLinkage;
67 case 6: return GlobalValue::DLLExportLinkage;
Duncan Sands5f4ee1f2009-03-11 08:08:06 +000068 case 7: return GlobalValue::ExternalWeakLinkage;
Duncan Sands4dc2b392009-03-11 20:14:15 +000069 case 8: return GlobalValue::CommonLinkage;
Rafael Espindolabb46f522009-01-15 20:18:42 +000070 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000071 case 10: return GlobalValue::WeakODRLinkage;
72 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000073 }
74}
75
76static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
77 switch (Val) {
78 default: // Map unknown visibilities to default.
79 case 0: return GlobalValue::DefaultVisibility;
80 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000081 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000082 }
83}
84
Chris Lattnerf581c3b2007-04-24 07:07:11 +000085static int GetDecodedCastOpcode(unsigned Val) {
86 switch (Val) {
87 default: return -1;
88 case bitc::CAST_TRUNC : return Instruction::Trunc;
89 case bitc::CAST_ZEXT : return Instruction::ZExt;
90 case bitc::CAST_SEXT : return Instruction::SExt;
91 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
92 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
93 case bitc::CAST_UITOFP : return Instruction::UIToFP;
94 case bitc::CAST_SITOFP : return Instruction::SIToFP;
95 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
96 case bitc::CAST_FPEXT : return Instruction::FPExt;
97 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
98 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
99 case bitc::CAST_BITCAST : return Instruction::BitCast;
100 }
101}
102static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
103 switch (Val) {
104 default: return -1;
105 case bitc::BINOP_ADD: return Instruction::Add;
106 case bitc::BINOP_SUB: return Instruction::Sub;
107 case bitc::BINOP_MUL: return Instruction::Mul;
108 case bitc::BINOP_UDIV: return Instruction::UDiv;
109 case bitc::BINOP_SDIV:
110 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
111 case bitc::BINOP_UREM: return Instruction::URem;
112 case bitc::BINOP_SREM:
113 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
114 case bitc::BINOP_SHL: return Instruction::Shl;
115 case bitc::BINOP_LSHR: return Instruction::LShr;
116 case bitc::BINOP_ASHR: return Instruction::AShr;
117 case bitc::BINOP_AND: return Instruction::And;
118 case bitc::BINOP_OR: return Instruction::Or;
119 case bitc::BINOP_XOR: return Instruction::Xor;
120 }
121}
122
Gabor Greifefe65362008-05-10 08:32:32 +0000123namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000124namespace {
125 /// @brief A class for maintaining the slot number definition
126 /// as a placeholder for the actual definition for forward constants defs.
127 class ConstantPlaceHolder : public ConstantExpr {
128 ConstantPlaceHolder(); // DO NOT IMPLEMENT
129 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000130 public:
131 // allocate space for exactly one operand
132 void *operator new(size_t s) {
133 return User::operator new(s, 1);
134 }
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000135 explicit ConstantPlaceHolder(const Type *Ty)
Gabor Greifefe65362008-05-10 08:32:32 +0000136 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
137 Op<0>() = UndefValue::get(Type::Int32Ty);
Chris Lattner522b7b12007-04-24 05:48:56 +0000138 }
Chris Lattnerea693df2008-08-21 02:34:16 +0000139
140 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
141 static inline bool classof(const ConstantPlaceHolder *) { return true; }
142 static bool classof(const Value *V) {
143 return isa<ConstantExpr>(V) &&
144 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
145 }
146
147
Gabor Greifefe65362008-05-10 08:32:32 +0000148 /// Provide fast operand accessors
149 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000150 };
151}
152
Gabor Greifefe65362008-05-10 08:32:32 +0000153
154 // FIXME: can we inherit this from ConstantExpr?
155template <>
156struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
157};
158
159DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
160}
161
162void BitcodeReaderValueList::resize(unsigned Desired) {
163 if (Desired > Capacity) {
164 // Since we expect many values to come from the bitcode file we better
165 // allocate the double amount, so that the array size grows exponentially
166 // at each reallocation. Also, add a small amount of 100 extra elements
167 // each time, to reallocate less frequently when the array is still small.
168 //
169 Capacity = Desired * 2 + 100;
170 Use *New = allocHungoffUses(Capacity);
171 Use *Old = OperandList;
172 unsigned Ops = getNumOperands();
173 for (int i(Ops - 1); i >= 0; --i)
174 New[i] = Old[i].get();
175 OperandList = New;
176 if (Old) Use::zap(Old, Old + Ops, true);
177 }
178}
179
Chris Lattner522b7b12007-04-24 05:48:56 +0000180Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
181 const Type *Ty) {
182 if (Idx >= size()) {
183 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000184 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000185 NumOperands = Idx+1;
186 }
187
Gabor Greifefe65362008-05-10 08:32:32 +0000188 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000189 assert(Ty == V->getType() && "Type mismatch in constant table!");
190 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000191 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000192
193 // Create and return a placeholder, which will later be RAUW'd.
194 Constant *C = new ConstantPlaceHolder(Ty);
Gabor Greif6c80c382008-05-26 21:33:52 +0000195 OperandList[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000196 return C;
197}
198
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000199Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
200 if (Idx >= size()) {
201 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000202 resize(Idx + 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000203 NumOperands = Idx+1;
204 }
205
Gabor Greifefe65362008-05-10 08:32:32 +0000206 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000207 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
208 return V;
209 }
210
Chris Lattner01ff65f2007-05-02 05:16:49 +0000211 // No type specified, must be invalid reference.
212 if (Ty == 0) return 0;
213
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000214 // Create and return a placeholder, which will later be RAUW'd.
215 Value *V = new Argument(Ty);
Gabor Greif6c80c382008-05-26 21:33:52 +0000216 OperandList[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000217 return V;
218}
219
Chris Lattnerea693df2008-08-21 02:34:16 +0000220/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
221/// resolves any forward references. The idea behind this is that we sometimes
222/// get constants (such as large arrays) which reference *many* forward ref
223/// constants. Replacing each of these causes a lot of thrashing when
224/// building/reuniquing the constant. Instead of doing this, we look at all the
225/// uses and rewrite all the place holders at once for any constant that uses
226/// a placeholder.
227void BitcodeReaderValueList::ResolveConstantForwardRefs() {
228 // Sort the values by-pointer so that they are efficient to look up with a
229 // binary search.
230 std::sort(ResolveConstants.begin(), ResolveConstants.end());
231
232 SmallVector<Constant*, 64> NewOps;
233
234 while (!ResolveConstants.empty()) {
235 Value *RealVal = getOperand(ResolveConstants.back().second);
236 Constant *Placeholder = ResolveConstants.back().first;
237 ResolveConstants.pop_back();
238
239 // Loop over all users of the placeholder, updating them to reference the
240 // new value. If they reference more than one placeholder, update them all
241 // at once.
242 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000243 Value::use_iterator UI = Placeholder->use_begin();
244
Chris Lattnerea693df2008-08-21 02:34:16 +0000245 // If the using object isn't uniqued, just update the operands. This
246 // handles instructions and initializers for global variables.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000247 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
248 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000249 continue;
250 }
251
252 // Otherwise, we have a constant that uses the placeholder. Replace that
253 // constant with a new constant that has *all* placeholder uses updated.
Chris Lattnerb6135a02008-08-21 17:31:45 +0000254 Constant *UserC = cast<Constant>(*UI);
Chris Lattnerea693df2008-08-21 02:34:16 +0000255 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
256 I != E; ++I) {
257 Value *NewOp;
258 if (!isa<ConstantPlaceHolder>(*I)) {
259 // Not a placeholder reference.
260 NewOp = *I;
261 } else if (*I == Placeholder) {
262 // Common case is that it just references this one placeholder.
263 NewOp = RealVal;
264 } else {
265 // Otherwise, look up the placeholder in ResolveConstants.
266 ResolveConstantsTy::iterator It =
267 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
268 std::pair<Constant*, unsigned>(cast<Constant>(*I),
269 0));
270 assert(It != ResolveConstants.end() && It->first == *I);
271 NewOp = this->getOperand(It->second);
272 }
273
274 NewOps.push_back(cast<Constant>(NewOp));
275 }
276
277 // Make the new constant.
278 Constant *NewC;
279 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
280 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
281 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
282 NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
283 UserCS->getType()->isPacked());
284 } else if (isa<ConstantVector>(UserC)) {
285 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
286 } else {
287 // Must be a constant expression.
288 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
289 NewOps.size());
290 }
291
292 UserC->replaceAllUsesWith(NewC);
293 UserC->destroyConstant();
294 NewOps.clear();
295 }
296
297 delete Placeholder;
298 }
299}
300
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000301
302const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
303 // If the TypeID is in range, return it.
304 if (ID < TypeList.size())
305 return TypeList[ID].get();
306 if (!isTypeTable) return 0;
307
308 // The type table allows forward references. Push as many Opaque types as
309 // needed to get up to ID.
310 while (TypeList.size() <= ID)
311 TypeList.push_back(OpaqueType::get());
312 return TypeList.back().get();
313}
314
Chris Lattner48c85b82007-05-04 03:30:17 +0000315//===----------------------------------------------------------------------===//
316// Functions for parsing blocks from the bitcode file
317//===----------------------------------------------------------------------===//
318
Devang Patel05988662008-09-25 21:00:45 +0000319bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000320 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000321 return Error("Malformed block record");
322
Devang Patel19c87462008-09-26 22:53:05 +0000323 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000324 return Error("Multiple PARAMATTR blocks found!");
325
326 SmallVector<uint64_t, 64> Record;
327
Devang Patel05988662008-09-25 21:00:45 +0000328 SmallVector<AttributeWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000329
330 // Read all the records.
331 while (1) {
332 unsigned Code = Stream.ReadCode();
333 if (Code == bitc::END_BLOCK) {
334 if (Stream.ReadBlockEnd())
335 return Error("Error at end of PARAMATTR block");
336 return false;
337 }
338
339 if (Code == bitc::ENTER_SUBBLOCK) {
340 // No known subblocks, always skip them.
341 Stream.ReadSubBlockID();
342 if (Stream.SkipBlock())
343 return Error("Malformed block record");
344 continue;
345 }
346
347 if (Code == bitc::DEFINE_ABBREV) {
348 Stream.ReadAbbrevRecord();
349 continue;
350 }
351
352 // Read a record.
353 Record.clear();
354 switch (Stream.ReadRecord(Code, Record)) {
355 default: // Default behavior: ignore.
356 break;
357 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
358 if (Record.size() & 1)
359 return Error("Invalid ENTRY record");
360
Chris Lattner9a6cb152008-10-05 18:22:09 +0000361 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000362 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000363 // to index ~0. Index 0 is used for return value attributes but used to be
364 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000365 Attributes RetAttribute = Attribute::None;
366 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000367 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000368 // FIXME: remove in LLVM 3.0
369 // The alignment is stored as a 16-bit raw value from bits 31--16.
370 // We shift the bits above 31 down by 11 bits.
371
372 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
373 if (Alignment && !isPowerOf2_32(Alignment))
374 return Error("Alignment is not a power of two.");
375
376 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
377 if (Alignment)
378 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
379 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
380 Record[i+1] = ReconstitutedAttr;
381
Devang Patel19c87462008-09-26 22:53:05 +0000382 if (Record[i] == 0)
383 RetAttribute = Record[i+1];
384 else if (Record[i] == ~0U)
385 FnAttribute = Record[i+1];
386 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000387
388 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
389 Attribute::ReadOnly|Attribute::ReadNone);
390
391 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
392 (RetAttribute & OldRetAttrs) != 0) {
393 if (FnAttribute == Attribute::None) { // add a slot so they get added.
394 Record.push_back(~0U);
395 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000396 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000397
398 FnAttribute |= RetAttribute & OldRetAttrs;
399 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000400 }
Chris Lattner461edd92008-03-12 02:25:52 +0000401
Devang Patel19c87462008-09-26 22:53:05 +0000402 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000403 if (Record[i] == 0) {
404 if (RetAttribute != Attribute::None)
405 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
406 } else if (Record[i] == ~0U) {
407 if (FnAttribute != Attribute::None)
408 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
409 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000410 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
411 }
Devang Patel19c87462008-09-26 22:53:05 +0000412
413 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000414 Attrs.clear();
415 break;
416 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000417 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000418 }
419}
420
421
Chris Lattner86697142007-05-01 05:01:34 +0000422bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000423 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000424 return Error("Malformed block record");
425
426 if (!TypeList.empty())
427 return Error("Multiple TYPE_BLOCKs found!");
428
429 SmallVector<uint64_t, 64> Record;
430 unsigned NumRecords = 0;
431
432 // Read all the records for this type table.
433 while (1) {
434 unsigned Code = Stream.ReadCode();
435 if (Code == bitc::END_BLOCK) {
436 if (NumRecords != TypeList.size())
437 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000438 if (Stream.ReadBlockEnd())
439 return Error("Error at end of type table block");
440 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000441 }
442
443 if (Code == bitc::ENTER_SUBBLOCK) {
444 // No known subblocks, always skip them.
445 Stream.ReadSubBlockID();
446 if (Stream.SkipBlock())
447 return Error("Malformed block record");
448 continue;
449 }
450
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000451 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000452 Stream.ReadAbbrevRecord();
453 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000454 }
455
456 // Read a record.
457 Record.clear();
458 const Type *ResultTy = 0;
459 switch (Stream.ReadRecord(Code, Record)) {
460 default: // Default behavior: unknown type.
461 ResultTy = 0;
462 break;
463 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
464 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
465 // type list. This allows us to reserve space.
466 if (Record.size() < 1)
467 return Error("Invalid TYPE_CODE_NUMENTRY record");
468 TypeList.reserve(Record[0]);
469 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000470 case bitc::TYPE_CODE_VOID: // VOID
471 ResultTy = Type::VoidTy;
472 break;
473 case bitc::TYPE_CODE_FLOAT: // FLOAT
474 ResultTy = Type::FloatTy;
475 break;
476 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
477 ResultTy = Type::DoubleTy;
478 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000479 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
480 ResultTy = Type::X86_FP80Ty;
481 break;
482 case bitc::TYPE_CODE_FP128: // FP128
483 ResultTy = Type::FP128Ty;
484 break;
485 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
486 ResultTy = Type::PPC_FP128Ty;
487 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000488 case bitc::TYPE_CODE_LABEL: // LABEL
489 ResultTy = Type::LabelTy;
490 break;
491 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
492 ResultTy = 0;
493 break;
494 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
495 if (Record.size() < 1)
496 return Error("Invalid Integer type record");
497
498 ResultTy = IntegerType::get(Record[0]);
499 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000500 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
501 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000502 if (Record.size() < 1)
503 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000504 unsigned AddressSpace = 0;
505 if (Record.size() == 2)
506 AddressSpace = Record[1];
507 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000508 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000509 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000510 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000511 // FIXME: attrid is dead, remove it in LLVM 3.0
512 // FUNCTION: [vararg, attrid, retty, paramty x N]
513 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000514 return Error("Invalid FUNCTION type record");
515 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000516 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000517 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000518
Chris Lattnera1afde72007-11-27 17:48:06 +0000519 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000520 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000521 break;
522 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000523 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000524 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000525 return Error("Invalid STRUCT type record");
526 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000527 for (unsigned i = 1, e = Record.size(); i != e; ++i)
528 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000529 ResultTy = StructType::get(EltTys, Record[0]);
530 break;
531 }
532 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
533 if (Record.size() < 2)
534 return Error("Invalid ARRAY type record");
535 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
536 break;
537 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
538 if (Record.size() < 2)
539 return Error("Invalid VECTOR type record");
540 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
541 break;
542 }
543
544 if (NumRecords == TypeList.size()) {
545 // If this is a new type slot, just append it.
546 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
547 ++NumRecords;
548 } else if (ResultTy == 0) {
549 // Otherwise, this was forward referenced, so an opaque type was created,
550 // but the result type is actually just an opaque. Leave the one we
551 // created previously.
552 ++NumRecords;
553 } else {
554 // Otherwise, this was forward referenced, so an opaque type was created.
555 // Resolve the opaque type to the real type now.
556 assert(NumRecords < TypeList.size() && "Typelist imbalance");
557 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
558
559 // Don't directly push the new type on the Tab. Instead we want to replace
560 // the opaque type we previously inserted with the new concrete value. The
561 // refinement from the abstract (opaque) type to the new type causes all
562 // uses of the abstract type to use the concrete type (NewTy). This will
563 // also cause the opaque type to be deleted.
564 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
565
566 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000567 // value table... or with a preexisting type that was already in the
568 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000569 assert(TypeList[NumRecords-1].get() != OldTy &&
570 "refineAbstractType didn't work!");
571 }
572 }
573}
574
575
Chris Lattner86697142007-05-01 05:01:34 +0000576bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000577 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000578 return Error("Malformed block record");
579
580 SmallVector<uint64_t, 64> Record;
581
582 // Read all the records for this type table.
583 std::string TypeName;
584 while (1) {
585 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000586 if (Code == bitc::END_BLOCK) {
587 if (Stream.ReadBlockEnd())
588 return Error("Error at end of type symbol table block");
589 return false;
590 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000591
592 if (Code == bitc::ENTER_SUBBLOCK) {
593 // No known subblocks, always skip them.
594 Stream.ReadSubBlockID();
595 if (Stream.SkipBlock())
596 return Error("Malformed block record");
597 continue;
598 }
599
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000600 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000601 Stream.ReadAbbrevRecord();
602 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000603 }
604
605 // Read a record.
606 Record.clear();
607 switch (Stream.ReadRecord(Code, Record)) {
608 default: // Default behavior: unknown type.
609 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000610 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000611 if (ConvertToString(Record, 1, TypeName))
612 return Error("Invalid TST_ENTRY record");
613 unsigned TypeID = Record[0];
614 if (TypeID >= TypeList.size())
615 return Error("Invalid Type ID in TST_ENTRY record");
616
617 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
618 TypeName.clear();
619 break;
620 }
621 }
622}
623
Chris Lattner86697142007-05-01 05:01:34 +0000624bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000625 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000626 return Error("Malformed block record");
627
628 SmallVector<uint64_t, 64> Record;
629
630 // Read all the records for this value table.
631 SmallString<128> ValueName;
632 while (1) {
633 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000634 if (Code == bitc::END_BLOCK) {
635 if (Stream.ReadBlockEnd())
636 return Error("Error at end of value symbol table block");
637 return false;
638 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000639 if (Code == bitc::ENTER_SUBBLOCK) {
640 // No known subblocks, always skip them.
641 Stream.ReadSubBlockID();
642 if (Stream.SkipBlock())
643 return Error("Malformed block record");
644 continue;
645 }
646
647 if (Code == bitc::DEFINE_ABBREV) {
648 Stream.ReadAbbrevRecord();
649 continue;
650 }
651
652 // Read a record.
653 Record.clear();
654 switch (Stream.ReadRecord(Code, Record)) {
655 default: // Default behavior: unknown type.
656 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000657 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000658 if (ConvertToString(Record, 1, ValueName))
659 return Error("Invalid TST_ENTRY record");
660 unsigned ValueID = Record[0];
661 if (ValueID >= ValueList.size())
662 return Error("Invalid Value ID in VST_ENTRY record");
663 Value *V = ValueList[ValueID];
664
665 V->setName(&ValueName[0], ValueName.size());
666 ValueName.clear();
667 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000668 }
669 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000670 if (ConvertToString(Record, 1, ValueName))
671 return Error("Invalid VST_BBENTRY record");
672 BasicBlock *BB = getBasicBlock(Record[0]);
673 if (BB == 0)
674 return Error("Invalid BB ID in VST_BBENTRY record");
675
676 BB->setName(&ValueName[0], ValueName.size());
677 ValueName.clear();
678 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000679 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000680 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000681 }
682}
683
Chris Lattner0eef0802007-04-24 04:04:35 +0000684/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
685/// the LSB for dense VBR encoding.
686static uint64_t DecodeSignRotatedValue(uint64_t V) {
687 if ((V & 1) == 0)
688 return V >> 1;
689 if (V != 1)
690 return -(V >> 1);
691 // There is no such thing as -0 with integers. "-0" really means MININT.
692 return 1ULL << 63;
693}
694
Chris Lattner07d98b42007-04-26 02:46:40 +0000695/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
696/// values and aliases that we can.
697bool BitcodeReader::ResolveGlobalAndAliasInits() {
698 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
699 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
700
701 GlobalInitWorklist.swap(GlobalInits);
702 AliasInitWorklist.swap(AliasInits);
703
704 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000705 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000706 if (ValID >= ValueList.size()) {
707 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000708 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000709 } else {
710 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
711 GlobalInitWorklist.back().first->setInitializer(C);
712 else
713 return Error("Global variable initializer is not a constant!");
714 }
715 GlobalInitWorklist.pop_back();
716 }
717
718 while (!AliasInitWorklist.empty()) {
719 unsigned ValID = AliasInitWorklist.back().second;
720 if (ValID >= ValueList.size()) {
721 AliasInits.push_back(AliasInitWorklist.back());
722 } else {
723 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000724 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000725 else
726 return Error("Alias initializer is not a constant!");
727 }
728 AliasInitWorklist.pop_back();
729 }
730 return false;
731}
732
733
Chris Lattner86697142007-05-01 05:01:34 +0000734bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000735 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000736 return Error("Malformed block record");
737
738 SmallVector<uint64_t, 64> Record;
739
740 // Read all the records for this value table.
741 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000742 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000743 while (1) {
744 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000745 if (Code == bitc::END_BLOCK)
746 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000747
748 if (Code == bitc::ENTER_SUBBLOCK) {
749 // No known subblocks, always skip them.
750 Stream.ReadSubBlockID();
751 if (Stream.SkipBlock())
752 return Error("Malformed block record");
753 continue;
754 }
755
756 if (Code == bitc::DEFINE_ABBREV) {
757 Stream.ReadAbbrevRecord();
758 continue;
759 }
760
761 // Read a record.
762 Record.clear();
763 Value *V = 0;
764 switch (Stream.ReadRecord(Code, Record)) {
765 default: // Default behavior: unknown constant
766 case bitc::CST_CODE_UNDEF: // UNDEF
767 V = UndefValue::get(CurTy);
768 break;
769 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
770 if (Record.empty())
771 return Error("Malformed CST_SETTYPE record");
772 if (Record[0] >= TypeList.size())
773 return Error("Invalid Type ID in CST_SETTYPE record");
774 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000775 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000776 case bitc::CST_CODE_NULL: // NULL
777 V = Constant::getNullValue(CurTy);
778 break;
779 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000780 if (!isa<IntegerType>(CurTy) || Record.empty())
781 return Error("Invalid CST_INTEGER record");
782 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
783 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000784 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
785 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000786 return Error("Invalid WIDE_INTEGER record");
787
Chris Lattner15e6d172007-05-04 19:11:41 +0000788 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000789 SmallVector<uint64_t, 8> Words;
790 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000791 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000792 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000793 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000794 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000795 break;
796 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000797 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000798 if (Record.empty())
799 return Error("Invalid FLOAT record");
800 if (CurTy == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000801 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000802 else if (CurTy == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000803 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000804 else if (CurTy == Type::X86_FP80Ty) {
805 // Bits are not stored the same way as a normal i80 APInt, compensate.
806 uint64_t Rearrange[2];
807 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
808 Rearrange[1] = Record[0] >> 48;
809 V = ConstantFP::get(APFloat(APInt(80, 2, Rearrange)));
810 } else if (CurTy == Type::FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000811 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000812 else if (CurTy == Type::PPC_FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000813 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000814 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000815 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000816 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000817 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000818
Chris Lattner15e6d172007-05-04 19:11:41 +0000819 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
820 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000821 return Error("Invalid CST_AGGREGATE record");
822
Chris Lattner15e6d172007-05-04 19:11:41 +0000823 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000824 std::vector<Constant*> Elts;
825
826 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
827 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000828 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000829 STy->getElementType(i)));
830 V = ConstantStruct::get(STy, Elts);
831 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
832 const Type *EltTy = ATy->getElementType();
833 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000834 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000835 V = ConstantArray::get(ATy, Elts);
836 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
837 const Type *EltTy = VTy->getElementType();
838 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000839 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000840 V = ConstantVector::get(Elts);
841 } else {
842 V = UndefValue::get(CurTy);
843 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000844 break;
845 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000846 case bitc::CST_CODE_STRING: { // STRING: [values]
847 if (Record.empty())
848 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000849
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000850 const ArrayType *ATy = cast<ArrayType>(CurTy);
851 const Type *EltTy = ATy->getElementType();
852
853 unsigned Size = Record.size();
854 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000855 for (unsigned i = 0; i != Size; ++i)
856 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
857 V = ConstantArray::get(ATy, Elts);
858 break;
859 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000860 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
861 if (Record.empty())
862 return Error("Invalid CST_AGGREGATE record");
863
864 const ArrayType *ATy = cast<ArrayType>(CurTy);
865 const Type *EltTy = ATy->getElementType();
866
867 unsigned Size = Record.size();
868 std::vector<Constant*> Elts;
869 for (unsigned i = 0; i != Size; ++i)
870 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
871 Elts.push_back(Constant::getNullValue(EltTy));
872 V = ConstantArray::get(ATy, Elts);
873 break;
874 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000875 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
876 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
877 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000878 if (Opc < 0) {
879 V = UndefValue::get(CurTy); // Unknown binop.
880 } else {
881 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
882 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
883 V = ConstantExpr::get(Opc, LHS, RHS);
884 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000885 break;
886 }
887 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
888 if (Record.size() < 3) return Error("Invalid CE_CAST record");
889 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000890 if (Opc < 0) {
891 V = UndefValue::get(CurTy); // Unknown cast.
892 } else {
893 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000894 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000895 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
896 V = ConstantExpr::getCast(Opc, Op, CurTy);
897 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000898 break;
899 }
900 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000901 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000902 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000903 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000904 const Type *ElTy = getTypeByID(Record[i]);
905 if (!ElTy) return Error("Invalid CE_GEP record");
906 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
907 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000908 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
909 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000910 }
911 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
912 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
913 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
914 Type::Int1Ty),
915 ValueList.getConstantFwdRef(Record[1],CurTy),
916 ValueList.getConstantFwdRef(Record[2],CurTy));
917 break;
918 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
919 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
920 const VectorType *OpTy =
921 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
922 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
923 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerba120aa2009-02-03 02:11:28 +0000924 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000925 V = ConstantExpr::getExtractElement(Op0, Op1);
926 break;
927 }
928 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
929 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
930 if (Record.size() < 3 || OpTy == 0)
931 return Error("Invalid CE_INSERTELT record");
932 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
933 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
934 OpTy->getElementType());
935 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
936 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
937 break;
938 }
939 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
940 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
941 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +0000942 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000943 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
944 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
945 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
946 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
947 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
948 break;
949 }
Nate Begeman0f123cf2009-02-12 21:28:33 +0000950 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
951 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
952 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
953 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
954 return Error("Invalid CE_SHUFVEC_EX record");
955 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
956 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
957 const Type *ShufTy=VectorType::get(Type::Int32Ty, RTy->getNumElements());
958 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
959 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
960 break;
961 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000962 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
963 if (Record.size() < 4) return Error("Invalid CE_CMP record");
964 const Type *OpTy = getTypeByID(Record[0]);
965 if (OpTy == 0) return Error("Invalid CE_CMP record");
966 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
967 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
968
969 if (OpTy->isFloatingPoint())
970 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanbaa64eb2008-05-12 20:33:52 +0000971 else if (!isa<VectorType>(OpTy))
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000972 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +0000973 else if (OpTy->isFPOrFPVector())
974 V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
975 else
976 V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000977 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000978 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000979 case bitc::CST_CODE_INLINEASM: {
980 if (Record.size() < 2) return Error("Invalid INLINEASM record");
981 std::string AsmStr, ConstrStr;
982 bool HasSideEffects = Record[0];
983 unsigned AsmStrSize = Record[1];
984 if (2+AsmStrSize >= Record.size())
985 return Error("Invalid INLINEASM record");
986 unsigned ConstStrSize = Record[2+AsmStrSize];
987 if (3+AsmStrSize+ConstStrSize > Record.size())
988 return Error("Invalid INLINEASM record");
989
990 for (unsigned i = 0; i != AsmStrSize; ++i)
991 AsmStr += (char)Record[2+i];
992 for (unsigned i = 0; i != ConstStrSize; ++i)
993 ConstrStr += (char)Record[3+AsmStrSize+i];
994 const PointerType *PTy = cast<PointerType>(CurTy);
995 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
996 AsmStr, ConstrStr, HasSideEffects);
997 break;
998 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000999 }
1000
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001001 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001002 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001003 }
Chris Lattnerea693df2008-08-21 02:34:16 +00001004
1005 if (NextCstNo != ValueList.size())
1006 return Error("Invalid constant reference!");
1007
1008 if (Stream.ReadBlockEnd())
1009 return Error("Error at end of constants block");
1010
1011 // Once all the constants have been read, go through and resolve forward
1012 // references.
1013 ValueList.ResolveConstantForwardRefs();
1014 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001015}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001016
Chris Lattner980e5aa2007-05-01 05:52:21 +00001017/// RememberAndSkipFunctionBody - When we see the block for a function body,
1018/// remember where it is and then skip it. This lets us lazily deserialize the
1019/// functions.
1020bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001021 // Get the function we are talking about.
1022 if (FunctionsWithBodies.empty())
1023 return Error("Insufficient function protos");
1024
1025 Function *Fn = FunctionsWithBodies.back();
1026 FunctionsWithBodies.pop_back();
1027
1028 // Save the current stream state.
1029 uint64_t CurBit = Stream.GetCurrentBitNo();
1030 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1031
1032 // Set the functions linkage to GhostLinkage so we know it is lazily
1033 // deserialized.
1034 Fn->setLinkage(GlobalValue::GhostLinkage);
1035
1036 // Skip over the function block for now.
1037 if (Stream.SkipBlock())
1038 return Error("Malformed block record");
1039 return false;
1040}
1041
Chris Lattner86697142007-05-01 05:01:34 +00001042bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001043 // Reject multiple MODULE_BLOCK's in a single bitstream.
1044 if (TheModule)
1045 return Error("Multiple MODULE_BLOCKs in same stream");
1046
Chris Lattnere17b6582007-05-05 00:17:00 +00001047 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001048 return Error("Malformed block record");
1049
1050 // Otherwise, create the module.
1051 TheModule = new Module(ModuleID);
1052
1053 SmallVector<uint64_t, 64> Record;
1054 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001055 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001056
1057 // Read all the records for this module.
1058 while (!Stream.AtEndOfStream()) {
1059 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001060 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001061 if (Stream.ReadBlockEnd())
1062 return Error("Error at end of module block");
1063
1064 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001065 ResolveGlobalAndAliasInits();
1066 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001067 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001068 if (!FunctionsWithBodies.empty())
1069 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001070
Chandler Carruth69940402007-08-04 01:51:18 +00001071 // Look for intrinsic functions which need to be upgraded at some point
1072 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1073 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001074 Function* NewFn;
1075 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001076 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1077 }
1078
Chris Lattner980e5aa2007-05-01 05:52:21 +00001079 // Force deallocation of memory for these vectors to favor the client that
1080 // want lazy deserialization.
1081 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1082 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1083 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001084 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001085 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001086
1087 if (Code == bitc::ENTER_SUBBLOCK) {
1088 switch (Stream.ReadSubBlockID()) {
1089 default: // Skip unknown content.
1090 if (Stream.SkipBlock())
1091 return Error("Malformed block record");
1092 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001093 case bitc::BLOCKINFO_BLOCK_ID:
1094 if (Stream.ReadBlockInfoBlock())
1095 return Error("Malformed BlockInfoBlock");
1096 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001097 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001098 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001099 return true;
1100 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001101 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001102 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001103 return true;
1104 break;
1105 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001106 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001107 return true;
1108 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001109 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001110 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001111 return true;
1112 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001113 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001114 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001115 return true;
1116 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001117 case bitc::FUNCTION_BLOCK_ID:
1118 // If this is the first function body we've seen, reverse the
1119 // FunctionsWithBodies list.
1120 if (!HasReversedFunctionsWithBodies) {
1121 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1122 HasReversedFunctionsWithBodies = true;
1123 }
1124
Chris Lattner980e5aa2007-05-01 05:52:21 +00001125 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001126 return true;
1127 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001128 }
1129 continue;
1130 }
1131
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001132 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001133 Stream.ReadAbbrevRecord();
1134 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001135 }
1136
1137 // Read a record.
1138 switch (Stream.ReadRecord(Code, Record)) {
1139 default: break; // Default behavior, ignore unknown content.
1140 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1141 if (Record.size() < 1)
1142 return Error("Malformed MODULE_CODE_VERSION");
1143 // Only version #0 is supported so far.
1144 if (Record[0] != 0)
1145 return Error("Unknown bitstream version!");
1146 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001147 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001148 std::string S;
1149 if (ConvertToString(Record, 0, S))
1150 return Error("Invalid MODULE_CODE_TRIPLE record");
1151 TheModule->setTargetTriple(S);
1152 break;
1153 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001154 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001155 std::string S;
1156 if (ConvertToString(Record, 0, S))
1157 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1158 TheModule->setDataLayout(S);
1159 break;
1160 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001161 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001162 std::string S;
1163 if (ConvertToString(Record, 0, S))
1164 return Error("Invalid MODULE_CODE_ASM record");
1165 TheModule->setModuleInlineAsm(S);
1166 break;
1167 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001168 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001169 std::string S;
1170 if (ConvertToString(Record, 0, S))
1171 return Error("Invalid MODULE_CODE_DEPLIB record");
1172 TheModule->addLibrary(S);
1173 break;
1174 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001175 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001176 std::string S;
1177 if (ConvertToString(Record, 0, S))
1178 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1179 SectionTable.push_back(S);
1180 break;
1181 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001182 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001183 std::string S;
1184 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001185 return Error("Invalid MODULE_CODE_GCNAME record");
1186 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001187 break;
1188 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001189 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001190 // linkage, alignment, section, visibility, threadlocal]
1191 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001192 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001193 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1194 const Type *Ty = getTypeByID(Record[0]);
1195 if (!isa<PointerType>(Ty))
1196 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001197 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001198 Ty = cast<PointerType>(Ty)->getElementType();
1199
1200 bool isConstant = Record[1];
1201 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1202 unsigned Alignment = (1 << Record[4]) >> 1;
1203 std::string Section;
1204 if (Record[5]) {
1205 if (Record[5]-1 >= SectionTable.size())
1206 return Error("Invalid section ID");
1207 Section = SectionTable[Record[5]-1];
1208 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001209 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001210 if (Record.size() > 6)
1211 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001212 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001213 if (Record.size() > 7)
1214 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001215
1216 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001217 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1218 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001219 NewGV->setAlignment(Alignment);
1220 if (!Section.empty())
1221 NewGV->setSection(Section);
1222 NewGV->setVisibility(Visibility);
1223 NewGV->setThreadLocal(isThreadLocal);
1224
Chris Lattner0b2482a2007-04-23 21:26:05 +00001225 ValueList.push_back(NewGV);
1226
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001227 // Remember which value to use for the global initializer.
1228 if (unsigned InitID = Record[2])
1229 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001230 break;
1231 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001232 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001233 // alignment, section, visibility, gc]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001234 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001235 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001236 return Error("Invalid MODULE_CODE_FUNCTION record");
1237 const Type *Ty = getTypeByID(Record[0]);
1238 if (!isa<PointerType>(Ty))
1239 return Error("Function not a pointer type!");
1240 const FunctionType *FTy =
1241 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1242 if (!FTy)
1243 return Error("Function not a pointer to function type!");
1244
Gabor Greif051a9502008-04-06 20:25:17 +00001245 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1246 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001247
1248 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001249 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001250 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001251 Func->setAttributes(getAttributes(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001252
1253 Func->setAlignment((1 << Record[5]) >> 1);
1254 if (Record[6]) {
1255 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001256 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001257 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001258 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001259 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001260 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001261 if (Record[8]-1 > GCTable.size())
1262 return Error("Invalid GC ID");
1263 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001264 }
Chris Lattner0b2482a2007-04-23 21:26:05 +00001265 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001266
1267 // If this is a function with a body, remember the prototype we are
1268 // creating now, so that we can match up the body with them later.
1269 if (!isProto)
1270 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001271 break;
1272 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001273 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001274 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001275 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001276 if (Record.size() < 3)
1277 return Error("Invalid MODULE_ALIAS record");
1278 const Type *Ty = getTypeByID(Record[0]);
1279 if (!isa<PointerType>(Ty))
1280 return Error("Function not a pointer type!");
1281
1282 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1283 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001284 // Old bitcode files didn't have visibility field.
1285 if (Record.size() > 3)
1286 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001287 ValueList.push_back(NewGA);
1288 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1289 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001290 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001291 /// MODULE_CODE_PURGEVALS: [numvals]
1292 case bitc::MODULE_CODE_PURGEVALS:
1293 // Trim down the value list to the specified size.
1294 if (Record.size() < 1 || Record[0] > ValueList.size())
1295 return Error("Invalid MODULE_PURGEVALS record");
1296 ValueList.shrinkTo(Record[0]);
1297 break;
1298 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001299 Record.clear();
1300 }
1301
1302 return Error("Premature end of bitstream");
1303}
1304
Chris Lattner6fa6a322008-07-09 05:14:23 +00001305/// SkipWrapperHeader - Some systems wrap bc files with a special header for
1306/// padding or other reasons. The format of this header is:
1307///
1308/// struct bc_header {
1309/// uint32_t Magic; // 0x0B17C0DE
1310/// uint32_t Version; // Version, currently always 0.
1311/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1312/// uint32_t BitcodeSize; // Size of traditional bitcode file.
1313/// ... potentially other gunk ...
1314/// };
1315///
1316/// This function is called when we find a file with a matching magic number.
1317/// In this case, skip down to the subsection of the file that is actually a BC
1318/// file.
1319static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
1320 enum {
1321 KnownHeaderSize = 4*4, // Size of header we read.
1322 OffsetField = 2*4, // Offset in bytes to Offset field.
1323 SizeField = 3*4 // Offset in bytes to Size field.
1324 };
1325
1326
1327 // Must contain the header!
1328 if (BufEnd-BufPtr < KnownHeaderSize) return true;
1329
1330 unsigned Offset = ( BufPtr[OffsetField ] |
1331 (BufPtr[OffsetField+1] << 8) |
1332 (BufPtr[OffsetField+2] << 16) |
1333 (BufPtr[OffsetField+3] << 24));
1334 unsigned Size = ( BufPtr[SizeField ] |
1335 (BufPtr[SizeField +1] << 8) |
1336 (BufPtr[SizeField +2] << 16) |
1337 (BufPtr[SizeField +3] << 24));
1338
1339 // Verify that Offset+Size fits in the file.
1340 if (Offset+Size > unsigned(BufEnd-BufPtr))
1341 return true;
1342 BufPtr += Offset;
1343 BufEnd = BufPtr+Size;
1344 return false;
1345}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001346
Chris Lattnerc453f762007-04-29 07:54:31 +00001347bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001348 TheModule = 0;
1349
Chris Lattnerc453f762007-04-29 07:54:31 +00001350 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001351 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1352
Chris Lattnerc453f762007-04-29 07:54:31 +00001353 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001354 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1355
1356 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1357 // The magic number is 0x0B17C0DE stored in little endian.
1358 if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 &&
1359 BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
1360 if (SkipWrapperHeader(BufPtr, BufEnd))
1361 return Error("Invalid bitcode wrapper header");
1362
1363 Stream.init(BufPtr, BufEnd);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001364
1365 // Sniff for the signature.
1366 if (Stream.Read(8) != 'B' ||
1367 Stream.Read(8) != 'C' ||
1368 Stream.Read(4) != 0x0 ||
1369 Stream.Read(4) != 0xC ||
1370 Stream.Read(4) != 0xE ||
1371 Stream.Read(4) != 0xD)
1372 return Error("Invalid bitcode signature");
1373
1374 // We expect a number of well-defined blocks, though we don't necessarily
1375 // need to understand them all.
1376 while (!Stream.AtEndOfStream()) {
1377 unsigned Code = Stream.ReadCode();
1378
1379 if (Code != bitc::ENTER_SUBBLOCK)
1380 return Error("Invalid record at top-level");
1381
1382 unsigned BlockID = Stream.ReadSubBlockID();
1383
1384 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001385 switch (BlockID) {
1386 case bitc::BLOCKINFO_BLOCK_ID:
1387 if (Stream.ReadBlockInfoBlock())
1388 return Error("Malformed BlockInfoBlock");
1389 break;
1390 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001391 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001392 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001393 break;
1394 default:
1395 if (Stream.SkipBlock())
1396 return Error("Malformed block record");
1397 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001398 }
1399 }
1400
1401 return false;
1402}
Chris Lattnerc453f762007-04-29 07:54:31 +00001403
Chris Lattner48f84872007-05-01 04:59:48 +00001404
Chris Lattner980e5aa2007-05-01 05:52:21 +00001405/// ParseFunctionBody - Lazily parse the specified function body block.
1406bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001407 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001408 return Error("Malformed block record");
1409
1410 unsigned ModuleValueListSize = ValueList.size();
1411
1412 // Add all the function arguments to the value table.
1413 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1414 ValueList.push_back(I);
1415
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001416 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001417 BasicBlock *CurBB = 0;
1418 unsigned CurBBNo = 0;
1419
Chris Lattner980e5aa2007-05-01 05:52:21 +00001420 // Read all the records.
1421 SmallVector<uint64_t, 64> Record;
1422 while (1) {
1423 unsigned Code = Stream.ReadCode();
1424 if (Code == bitc::END_BLOCK) {
1425 if (Stream.ReadBlockEnd())
1426 return Error("Error at end of function block");
1427 break;
1428 }
1429
1430 if (Code == bitc::ENTER_SUBBLOCK) {
1431 switch (Stream.ReadSubBlockID()) {
1432 default: // Skip unknown content.
1433 if (Stream.SkipBlock())
1434 return Error("Malformed block record");
1435 break;
1436 case bitc::CONSTANTS_BLOCK_ID:
1437 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001438 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001439 break;
1440 case bitc::VALUE_SYMTAB_BLOCK_ID:
1441 if (ParseValueSymbolTable()) return true;
1442 break;
1443 }
1444 continue;
1445 }
1446
1447 if (Code == bitc::DEFINE_ABBREV) {
1448 Stream.ReadAbbrevRecord();
1449 continue;
1450 }
1451
1452 // Read a record.
1453 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001454 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001455 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001456 default: // Default behavior: reject
1457 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001458 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001459 if (Record.size() < 1 || Record[0] == 0)
1460 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001461 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001462 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001463 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001464 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001465 CurBB = FunctionBBs[0];
1466 continue;
1467
Chris Lattnerabfbf852007-05-06 00:21:25 +00001468 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1469 unsigned OpNum = 0;
1470 Value *LHS, *RHS;
1471 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1472 getValue(Record, OpNum, LHS->getType(), RHS) ||
1473 OpNum+1 != Record.size())
1474 return Error("Invalid BINOP record");
1475
1476 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1477 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001478 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001479 break;
1480 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001481 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1482 unsigned OpNum = 0;
1483 Value *Op;
1484 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1485 OpNum+2 != Record.size())
1486 return Error("Invalid CAST record");
1487
1488 const Type *ResTy = getTypeByID(Record[OpNum]);
1489 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1490 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001491 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001492 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Chris Lattner231cbcb2007-05-02 04:27:25 +00001493 break;
1494 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001495 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001496 unsigned OpNum = 0;
1497 Value *BasePtr;
1498 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001499 return Error("Invalid GEP record");
1500
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001501 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001502 while (OpNum != Record.size()) {
1503 Value *Op;
1504 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001505 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001506 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001507 }
1508
Gabor Greif051a9502008-04-06 20:25:17 +00001509 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001510 break;
1511 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001512
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001513 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1514 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001515 unsigned OpNum = 0;
1516 Value *Agg;
1517 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1518 return Error("Invalid EXTRACTVAL record");
1519
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001520 SmallVector<unsigned, 4> EXTRACTVALIdx;
1521 for (unsigned RecSize = Record.size();
1522 OpNum != RecSize; ++OpNum) {
1523 uint64_t Index = Record[OpNum];
1524 if ((unsigned)Index != Index)
1525 return Error("Invalid EXTRACTVAL index");
1526 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001527 }
1528
1529 I = ExtractValueInst::Create(Agg,
1530 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1531 break;
1532 }
1533
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001534 case bitc::FUNC_CODE_INST_INSERTVAL: {
1535 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00001536 unsigned OpNum = 0;
1537 Value *Agg;
1538 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1539 return Error("Invalid INSERTVAL record");
1540 Value *Val;
1541 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1542 return Error("Invalid INSERTVAL record");
1543
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001544 SmallVector<unsigned, 4> INSERTVALIdx;
1545 for (unsigned RecSize = Record.size();
1546 OpNum != RecSize; ++OpNum) {
1547 uint64_t Index = Record[OpNum];
1548 if ((unsigned)Index != Index)
1549 return Error("Invalid INSERTVAL index");
1550 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00001551 }
1552
1553 I = InsertValueInst::Create(Agg, Val,
1554 INSERTVALIdx.begin(), INSERTVALIdx.end());
1555 break;
1556 }
1557
Chris Lattnerabfbf852007-05-06 00:21:25 +00001558 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001559 // obsolete form of select
1560 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00001561 unsigned OpNum = 0;
1562 Value *TrueVal, *FalseVal, *Cond;
1563 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1564 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Dan Gohmanbe919402008-09-09 02:08:49 +00001565 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001566 return Error("Invalid SELECT record");
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001567
1568 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1569 break;
1570 }
1571
1572 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1573 // new form of select
1574 // handles select i1 or select [N x i1]
1575 unsigned OpNum = 0;
1576 Value *TrueVal, *FalseVal, *Cond;
1577 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1578 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1579 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1580 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00001581
1582 // select condition can be either i1 or [N x i1]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001583 if (const VectorType* vector_type =
1584 dyn_cast<const VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00001585 // expect <n x i1>
1586 if (vector_type->getElementType() != Type::Int1Ty)
1587 return Error("Invalid SELECT condition type");
1588 } else {
1589 // expect i1
1590 if (Cond->getType() != Type::Int1Ty)
1591 return Error("Invalid SELECT condition type");
1592 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001593
Gabor Greif051a9502008-04-06 20:25:17 +00001594 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001595 break;
1596 }
1597
1598 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001599 unsigned OpNum = 0;
1600 Value *Vec, *Idx;
1601 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1602 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001603 return Error("Invalid EXTRACTELT record");
1604 I = new ExtractElementInst(Vec, Idx);
1605 break;
1606 }
1607
1608 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001609 unsigned OpNum = 0;
1610 Value *Vec, *Elt, *Idx;
1611 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1612 getValue(Record, OpNum,
1613 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1614 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001615 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001616 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001617 break;
1618 }
1619
Chris Lattnerabfbf852007-05-06 00:21:25 +00001620 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1621 unsigned OpNum = 0;
1622 Value *Vec1, *Vec2, *Mask;
1623 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1624 getValue(Record, OpNum, Vec1->getType(), Vec2))
1625 return Error("Invalid SHUFFLEVEC record");
1626
Mon P Wangaeb06d22008-11-10 04:46:22 +00001627 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001628 return Error("Invalid SHUFFLEVEC record");
1629 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1630 break;
1631 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001632
Chris Lattner01ff65f2007-05-02 05:16:49 +00001633 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001634 // VFCmp/VICmp
1635 // or old form of ICmp/FCmp returning bool
Chris Lattner7337ab92007-05-06 00:00:00 +00001636 unsigned OpNum = 0;
1637 Value *LHS, *RHS;
1638 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1639 getValue(Record, OpNum, LHS->getType(), RHS) ||
1640 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001641 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001642
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001643 if (LHS->getType()->isFloatingPoint())
Nate Begemanac80ade2008-05-12 19:01:56 +00001644 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanbaa64eb2008-05-12 20:33:52 +00001645 else if (!isa<VectorType>(LHS->getType()))
1646 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Nate Begemanac80ade2008-05-12 19:01:56 +00001647 else if (LHS->getType()->isFPOrFPVector())
1648 I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1649 else
1650 I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001651 break;
1652 }
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001653 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1654 // Fcmp/ICmp returning bool or vector of bool
Dan Gohmanf72fb672008-09-09 01:02:47 +00001655 unsigned OpNum = 0;
1656 Value *LHS, *RHS;
1657 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1658 getValue(Record, OpNum, LHS->getType(), RHS) ||
1659 OpNum+1 != Record.size())
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00001660 return Error("Invalid CMP2 record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00001661
Dan Gohmanf72fb672008-09-09 01:02:47 +00001662 if (LHS->getType()->isFPOrFPVector())
1663 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1664 else
1665 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1666 break;
1667 }
Devang Patel197be3d2008-02-22 02:49:49 +00001668 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1669 if (Record.size() != 2)
1670 return Error("Invalid GETRESULT record");
1671 unsigned OpNum = 0;
1672 Value *Op;
1673 getValueTypePair(Record, OpNum, NextValueNo, Op);
1674 unsigned Index = Record[1];
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001675 I = ExtractValueInst::Create(Op, Index);
Devang Patel197be3d2008-02-22 02:49:49 +00001676 break;
1677 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001678
Chris Lattner231cbcb2007-05-02 04:27:25 +00001679 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001680 {
1681 unsigned Size = Record.size();
1682 if (Size == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00001683 I = ReturnInst::Create();
Devang Pateld9d99ff2008-02-26 01:29:32 +00001684 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001685 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00001686
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001687 unsigned OpNum = 0;
1688 SmallVector<Value *,4> Vs;
1689 do {
1690 Value *Op = NULL;
1691 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1692 return Error("Invalid RET record");
1693 Vs.push_back(Op);
1694 } while(OpNum != Record.size());
1695
1696 const Type *ReturnType = F->getReturnType();
1697 if (Vs.size() > 1 ||
1698 (isa<StructType>(ReturnType) &&
1699 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1700 Value *RV = UndefValue::get(ReturnType);
1701 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1702 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1703 CurBB->getInstList().push_back(I);
1704 ValueList.AssignValue(I, NextValueNo++);
1705 RV = I;
1706 }
1707 I = ReturnInst::Create(RV);
Devang Pateld9d99ff2008-02-26 01:29:32 +00001708 break;
1709 }
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001710
1711 I = ReturnInst::Create(Vs[0]);
1712 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00001713 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001714 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001715 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001716 return Error("Invalid BR record");
1717 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1718 if (TrueDest == 0)
1719 return Error("Invalid BR record");
1720
1721 if (Record.size() == 1)
Gabor Greif051a9502008-04-06 20:25:17 +00001722 I = BranchInst::Create(TrueDest);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001723 else {
1724 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1725 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1726 if (FalseDest == 0 || Cond == 0)
1727 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001728 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001729 }
1730 break;
1731 }
1732 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1733 if (Record.size() < 3 || (Record.size() & 1) == 0)
1734 return Error("Invalid SWITCH record");
1735 const Type *OpTy = getTypeByID(Record[0]);
1736 Value *Cond = getFnValueByID(Record[1], OpTy);
1737 BasicBlock *Default = getBasicBlock(Record[2]);
1738 if (OpTy == 0 || Cond == 0 || Default == 0)
1739 return Error("Invalid SWITCH record");
1740 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001741 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001742 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1743 ConstantInt *CaseVal =
1744 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1745 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1746 if (CaseVal == 0 || DestBB == 0) {
1747 delete SI;
1748 return Error("Invalid SWITCH record!");
1749 }
1750 SI->addCase(CaseVal, DestBB);
1751 }
1752 I = SI;
1753 break;
1754 }
1755
Duncan Sandsdc024672007-11-27 13:23:08 +00001756 case bitc::FUNC_CODE_INST_INVOKE: {
1757 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001758 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00001759 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001760 unsigned CCInfo = Record[1];
1761 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1762 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001763
Chris Lattnera9bb7132007-05-08 05:38:01 +00001764 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001765 Value *Callee;
1766 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001767 return Error("Invalid INVOKE record");
1768
Chris Lattner7337ab92007-05-06 00:00:00 +00001769 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1770 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001771 dyn_cast<FunctionType>(CalleeTy->getElementType());
1772
1773 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001774 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1775 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001776 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001777
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001778 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001779 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1780 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1781 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001782 }
1783
Chris Lattner7337ab92007-05-06 00:00:00 +00001784 if (!FTy->isVarArg()) {
1785 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001786 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001787 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001788 // Read type/value pairs for varargs params.
1789 while (OpNum != Record.size()) {
1790 Value *Op;
1791 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1792 return Error("Invalid INVOKE record");
1793 Ops.push_back(Op);
1794 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001795 }
1796
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001797 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1798 Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001799 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Devang Patel05988662008-09-25 21:00:45 +00001800 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001801 break;
1802 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001803 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1804 I = new UnwindInst();
1805 break;
1806 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1807 I = new UnreachableInst();
1808 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001809 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001810 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001811 return Error("Invalid PHI record");
1812 const Type *Ty = getTypeByID(Record[0]);
1813 if (!Ty) return Error("Invalid PHI record");
1814
Gabor Greif051a9502008-04-06 20:25:17 +00001815 PHINode *PN = PHINode::Create(Ty);
Chris Lattner86941612008-04-13 00:14:42 +00001816 PN->reserveOperandSpace((Record.size()-1)/2);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001817
Chris Lattner15e6d172007-05-04 19:11:41 +00001818 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1819 Value *V = getFnValueByID(Record[1+i], Ty);
1820 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001821 if (!V || !BB) return Error("Invalid PHI record");
1822 PN->addIncoming(V, BB);
1823 }
1824 I = PN;
1825 break;
1826 }
1827
1828 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1829 if (Record.size() < 3)
1830 return Error("Invalid MALLOC record");
1831 const PointerType *Ty =
1832 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1833 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1834 unsigned Align = Record[2];
1835 if (!Ty || !Size) return Error("Invalid MALLOC record");
1836 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1837 break;
1838 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001839 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1840 unsigned OpNum = 0;
1841 Value *Op;
1842 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1843 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001844 return Error("Invalid FREE record");
1845 I = new FreeInst(Op);
1846 break;
1847 }
1848 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1849 if (Record.size() < 3)
1850 return Error("Invalid ALLOCA record");
1851 const PointerType *Ty =
1852 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1853 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1854 unsigned Align = Record[2];
1855 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1856 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1857 break;
1858 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001859 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001860 unsigned OpNum = 0;
1861 Value *Op;
1862 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1863 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001864 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001865
1866 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001867 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001868 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001869 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1870 unsigned OpNum = 0;
1871 Value *Val, *Ptr;
1872 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1873 getValue(Record, OpNum,
1874 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1875 OpNum+2 != Record.size())
1876 return Error("Invalid STORE record");
1877
1878 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1879 break;
1880 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001881 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001882 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001883 unsigned OpNum = 0;
1884 Value *Val, *Ptr;
1885 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001886 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001887 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001888 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001889
1890 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001891 break;
1892 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001893 case bitc::FUNC_CODE_INST_CALL: {
1894 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1895 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001896 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001897
Devang Patel05988662008-09-25 21:00:45 +00001898 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001899 unsigned CCInfo = Record[1];
1900
1901 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001902 Value *Callee;
1903 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1904 return Error("Invalid CALL record");
1905
1906 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001907 const FunctionType *FTy = 0;
1908 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001909 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001910 return Error("Invalid CALL record");
1911
1912 SmallVector<Value*, 16> Args;
1913 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001914 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001915 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1916 Args.push_back(getBasicBlock(Record[OpNum]));
1917 else
1918 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001919 if (Args.back() == 0) return Error("Invalid CALL record");
1920 }
1921
Chris Lattner0579f7f2007-05-03 22:04:19 +00001922 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001923 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001924 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001925 return Error("Invalid CALL record");
1926 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001927 while (OpNum != Record.size()) {
1928 Value *Op;
1929 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1930 return Error("Invalid CALL record");
1931 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001932 }
1933 }
1934
Gabor Greif051a9502008-04-06 20:25:17 +00001935 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001936 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1937 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00001938 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001939 break;
1940 }
1941 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1942 if (Record.size() < 3)
1943 return Error("Invalid VAARG record");
1944 const Type *OpTy = getTypeByID(Record[0]);
1945 Value *Op = getFnValueByID(Record[1], OpTy);
1946 const Type *ResTy = getTypeByID(Record[2]);
1947 if (!OpTy || !Op || !ResTy)
1948 return Error("Invalid VAARG record");
1949 I = new VAArgInst(Op, ResTy);
1950 break;
1951 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001952 }
1953
1954 // Add instruction to end of current BB. If there is no current BB, reject
1955 // this file.
1956 if (CurBB == 0) {
1957 delete I;
1958 return Error("Invalid instruction with no BB");
1959 }
1960 CurBB->getInstList().push_back(I);
1961
1962 // If this was a terminator instruction, move to the next block.
1963 if (isa<TerminatorInst>(I)) {
1964 ++CurBBNo;
1965 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1966 }
1967
1968 // Non-void values get registered in the value table for future use.
1969 if (I && I->getType() != Type::VoidTy)
1970 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001971 }
1972
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001973 // Check the function list for unresolved values.
1974 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1975 if (A->getParent() == 0) {
1976 // We found at least one unresolved value. Nuke them all to avoid leaks.
1977 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1978 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1979 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1980 delete A;
1981 }
1982 }
Chris Lattner35a04702007-05-04 03:50:29 +00001983 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001984 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001985 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001986
1987 // Trim the value list down to the size it was before we parsed this function.
1988 ValueList.shrinkTo(ModuleValueListSize);
1989 std::vector<BasicBlock*>().swap(FunctionBBs);
1990
Chris Lattner48f84872007-05-01 04:59:48 +00001991 return false;
1992}
1993
Chris Lattnerb348bb82007-05-18 04:02:46 +00001994//===----------------------------------------------------------------------===//
1995// ModuleProvider implementation
1996//===----------------------------------------------------------------------===//
1997
1998
1999bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2000 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00002001 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002002
2003 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2004 DeferredFunctionInfo.find(F);
2005 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2006
2007 // Move the bit stream to the saved position of the deferred function body and
2008 // restore the real linkage type for the function.
2009 Stream.JumpToBit(DFII->second.first);
2010 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2011
2012 if (ParseFunctionBody(F)) {
2013 if (ErrInfo) *ErrInfo = ErrorString;
2014 return true;
2015 }
Chandler Carruth69940402007-08-04 01:51:18 +00002016
2017 // Upgrade any old intrinsic calls in the function.
2018 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2019 E = UpgradedIntrinsics.end(); I != E; ++I) {
2020 if (I->first != I->second) {
2021 for (Value::use_iterator UI = I->first->use_begin(),
2022 UE = I->first->use_end(); UI != UE; ) {
2023 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2024 UpgradeIntrinsicCall(CI, I->second);
2025 }
2026 }
2027 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00002028
2029 return false;
2030}
2031
2032void BitcodeReader::dematerializeFunction(Function *F) {
2033 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00002034 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00002035 return;
2036
2037 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2038
2039 // Just forget the function body, we can remat it later.
2040 F->deleteBody();
2041 F->setLinkage(GlobalValue::GhostLinkage);
2042}
2043
2044
2045Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2046 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
2047 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
2048 ++I) {
2049 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00002050 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00002051 materializeFunction(F, ErrInfo))
2052 return 0;
2053 }
Chandler Carruth69940402007-08-04 01:51:18 +00002054
2055 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2056 // delete the old functions to clean up. We can't do this unless the entire
2057 // module is materialized because there could always be another function body
2058 // with calls to the old function.
2059 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2060 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2061 if (I->first != I->second) {
2062 for (Value::use_iterator UI = I->first->use_begin(),
2063 UE = I->first->use_end(); UI != UE; ) {
2064 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2065 UpgradeIntrinsicCall(CI, I->second);
2066 }
2067 ValueList.replaceUsesOfWith(I->first, I->second);
2068 I->first->eraseFromParent();
2069 }
2070 }
2071 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2072
Chris Lattnerb348bb82007-05-18 04:02:46 +00002073 return TheModule;
2074}
2075
2076
2077/// This method is provided by the parent ModuleProvde class and overriden
2078/// here. It simply releases the module from its provided and frees up our
2079/// state.
2080/// @brief Release our hold on the generated module
2081Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2082 // Since we're losing control of this Module, we must hand it back complete
2083 Module *M = ModuleProvider::releaseModule(ErrInfo);
2084 FreeState();
2085 return M;
2086}
2087
Chris Lattner48f84872007-05-01 04:59:48 +00002088
Chris Lattnerc453f762007-04-29 07:54:31 +00002089//===----------------------------------------------------------------------===//
2090// External interface
2091//===----------------------------------------------------------------------===//
2092
2093/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2094///
2095ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2096 std::string *ErrMsg) {
2097 BitcodeReader *R = new BitcodeReader(Buffer);
2098 if (R->ParseBitcode()) {
2099 if (ErrMsg)
2100 *ErrMsg = R->getErrorString();
2101
2102 // Don't let the BitcodeReader dtor delete 'Buffer'.
2103 R->releaseMemoryBuffer();
2104 delete R;
2105 return 0;
2106 }
2107 return R;
2108}
2109
2110/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2111/// If an error occurs, return null and fill in *ErrMsg if non-null.
2112Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
2113 BitcodeReader *R;
2114 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
2115 if (!R) return 0;
2116
Chris Lattnerb348bb82007-05-18 04:02:46 +00002117 // Read in the entire module.
2118 Module *M = R->materializeModule(ErrMsg);
2119
2120 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2121 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00002122 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002123
2124 // If there was no error, tell ModuleProvider not to delete it when its dtor
2125 // is run.
2126 if (M)
2127 M = R->releaseModule(ErrMsg);
2128
Chris Lattnerc453f762007-04-29 07:54:31 +00002129 delete R;
2130 return M;
2131}