blob: c86ee3048a9b65cd4df0a4ce4768e77bff6c1301 [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"
Dale Johannesen22c39792008-02-22 22:17:59 +000021#include "llvm/ParamAttrsList.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000024#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000025#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000026#include "llvm/Support/MemoryBuffer.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
35 // Drop references to ParamAttrs.
36 for (unsigned i = 0, e = ParamAttrs.size(); i != e; ++i)
37 ParamAttrs[i]->dropRef();
38
Chris Lattnerb348bb82007-05-18 04:02:46 +000039 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
40 std::vector<BasicBlock*>().swap(FunctionBBs);
41 std::vector<Function*>().swap(FunctionsWithBodies);
42 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000043}
44
Chris Lattner48c85b82007-05-04 03:30:17 +000045//===----------------------------------------------------------------------===//
46// Helper functions to implement forward reference resolution, etc.
47//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000048
Chris Lattnercaee0dc2007-04-22 06:23:29 +000049/// ConvertToString - Convert a string from a record into an std::string, return
50/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000051template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000052static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000053 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000054 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000055 return true;
56
Chris Lattner15e6d172007-05-04 19:11:41 +000057 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000059 return false;
60}
61
62static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
63 switch (Val) {
64 default: // Map unknown/new linkages to external
65 case 0: return GlobalValue::ExternalLinkage;
66 case 1: return GlobalValue::WeakLinkage;
67 case 2: return GlobalValue::AppendingLinkage;
68 case 3: return GlobalValue::InternalLinkage;
69 case 4: return GlobalValue::LinkOnceLinkage;
70 case 5: return GlobalValue::DLLImportLinkage;
71 case 6: return GlobalValue::DLLExportLinkage;
72 case 7: return GlobalValue::ExternalWeakLinkage;
73 }
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
123
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
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000130 public:
131 Use Op;
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000132 explicit ConstantPlaceHolder(const Type *Ty)
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000133 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
134 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000135 }
136 };
137}
138
139Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
140 const Type *Ty) {
141 if (Idx >= size()) {
142 // Insert a bunch of null values.
143 Uses.resize(Idx+1);
144 OperandList = &Uses[0];
145 NumOperands = Idx+1;
146 }
147
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000148 if (Value *V = Uses[Idx]) {
149 assert(Ty == V->getType() && "Type mismatch in constant table!");
150 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000151 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000152
153 // Create and return a placeholder, which will later be RAUW'd.
154 Constant *C = new ConstantPlaceHolder(Ty);
155 Uses[Idx].init(C, this);
156 return C;
157}
158
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000159Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
160 if (Idx >= size()) {
161 // Insert a bunch of null values.
162 Uses.resize(Idx+1);
163 OperandList = &Uses[0];
164 NumOperands = Idx+1;
165 }
166
167 if (Value *V = Uses[Idx]) {
168 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
169 return V;
170 }
171
Chris Lattner01ff65f2007-05-02 05:16:49 +0000172 // No type specified, must be invalid reference.
173 if (Ty == 0) return 0;
174
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000175 // Create and return a placeholder, which will later be RAUW'd.
176 Value *V = new Argument(Ty);
177 Uses[Idx].init(V, this);
178 return V;
179}
180
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000181
182const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
183 // If the TypeID is in range, return it.
184 if (ID < TypeList.size())
185 return TypeList[ID].get();
186 if (!isTypeTable) return 0;
187
188 // The type table allows forward references. Push as many Opaque types as
189 // needed to get up to ID.
190 while (TypeList.size() <= ID)
191 TypeList.push_back(OpaqueType::get());
192 return TypeList.back().get();
193}
194
Chris Lattner48c85b82007-05-04 03:30:17 +0000195//===----------------------------------------------------------------------===//
196// Functions for parsing blocks from the bitcode file
197//===----------------------------------------------------------------------===//
198
199bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000200 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000201 return Error("Malformed block record");
202
203 if (!ParamAttrs.empty())
204 return Error("Multiple PARAMATTR blocks found!");
205
206 SmallVector<uint64_t, 64> Record;
207
208 ParamAttrsVector Attrs;
209
210 // Read all the records.
211 while (1) {
212 unsigned Code = Stream.ReadCode();
213 if (Code == bitc::END_BLOCK) {
214 if (Stream.ReadBlockEnd())
215 return Error("Error at end of PARAMATTR block");
216 return false;
217 }
218
219 if (Code == bitc::ENTER_SUBBLOCK) {
220 // No known subblocks, always skip them.
221 Stream.ReadSubBlockID();
222 if (Stream.SkipBlock())
223 return Error("Malformed block record");
224 continue;
225 }
226
227 if (Code == bitc::DEFINE_ABBREV) {
228 Stream.ReadAbbrevRecord();
229 continue;
230 }
231
232 // Read a record.
233 Record.clear();
234 switch (Stream.ReadRecord(Code, Record)) {
235 default: // Default behavior: ignore.
236 break;
237 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
238 if (Record.size() & 1)
239 return Error("Invalid ENTRY record");
240
Chris Lattner48c85b82007-05-04 03:30:17 +0000241 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Duncan Sands5e41f652007-11-20 14:09:29 +0000242 if (Record[i+1] != ParamAttr::None)
243 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
Chris Lattner48c85b82007-05-04 03:30:17 +0000244 }
Chris Lattner461edd92008-03-12 02:25:52 +0000245 if (Attrs.empty()) {
246 ParamAttrs.push_back(0);
247 } else {
248 ParamAttrs.push_back(ParamAttrsList::get(Attrs));
249 ParamAttrs.back()->addRef();
250 }
251
Chris Lattner48c85b82007-05-04 03:30:17 +0000252 Attrs.clear();
253 break;
254 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000255 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000256 }
257}
258
259
Chris Lattner86697142007-05-01 05:01:34 +0000260bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000261 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000262 return Error("Malformed block record");
263
264 if (!TypeList.empty())
265 return Error("Multiple TYPE_BLOCKs found!");
266
267 SmallVector<uint64_t, 64> Record;
268 unsigned NumRecords = 0;
269
270 // Read all the records for this type table.
271 while (1) {
272 unsigned Code = Stream.ReadCode();
273 if (Code == bitc::END_BLOCK) {
274 if (NumRecords != TypeList.size())
275 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000276 if (Stream.ReadBlockEnd())
277 return Error("Error at end of type table block");
278 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000279 }
280
281 if (Code == bitc::ENTER_SUBBLOCK) {
282 // No known subblocks, always skip them.
283 Stream.ReadSubBlockID();
284 if (Stream.SkipBlock())
285 return Error("Malformed block record");
286 continue;
287 }
288
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000289 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000290 Stream.ReadAbbrevRecord();
291 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000292 }
293
294 // Read a record.
295 Record.clear();
296 const Type *ResultTy = 0;
297 switch (Stream.ReadRecord(Code, Record)) {
298 default: // Default behavior: unknown type.
299 ResultTy = 0;
300 break;
301 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
302 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
303 // type list. This allows us to reserve space.
304 if (Record.size() < 1)
305 return Error("Invalid TYPE_CODE_NUMENTRY record");
306 TypeList.reserve(Record[0]);
307 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000308 case bitc::TYPE_CODE_VOID: // VOID
309 ResultTy = Type::VoidTy;
310 break;
311 case bitc::TYPE_CODE_FLOAT: // FLOAT
312 ResultTy = Type::FloatTy;
313 break;
314 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
315 ResultTy = Type::DoubleTy;
316 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000317 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
318 ResultTy = Type::X86_FP80Ty;
319 break;
320 case bitc::TYPE_CODE_FP128: // FP128
321 ResultTy = Type::FP128Ty;
322 break;
323 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
324 ResultTy = Type::PPC_FP128Ty;
325 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000326 case bitc::TYPE_CODE_LABEL: // LABEL
327 ResultTy = Type::LabelTy;
328 break;
329 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
330 ResultTy = 0;
331 break;
332 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
333 if (Record.size() < 1)
334 return Error("Invalid Integer type record");
335
336 ResultTy = IntegerType::get(Record[0]);
337 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000338 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
339 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000340 if (Record.size() < 1)
341 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000342 unsigned AddressSpace = 0;
343 if (Record.size() == 2)
344 AddressSpace = Record[1];
345 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000346 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000347 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000348 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000349 // FIXME: attrid is dead, remove it in LLVM 3.0
350 // FUNCTION: [vararg, attrid, retty, paramty x N]
351 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000352 return Error("Invalid FUNCTION type record");
353 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000354 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000355 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000356
Chris Lattnera1afde72007-11-27 17:48:06 +0000357 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000358 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000359 break;
360 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000361 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000362 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000363 return Error("Invalid STRUCT type record");
364 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000365 for (unsigned i = 1, e = Record.size(); i != e; ++i)
366 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000367 ResultTy = StructType::get(EltTys, Record[0]);
368 break;
369 }
370 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
371 if (Record.size() < 2)
372 return Error("Invalid ARRAY type record");
373 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
374 break;
375 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
376 if (Record.size() < 2)
377 return Error("Invalid VECTOR type record");
378 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
379 break;
380 }
381
382 if (NumRecords == TypeList.size()) {
383 // If this is a new type slot, just append it.
384 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
385 ++NumRecords;
386 } else if (ResultTy == 0) {
387 // Otherwise, this was forward referenced, so an opaque type was created,
388 // but the result type is actually just an opaque. Leave the one we
389 // created previously.
390 ++NumRecords;
391 } else {
392 // Otherwise, this was forward referenced, so an opaque type was created.
393 // Resolve the opaque type to the real type now.
394 assert(NumRecords < TypeList.size() && "Typelist imbalance");
395 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
396
397 // Don't directly push the new type on the Tab. Instead we want to replace
398 // the opaque type we previously inserted with the new concrete value. The
399 // refinement from the abstract (opaque) type to the new type causes all
400 // uses of the abstract type to use the concrete type (NewTy). This will
401 // also cause the opaque type to be deleted.
402 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
403
404 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000405 // value table... or with a preexisting type that was already in the
406 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000407 assert(TypeList[NumRecords-1].get() != OldTy &&
408 "refineAbstractType didn't work!");
409 }
410 }
411}
412
413
Chris Lattner86697142007-05-01 05:01:34 +0000414bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000415 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000416 return Error("Malformed block record");
417
418 SmallVector<uint64_t, 64> Record;
419
420 // Read all the records for this type table.
421 std::string TypeName;
422 while (1) {
423 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000424 if (Code == bitc::END_BLOCK) {
425 if (Stream.ReadBlockEnd())
426 return Error("Error at end of type symbol table block");
427 return false;
428 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000429
430 if (Code == bitc::ENTER_SUBBLOCK) {
431 // No known subblocks, always skip them.
432 Stream.ReadSubBlockID();
433 if (Stream.SkipBlock())
434 return Error("Malformed block record");
435 continue;
436 }
437
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000438 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000439 Stream.ReadAbbrevRecord();
440 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000441 }
442
443 // Read a record.
444 Record.clear();
445 switch (Stream.ReadRecord(Code, Record)) {
446 default: // Default behavior: unknown type.
447 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000448 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000449 if (ConvertToString(Record, 1, TypeName))
450 return Error("Invalid TST_ENTRY record");
451 unsigned TypeID = Record[0];
452 if (TypeID >= TypeList.size())
453 return Error("Invalid Type ID in TST_ENTRY record");
454
455 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
456 TypeName.clear();
457 break;
458 }
459 }
460}
461
Chris Lattner86697142007-05-01 05:01:34 +0000462bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000463 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000464 return Error("Malformed block record");
465
466 SmallVector<uint64_t, 64> Record;
467
468 // Read all the records for this value table.
469 SmallString<128> ValueName;
470 while (1) {
471 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000472 if (Code == bitc::END_BLOCK) {
473 if (Stream.ReadBlockEnd())
474 return Error("Error at end of value symbol table block");
475 return false;
476 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000477 if (Code == bitc::ENTER_SUBBLOCK) {
478 // No known subblocks, always skip them.
479 Stream.ReadSubBlockID();
480 if (Stream.SkipBlock())
481 return Error("Malformed block record");
482 continue;
483 }
484
485 if (Code == bitc::DEFINE_ABBREV) {
486 Stream.ReadAbbrevRecord();
487 continue;
488 }
489
490 // Read a record.
491 Record.clear();
492 switch (Stream.ReadRecord(Code, Record)) {
493 default: // Default behavior: unknown type.
494 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000495 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000496 if (ConvertToString(Record, 1, ValueName))
497 return Error("Invalid TST_ENTRY record");
498 unsigned ValueID = Record[0];
499 if (ValueID >= ValueList.size())
500 return Error("Invalid Value ID in VST_ENTRY record");
501 Value *V = ValueList[ValueID];
502
503 V->setName(&ValueName[0], ValueName.size());
504 ValueName.clear();
505 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000506 }
507 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000508 if (ConvertToString(Record, 1, ValueName))
509 return Error("Invalid VST_BBENTRY record");
510 BasicBlock *BB = getBasicBlock(Record[0]);
511 if (BB == 0)
512 return Error("Invalid BB ID in VST_BBENTRY record");
513
514 BB->setName(&ValueName[0], ValueName.size());
515 ValueName.clear();
516 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000517 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000518 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000519 }
520}
521
Chris Lattner0eef0802007-04-24 04:04:35 +0000522/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
523/// the LSB for dense VBR encoding.
524static uint64_t DecodeSignRotatedValue(uint64_t V) {
525 if ((V & 1) == 0)
526 return V >> 1;
527 if (V != 1)
528 return -(V >> 1);
529 // There is no such thing as -0 with integers. "-0" really means MININT.
530 return 1ULL << 63;
531}
532
Chris Lattner07d98b42007-04-26 02:46:40 +0000533/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
534/// values and aliases that we can.
535bool BitcodeReader::ResolveGlobalAndAliasInits() {
536 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
537 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
538
539 GlobalInitWorklist.swap(GlobalInits);
540 AliasInitWorklist.swap(AliasInits);
541
542 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000543 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000544 if (ValID >= ValueList.size()) {
545 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000546 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000547 } else {
548 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
549 GlobalInitWorklist.back().first->setInitializer(C);
550 else
551 return Error("Global variable initializer is not a constant!");
552 }
553 GlobalInitWorklist.pop_back();
554 }
555
556 while (!AliasInitWorklist.empty()) {
557 unsigned ValID = AliasInitWorklist.back().second;
558 if (ValID >= ValueList.size()) {
559 AliasInits.push_back(AliasInitWorklist.back());
560 } else {
561 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000562 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000563 else
564 return Error("Alias initializer is not a constant!");
565 }
566 AliasInitWorklist.pop_back();
567 }
568 return false;
569}
570
571
Chris Lattner86697142007-05-01 05:01:34 +0000572bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000573 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000574 return Error("Malformed block record");
575
576 SmallVector<uint64_t, 64> Record;
577
578 // Read all the records for this value table.
579 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000580 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000581 while (1) {
582 unsigned Code = Stream.ReadCode();
583 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000584 if (NextCstNo != ValueList.size())
585 return Error("Invalid constant reference!");
586
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000587 if (Stream.ReadBlockEnd())
588 return Error("Error at end of constants block");
589 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000590 }
591
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
600 if (Code == bitc::DEFINE_ABBREV) {
601 Stream.ReadAbbrevRecord();
602 continue;
603 }
604
605 // Read a record.
606 Record.clear();
607 Value *V = 0;
608 switch (Stream.ReadRecord(Code, Record)) {
609 default: // Default behavior: unknown constant
610 case bitc::CST_CODE_UNDEF: // UNDEF
611 V = UndefValue::get(CurTy);
612 break;
613 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
614 if (Record.empty())
615 return Error("Malformed CST_SETTYPE record");
616 if (Record[0] >= TypeList.size())
617 return Error("Invalid Type ID in CST_SETTYPE record");
618 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000619 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000620 case bitc::CST_CODE_NULL: // NULL
621 V = Constant::getNullValue(CurTy);
622 break;
623 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000624 if (!isa<IntegerType>(CurTy) || Record.empty())
625 return Error("Invalid CST_INTEGER record");
626 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
627 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000628 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
629 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000630 return Error("Invalid WIDE_INTEGER record");
631
Chris Lattner15e6d172007-05-04 19:11:41 +0000632 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000633 SmallVector<uint64_t, 8> Words;
634 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000635 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000636 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000637 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000638 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000639 break;
640 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000641 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000642 if (Record.empty())
643 return Error("Invalid FLOAT record");
644 if (CurTy == Type::FloatTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000645 V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000646 else if (CurTy == Type::DoubleTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000647 V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000648 else if (CurTy == Type::X86_FP80Ty)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000649 V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000650 else if (CurTy == Type::FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000651 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000652 else if (CurTy == Type::PPC_FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000653 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000654 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000655 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000656 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000657 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000658
Chris Lattner15e6d172007-05-04 19:11:41 +0000659 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
660 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000661 return Error("Invalid CST_AGGREGATE record");
662
Chris Lattner15e6d172007-05-04 19:11:41 +0000663 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000664 std::vector<Constant*> Elts;
665
666 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
667 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000668 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000669 STy->getElementType(i)));
670 V = ConstantStruct::get(STy, Elts);
671 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
672 const Type *EltTy = ATy->getElementType();
673 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000674 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000675 V = ConstantArray::get(ATy, Elts);
676 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
677 const Type *EltTy = VTy->getElementType();
678 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000679 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000680 V = ConstantVector::get(Elts);
681 } else {
682 V = UndefValue::get(CurTy);
683 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000684 break;
685 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000686 case bitc::CST_CODE_STRING: { // STRING: [values]
687 if (Record.empty())
688 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000689
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000690 const ArrayType *ATy = cast<ArrayType>(CurTy);
691 const Type *EltTy = ATy->getElementType();
692
693 unsigned Size = Record.size();
694 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000695 for (unsigned i = 0; i != Size; ++i)
696 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
697 V = ConstantArray::get(ATy, Elts);
698 break;
699 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000700 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
701 if (Record.empty())
702 return Error("Invalid CST_AGGREGATE record");
703
704 const ArrayType *ATy = cast<ArrayType>(CurTy);
705 const Type *EltTy = ATy->getElementType();
706
707 unsigned Size = Record.size();
708 std::vector<Constant*> Elts;
709 for (unsigned i = 0; i != Size; ++i)
710 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
711 Elts.push_back(Constant::getNullValue(EltTy));
712 V = ConstantArray::get(ATy, Elts);
713 break;
714 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000715 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
716 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
717 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000718 if (Opc < 0) {
719 V = UndefValue::get(CurTy); // Unknown binop.
720 } else {
721 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
722 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
723 V = ConstantExpr::get(Opc, LHS, RHS);
724 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000725 break;
726 }
727 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
728 if (Record.size() < 3) return Error("Invalid CE_CAST record");
729 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000730 if (Opc < 0) {
731 V = UndefValue::get(CurTy); // Unknown cast.
732 } else {
733 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000734 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000735 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
736 V = ConstantExpr::getCast(Opc, Op, CurTy);
737 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000738 break;
739 }
740 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000741 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000742 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000743 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000744 const Type *ElTy = getTypeByID(Record[i]);
745 if (!ElTy) return Error("Invalid CE_GEP record");
746 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
747 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000748 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
749 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000750 }
751 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
752 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
753 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
754 Type::Int1Ty),
755 ValueList.getConstantFwdRef(Record[1],CurTy),
756 ValueList.getConstantFwdRef(Record[2],CurTy));
757 break;
758 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
759 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
760 const VectorType *OpTy =
761 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
762 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
763 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
764 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
765 OpTy->getElementType());
766 V = ConstantExpr::getExtractElement(Op0, Op1);
767 break;
768 }
769 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
770 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
771 if (Record.size() < 3 || OpTy == 0)
772 return Error("Invalid CE_INSERTELT record");
773 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
774 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
775 OpTy->getElementType());
776 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
777 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
778 break;
779 }
780 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
781 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
782 if (Record.size() < 3 || OpTy == 0)
783 return Error("Invalid CE_INSERTELT record");
784 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
785 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
786 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
787 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
788 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
789 break;
790 }
791 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
792 if (Record.size() < 4) return Error("Invalid CE_CMP record");
793 const Type *OpTy = getTypeByID(Record[0]);
794 if (OpTy == 0) return Error("Invalid CE_CMP record");
795 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
796 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
797
798 if (OpTy->isFloatingPoint())
799 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
800 else
801 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
802 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000803 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000804 case bitc::CST_CODE_INLINEASM: {
805 if (Record.size() < 2) return Error("Invalid INLINEASM record");
806 std::string AsmStr, ConstrStr;
807 bool HasSideEffects = Record[0];
808 unsigned AsmStrSize = Record[1];
809 if (2+AsmStrSize >= Record.size())
810 return Error("Invalid INLINEASM record");
811 unsigned ConstStrSize = Record[2+AsmStrSize];
812 if (3+AsmStrSize+ConstStrSize > Record.size())
813 return Error("Invalid INLINEASM record");
814
815 for (unsigned i = 0; i != AsmStrSize; ++i)
816 AsmStr += (char)Record[2+i];
817 for (unsigned i = 0; i != ConstStrSize; ++i)
818 ConstrStr += (char)Record[3+AsmStrSize+i];
819 const PointerType *PTy = cast<PointerType>(CurTy);
820 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
821 AsmStr, ConstrStr, HasSideEffects);
822 break;
823 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000824 }
825
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000826 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000827 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000828 }
829}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000830
Chris Lattner980e5aa2007-05-01 05:52:21 +0000831/// RememberAndSkipFunctionBody - When we see the block for a function body,
832/// remember where it is and then skip it. This lets us lazily deserialize the
833/// functions.
834bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000835 // Get the function we are talking about.
836 if (FunctionsWithBodies.empty())
837 return Error("Insufficient function protos");
838
839 Function *Fn = FunctionsWithBodies.back();
840 FunctionsWithBodies.pop_back();
841
842 // Save the current stream state.
843 uint64_t CurBit = Stream.GetCurrentBitNo();
844 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
845
846 // Set the functions linkage to GhostLinkage so we know it is lazily
847 // deserialized.
848 Fn->setLinkage(GlobalValue::GhostLinkage);
849
850 // Skip over the function block for now.
851 if (Stream.SkipBlock())
852 return Error("Malformed block record");
853 return false;
854}
855
Chris Lattner86697142007-05-01 05:01:34 +0000856bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000857 // Reject multiple MODULE_BLOCK's in a single bitstream.
858 if (TheModule)
859 return Error("Multiple MODULE_BLOCKs in same stream");
860
Chris Lattnere17b6582007-05-05 00:17:00 +0000861 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000862 return Error("Malformed block record");
863
864 // Otherwise, create the module.
865 TheModule = new Module(ModuleID);
866
867 SmallVector<uint64_t, 64> Record;
868 std::vector<std::string> SectionTable;
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000869 std::vector<std::string> CollectorTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000870
871 // Read all the records for this module.
872 while (!Stream.AtEndOfStream()) {
873 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000874 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000875 if (Stream.ReadBlockEnd())
876 return Error("Error at end of module block");
877
878 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000879 ResolveGlobalAndAliasInits();
880 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000881 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000882 if (!FunctionsWithBodies.empty())
883 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000884
Chandler Carruth69940402007-08-04 01:51:18 +0000885 // Look for intrinsic functions which need to be upgraded at some point
886 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
887 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +0000888 Function* NewFn;
889 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +0000890 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
891 }
892
Chris Lattner980e5aa2007-05-01 05:52:21 +0000893 // Force deallocation of memory for these vectors to favor the client that
894 // want lazy deserialization.
895 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
896 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
897 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000898 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000899 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000900
901 if (Code == bitc::ENTER_SUBBLOCK) {
902 switch (Stream.ReadSubBlockID()) {
903 default: // Skip unknown content.
904 if (Stream.SkipBlock())
905 return Error("Malformed block record");
906 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000907 case bitc::BLOCKINFO_BLOCK_ID:
908 if (Stream.ReadBlockInfoBlock())
909 return Error("Malformed BlockInfoBlock");
910 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000911 case bitc::PARAMATTR_BLOCK_ID:
912 if (ParseParamAttrBlock())
913 return true;
914 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000915 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000916 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000917 return true;
918 break;
919 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000920 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000921 return true;
922 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000923 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000924 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000925 return true;
926 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000927 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000928 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000929 return true;
930 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000931 case bitc::FUNCTION_BLOCK_ID:
932 // If this is the first function body we've seen, reverse the
933 // FunctionsWithBodies list.
934 if (!HasReversedFunctionsWithBodies) {
935 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
936 HasReversedFunctionsWithBodies = true;
937 }
938
Chris Lattner980e5aa2007-05-01 05:52:21 +0000939 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000940 return true;
941 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000942 }
943 continue;
944 }
945
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000946 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000947 Stream.ReadAbbrevRecord();
948 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000949 }
950
951 // Read a record.
952 switch (Stream.ReadRecord(Code, Record)) {
953 default: break; // Default behavior, ignore unknown content.
954 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
955 if (Record.size() < 1)
956 return Error("Malformed MODULE_CODE_VERSION");
957 // Only version #0 is supported so far.
958 if (Record[0] != 0)
959 return Error("Unknown bitstream version!");
960 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000961 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000962 std::string S;
963 if (ConvertToString(Record, 0, S))
964 return Error("Invalid MODULE_CODE_TRIPLE record");
965 TheModule->setTargetTriple(S);
966 break;
967 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000968 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000969 std::string S;
970 if (ConvertToString(Record, 0, S))
971 return Error("Invalid MODULE_CODE_DATALAYOUT record");
972 TheModule->setDataLayout(S);
973 break;
974 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000975 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000976 std::string S;
977 if (ConvertToString(Record, 0, S))
978 return Error("Invalid MODULE_CODE_ASM record");
979 TheModule->setModuleInlineAsm(S);
980 break;
981 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000982 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000983 std::string S;
984 if (ConvertToString(Record, 0, S))
985 return Error("Invalid MODULE_CODE_DEPLIB record");
986 TheModule->addLibrary(S);
987 break;
988 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000989 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000990 std::string S;
991 if (ConvertToString(Record, 0, S))
992 return Error("Invalid MODULE_CODE_SECTIONNAME record");
993 SectionTable.push_back(S);
994 break;
995 }
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000996 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
997 std::string S;
998 if (ConvertToString(Record, 0, S))
999 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
1000 CollectorTable.push_back(S);
1001 break;
1002 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001003 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001004 // linkage, alignment, section, visibility, threadlocal]
1005 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001006 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001007 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1008 const Type *Ty = getTypeByID(Record[0]);
1009 if (!isa<PointerType>(Ty))
1010 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001011 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001012 Ty = cast<PointerType>(Ty)->getElementType();
1013
1014 bool isConstant = Record[1];
1015 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1016 unsigned Alignment = (1 << Record[4]) >> 1;
1017 std::string Section;
1018 if (Record[5]) {
1019 if (Record[5]-1 >= SectionTable.size())
1020 return Error("Invalid section ID");
1021 Section = SectionTable[Record[5]-1];
1022 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001023 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001024 if (Record.size() > 6)
1025 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001026 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001027 if (Record.size() > 7)
1028 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001029
1030 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001031 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1032 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001033 NewGV->setAlignment(Alignment);
1034 if (!Section.empty())
1035 NewGV->setSection(Section);
1036 NewGV->setVisibility(Visibility);
1037 NewGV->setThreadLocal(isThreadLocal);
1038
Chris Lattner0b2482a2007-04-23 21:26:05 +00001039 ValueList.push_back(NewGV);
1040
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001041 // Remember which value to use for the global initializer.
1042 if (unsigned InitID = Record[2])
1043 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001044 break;
1045 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001046 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001047 // alignment, section, visibility, collector]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001048 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001049 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001050 return Error("Invalid MODULE_CODE_FUNCTION record");
1051 const Type *Ty = getTypeByID(Record[0]);
1052 if (!isa<PointerType>(Ty))
1053 return Error("Function not a pointer type!");
1054 const FunctionType *FTy =
1055 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1056 if (!FTy)
1057 return Error("Function not a pointer to function type!");
1058
1059 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1060 "", TheModule);
1061
1062 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001063 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001064 Func->setLinkage(GetDecodedLinkage(Record[3]));
Duncan Sandsdc024672007-11-27 13:23:08 +00001065 const ParamAttrsList *PAL = getParamAttrs(Record[4]);
1066 Func->setParamAttrs(PAL);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001067
1068 Func->setAlignment((1 << Record[5]) >> 1);
1069 if (Record[6]) {
1070 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001071 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001072 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001073 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001074 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001075 if (Record.size() > 8 && Record[8]) {
1076 if (Record[8]-1 > CollectorTable.size())
1077 return Error("Invalid collector ID");
1078 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1079 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001080
Chris Lattner0b2482a2007-04-23 21:26:05 +00001081 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001082
1083 // If this is a function with a body, remember the prototype we are
1084 // creating now, so that we can match up the body with them later.
1085 if (!isProto)
1086 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001087 break;
1088 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001089 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001090 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001091 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001092 if (Record.size() < 3)
1093 return Error("Invalid MODULE_ALIAS record");
1094 const Type *Ty = getTypeByID(Record[0]);
1095 if (!isa<PointerType>(Ty))
1096 return Error("Function not a pointer type!");
1097
1098 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1099 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001100 // Old bitcode files didn't have visibility field.
1101 if (Record.size() > 3)
1102 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001103 ValueList.push_back(NewGA);
1104 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1105 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001106 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001107 /// MODULE_CODE_PURGEVALS: [numvals]
1108 case bitc::MODULE_CODE_PURGEVALS:
1109 // Trim down the value list to the specified size.
1110 if (Record.size() < 1 || Record[0] > ValueList.size())
1111 return Error("Invalid MODULE_PURGEVALS record");
1112 ValueList.shrinkTo(Record[0]);
1113 break;
1114 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001115 Record.clear();
1116 }
1117
1118 return Error("Premature end of bitstream");
1119}
1120
1121
Chris Lattnerc453f762007-04-29 07:54:31 +00001122bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001123 TheModule = 0;
1124
Chris Lattnerc453f762007-04-29 07:54:31 +00001125 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001126 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1127
Chris Lattnerc453f762007-04-29 07:54:31 +00001128 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001129 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001130
1131 // Sniff for the signature.
1132 if (Stream.Read(8) != 'B' ||
1133 Stream.Read(8) != 'C' ||
1134 Stream.Read(4) != 0x0 ||
1135 Stream.Read(4) != 0xC ||
1136 Stream.Read(4) != 0xE ||
1137 Stream.Read(4) != 0xD)
1138 return Error("Invalid bitcode signature");
1139
1140 // We expect a number of well-defined blocks, though we don't necessarily
1141 // need to understand them all.
1142 while (!Stream.AtEndOfStream()) {
1143 unsigned Code = Stream.ReadCode();
1144
1145 if (Code != bitc::ENTER_SUBBLOCK)
1146 return Error("Invalid record at top-level");
1147
1148 unsigned BlockID = Stream.ReadSubBlockID();
1149
1150 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001151 switch (BlockID) {
1152 case bitc::BLOCKINFO_BLOCK_ID:
1153 if (Stream.ReadBlockInfoBlock())
1154 return Error("Malformed BlockInfoBlock");
1155 break;
1156 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001157 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001158 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001159 break;
1160 default:
1161 if (Stream.SkipBlock())
1162 return Error("Malformed block record");
1163 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001164 }
1165 }
1166
1167 return false;
1168}
Chris Lattnerc453f762007-04-29 07:54:31 +00001169
Chris Lattner48f84872007-05-01 04:59:48 +00001170
Chris Lattner980e5aa2007-05-01 05:52:21 +00001171/// ParseFunctionBody - Lazily parse the specified function body block.
1172bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001173 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001174 return Error("Malformed block record");
1175
1176 unsigned ModuleValueListSize = ValueList.size();
1177
1178 // Add all the function arguments to the value table.
1179 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1180 ValueList.push_back(I);
1181
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001182 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001183 BasicBlock *CurBB = 0;
1184 unsigned CurBBNo = 0;
1185
Chris Lattner980e5aa2007-05-01 05:52:21 +00001186 // Read all the records.
1187 SmallVector<uint64_t, 64> Record;
1188 while (1) {
1189 unsigned Code = Stream.ReadCode();
1190 if (Code == bitc::END_BLOCK) {
1191 if (Stream.ReadBlockEnd())
1192 return Error("Error at end of function block");
1193 break;
1194 }
1195
1196 if (Code == bitc::ENTER_SUBBLOCK) {
1197 switch (Stream.ReadSubBlockID()) {
1198 default: // Skip unknown content.
1199 if (Stream.SkipBlock())
1200 return Error("Malformed block record");
1201 break;
1202 case bitc::CONSTANTS_BLOCK_ID:
1203 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001204 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001205 break;
1206 case bitc::VALUE_SYMTAB_BLOCK_ID:
1207 if (ParseValueSymbolTable()) return true;
1208 break;
1209 }
1210 continue;
1211 }
1212
1213 if (Code == bitc::DEFINE_ABBREV) {
1214 Stream.ReadAbbrevRecord();
1215 continue;
1216 }
1217
1218 // Read a record.
1219 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001220 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001221 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001222 default: // Default behavior: reject
1223 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001224 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001225 if (Record.size() < 1 || Record[0] == 0)
1226 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001227 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001228 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001229 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1230 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001231 CurBB = FunctionBBs[0];
1232 continue;
1233
Nick Lewyckyfc82fab2008-03-02 02:48:09 +00001234 case bitc::FUNC_CODE_INST_BB_UNWINDDEST: // BB_UNWINDDEST: [bb#]
1235 if (CurBB->getUnwindDest())
1236 return Error("Only permit one BB_UNWINDDEST per BB");
1237 if (Record.size() != 1)
1238 return Error("Invalid BB_UNWINDDEST record");
1239
1240 CurBB->setUnwindDest(getBasicBlock(Record[0]));
1241 continue;
1242
Chris Lattnerabfbf852007-05-06 00:21:25 +00001243 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1244 unsigned OpNum = 0;
1245 Value *LHS, *RHS;
1246 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1247 getValue(Record, OpNum, LHS->getType(), RHS) ||
1248 OpNum+1 != Record.size())
1249 return Error("Invalid BINOP record");
1250
1251 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1252 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001253 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001254 break;
1255 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001256 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1257 unsigned OpNum = 0;
1258 Value *Op;
1259 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1260 OpNum+2 != Record.size())
1261 return Error("Invalid CAST record");
1262
1263 const Type *ResTy = getTypeByID(Record[OpNum]);
1264 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1265 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001266 return Error("Invalid CAST record");
1267 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1268 break;
1269 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001270 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001271 unsigned OpNum = 0;
1272 Value *BasePtr;
1273 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001274 return Error("Invalid GEP record");
1275
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001276 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001277 while (OpNum != Record.size()) {
1278 Value *Op;
1279 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001280 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001281 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001282 }
1283
David Greeneb8f74792007-09-04 15:46:09 +00001284 I = new GetElementPtrInst(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001285 break;
1286 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001287
Chris Lattnerabfbf852007-05-06 00:21:25 +00001288 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1289 unsigned OpNum = 0;
1290 Value *TrueVal, *FalseVal, *Cond;
1291 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1292 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1293 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001294 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001295
1296 I = new SelectInst(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001297 break;
1298 }
1299
1300 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001301 unsigned OpNum = 0;
1302 Value *Vec, *Idx;
1303 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1304 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001305 return Error("Invalid EXTRACTELT record");
1306 I = new ExtractElementInst(Vec, Idx);
1307 break;
1308 }
1309
1310 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001311 unsigned OpNum = 0;
1312 Value *Vec, *Elt, *Idx;
1313 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1314 getValue(Record, OpNum,
1315 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1316 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001317 return Error("Invalid INSERTELT record");
1318 I = new InsertElementInst(Vec, Elt, Idx);
1319 break;
1320 }
1321
Chris Lattnerabfbf852007-05-06 00:21:25 +00001322 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1323 unsigned OpNum = 0;
1324 Value *Vec1, *Vec2, *Mask;
1325 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1326 getValue(Record, OpNum, Vec1->getType(), Vec2))
1327 return Error("Invalid SHUFFLEVEC record");
1328
1329 const Type *MaskTy =
1330 VectorType::get(Type::Int32Ty,
1331 cast<VectorType>(Vec1->getType())->getNumElements());
1332
1333 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001334 return Error("Invalid SHUFFLEVEC record");
1335 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1336 break;
1337 }
1338
1339 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001340 unsigned OpNum = 0;
1341 Value *LHS, *RHS;
1342 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1343 getValue(Record, OpNum, LHS->getType(), RHS) ||
1344 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001345 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001346
1347 if (LHS->getType()->isFPOrFPVector())
1348 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001349 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001350 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001351 break;
1352 }
Devang Patel197be3d2008-02-22 02:49:49 +00001353 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1354 if (Record.size() != 2)
1355 return Error("Invalid GETRESULT record");
1356 unsigned OpNum = 0;
1357 Value *Op;
1358 getValueTypePair(Record, OpNum, NextValueNo, Op);
1359 unsigned Index = Record[1];
1360 I = new GetResultInst(Op, Index);
1361 break;
1362 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001363
Chris Lattner231cbcb2007-05-02 04:27:25 +00001364 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001365 {
1366 unsigned Size = Record.size();
1367 if (Size == 0) {
1368 I = new ReturnInst();
1369 break;
1370 } else {
1371 unsigned OpNum = 0;
Devang Patelf4511cd2008-02-26 19:38:17 +00001372 SmallVector<Value *,4> Vs;
Devang Pateld9d99ff2008-02-26 01:29:32 +00001373 do {
1374 Value *Op = NULL;
1375 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1376 return Error("Invalid RET record");
1377 Vs.push_back(Op);
1378 } while(OpNum != Record.size());
1379
Devang Patelf4511cd2008-02-26 19:38:17 +00001380 // SmallVector Vs has at least one element.
1381 I = new ReturnInst(&Vs[0], Vs.size());
Devang Pateld9d99ff2008-02-26 01:29:32 +00001382 break;
1383 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001384 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001385 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001386 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001387 return Error("Invalid BR record");
1388 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1389 if (TrueDest == 0)
1390 return Error("Invalid BR record");
1391
1392 if (Record.size() == 1)
1393 I = new BranchInst(TrueDest);
1394 else {
1395 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1396 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1397 if (FalseDest == 0 || Cond == 0)
1398 return Error("Invalid BR record");
1399 I = new BranchInst(TrueDest, FalseDest, Cond);
1400 }
1401 break;
1402 }
1403 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1404 if (Record.size() < 3 || (Record.size() & 1) == 0)
1405 return Error("Invalid SWITCH record");
1406 const Type *OpTy = getTypeByID(Record[0]);
1407 Value *Cond = getFnValueByID(Record[1], OpTy);
1408 BasicBlock *Default = getBasicBlock(Record[2]);
1409 if (OpTy == 0 || Cond == 0 || Default == 0)
1410 return Error("Invalid SWITCH record");
1411 unsigned NumCases = (Record.size()-3)/2;
1412 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1413 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1414 ConstantInt *CaseVal =
1415 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1416 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1417 if (CaseVal == 0 || DestBB == 0) {
1418 delete SI;
1419 return Error("Invalid SWITCH record!");
1420 }
1421 SI->addCase(CaseVal, DestBB);
1422 }
1423 I = SI;
1424 break;
1425 }
1426
Duncan Sandsdc024672007-11-27 13:23:08 +00001427 case bitc::FUNC_CODE_INST_INVOKE: {
1428 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001429 if (Record.size() < 4) return Error("Invalid INVOKE record");
Duncan Sandsdc024672007-11-27 13:23:08 +00001430 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001431 unsigned CCInfo = Record[1];
1432 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1433 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001434
Chris Lattnera9bb7132007-05-08 05:38:01 +00001435 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001436 Value *Callee;
1437 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001438 return Error("Invalid INVOKE record");
1439
Chris Lattner7337ab92007-05-06 00:00:00 +00001440 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1441 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001442 dyn_cast<FunctionType>(CalleeTy->getElementType());
1443
1444 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001445 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1446 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001447 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001448
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001449 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001450 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1451 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1452 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001453 }
1454
Chris Lattner7337ab92007-05-06 00:00:00 +00001455 if (!FTy->isVarArg()) {
1456 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001457 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001458 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001459 // Read type/value pairs for varargs params.
1460 while (OpNum != Record.size()) {
1461 Value *Op;
1462 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1463 return Error("Invalid INVOKE record");
1464 Ops.push_back(Op);
1465 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001466 }
1467
David Greenef1355a52007-08-27 19:04:21 +00001468 I = new InvokeInst(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001469 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Duncan Sandsdc024672007-11-27 13:23:08 +00001470 cast<InvokeInst>(I)->setParamAttrs(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001471 break;
1472 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001473 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1474 I = new UnwindInst();
1475 break;
1476 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1477 I = new UnreachableInst();
1478 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001479 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001480 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001481 return Error("Invalid PHI record");
1482 const Type *Ty = getTypeByID(Record[0]);
1483 if (!Ty) return Error("Invalid PHI record");
1484
1485 PHINode *PN = new PHINode(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001486 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001487
Chris Lattner15e6d172007-05-04 19:11:41 +00001488 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1489 Value *V = getFnValueByID(Record[1+i], Ty);
1490 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001491 if (!V || !BB) return Error("Invalid PHI record");
1492 PN->addIncoming(V, BB);
1493 }
1494 I = PN;
1495 break;
1496 }
1497
1498 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1499 if (Record.size() < 3)
1500 return Error("Invalid MALLOC record");
1501 const PointerType *Ty =
1502 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1503 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1504 unsigned Align = Record[2];
1505 if (!Ty || !Size) return Error("Invalid MALLOC record");
1506 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1507 break;
1508 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001509 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1510 unsigned OpNum = 0;
1511 Value *Op;
1512 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1513 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001514 return Error("Invalid FREE record");
1515 I = new FreeInst(Op);
1516 break;
1517 }
1518 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1519 if (Record.size() < 3)
1520 return Error("Invalid ALLOCA record");
1521 const PointerType *Ty =
1522 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1523 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1524 unsigned Align = Record[2];
1525 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1526 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1527 break;
1528 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001529 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001530 unsigned OpNum = 0;
1531 Value *Op;
1532 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1533 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001534 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001535
1536 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001537 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001538 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001539 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1540 unsigned OpNum = 0;
1541 Value *Val, *Ptr;
1542 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1543 getValue(Record, OpNum,
1544 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1545 OpNum+2 != Record.size())
1546 return Error("Invalid STORE record");
1547
1548 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1549 break;
1550 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001551 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001552 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001553 unsigned OpNum = 0;
1554 Value *Val, *Ptr;
1555 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001556 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001557 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001558 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001559
1560 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001561 break;
1562 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001563 case bitc::FUNC_CODE_INST_CALL: {
1564 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1565 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001566 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001567
Duncan Sandsdc024672007-11-27 13:23:08 +00001568 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001569 unsigned CCInfo = Record[1];
1570
1571 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001572 Value *Callee;
1573 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1574 return Error("Invalid CALL record");
1575
1576 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001577 const FunctionType *FTy = 0;
1578 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001579 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001580 return Error("Invalid CALL record");
1581
1582 SmallVector<Value*, 16> Args;
1583 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001584 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001585 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1586 Args.push_back(getBasicBlock(Record[OpNum]));
1587 else
1588 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001589 if (Args.back() == 0) return Error("Invalid CALL record");
1590 }
1591
Chris Lattner0579f7f2007-05-03 22:04:19 +00001592 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001593 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001594 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001595 return Error("Invalid CALL record");
1596 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001597 while (OpNum != Record.size()) {
1598 Value *Op;
1599 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1600 return Error("Invalid CALL record");
1601 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001602 }
1603 }
1604
David Greene52eec542007-08-01 03:43:44 +00001605 I = new CallInst(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001606 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1607 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Duncan Sandsdc024672007-11-27 13:23:08 +00001608 cast<CallInst>(I)->setParamAttrs(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001609 break;
1610 }
1611 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1612 if (Record.size() < 3)
1613 return Error("Invalid VAARG record");
1614 const Type *OpTy = getTypeByID(Record[0]);
1615 Value *Op = getFnValueByID(Record[1], OpTy);
1616 const Type *ResTy = getTypeByID(Record[2]);
1617 if (!OpTy || !Op || !ResTy)
1618 return Error("Invalid VAARG record");
1619 I = new VAArgInst(Op, ResTy);
1620 break;
1621 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001622 }
1623
1624 // Add instruction to end of current BB. If there is no current BB, reject
1625 // this file.
1626 if (CurBB == 0) {
1627 delete I;
1628 return Error("Invalid instruction with no BB");
1629 }
1630 CurBB->getInstList().push_back(I);
1631
1632 // If this was a terminator instruction, move to the next block.
1633 if (isa<TerminatorInst>(I)) {
1634 ++CurBBNo;
1635 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1636 }
1637
1638 // Non-void values get registered in the value table for future use.
1639 if (I && I->getType() != Type::VoidTy)
1640 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001641 }
1642
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001643 // Check the function list for unresolved values.
1644 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1645 if (A->getParent() == 0) {
1646 // We found at least one unresolved value. Nuke them all to avoid leaks.
1647 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1648 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1649 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1650 delete A;
1651 }
1652 }
Chris Lattner35a04702007-05-04 03:50:29 +00001653 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001654 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001655 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001656
1657 // Trim the value list down to the size it was before we parsed this function.
1658 ValueList.shrinkTo(ModuleValueListSize);
1659 std::vector<BasicBlock*>().swap(FunctionBBs);
1660
Chris Lattner48f84872007-05-01 04:59:48 +00001661 return false;
1662}
1663
Chris Lattnerb348bb82007-05-18 04:02:46 +00001664//===----------------------------------------------------------------------===//
1665// ModuleProvider implementation
1666//===----------------------------------------------------------------------===//
1667
1668
1669bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1670 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001671 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001672
1673 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1674 DeferredFunctionInfo.find(F);
1675 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1676
1677 // Move the bit stream to the saved position of the deferred function body and
1678 // restore the real linkage type for the function.
1679 Stream.JumpToBit(DFII->second.first);
1680 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1681
1682 if (ParseFunctionBody(F)) {
1683 if (ErrInfo) *ErrInfo = ErrorString;
1684 return true;
1685 }
Chandler Carruth69940402007-08-04 01:51:18 +00001686
1687 // Upgrade any old intrinsic calls in the function.
1688 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1689 E = UpgradedIntrinsics.end(); I != E; ++I) {
1690 if (I->first != I->second) {
1691 for (Value::use_iterator UI = I->first->use_begin(),
1692 UE = I->first->use_end(); UI != UE; ) {
1693 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1694 UpgradeIntrinsicCall(CI, I->second);
1695 }
1696 }
1697 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001698
1699 return false;
1700}
1701
1702void BitcodeReader::dematerializeFunction(Function *F) {
1703 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001704 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001705 return;
1706
1707 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1708
1709 // Just forget the function body, we can remat it later.
1710 F->deleteBody();
1711 F->setLinkage(GlobalValue::GhostLinkage);
1712}
1713
1714
1715Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1716 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1717 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1718 ++I) {
1719 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001720 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001721 materializeFunction(F, ErrInfo))
1722 return 0;
1723 }
Chandler Carruth69940402007-08-04 01:51:18 +00001724
1725 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1726 // delete the old functions to clean up. We can't do this unless the entire
1727 // module is materialized because there could always be another function body
1728 // with calls to the old function.
1729 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1730 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1731 if (I->first != I->second) {
1732 for (Value::use_iterator UI = I->first->use_begin(),
1733 UE = I->first->use_end(); UI != UE; ) {
1734 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1735 UpgradeIntrinsicCall(CI, I->second);
1736 }
1737 ValueList.replaceUsesOfWith(I->first, I->second);
1738 I->first->eraseFromParent();
1739 }
1740 }
1741 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1742
Chris Lattnerb348bb82007-05-18 04:02:46 +00001743 return TheModule;
1744}
1745
1746
1747/// This method is provided by the parent ModuleProvde class and overriden
1748/// here. It simply releases the module from its provided and frees up our
1749/// state.
1750/// @brief Release our hold on the generated module
1751Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1752 // Since we're losing control of this Module, we must hand it back complete
1753 Module *M = ModuleProvider::releaseModule(ErrInfo);
1754 FreeState();
1755 return M;
1756}
1757
Chris Lattner48f84872007-05-01 04:59:48 +00001758
Chris Lattnerc453f762007-04-29 07:54:31 +00001759//===----------------------------------------------------------------------===//
1760// External interface
1761//===----------------------------------------------------------------------===//
1762
1763/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1764///
1765ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1766 std::string *ErrMsg) {
1767 BitcodeReader *R = new BitcodeReader(Buffer);
1768 if (R->ParseBitcode()) {
1769 if (ErrMsg)
1770 *ErrMsg = R->getErrorString();
1771
1772 // Don't let the BitcodeReader dtor delete 'Buffer'.
1773 R->releaseMemoryBuffer();
1774 delete R;
1775 return 0;
1776 }
1777 return R;
1778}
1779
1780/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1781/// If an error occurs, return null and fill in *ErrMsg if non-null.
1782Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1783 BitcodeReader *R;
1784 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1785 if (!R) return 0;
1786
Chris Lattnerb348bb82007-05-18 04:02:46 +00001787 // Read in the entire module.
1788 Module *M = R->materializeModule(ErrMsg);
1789
1790 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1791 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001792 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001793
1794 // If there was no error, tell ModuleProvider not to delete it when its dtor
1795 // is run.
1796 if (M)
1797 M = R->releaseModule(ErrMsg);
1798
Chris Lattnerc453f762007-04-29 07:54:31 +00001799 delete R;
1800 return M;
1801}