blob: 1ab9f54d5bf2bd1cc09555a762be2d75250f3fb9 [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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 Lattnera7c49aa2007-05-01 07:01:57 +000018#include "llvm/Instructions.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000019#include "llvm/Module.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000020#include "llvm/ADT/SmallString.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000021#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000022#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000023using namespace llvm;
24
Chris Lattnerc453f762007-04-29 07:54:31 +000025BitcodeReader::~BitcodeReader() {
26 delete Buffer;
27}
28
29
Chris Lattnercaee0dc2007-04-22 06:23:29 +000030/// ConvertToString - Convert a string from a record into an std::string, return
31/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000032template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000033static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000034 StrTy &Result) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +000035 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
36 return true;
37
38 for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
39 Result += (char)Record[Idx+i+1];
40 return false;
41}
42
43static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
44 switch (Val) {
45 default: // Map unknown/new linkages to external
46 case 0: return GlobalValue::ExternalLinkage;
47 case 1: return GlobalValue::WeakLinkage;
48 case 2: return GlobalValue::AppendingLinkage;
49 case 3: return GlobalValue::InternalLinkage;
50 case 4: return GlobalValue::LinkOnceLinkage;
51 case 5: return GlobalValue::DLLImportLinkage;
52 case 6: return GlobalValue::DLLExportLinkage;
53 case 7: return GlobalValue::ExternalWeakLinkage;
54 }
55}
56
57static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
58 switch (Val) {
59 default: // Map unknown visibilities to default.
60 case 0: return GlobalValue::DefaultVisibility;
61 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000062 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063 }
64}
65
Chris Lattnerf581c3b2007-04-24 07:07:11 +000066static int GetDecodedCastOpcode(unsigned Val) {
67 switch (Val) {
68 default: return -1;
69 case bitc::CAST_TRUNC : return Instruction::Trunc;
70 case bitc::CAST_ZEXT : return Instruction::ZExt;
71 case bitc::CAST_SEXT : return Instruction::SExt;
72 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
73 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
74 case bitc::CAST_UITOFP : return Instruction::UIToFP;
75 case bitc::CAST_SITOFP : return Instruction::SIToFP;
76 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
77 case bitc::CAST_FPEXT : return Instruction::FPExt;
78 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
79 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
80 case bitc::CAST_BITCAST : return Instruction::BitCast;
81 }
82}
83static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
84 switch (Val) {
85 default: return -1;
86 case bitc::BINOP_ADD: return Instruction::Add;
87 case bitc::BINOP_SUB: return Instruction::Sub;
88 case bitc::BINOP_MUL: return Instruction::Mul;
89 case bitc::BINOP_UDIV: return Instruction::UDiv;
90 case bitc::BINOP_SDIV:
91 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
92 case bitc::BINOP_UREM: return Instruction::URem;
93 case bitc::BINOP_SREM:
94 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
95 case bitc::BINOP_SHL: return Instruction::Shl;
96 case bitc::BINOP_LSHR: return Instruction::LShr;
97 case bitc::BINOP_ASHR: return Instruction::AShr;
98 case bitc::BINOP_AND: return Instruction::And;
99 case bitc::BINOP_OR: return Instruction::Or;
100 case bitc::BINOP_XOR: return Instruction::Xor;
101 }
102}
103
104
Chris Lattner522b7b12007-04-24 05:48:56 +0000105namespace {
106 /// @brief A class for maintaining the slot number definition
107 /// as a placeholder for the actual definition for forward constants defs.
108 class ConstantPlaceHolder : public ConstantExpr {
109 ConstantPlaceHolder(); // DO NOT IMPLEMENT
110 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000111 public:
112 Use Op;
113 ConstantPlaceHolder(const Type *Ty)
114 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
115 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000116 }
117 };
118}
119
120Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
121 const Type *Ty) {
122 if (Idx >= size()) {
123 // Insert a bunch of null values.
124 Uses.resize(Idx+1);
125 OperandList = &Uses[0];
126 NumOperands = Idx+1;
127 }
128
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000129 if (Value *V = Uses[Idx]) {
130 assert(Ty == V->getType() && "Type mismatch in constant table!");
131 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000132 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000133
134 // Create and return a placeholder, which will later be RAUW'd.
135 Constant *C = new ConstantPlaceHolder(Ty);
136 Uses[Idx].init(C, this);
137 return C;
138}
139
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000140Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, 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
148 if (Value *V = Uses[Idx]) {
149 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
150 return V;
151 }
152
Chris Lattner01ff65f2007-05-02 05:16:49 +0000153 // No type specified, must be invalid reference.
154 if (Ty == 0) return 0;
155
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000156 // Create and return a placeholder, which will later be RAUW'd.
157 Value *V = new Argument(Ty);
158 Uses[Idx].init(V, this);
159 return V;
160}
161
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000162
163const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
164 // If the TypeID is in range, return it.
165 if (ID < TypeList.size())
166 return TypeList[ID].get();
167 if (!isTypeTable) return 0;
168
169 // The type table allows forward references. Push as many Opaque types as
170 // needed to get up to ID.
171 while (TypeList.size() <= ID)
172 TypeList.push_back(OpaqueType::get());
173 return TypeList.back().get();
174}
175
Chris Lattner86697142007-05-01 05:01:34 +0000176bool BitcodeReader::ParseTypeTable() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000177 if (Stream.EnterSubBlock())
178 return Error("Malformed block record");
179
180 if (!TypeList.empty())
181 return Error("Multiple TYPE_BLOCKs found!");
182
183 SmallVector<uint64_t, 64> Record;
184 unsigned NumRecords = 0;
185
186 // Read all the records for this type table.
187 while (1) {
188 unsigned Code = Stream.ReadCode();
189 if (Code == bitc::END_BLOCK) {
190 if (NumRecords != TypeList.size())
191 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000192 if (Stream.ReadBlockEnd())
193 return Error("Error at end of type table block");
194 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000195 }
196
197 if (Code == bitc::ENTER_SUBBLOCK) {
198 // No known subblocks, always skip them.
199 Stream.ReadSubBlockID();
200 if (Stream.SkipBlock())
201 return Error("Malformed block record");
202 continue;
203 }
204
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000205 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000206 Stream.ReadAbbrevRecord();
207 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000208 }
209
210 // Read a record.
211 Record.clear();
212 const Type *ResultTy = 0;
213 switch (Stream.ReadRecord(Code, Record)) {
214 default: // Default behavior: unknown type.
215 ResultTy = 0;
216 break;
217 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
218 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
219 // type list. This allows us to reserve space.
220 if (Record.size() < 1)
221 return Error("Invalid TYPE_CODE_NUMENTRY record");
222 TypeList.reserve(Record[0]);
223 continue;
224 case bitc::TYPE_CODE_META: // TYPE_CODE_META: [metacode]...
225 // No metadata supported yet.
226 if (Record.size() < 1)
227 return Error("Invalid TYPE_CODE_META record");
228 continue;
229
230 case bitc::TYPE_CODE_VOID: // VOID
231 ResultTy = Type::VoidTy;
232 break;
233 case bitc::TYPE_CODE_FLOAT: // FLOAT
234 ResultTy = Type::FloatTy;
235 break;
236 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
237 ResultTy = Type::DoubleTy;
238 break;
239 case bitc::TYPE_CODE_LABEL: // LABEL
240 ResultTy = Type::LabelTy;
241 break;
242 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
243 ResultTy = 0;
244 break;
245 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
246 if (Record.size() < 1)
247 return Error("Invalid Integer type record");
248
249 ResultTy = IntegerType::get(Record[0]);
250 break;
251 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
252 if (Record.size() < 1)
253 return Error("Invalid POINTER type record");
254 ResultTy = PointerType::get(getTypeByID(Record[0], true));
255 break;
256 case bitc::TYPE_CODE_FUNCTION: {
257 // FUNCTION: [vararg, retty, #pararms, paramty N]
258 if (Record.size() < 3 || Record.size() < Record[2]+3)
259 return Error("Invalid FUNCTION type record");
260 std::vector<const Type*> ArgTys;
261 for (unsigned i = 0, e = Record[2]; i != e; ++i)
262 ArgTys.push_back(getTypeByID(Record[3+i], true));
263
264 // FIXME: PARAM TYS.
265 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
266 Record[0]);
267 break;
268 }
269 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
270 if (Record.size() < 2 || Record.size() < Record[1]+2)
271 return Error("Invalid STRUCT type record");
272 std::vector<const Type*> EltTys;
273 for (unsigned i = 0, e = Record[1]; i != e; ++i)
274 EltTys.push_back(getTypeByID(Record[2+i], true));
275 ResultTy = StructType::get(EltTys, Record[0]);
276 break;
277 }
278 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
279 if (Record.size() < 2)
280 return Error("Invalid ARRAY type record");
281 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
282 break;
283 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
284 if (Record.size() < 2)
285 return Error("Invalid VECTOR type record");
286 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
287 break;
288 }
289
290 if (NumRecords == TypeList.size()) {
291 // If this is a new type slot, just append it.
292 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
293 ++NumRecords;
294 } else if (ResultTy == 0) {
295 // Otherwise, this was forward referenced, so an opaque type was created,
296 // but the result type is actually just an opaque. Leave the one we
297 // created previously.
298 ++NumRecords;
299 } else {
300 // Otherwise, this was forward referenced, so an opaque type was created.
301 // Resolve the opaque type to the real type now.
302 assert(NumRecords < TypeList.size() && "Typelist imbalance");
303 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
304
305 // Don't directly push the new type on the Tab. Instead we want to replace
306 // the opaque type we previously inserted with the new concrete value. The
307 // refinement from the abstract (opaque) type to the new type causes all
308 // uses of the abstract type to use the concrete type (NewTy). This will
309 // also cause the opaque type to be deleted.
310 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
311
312 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000313 // value table... or with a preexisting type that was already in the
314 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000315 assert(TypeList[NumRecords-1].get() != OldTy &&
316 "refineAbstractType didn't work!");
317 }
318 }
319}
320
321
Chris Lattner86697142007-05-01 05:01:34 +0000322bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000323 if (Stream.EnterSubBlock())
324 return Error("Malformed block record");
325
326 SmallVector<uint64_t, 64> Record;
327
328 // Read all the records for this type table.
329 std::string TypeName;
330 while (1) {
331 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000332 if (Code == bitc::END_BLOCK) {
333 if (Stream.ReadBlockEnd())
334 return Error("Error at end of type symbol table block");
335 return false;
336 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000337
338 if (Code == bitc::ENTER_SUBBLOCK) {
339 // No known subblocks, always skip them.
340 Stream.ReadSubBlockID();
341 if (Stream.SkipBlock())
342 return Error("Malformed block record");
343 continue;
344 }
345
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000346 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000347 Stream.ReadAbbrevRecord();
348 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000349 }
350
351 // Read a record.
352 Record.clear();
353 switch (Stream.ReadRecord(Code, Record)) {
354 default: // Default behavior: unknown type.
355 break;
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000356 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000357 if (ConvertToString(Record, 1, TypeName))
358 return Error("Invalid TST_ENTRY record");
359 unsigned TypeID = Record[0];
360 if (TypeID >= TypeList.size())
361 return Error("Invalid Type ID in TST_ENTRY record");
362
363 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
364 TypeName.clear();
365 break;
366 }
367 }
368}
369
Chris Lattner86697142007-05-01 05:01:34 +0000370bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000371 if (Stream.EnterSubBlock())
372 return Error("Malformed block record");
373
374 SmallVector<uint64_t, 64> Record;
375
376 // Read all the records for this value table.
377 SmallString<128> ValueName;
378 while (1) {
379 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000380 if (Code == bitc::END_BLOCK) {
381 if (Stream.ReadBlockEnd())
382 return Error("Error at end of value symbol table block");
383 return false;
384 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000385 if (Code == bitc::ENTER_SUBBLOCK) {
386 // No known subblocks, always skip them.
387 Stream.ReadSubBlockID();
388 if (Stream.SkipBlock())
389 return Error("Malformed block record");
390 continue;
391 }
392
393 if (Code == bitc::DEFINE_ABBREV) {
394 Stream.ReadAbbrevRecord();
395 continue;
396 }
397
398 // Read a record.
399 Record.clear();
400 switch (Stream.ReadRecord(Code, Record)) {
401 default: // Default behavior: unknown type.
402 break;
Chris Lattnerf61e6452007-05-03 22:09:51 +0000403 case bitc::VST_CODE_ENTRY: // VST_ENTRY: [valueid, namelen, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000404 if (ConvertToString(Record, 1, ValueName))
405 return Error("Invalid TST_ENTRY record");
406 unsigned ValueID = Record[0];
407 if (ValueID >= ValueList.size())
408 return Error("Invalid Value ID in VST_ENTRY record");
409 Value *V = ValueList[ValueID];
410
411 V->setName(&ValueName[0], ValueName.size());
412 ValueName.clear();
413 break;
Chris Lattnere825ed52007-05-03 22:18:21 +0000414 case bitc::VST_CODE_BBENTRY:
415 if (ConvertToString(Record, 1, ValueName))
416 return Error("Invalid VST_BBENTRY record");
417 BasicBlock *BB = getBasicBlock(Record[0]);
418 if (BB == 0)
419 return Error("Invalid BB ID in VST_BBENTRY record");
420
421 BB->setName(&ValueName[0], ValueName.size());
422 ValueName.clear();
423 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000424 }
425 }
426}
427
Chris Lattner0eef0802007-04-24 04:04:35 +0000428/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
429/// the LSB for dense VBR encoding.
430static uint64_t DecodeSignRotatedValue(uint64_t V) {
431 if ((V & 1) == 0)
432 return V >> 1;
433 if (V != 1)
434 return -(V >> 1);
435 // There is no such thing as -0 with integers. "-0" really means MININT.
436 return 1ULL << 63;
437}
438
Chris Lattner07d98b42007-04-26 02:46:40 +0000439/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
440/// values and aliases that we can.
441bool BitcodeReader::ResolveGlobalAndAliasInits() {
442 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
443 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
444
445 GlobalInitWorklist.swap(GlobalInits);
446 AliasInitWorklist.swap(AliasInits);
447
448 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000449 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000450 if (ValID >= ValueList.size()) {
451 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000452 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000453 } else {
454 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
455 GlobalInitWorklist.back().first->setInitializer(C);
456 else
457 return Error("Global variable initializer is not a constant!");
458 }
459 GlobalInitWorklist.pop_back();
460 }
461
462 while (!AliasInitWorklist.empty()) {
463 unsigned ValID = AliasInitWorklist.back().second;
464 if (ValID >= ValueList.size()) {
465 AliasInits.push_back(AliasInitWorklist.back());
466 } else {
467 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000468 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000469 else
470 return Error("Alias initializer is not a constant!");
471 }
472 AliasInitWorklist.pop_back();
473 }
474 return false;
475}
476
477
Chris Lattner86697142007-05-01 05:01:34 +0000478bool BitcodeReader::ParseConstants() {
Chris Lattnere16504e2007-04-24 03:30:34 +0000479 if (Stream.EnterSubBlock())
480 return Error("Malformed block record");
481
482 SmallVector<uint64_t, 64> Record;
483
484 // Read all the records for this value table.
485 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000486 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000487 while (1) {
488 unsigned Code = Stream.ReadCode();
489 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000490 if (NextCstNo != ValueList.size())
491 return Error("Invalid constant reference!");
492
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000493 if (Stream.ReadBlockEnd())
494 return Error("Error at end of constants block");
495 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000496 }
497
498 if (Code == bitc::ENTER_SUBBLOCK) {
499 // No known subblocks, always skip them.
500 Stream.ReadSubBlockID();
501 if (Stream.SkipBlock())
502 return Error("Malformed block record");
503 continue;
504 }
505
506 if (Code == bitc::DEFINE_ABBREV) {
507 Stream.ReadAbbrevRecord();
508 continue;
509 }
510
511 // Read a record.
512 Record.clear();
513 Value *V = 0;
514 switch (Stream.ReadRecord(Code, Record)) {
515 default: // Default behavior: unknown constant
516 case bitc::CST_CODE_UNDEF: // UNDEF
517 V = UndefValue::get(CurTy);
518 break;
519 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
520 if (Record.empty())
521 return Error("Malformed CST_SETTYPE record");
522 if (Record[0] >= TypeList.size())
523 return Error("Invalid Type ID in CST_SETTYPE record");
524 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000525 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000526 case bitc::CST_CODE_NULL: // NULL
527 V = Constant::getNullValue(CurTy);
528 break;
529 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000530 if (!isa<IntegerType>(CurTy) || Record.empty())
531 return Error("Invalid CST_INTEGER record");
532 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
533 break;
534 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
535 if (!isa<IntegerType>(CurTy) || Record.empty() ||
536 Record.size() < Record[0]+1)
537 return Error("Invalid WIDE_INTEGER record");
538
539 unsigned NumWords = Record[0];
Chris Lattner084a8442007-04-24 17:22:05 +0000540 SmallVector<uint64_t, 8> Words;
541 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000542 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner084a8442007-04-24 17:22:05 +0000543 Words[i] = DecodeSignRotatedValue(Record[i+1]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000544 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000545 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000546 break;
547 }
548 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
549 if (Record.empty())
550 return Error("Invalid FLOAT record");
551 if (CurTy == Type::FloatTy)
552 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
553 else if (CurTy == Type::DoubleTy)
554 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
Chris Lattnere16504e2007-04-24 03:30:34 +0000555 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000556 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000557 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000558
559 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
560 if (Record.empty() || Record.size() < Record[0]+1)
561 return Error("Invalid CST_AGGREGATE record");
562
563 unsigned Size = Record[0];
564 std::vector<Constant*> Elts;
565
566 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
567 for (unsigned i = 0; i != Size; ++i)
568 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
569 STy->getElementType(i)));
570 V = ConstantStruct::get(STy, Elts);
571 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
572 const Type *EltTy = ATy->getElementType();
573 for (unsigned i = 0; i != Size; ++i)
574 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
575 V = ConstantArray::get(ATy, Elts);
576 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
577 const Type *EltTy = VTy->getElementType();
578 for (unsigned i = 0; i != Size; ++i)
579 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
580 V = ConstantVector::get(Elts);
581 } else {
582 V = UndefValue::get(CurTy);
583 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000584 break;
585 }
586
587 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
588 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
589 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000590 if (Opc < 0) {
591 V = UndefValue::get(CurTy); // Unknown binop.
592 } else {
593 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
594 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
595 V = ConstantExpr::get(Opc, LHS, RHS);
596 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000597 break;
598 }
599 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
600 if (Record.size() < 3) return Error("Invalid CE_CAST record");
601 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000602 if (Opc < 0) {
603 V = UndefValue::get(CurTy); // Unknown cast.
604 } else {
605 const Type *OpTy = getTypeByID(Record[1]);
606 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
607 V = ConstantExpr::getCast(Opc, Op, CurTy);
608 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000609 break;
610 }
611 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
612 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
613 SmallVector<Constant*, 16> Elts;
614 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
615 const Type *ElTy = getTypeByID(Record[i]);
616 if (!ElTy) return Error("Invalid CE_GEP record");
617 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
618 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000619 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
620 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000621 }
622 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
623 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
624 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
625 Type::Int1Ty),
626 ValueList.getConstantFwdRef(Record[1],CurTy),
627 ValueList.getConstantFwdRef(Record[2],CurTy));
628 break;
629 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
630 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
631 const VectorType *OpTy =
632 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
633 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
634 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
635 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
636 OpTy->getElementType());
637 V = ConstantExpr::getExtractElement(Op0, Op1);
638 break;
639 }
640 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
641 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
642 if (Record.size() < 3 || OpTy == 0)
643 return Error("Invalid CE_INSERTELT record");
644 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
645 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
646 OpTy->getElementType());
647 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
648 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
649 break;
650 }
651 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
652 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
653 if (Record.size() < 3 || OpTy == 0)
654 return Error("Invalid CE_INSERTELT record");
655 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
656 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
657 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
658 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
659 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
660 break;
661 }
662 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
663 if (Record.size() < 4) return Error("Invalid CE_CMP record");
664 const Type *OpTy = getTypeByID(Record[0]);
665 if (OpTy == 0) return Error("Invalid CE_CMP record");
666 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
667 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
668
669 if (OpTy->isFloatingPoint())
670 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
671 else
672 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
673 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000674 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000675 }
676
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000677 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000678 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000679 }
680}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000681
Chris Lattner980e5aa2007-05-01 05:52:21 +0000682/// RememberAndSkipFunctionBody - When we see the block for a function body,
683/// remember where it is and then skip it. This lets us lazily deserialize the
684/// functions.
685bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000686 // Get the function we are talking about.
687 if (FunctionsWithBodies.empty())
688 return Error("Insufficient function protos");
689
690 Function *Fn = FunctionsWithBodies.back();
691 FunctionsWithBodies.pop_back();
692
693 // Save the current stream state.
694 uint64_t CurBit = Stream.GetCurrentBitNo();
695 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
696
697 // Set the functions linkage to GhostLinkage so we know it is lazily
698 // deserialized.
699 Fn->setLinkage(GlobalValue::GhostLinkage);
700
701 // Skip over the function block for now.
702 if (Stream.SkipBlock())
703 return Error("Malformed block record");
704 return false;
705}
706
Chris Lattner86697142007-05-01 05:01:34 +0000707bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000708 // Reject multiple MODULE_BLOCK's in a single bitstream.
709 if (TheModule)
710 return Error("Multiple MODULE_BLOCKs in same stream");
711
712 if (Stream.EnterSubBlock())
713 return Error("Malformed block record");
714
715 // Otherwise, create the module.
716 TheModule = new Module(ModuleID);
717
718 SmallVector<uint64_t, 64> Record;
719 std::vector<std::string> SectionTable;
720
721 // Read all the records for this module.
722 while (!Stream.AtEndOfStream()) {
723 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000724 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000725 if (Stream.ReadBlockEnd())
726 return Error("Error at end of module block");
727
728 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000729 ResolveGlobalAndAliasInits();
730 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000731 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000732 if (!FunctionsWithBodies.empty())
733 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000734
735 // Force deallocation of memory for these vectors to favor the client that
736 // want lazy deserialization.
737 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
738 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
739 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000740 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000741 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000742
743 if (Code == bitc::ENTER_SUBBLOCK) {
744 switch (Stream.ReadSubBlockID()) {
745 default: // Skip unknown content.
746 if (Stream.SkipBlock())
747 return Error("Malformed block record");
748 break;
749 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000750 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000751 return true;
752 break;
753 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000754 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000755 return true;
756 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000757 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000758 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000759 return true;
760 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000761 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000762 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000763 return true;
764 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000765 case bitc::FUNCTION_BLOCK_ID:
766 // If this is the first function body we've seen, reverse the
767 // FunctionsWithBodies list.
768 if (!HasReversedFunctionsWithBodies) {
769 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
770 HasReversedFunctionsWithBodies = true;
771 }
772
Chris Lattner980e5aa2007-05-01 05:52:21 +0000773 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000774 return true;
775 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000776 }
777 continue;
778 }
779
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000780 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000781 Stream.ReadAbbrevRecord();
782 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000783 }
784
785 // Read a record.
786 switch (Stream.ReadRecord(Code, Record)) {
787 default: break; // Default behavior, ignore unknown content.
788 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
789 if (Record.size() < 1)
790 return Error("Malformed MODULE_CODE_VERSION");
791 // Only version #0 is supported so far.
792 if (Record[0] != 0)
793 return Error("Unknown bitstream version!");
794 break;
795 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
796 std::string S;
797 if (ConvertToString(Record, 0, S))
798 return Error("Invalid MODULE_CODE_TRIPLE record");
799 TheModule->setTargetTriple(S);
800 break;
801 }
802 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
803 std::string S;
804 if (ConvertToString(Record, 0, S))
805 return Error("Invalid MODULE_CODE_DATALAYOUT record");
806 TheModule->setDataLayout(S);
807 break;
808 }
809 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
810 std::string S;
811 if (ConvertToString(Record, 0, S))
812 return Error("Invalid MODULE_CODE_ASM record");
813 TheModule->setModuleInlineAsm(S);
814 break;
815 }
816 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
817 std::string S;
818 if (ConvertToString(Record, 0, S))
819 return Error("Invalid MODULE_CODE_DEPLIB record");
820 TheModule->addLibrary(S);
821 break;
822 }
823 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
824 std::string S;
825 if (ConvertToString(Record, 0, S))
826 return Error("Invalid MODULE_CODE_SECTIONNAME record");
827 SectionTable.push_back(S);
828 break;
829 }
830 // GLOBALVAR: [type, isconst, initid,
831 // linkage, alignment, section, visibility, threadlocal]
832 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000833 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000834 return Error("Invalid MODULE_CODE_GLOBALVAR record");
835 const Type *Ty = getTypeByID(Record[0]);
836 if (!isa<PointerType>(Ty))
837 return Error("Global not a pointer type!");
838 Ty = cast<PointerType>(Ty)->getElementType();
839
840 bool isConstant = Record[1];
841 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
842 unsigned Alignment = (1 << Record[4]) >> 1;
843 std::string Section;
844 if (Record[5]) {
845 if (Record[5]-1 >= SectionTable.size())
846 return Error("Invalid section ID");
847 Section = SectionTable[Record[5]-1];
848 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000849 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
850 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
851 bool isThreadLocal = false;
852 if (Record.size() >= 7) isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000853
854 GlobalVariable *NewGV =
855 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
856 NewGV->setAlignment(Alignment);
857 if (!Section.empty())
858 NewGV->setSection(Section);
859 NewGV->setVisibility(Visibility);
860 NewGV->setThreadLocal(isThreadLocal);
861
Chris Lattner0b2482a2007-04-23 21:26:05 +0000862 ValueList.push_back(NewGV);
863
Chris Lattner6dbfd7b2007-04-24 00:18:21 +0000864 // Remember which value to use for the global initializer.
865 if (unsigned InitID = Record[2])
866 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000867 break;
868 }
869 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
870 // visibility]
871 case bitc::MODULE_CODE_FUNCTION: {
872 if (Record.size() < 7)
873 return Error("Invalid MODULE_CODE_FUNCTION record");
874 const Type *Ty = getTypeByID(Record[0]);
875 if (!isa<PointerType>(Ty))
876 return Error("Function not a pointer type!");
877 const FunctionType *FTy =
878 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
879 if (!FTy)
880 return Error("Function not a pointer to function type!");
881
882 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
883 "", TheModule);
884
885 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +0000886 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000887 Func->setLinkage(GetDecodedLinkage(Record[3]));
888 Func->setAlignment((1 << Record[4]) >> 1);
889 if (Record[5]) {
890 if (Record[5]-1 >= SectionTable.size())
891 return Error("Invalid section ID");
892 Func->setSection(SectionTable[Record[5]-1]);
893 }
894 Func->setVisibility(GetDecodedVisibility(Record[6]));
895
Chris Lattner0b2482a2007-04-23 21:26:05 +0000896 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +0000897
898 // If this is a function with a body, remember the prototype we are
899 // creating now, so that we can match up the body with them later.
900 if (!isProto)
901 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000902 break;
903 }
Chris Lattner07d98b42007-04-26 02:46:40 +0000904 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +0000905 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +0000906 if (Record.size() < 3)
907 return Error("Invalid MODULE_ALIAS record");
908 const Type *Ty = getTypeByID(Record[0]);
909 if (!isa<PointerType>(Ty))
910 return Error("Function not a pointer type!");
911
912 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
913 "", 0, TheModule);
914 ValueList.push_back(NewGA);
915 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
916 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000917 }
Chris Lattner198f34a2007-04-26 03:27:58 +0000918 /// MODULE_CODE_PURGEVALS: [numvals]
919 case bitc::MODULE_CODE_PURGEVALS:
920 // Trim down the value list to the specified size.
921 if (Record.size() < 1 || Record[0] > ValueList.size())
922 return Error("Invalid MODULE_PURGEVALS record");
923 ValueList.shrinkTo(Record[0]);
924 break;
925 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000926 Record.clear();
927 }
928
929 return Error("Premature end of bitstream");
930}
931
932
Chris Lattnerc453f762007-04-29 07:54:31 +0000933bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000934 TheModule = 0;
935
Chris Lattnerc453f762007-04-29 07:54:31 +0000936 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000937 return Error("Bitcode stream should be a multiple of 4 bytes in length");
938
Chris Lattnerc453f762007-04-29 07:54:31 +0000939 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +0000940 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000941
942 // Sniff for the signature.
943 if (Stream.Read(8) != 'B' ||
944 Stream.Read(8) != 'C' ||
945 Stream.Read(4) != 0x0 ||
946 Stream.Read(4) != 0xC ||
947 Stream.Read(4) != 0xE ||
948 Stream.Read(4) != 0xD)
949 return Error("Invalid bitcode signature");
950
951 // We expect a number of well-defined blocks, though we don't necessarily
952 // need to understand them all.
953 while (!Stream.AtEndOfStream()) {
954 unsigned Code = Stream.ReadCode();
955
956 if (Code != bitc::ENTER_SUBBLOCK)
957 return Error("Invalid record at top-level");
958
959 unsigned BlockID = Stream.ReadSubBlockID();
960
961 // We only know the MODULE subblock ID.
962 if (BlockID == bitc::MODULE_BLOCK_ID) {
Chris Lattner86697142007-05-01 05:01:34 +0000963 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000964 return true;
965 } else if (Stream.SkipBlock()) {
966 return Error("Malformed block record");
967 }
968 }
969
970 return false;
971}
Chris Lattnerc453f762007-04-29 07:54:31 +0000972
Chris Lattner48f84872007-05-01 04:59:48 +0000973
974bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
975 // If it already is material, ignore the request.
976 if (!F->hasNotBeenReadFromBytecode()) return false;
977
978 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
979 DeferredFunctionInfo.find(F);
980 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
981
982 // Move the bit stream to the saved position of the deferred function body and
983 // restore the real linkage type for the function.
984 Stream.JumpToBit(DFII->second.first);
985 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
986 DeferredFunctionInfo.erase(DFII);
987
Chris Lattner980e5aa2007-05-01 05:52:21 +0000988 if (ParseFunctionBody(F)) {
989 if (ErrInfo) *ErrInfo = ErrorString;
990 return true;
991 }
992
993 return false;
994}
995
996Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
997 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
998 DeferredFunctionInfo.begin();
999 while (!DeferredFunctionInfo.empty()) {
1000 Function *F = (*I++).first;
1001 assert(F->hasNotBeenReadFromBytecode() &&
1002 "Deserialized function found in map!");
1003 if (materializeFunction(F, ErrInfo))
1004 return 0;
1005 }
1006 return TheModule;
1007}
1008
1009
1010/// ParseFunctionBody - Lazily parse the specified function body block.
1011bool BitcodeReader::ParseFunctionBody(Function *F) {
1012 if (Stream.EnterSubBlock())
1013 return Error("Malformed block record");
1014
1015 unsigned ModuleValueListSize = ValueList.size();
1016
1017 // Add all the function arguments to the value table.
1018 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1019 ValueList.push_back(I);
1020
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001021 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001022 BasicBlock *CurBB = 0;
1023 unsigned CurBBNo = 0;
1024
Chris Lattner980e5aa2007-05-01 05:52:21 +00001025 // Read all the records.
1026 SmallVector<uint64_t, 64> Record;
1027 while (1) {
1028 unsigned Code = Stream.ReadCode();
1029 if (Code == bitc::END_BLOCK) {
1030 if (Stream.ReadBlockEnd())
1031 return Error("Error at end of function block");
1032 break;
1033 }
1034
1035 if (Code == bitc::ENTER_SUBBLOCK) {
1036 switch (Stream.ReadSubBlockID()) {
1037 default: // Skip unknown content.
1038 if (Stream.SkipBlock())
1039 return Error("Malformed block record");
1040 break;
1041 case bitc::CONSTANTS_BLOCK_ID:
1042 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001043 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001044 break;
1045 case bitc::VALUE_SYMTAB_BLOCK_ID:
1046 if (ParseValueSymbolTable()) return true;
1047 break;
1048 }
1049 continue;
1050 }
1051
1052 if (Code == bitc::DEFINE_ABBREV) {
1053 Stream.ReadAbbrevRecord();
1054 continue;
1055 }
1056
1057 // Read a record.
1058 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001059 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001060 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001061 default: // Default behavior: reject
1062 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001063 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001064 if (Record.size() < 1 || Record[0] == 0)
1065 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001066 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001067 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001068 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1069 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001070 CurBB = FunctionBBs[0];
1071 continue;
1072
Chris Lattner231cbcb2007-05-02 04:27:25 +00001073 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001074 if (Record.size() < 4) return Error("Invalid BINOP record");
1075 const Type *Ty = getTypeByID(Record[1]);
1076 int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1077 Value *LHS = getFnValueByID(Record[2], Ty);
1078 Value *RHS = getFnValueByID(Record[3], Ty);
1079 if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1080 return Error("Invalid BINOP record");
1081 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001082 break;
1083 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001084 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
1085 if (Record.size() < 4) return Error("Invalid CAST record");
1086 int Opc = GetDecodedCastOpcode(Record[0]);
1087 const Type *ResTy = getTypeByID(Record[1]);
1088 const Type *OpTy = getTypeByID(Record[2]);
1089 Value *Op = getFnValueByID(Record[3], OpTy);
1090 if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1091 return Error("Invalid CAST record");
1092 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1093 break;
1094 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001095 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n, n x operands]
1096 if (Record.size() < 2 || (Record.size() & 1))
1097 return Error("Invalid GEP record");
1098 const Type *OpTy = getTypeByID(Record[0]);
1099 Value *Op = getFnValueByID(Record[1], OpTy);
1100 if (OpTy == 0 || Op == 0)
1101 return Error("Invalid GEP record");
1102
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001103 SmallVector<Value*, 16> GEPIdx;
Chris Lattner01ff65f2007-05-02 05:16:49 +00001104 for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
1105 const Type *IdxTy = getTypeByID(Record[i*2]);
1106 Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
1107 if (IdxTy == 0 || Idx == 0)
1108 return Error("Invalid GEP record");
1109 GEPIdx.push_back(Idx);
1110 }
1111
1112 I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
1113 break;
1114 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001115
Chris Lattner01ff65f2007-05-02 05:16:49 +00001116 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
1117 if (Record.size() < 4) return Error("Invalid SELECT record");
1118 const Type *Ty = getTypeByID(Record[0]);
1119 Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
1120 Value *LHS = getFnValueByID(Record[2], Ty);
1121 Value *RHS = getFnValueByID(Record[3], Ty);
1122 if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
1123 return Error("Invalid SELECT record");
1124 I = new SelectInst(Cond, LHS, RHS);
1125 break;
1126 }
1127
1128 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1129 if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
1130 const Type *OpTy = getTypeByID(Record[0]);
1131 Value *Vec = getFnValueByID(Record[1], OpTy);
1132 Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
1133 if (OpTy == 0 || Vec == 0 || Idx == 0)
1134 return Error("Invalid EXTRACTELT record");
1135 I = new ExtractElementInst(Vec, Idx);
1136 break;
1137 }
1138
1139 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1140 if (Record.size() < 4) return Error("Invalid INSERTELT record");
1141 const VectorType *OpTy =
1142 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1143 if (OpTy == 0) return Error("Invalid INSERTELT record");
1144 Value *Vec = getFnValueByID(Record[1], OpTy);
1145 Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
1146 Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
1147 if (Vec == 0 || Elt == 0 || Idx == 0)
1148 return Error("Invalid INSERTELT record");
1149 I = new InsertElementInst(Vec, Elt, Idx);
1150 break;
1151 }
1152
1153 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
1154 if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
1155 const VectorType *OpTy =
1156 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1157 if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
1158 Value *Vec1 = getFnValueByID(Record[1], OpTy);
1159 Value *Vec2 = getFnValueByID(Record[2], OpTy);
1160 Value *Mask = getFnValueByID(Record[3],
1161 VectorType::get(Type::Int32Ty,
1162 OpTy->getNumElements()));
1163 if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
1164 return Error("Invalid SHUFFLEVEC record");
1165 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1166 break;
1167 }
1168
1169 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1170 if (Record.size() < 4) return Error("Invalid CMP record");
1171 const Type *OpTy = getTypeByID(Record[0]);
1172 Value *LHS = getFnValueByID(Record[1], OpTy);
1173 Value *RHS = getFnValueByID(Record[2], OpTy);
1174 if (OpTy == 0 || LHS == 0 || RHS == 0)
1175 return Error("Invalid CMP record");
1176 if (OpTy->isFPOrFPVector())
1177 I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
1178 else
1179 I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
1180 break;
1181 }
1182
Chris Lattner231cbcb2007-05-02 04:27:25 +00001183 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1184 if (Record.size() == 0) {
1185 I = new ReturnInst();
1186 break;
1187 }
1188 if (Record.size() == 2) {
1189 const Type *OpTy = getTypeByID(Record[0]);
1190 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001191 if (!OpTy || !Op)
1192 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001193 I = new ReturnInst(Op);
1194 break;
1195 }
1196 return Error("Invalid RET record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001197 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001198 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001199 return Error("Invalid BR record");
1200 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1201 if (TrueDest == 0)
1202 return Error("Invalid BR record");
1203
1204 if (Record.size() == 1)
1205 I = new BranchInst(TrueDest);
1206 else {
1207 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1208 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1209 if (FalseDest == 0 || Cond == 0)
1210 return Error("Invalid BR record");
1211 I = new BranchInst(TrueDest, FalseDest, Cond);
1212 }
1213 break;
1214 }
1215 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1216 if (Record.size() < 3 || (Record.size() & 1) == 0)
1217 return Error("Invalid SWITCH record");
1218 const Type *OpTy = getTypeByID(Record[0]);
1219 Value *Cond = getFnValueByID(Record[1], OpTy);
1220 BasicBlock *Default = getBasicBlock(Record[2]);
1221 if (OpTy == 0 || Cond == 0 || Default == 0)
1222 return Error("Invalid SWITCH record");
1223 unsigned NumCases = (Record.size()-3)/2;
1224 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1225 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1226 ConstantInt *CaseVal =
1227 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1228 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1229 if (CaseVal == 0 || DestBB == 0) {
1230 delete SI;
1231 return Error("Invalid SWITCH record!");
1232 }
1233 SI->addCase(CaseVal, DestBB);
1234 }
1235 I = SI;
1236 break;
1237 }
1238
1239 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [fnty, op0,op1,op2, ...]
1240 if (Record.size() < 4)
1241 return Error("Invalid INVOKE record");
1242 const PointerType *CalleeTy =
1243 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1244 Value *Callee = getFnValueByID(Record[1], CalleeTy);
1245 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1246 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1247 if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
1248 return Error("Invalid INVOKE record");
1249
1250 const FunctionType *FTy =
1251 dyn_cast<FunctionType>(CalleeTy->getElementType());
1252
1253 // Check that the right number of fixed parameters are here.
1254 if (FTy == 0 || Record.size() < 4+FTy->getNumParams())
1255 return Error("Invalid INVOKE record");
1256
1257 SmallVector<Value*, 16> Ops;
1258 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1259 Ops.push_back(getFnValueByID(Record[4+i], FTy->getParamType(4+i)));
1260 if (Ops.back() == 0)
1261 return Error("Invalid INVOKE record");
1262 }
1263
1264 unsigned FirstVarargParam = 4+FTy->getNumParams();
1265 if (FTy->isVarArg()) {
1266 // Read type/value pairs for varargs params.
1267 if ((Record.size()-FirstVarargParam) & 1)
1268 return Error("Invalid INVOKE record");
1269
1270 for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
1271 const Type *ArgTy = getTypeByID(Record[i]);
1272 Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
1273 if (Ops.back() == 0 || ArgTy == 0)
1274 return Error("Invalid INVOKE record");
1275 }
1276 } else {
1277 if (Record.size() != FirstVarargParam)
1278 return Error("Invalid INVOKE record");
1279 }
1280
1281 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1282 break;
1283 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001284 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1285 I = new UnwindInst();
1286 break;
1287 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1288 I = new UnreachableInst();
1289 break;
Chris Lattner2a98cca2007-05-03 18:58:09 +00001290 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
1291 if (Record.size() < 2 || Record.size() < 2+Record[1] || (Record[1]&1))
1292 return Error("Invalid PHI record");
1293 const Type *Ty = getTypeByID(Record[0]);
1294 if (!Ty) return Error("Invalid PHI record");
1295
1296 PHINode *PN = new PHINode(Ty);
1297 PN->reserveOperandSpace(Record[1]);
1298
1299 for (unsigned i = 0, e = Record[1]; i != e; i += 2) {
1300 Value *V = getFnValueByID(Record[2+i], Ty);
1301 BasicBlock *BB = getBasicBlock(Record[3+i]);
1302 if (!V || !BB) return Error("Invalid PHI record");
1303 PN->addIncoming(V, BB);
1304 }
1305 I = PN;
1306 break;
1307 }
1308
1309 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1310 if (Record.size() < 3)
1311 return Error("Invalid MALLOC record");
1312 const PointerType *Ty =
1313 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1314 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1315 unsigned Align = Record[2];
1316 if (!Ty || !Size) return Error("Invalid MALLOC record");
1317 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1318 break;
1319 }
1320 case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
1321 if (Record.size() < 2)
1322 return Error("Invalid FREE record");
1323 const Type *OpTy = getTypeByID(Record[0]);
1324 Value *Op = getFnValueByID(Record[1], OpTy);
1325 if (!OpTy || !Op)
1326 return Error("Invalid FREE record");
1327 I = new FreeInst(Op);
1328 break;
1329 }
1330 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1331 if (Record.size() < 3)
1332 return Error("Invalid ALLOCA record");
1333 const PointerType *Ty =
1334 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1335 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1336 unsigned Align = Record[2];
1337 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1338 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1339 break;
1340 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001341 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1342 if (Record.size() < 4)
1343 return Error("Invalid LOAD record");
1344 const Type *OpTy = getTypeByID(Record[0]);
1345 Value *Op = getFnValueByID(Record[1], OpTy);
1346 if (!OpTy || !Op)
1347 return Error("Invalid LOAD record");
1348 I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001349 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001350 }
1351 case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
1352 if (Record.size() < 5)
1353 return Error("Invalid LOAD record");
1354 const Type *OpTy = getTypeByID(Record[0]);
1355 Value *Op = getFnValueByID(Record[1], OpTy);
1356 Value *Ptr = getFnValueByID(Record[2], PointerType::get(OpTy));
1357 if (!OpTy || !Op || !Ptr)
1358 return Error("Invalid STORE record");
1359 I = new StoreInst(Op, Ptr, (1 << Record[3]) >> 1, Record[4]);
1360 break;
1361 }
1362 case bitc::FUNC_CODE_INST_CALL: { // CALL: [fnty, fnid, arg0, arg1...]
1363 if (Record.size() < 2)
1364 return Error("Invalid CALL record");
1365 const PointerType *OpTy =
1366 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1367 const FunctionType *FTy = 0;
1368 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1369 Value *Callee = getFnValueByID(Record[1], OpTy);
1370 if (!FTy || !Callee || Record.size() < FTy->getNumParams()+2)
1371 return Error("Invalid CALL record");
1372
1373 SmallVector<Value*, 16> Args;
1374 // Read the fixed params.
1375 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1376 Args.push_back(getFnValueByID(Record[i+2], FTy->getParamType(i)));
1377 if (Args.back() == 0) return Error("Invalid CALL record");
1378 }
1379
1380
1381 // Read type/value pairs for varargs params.
1382 unsigned NextArg = FTy->getNumParams()+2;
1383 if (!FTy->isVarArg()) {
1384 if (NextArg != Record.size())
1385 return Error("Invalid CALL record");
1386 } else {
1387 if ((Record.size()-NextArg) & 1)
1388 return Error("Invalid CALL record");
1389 for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
1390 Args.push_back(getFnValueByID(Record[NextArg+1],
1391 getTypeByID(Record[NextArg])));
1392 if (Args.back() == 0) return Error("Invalid CALL record");
1393 }
1394 }
1395
1396 I = new CallInst(Callee, &Args[0], Args.size());
1397 break;
1398 }
1399 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1400 if (Record.size() < 3)
1401 return Error("Invalid VAARG record");
1402 const Type *OpTy = getTypeByID(Record[0]);
1403 Value *Op = getFnValueByID(Record[1], OpTy);
1404 const Type *ResTy = getTypeByID(Record[2]);
1405 if (!OpTy || !Op || !ResTy)
1406 return Error("Invalid VAARG record");
1407 I = new VAArgInst(Op, ResTy);
1408 break;
1409 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001410 }
1411
1412 // Add instruction to end of current BB. If there is no current BB, reject
1413 // this file.
1414 if (CurBB == 0) {
1415 delete I;
1416 return Error("Invalid instruction with no BB");
1417 }
1418 CurBB->getInstList().push_back(I);
1419
1420 // If this was a terminator instruction, move to the next block.
1421 if (isa<TerminatorInst>(I)) {
1422 ++CurBBNo;
1423 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1424 }
1425
1426 // Non-void values get registered in the value table for future use.
1427 if (I && I->getType() != Type::VoidTy)
1428 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001429 }
1430
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001431 // Check the function list for unresolved values.
1432 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1433 if (A->getParent() == 0) {
1434 // We found at least one unresolved value. Nuke them all to avoid leaks.
1435 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1436 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1437 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1438 delete A;
1439 }
1440 }
1441 }
1442 return Error("Never resolved value found in function!");
1443 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001444
1445 // Trim the value list down to the size it was before we parsed this function.
1446 ValueList.shrinkTo(ModuleValueListSize);
1447 std::vector<BasicBlock*>().swap(FunctionBBs);
1448
Chris Lattner48f84872007-05-01 04:59:48 +00001449 return false;
1450}
1451
1452
Chris Lattnerc453f762007-04-29 07:54:31 +00001453//===----------------------------------------------------------------------===//
1454// External interface
1455//===----------------------------------------------------------------------===//
1456
1457/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1458///
1459ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1460 std::string *ErrMsg) {
1461 BitcodeReader *R = new BitcodeReader(Buffer);
1462 if (R->ParseBitcode()) {
1463 if (ErrMsg)
1464 *ErrMsg = R->getErrorString();
1465
1466 // Don't let the BitcodeReader dtor delete 'Buffer'.
1467 R->releaseMemoryBuffer();
1468 delete R;
1469 return 0;
1470 }
1471 return R;
1472}
1473
1474/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1475/// If an error occurs, return null and fill in *ErrMsg if non-null.
1476Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1477 BitcodeReader *R;
1478 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1479 if (!R) return 0;
1480
1481 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1482 // delete it when its dtor is run.
1483 Module *M = R->releaseModule(ErrMsg);
1484
1485 // Don't let the BitcodeReader dtor delete 'Buffer'.
1486 R->releaseMemoryBuffer();
1487 delete R;
1488 return M;
1489}