blob: c405feb898da64f0552829a2af69f80a475ff323 [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 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"
Chris Lattner48c85b82007-05-04 03:30:17 +000021#include "llvm/ParameterAttributes.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"
Chris Lattner0eef0802007-04-24 04:04:35 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000025#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000026using namespace llvm;
27
Chris Lattnerb348bb82007-05-18 04:02:46 +000028void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000029 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000030 Buffer = 0;
31 std::vector<PATypeHolder>().swap(TypeList);
32 ValueList.clear();
33 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
34 std::vector<BasicBlock*>().swap(FunctionBBs);
35 std::vector<Function*>().swap(FunctionsWithBodies);
36 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000037}
38
Chris Lattner48c85b82007-05-04 03:30:17 +000039//===----------------------------------------------------------------------===//
40// Helper functions to implement forward reference resolution, etc.
41//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000042
Chris Lattnercaee0dc2007-04-22 06:23:29 +000043/// ConvertToString - Convert a string from a record into an std::string, return
44/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000045template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000046static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000047 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000048 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000049 return true;
50
Chris Lattner15e6d172007-05-04 19:11:41 +000051 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
52 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000053 return false;
54}
55
56static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
57 switch (Val) {
58 default: // Map unknown/new linkages to external
59 case 0: return GlobalValue::ExternalLinkage;
60 case 1: return GlobalValue::WeakLinkage;
61 case 2: return GlobalValue::AppendingLinkage;
62 case 3: return GlobalValue::InternalLinkage;
63 case 4: return GlobalValue::LinkOnceLinkage;
64 case 5: return GlobalValue::DLLImportLinkage;
65 case 6: return GlobalValue::DLLExportLinkage;
66 case 7: return GlobalValue::ExternalWeakLinkage;
67 }
68}
69
70static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
71 switch (Val) {
72 default: // Map unknown visibilities to default.
73 case 0: return GlobalValue::DefaultVisibility;
74 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000075 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000076 }
77}
78
Chris Lattnerf581c3b2007-04-24 07:07:11 +000079static int GetDecodedCastOpcode(unsigned Val) {
80 switch (Val) {
81 default: return -1;
82 case bitc::CAST_TRUNC : return Instruction::Trunc;
83 case bitc::CAST_ZEXT : return Instruction::ZExt;
84 case bitc::CAST_SEXT : return Instruction::SExt;
85 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
86 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
87 case bitc::CAST_UITOFP : return Instruction::UIToFP;
88 case bitc::CAST_SITOFP : return Instruction::SIToFP;
89 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
90 case bitc::CAST_FPEXT : return Instruction::FPExt;
91 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
92 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
93 case bitc::CAST_BITCAST : return Instruction::BitCast;
94 }
95}
96static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
97 switch (Val) {
98 default: return -1;
99 case bitc::BINOP_ADD: return Instruction::Add;
100 case bitc::BINOP_SUB: return Instruction::Sub;
101 case bitc::BINOP_MUL: return Instruction::Mul;
102 case bitc::BINOP_UDIV: return Instruction::UDiv;
103 case bitc::BINOP_SDIV:
104 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
105 case bitc::BINOP_UREM: return Instruction::URem;
106 case bitc::BINOP_SREM:
107 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
108 case bitc::BINOP_SHL: return Instruction::Shl;
109 case bitc::BINOP_LSHR: return Instruction::LShr;
110 case bitc::BINOP_ASHR: return Instruction::AShr;
111 case bitc::BINOP_AND: return Instruction::And;
112 case bitc::BINOP_OR: return Instruction::Or;
113 case bitc::BINOP_XOR: return Instruction::Xor;
114 }
115}
116
117
Chris Lattner522b7b12007-04-24 05:48:56 +0000118namespace {
119 /// @brief A class for maintaining the slot number definition
120 /// as a placeholder for the actual definition for forward constants defs.
121 class ConstantPlaceHolder : public ConstantExpr {
122 ConstantPlaceHolder(); // DO NOT IMPLEMENT
123 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000124 public:
125 Use Op;
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000126 explicit ConstantPlaceHolder(const Type *Ty)
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000127 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
128 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000129 }
130 };
131}
132
133Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
134 const Type *Ty) {
135 if (Idx >= size()) {
136 // Insert a bunch of null values.
137 Uses.resize(Idx+1);
138 OperandList = &Uses[0];
139 NumOperands = Idx+1;
140 }
141
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000142 if (Value *V = Uses[Idx]) {
143 assert(Ty == V->getType() && "Type mismatch in constant table!");
144 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000145 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000146
147 // Create and return a placeholder, which will later be RAUW'd.
148 Constant *C = new ConstantPlaceHolder(Ty);
149 Uses[Idx].init(C, this);
150 return C;
151}
152
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000153Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
154 if (Idx >= size()) {
155 // Insert a bunch of null values.
156 Uses.resize(Idx+1);
157 OperandList = &Uses[0];
158 NumOperands = Idx+1;
159 }
160
161 if (Value *V = Uses[Idx]) {
162 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
163 return V;
164 }
165
Chris Lattner01ff65f2007-05-02 05:16:49 +0000166 // No type specified, must be invalid reference.
167 if (Ty == 0) return 0;
168
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000169 // Create and return a placeholder, which will later be RAUW'd.
170 Value *V = new Argument(Ty);
171 Uses[Idx].init(V, this);
172 return V;
173}
174
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000175
176const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
177 // If the TypeID is in range, return it.
178 if (ID < TypeList.size())
179 return TypeList[ID].get();
180 if (!isTypeTable) return 0;
181
182 // The type table allows forward references. Push as many Opaque types as
183 // needed to get up to ID.
184 while (TypeList.size() <= ID)
185 TypeList.push_back(OpaqueType::get());
186 return TypeList.back().get();
187}
188
Chris Lattner48c85b82007-05-04 03:30:17 +0000189//===----------------------------------------------------------------------===//
190// Functions for parsing blocks from the bitcode file
191//===----------------------------------------------------------------------===//
192
193bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000194 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000195 return Error("Malformed block record");
196
197 if (!ParamAttrs.empty())
198 return Error("Multiple PARAMATTR blocks found!");
199
200 SmallVector<uint64_t, 64> Record;
201
202 ParamAttrsVector Attrs;
203
204 // Read all the records.
205 while (1) {
206 unsigned Code = Stream.ReadCode();
207 if (Code == bitc::END_BLOCK) {
208 if (Stream.ReadBlockEnd())
209 return Error("Error at end of PARAMATTR block");
210 return false;
211 }
212
213 if (Code == bitc::ENTER_SUBBLOCK) {
214 // No known subblocks, always skip them.
215 Stream.ReadSubBlockID();
216 if (Stream.SkipBlock())
217 return Error("Malformed block record");
218 continue;
219 }
220
221 if (Code == bitc::DEFINE_ABBREV) {
222 Stream.ReadAbbrevRecord();
223 continue;
224 }
225
226 // Read a record.
227 Record.clear();
228 switch (Stream.ReadRecord(Code, Record)) {
229 default: // Default behavior: ignore.
230 break;
231 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
232 if (Record.size() & 1)
233 return Error("Invalid ENTRY record");
234
Chris Lattner48c85b82007-05-04 03:30:17 +0000235 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Duncan Sands5e41f652007-11-20 14:09:29 +0000236 if (Record[i+1] != ParamAttr::None)
237 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
Chris Lattner48c85b82007-05-04 03:30:17 +0000238 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000239 ParamAttrs.push_back(Attrs.empty() ? NULL : ParamAttrsList::get(Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000240 Attrs.clear();
241 break;
242 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000243 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000244 }
245}
246
247
Chris Lattner86697142007-05-01 05:01:34 +0000248bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000249 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000250 return Error("Malformed block record");
251
252 if (!TypeList.empty())
253 return Error("Multiple TYPE_BLOCKs found!");
254
255 SmallVector<uint64_t, 64> Record;
256 unsigned NumRecords = 0;
257
258 // Read all the records for this type table.
259 while (1) {
260 unsigned Code = Stream.ReadCode();
261 if (Code == bitc::END_BLOCK) {
262 if (NumRecords != TypeList.size())
263 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000264 if (Stream.ReadBlockEnd())
265 return Error("Error at end of type table block");
266 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000267 }
268
269 if (Code == bitc::ENTER_SUBBLOCK) {
270 // No known subblocks, always skip them.
271 Stream.ReadSubBlockID();
272 if (Stream.SkipBlock())
273 return Error("Malformed block record");
274 continue;
275 }
276
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000277 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000278 Stream.ReadAbbrevRecord();
279 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000280 }
281
282 // Read a record.
283 Record.clear();
284 const Type *ResultTy = 0;
285 switch (Stream.ReadRecord(Code, Record)) {
286 default: // Default behavior: unknown type.
287 ResultTy = 0;
288 break;
289 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
290 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
291 // type list. This allows us to reserve space.
292 if (Record.size() < 1)
293 return Error("Invalid TYPE_CODE_NUMENTRY record");
294 TypeList.reserve(Record[0]);
295 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000296 case bitc::TYPE_CODE_VOID: // VOID
297 ResultTy = Type::VoidTy;
298 break;
299 case bitc::TYPE_CODE_FLOAT: // FLOAT
300 ResultTy = Type::FloatTy;
301 break;
302 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
303 ResultTy = Type::DoubleTy;
304 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000305 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
306 ResultTy = Type::X86_FP80Ty;
307 break;
308 case bitc::TYPE_CODE_FP128: // FP128
309 ResultTy = Type::FP128Ty;
310 break;
311 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
312 ResultTy = Type::PPC_FP128Ty;
313 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000314 case bitc::TYPE_CODE_LABEL: // LABEL
315 ResultTy = Type::LabelTy;
316 break;
317 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
318 ResultTy = 0;
319 break;
320 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
321 if (Record.size() < 1)
322 return Error("Invalid Integer type record");
323
324 ResultTy = IntegerType::get(Record[0]);
325 break;
326 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
327 if (Record.size() < 1)
328 return Error("Invalid POINTER type record");
329 ResultTy = PointerType::get(getTypeByID(Record[0], true));
330 break;
331 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000332 // FIXME: attrid is dead, remove it in LLVM 3.0
333 // FUNCTION: [vararg, attrid, retty, paramty x N]
334 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000335 return Error("Invalid FUNCTION type record");
336 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000337 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000338 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000339
Chris Lattnera1afde72007-11-27 17:48:06 +0000340 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000341 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000342 break;
343 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000344 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000345 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000346 return Error("Invalid STRUCT type record");
347 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000348 for (unsigned i = 1, e = Record.size(); i != e; ++i)
349 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000350 ResultTy = StructType::get(EltTys, Record[0]);
351 break;
352 }
353 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
354 if (Record.size() < 2)
355 return Error("Invalid ARRAY type record");
356 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
357 break;
358 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
359 if (Record.size() < 2)
360 return Error("Invalid VECTOR type record");
361 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
362 break;
363 }
364
365 if (NumRecords == TypeList.size()) {
366 // If this is a new type slot, just append it.
367 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
368 ++NumRecords;
369 } else if (ResultTy == 0) {
370 // Otherwise, this was forward referenced, so an opaque type was created,
371 // but the result type is actually just an opaque. Leave the one we
372 // created previously.
373 ++NumRecords;
374 } else {
375 // Otherwise, this was forward referenced, so an opaque type was created.
376 // Resolve the opaque type to the real type now.
377 assert(NumRecords < TypeList.size() && "Typelist imbalance");
378 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
379
380 // Don't directly push the new type on the Tab. Instead we want to replace
381 // the opaque type we previously inserted with the new concrete value. The
382 // refinement from the abstract (opaque) type to the new type causes all
383 // uses of the abstract type to use the concrete type (NewTy). This will
384 // also cause the opaque type to be deleted.
385 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
386
387 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000388 // value table... or with a preexisting type that was already in the
389 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000390 assert(TypeList[NumRecords-1].get() != OldTy &&
391 "refineAbstractType didn't work!");
392 }
393 }
394}
395
396
Chris Lattner86697142007-05-01 05:01:34 +0000397bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000398 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000399 return Error("Malformed block record");
400
401 SmallVector<uint64_t, 64> Record;
402
403 // Read all the records for this type table.
404 std::string TypeName;
405 while (1) {
406 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000407 if (Code == bitc::END_BLOCK) {
408 if (Stream.ReadBlockEnd())
409 return Error("Error at end of type symbol table block");
410 return false;
411 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000412
413 if (Code == bitc::ENTER_SUBBLOCK) {
414 // No known subblocks, always skip them.
415 Stream.ReadSubBlockID();
416 if (Stream.SkipBlock())
417 return Error("Malformed block record");
418 continue;
419 }
420
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000421 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000422 Stream.ReadAbbrevRecord();
423 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000424 }
425
426 // Read a record.
427 Record.clear();
428 switch (Stream.ReadRecord(Code, Record)) {
429 default: // Default behavior: unknown type.
430 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000431 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000432 if (ConvertToString(Record, 1, TypeName))
433 return Error("Invalid TST_ENTRY record");
434 unsigned TypeID = Record[0];
435 if (TypeID >= TypeList.size())
436 return Error("Invalid Type ID in TST_ENTRY record");
437
438 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
439 TypeName.clear();
440 break;
441 }
442 }
443}
444
Chris Lattner86697142007-05-01 05:01:34 +0000445bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000446 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000447 return Error("Malformed block record");
448
449 SmallVector<uint64_t, 64> Record;
450
451 // Read all the records for this value table.
452 SmallString<128> ValueName;
453 while (1) {
454 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000455 if (Code == bitc::END_BLOCK) {
456 if (Stream.ReadBlockEnd())
457 return Error("Error at end of value symbol table block");
458 return false;
459 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000460 if (Code == bitc::ENTER_SUBBLOCK) {
461 // No known subblocks, always skip them.
462 Stream.ReadSubBlockID();
463 if (Stream.SkipBlock())
464 return Error("Malformed block record");
465 continue;
466 }
467
468 if (Code == bitc::DEFINE_ABBREV) {
469 Stream.ReadAbbrevRecord();
470 continue;
471 }
472
473 // Read a record.
474 Record.clear();
475 switch (Stream.ReadRecord(Code, Record)) {
476 default: // Default behavior: unknown type.
477 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000478 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000479 if (ConvertToString(Record, 1, ValueName))
480 return Error("Invalid TST_ENTRY record");
481 unsigned ValueID = Record[0];
482 if (ValueID >= ValueList.size())
483 return Error("Invalid Value ID in VST_ENTRY record");
484 Value *V = ValueList[ValueID];
485
486 V->setName(&ValueName[0], ValueName.size());
487 ValueName.clear();
488 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000489 }
490 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000491 if (ConvertToString(Record, 1, ValueName))
492 return Error("Invalid VST_BBENTRY record");
493 BasicBlock *BB = getBasicBlock(Record[0]);
494 if (BB == 0)
495 return Error("Invalid BB ID in VST_BBENTRY record");
496
497 BB->setName(&ValueName[0], ValueName.size());
498 ValueName.clear();
499 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000500 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000501 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000502 }
503}
504
Chris Lattner0eef0802007-04-24 04:04:35 +0000505/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
506/// the LSB for dense VBR encoding.
507static uint64_t DecodeSignRotatedValue(uint64_t V) {
508 if ((V & 1) == 0)
509 return V >> 1;
510 if (V != 1)
511 return -(V >> 1);
512 // There is no such thing as -0 with integers. "-0" really means MININT.
513 return 1ULL << 63;
514}
515
Chris Lattner07d98b42007-04-26 02:46:40 +0000516/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
517/// values and aliases that we can.
518bool BitcodeReader::ResolveGlobalAndAliasInits() {
519 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
520 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
521
522 GlobalInitWorklist.swap(GlobalInits);
523 AliasInitWorklist.swap(AliasInits);
524
525 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000526 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000527 if (ValID >= ValueList.size()) {
528 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000529 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000530 } else {
531 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
532 GlobalInitWorklist.back().first->setInitializer(C);
533 else
534 return Error("Global variable initializer is not a constant!");
535 }
536 GlobalInitWorklist.pop_back();
537 }
538
539 while (!AliasInitWorklist.empty()) {
540 unsigned ValID = AliasInitWorklist.back().second;
541 if (ValID >= ValueList.size()) {
542 AliasInits.push_back(AliasInitWorklist.back());
543 } else {
544 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000545 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000546 else
547 return Error("Alias initializer is not a constant!");
548 }
549 AliasInitWorklist.pop_back();
550 }
551 return false;
552}
553
554
Chris Lattner86697142007-05-01 05:01:34 +0000555bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000556 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000557 return Error("Malformed block record");
558
559 SmallVector<uint64_t, 64> Record;
560
561 // Read all the records for this value table.
562 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000563 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000564 while (1) {
565 unsigned Code = Stream.ReadCode();
566 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000567 if (NextCstNo != ValueList.size())
568 return Error("Invalid constant reference!");
569
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000570 if (Stream.ReadBlockEnd())
571 return Error("Error at end of constants block");
572 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000573 }
574
575 if (Code == bitc::ENTER_SUBBLOCK) {
576 // No known subblocks, always skip them.
577 Stream.ReadSubBlockID();
578 if (Stream.SkipBlock())
579 return Error("Malformed block record");
580 continue;
581 }
582
583 if (Code == bitc::DEFINE_ABBREV) {
584 Stream.ReadAbbrevRecord();
585 continue;
586 }
587
588 // Read a record.
589 Record.clear();
590 Value *V = 0;
591 switch (Stream.ReadRecord(Code, Record)) {
592 default: // Default behavior: unknown constant
593 case bitc::CST_CODE_UNDEF: // UNDEF
594 V = UndefValue::get(CurTy);
595 break;
596 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
597 if (Record.empty())
598 return Error("Malformed CST_SETTYPE record");
599 if (Record[0] >= TypeList.size())
600 return Error("Invalid Type ID in CST_SETTYPE record");
601 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000602 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000603 case bitc::CST_CODE_NULL: // NULL
604 V = Constant::getNullValue(CurTy);
605 break;
606 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000607 if (!isa<IntegerType>(CurTy) || Record.empty())
608 return Error("Invalid CST_INTEGER record");
609 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
610 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000611 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
612 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000613 return Error("Invalid WIDE_INTEGER record");
614
Chris Lattner15e6d172007-05-04 19:11:41 +0000615 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000616 SmallVector<uint64_t, 8> Words;
617 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000618 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000619 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000620 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000621 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000622 break;
623 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000624 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000625 if (Record.empty())
626 return Error("Invalid FLOAT record");
627 if (CurTy == Type::FloatTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000628 V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000629 else if (CurTy == Type::DoubleTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000630 V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000631 else if (CurTy == Type::X86_FP80Ty)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000632 V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000633 else if (CurTy == Type::FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000634 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000635 else if (CurTy == Type::PPC_FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000636 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000637 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000638 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000639 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000640 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000641
Chris Lattner15e6d172007-05-04 19:11:41 +0000642 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
643 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000644 return Error("Invalid CST_AGGREGATE record");
645
Chris Lattner15e6d172007-05-04 19:11:41 +0000646 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000647 std::vector<Constant*> Elts;
648
649 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
650 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000651 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000652 STy->getElementType(i)));
653 V = ConstantStruct::get(STy, Elts);
654 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
655 const Type *EltTy = ATy->getElementType();
656 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000657 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000658 V = ConstantArray::get(ATy, Elts);
659 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
660 const Type *EltTy = VTy->getElementType();
661 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000662 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000663 V = ConstantVector::get(Elts);
664 } else {
665 V = UndefValue::get(CurTy);
666 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000667 break;
668 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000669 case bitc::CST_CODE_STRING: { // STRING: [values]
670 if (Record.empty())
671 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000672
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000673 const ArrayType *ATy = cast<ArrayType>(CurTy);
674 const Type *EltTy = ATy->getElementType();
675
676 unsigned Size = Record.size();
677 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000678 for (unsigned i = 0; i != Size; ++i)
679 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
680 V = ConstantArray::get(ATy, Elts);
681 break;
682 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000683 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
684 if (Record.empty())
685 return Error("Invalid CST_AGGREGATE record");
686
687 const ArrayType *ATy = cast<ArrayType>(CurTy);
688 const Type *EltTy = ATy->getElementType();
689
690 unsigned Size = Record.size();
691 std::vector<Constant*> Elts;
692 for (unsigned i = 0; i != Size; ++i)
693 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
694 Elts.push_back(Constant::getNullValue(EltTy));
695 V = ConstantArray::get(ATy, Elts);
696 break;
697 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000698 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
699 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
700 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000701 if (Opc < 0) {
702 V = UndefValue::get(CurTy); // Unknown binop.
703 } else {
704 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
705 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
706 V = ConstantExpr::get(Opc, LHS, RHS);
707 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000708 break;
709 }
710 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
711 if (Record.size() < 3) return Error("Invalid CE_CAST record");
712 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000713 if (Opc < 0) {
714 V = UndefValue::get(CurTy); // Unknown cast.
715 } else {
716 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000717 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000718 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
719 V = ConstantExpr::getCast(Opc, Op, CurTy);
720 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000721 break;
722 }
723 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000724 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000725 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000726 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000727 const Type *ElTy = getTypeByID(Record[i]);
728 if (!ElTy) return Error("Invalid CE_GEP record");
729 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
730 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000731 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
732 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000733 }
734 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
735 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
736 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
737 Type::Int1Ty),
738 ValueList.getConstantFwdRef(Record[1],CurTy),
739 ValueList.getConstantFwdRef(Record[2],CurTy));
740 break;
741 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
742 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
743 const VectorType *OpTy =
744 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
745 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
746 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
747 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
748 OpTy->getElementType());
749 V = ConstantExpr::getExtractElement(Op0, Op1);
750 break;
751 }
752 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
753 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
754 if (Record.size() < 3 || OpTy == 0)
755 return Error("Invalid CE_INSERTELT record");
756 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
757 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
758 OpTy->getElementType());
759 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
760 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
761 break;
762 }
763 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
764 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
765 if (Record.size() < 3 || OpTy == 0)
766 return Error("Invalid CE_INSERTELT record");
767 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
768 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
769 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
770 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
771 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
772 break;
773 }
774 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
775 if (Record.size() < 4) return Error("Invalid CE_CMP record");
776 const Type *OpTy = getTypeByID(Record[0]);
777 if (OpTy == 0) return Error("Invalid CE_CMP record");
778 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
779 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
780
781 if (OpTy->isFloatingPoint())
782 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
783 else
784 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
785 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000786 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000787 case bitc::CST_CODE_INLINEASM: {
788 if (Record.size() < 2) return Error("Invalid INLINEASM record");
789 std::string AsmStr, ConstrStr;
790 bool HasSideEffects = Record[0];
791 unsigned AsmStrSize = Record[1];
792 if (2+AsmStrSize >= Record.size())
793 return Error("Invalid INLINEASM record");
794 unsigned ConstStrSize = Record[2+AsmStrSize];
795 if (3+AsmStrSize+ConstStrSize > Record.size())
796 return Error("Invalid INLINEASM record");
797
798 for (unsigned i = 0; i != AsmStrSize; ++i)
799 AsmStr += (char)Record[2+i];
800 for (unsigned i = 0; i != ConstStrSize; ++i)
801 ConstrStr += (char)Record[3+AsmStrSize+i];
802 const PointerType *PTy = cast<PointerType>(CurTy);
803 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
804 AsmStr, ConstrStr, HasSideEffects);
805 break;
806 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000807 }
808
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000809 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000810 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000811 }
812}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000813
Chris Lattner980e5aa2007-05-01 05:52:21 +0000814/// RememberAndSkipFunctionBody - When we see the block for a function body,
815/// remember where it is and then skip it. This lets us lazily deserialize the
816/// functions.
817bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000818 // Get the function we are talking about.
819 if (FunctionsWithBodies.empty())
820 return Error("Insufficient function protos");
821
822 Function *Fn = FunctionsWithBodies.back();
823 FunctionsWithBodies.pop_back();
824
825 // Save the current stream state.
826 uint64_t CurBit = Stream.GetCurrentBitNo();
827 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
828
829 // Set the functions linkage to GhostLinkage so we know it is lazily
830 // deserialized.
831 Fn->setLinkage(GlobalValue::GhostLinkage);
832
833 // Skip over the function block for now.
834 if (Stream.SkipBlock())
835 return Error("Malformed block record");
836 return false;
837}
838
Chris Lattner86697142007-05-01 05:01:34 +0000839bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000840 // Reject multiple MODULE_BLOCK's in a single bitstream.
841 if (TheModule)
842 return Error("Multiple MODULE_BLOCKs in same stream");
843
Chris Lattnere17b6582007-05-05 00:17:00 +0000844 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000845 return Error("Malformed block record");
846
847 // Otherwise, create the module.
848 TheModule = new Module(ModuleID);
849
850 SmallVector<uint64_t, 64> Record;
851 std::vector<std::string> SectionTable;
852
853 // Read all the records for this module.
854 while (!Stream.AtEndOfStream()) {
855 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000856 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000857 if (Stream.ReadBlockEnd())
858 return Error("Error at end of module block");
859
860 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000861 ResolveGlobalAndAliasInits();
862 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000863 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000864 if (!FunctionsWithBodies.empty())
865 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000866
Chandler Carruth69940402007-08-04 01:51:18 +0000867 // Look for intrinsic functions which need to be upgraded at some point
868 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
869 FI != FE; ++FI) {
870 if (Function* NewFn = UpgradeIntrinsicFunction(FI))
871 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
872 }
873
Chris Lattner980e5aa2007-05-01 05:52:21 +0000874 // Force deallocation of memory for these vectors to favor the client that
875 // want lazy deserialization.
876 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
877 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
878 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000879 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000880 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000881
882 if (Code == bitc::ENTER_SUBBLOCK) {
883 switch (Stream.ReadSubBlockID()) {
884 default: // Skip unknown content.
885 if (Stream.SkipBlock())
886 return Error("Malformed block record");
887 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000888 case bitc::BLOCKINFO_BLOCK_ID:
889 if (Stream.ReadBlockInfoBlock())
890 return Error("Malformed BlockInfoBlock");
891 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000892 case bitc::PARAMATTR_BLOCK_ID:
893 if (ParseParamAttrBlock())
894 return true;
895 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000896 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000897 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000898 return true;
899 break;
900 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000901 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000902 return true;
903 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000904 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000905 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000906 return true;
907 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000908 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000909 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000910 return true;
911 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000912 case bitc::FUNCTION_BLOCK_ID:
913 // If this is the first function body we've seen, reverse the
914 // FunctionsWithBodies list.
915 if (!HasReversedFunctionsWithBodies) {
916 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
917 HasReversedFunctionsWithBodies = true;
918 }
919
Chris Lattner980e5aa2007-05-01 05:52:21 +0000920 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000921 return true;
922 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000923 }
924 continue;
925 }
926
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000927 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000928 Stream.ReadAbbrevRecord();
929 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000930 }
931
932 // Read a record.
933 switch (Stream.ReadRecord(Code, Record)) {
934 default: break; // Default behavior, ignore unknown content.
935 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
936 if (Record.size() < 1)
937 return Error("Malformed MODULE_CODE_VERSION");
938 // Only version #0 is supported so far.
939 if (Record[0] != 0)
940 return Error("Unknown bitstream version!");
941 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000942 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000943 std::string S;
944 if (ConvertToString(Record, 0, S))
945 return Error("Invalid MODULE_CODE_TRIPLE record");
946 TheModule->setTargetTriple(S);
947 break;
948 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000949 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000950 std::string S;
951 if (ConvertToString(Record, 0, S))
952 return Error("Invalid MODULE_CODE_DATALAYOUT record");
953 TheModule->setDataLayout(S);
954 break;
955 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000956 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000957 std::string S;
958 if (ConvertToString(Record, 0, S))
959 return Error("Invalid MODULE_CODE_ASM record");
960 TheModule->setModuleInlineAsm(S);
961 break;
962 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000963 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000964 std::string S;
965 if (ConvertToString(Record, 0, S))
966 return Error("Invalid MODULE_CODE_DEPLIB record");
967 TheModule->addLibrary(S);
968 break;
969 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000970 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000971 std::string S;
972 if (ConvertToString(Record, 0, S))
973 return Error("Invalid MODULE_CODE_SECTIONNAME record");
974 SectionTable.push_back(S);
975 break;
976 }
977 // GLOBALVAR: [type, isconst, initid,
978 // linkage, alignment, section, visibility, threadlocal]
979 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000980 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000981 return Error("Invalid MODULE_CODE_GLOBALVAR record");
982 const Type *Ty = getTypeByID(Record[0]);
983 if (!isa<PointerType>(Ty))
984 return Error("Global not a pointer type!");
985 Ty = cast<PointerType>(Ty)->getElementType();
986
987 bool isConstant = Record[1];
988 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
989 unsigned Alignment = (1 << Record[4]) >> 1;
990 std::string Section;
991 if (Record[5]) {
992 if (Record[5]-1 >= SectionTable.size())
993 return Error("Invalid section ID");
994 Section = SectionTable[Record[5]-1];
995 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000996 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +0000997 if (Record.size() > 6)
998 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000999 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001000 if (Record.size() > 7)
1001 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001002
1003 GlobalVariable *NewGV =
1004 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
1005 NewGV->setAlignment(Alignment);
1006 if (!Section.empty())
1007 NewGV->setSection(Section);
1008 NewGV->setVisibility(Visibility);
1009 NewGV->setThreadLocal(isThreadLocal);
1010
Chris Lattner0b2482a2007-04-23 21:26:05 +00001011 ValueList.push_back(NewGV);
1012
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001013 // Remember which value to use for the global initializer.
1014 if (unsigned InitID = Record[2])
1015 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001016 break;
1017 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001018 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1019 // alignment, section, visibility]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001020 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001021 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001022 return Error("Invalid MODULE_CODE_FUNCTION record");
1023 const Type *Ty = getTypeByID(Record[0]);
1024 if (!isa<PointerType>(Ty))
1025 return Error("Function not a pointer type!");
1026 const FunctionType *FTy =
1027 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1028 if (!FTy)
1029 return Error("Function not a pointer to function type!");
1030
1031 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1032 "", TheModule);
1033
1034 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001035 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001036 Func->setLinkage(GetDecodedLinkage(Record[3]));
Duncan Sandsdc024672007-11-27 13:23:08 +00001037 const ParamAttrsList *PAL = getParamAttrs(Record[4]);
1038 Func->setParamAttrs(PAL);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001039
1040 Func->setAlignment((1 << Record[5]) >> 1);
1041 if (Record[6]) {
1042 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001043 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001044 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001045 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001046 Func->setVisibility(GetDecodedVisibility(Record[7]));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001047
Chris Lattner0b2482a2007-04-23 21:26:05 +00001048 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001049
1050 // If this is a function with a body, remember the prototype we are
1051 // creating now, so that we can match up the body with them later.
1052 if (!isProto)
1053 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001054 break;
1055 }
Chris Lattner07d98b42007-04-26 02:46:40 +00001056 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +00001057 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001058 if (Record.size() < 3)
1059 return Error("Invalid MODULE_ALIAS record");
1060 const Type *Ty = getTypeByID(Record[0]);
1061 if (!isa<PointerType>(Ty))
1062 return Error("Function not a pointer type!");
1063
1064 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1065 "", 0, TheModule);
1066 ValueList.push_back(NewGA);
1067 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1068 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001069 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001070 /// MODULE_CODE_PURGEVALS: [numvals]
1071 case bitc::MODULE_CODE_PURGEVALS:
1072 // Trim down the value list to the specified size.
1073 if (Record.size() < 1 || Record[0] > ValueList.size())
1074 return Error("Invalid MODULE_PURGEVALS record");
1075 ValueList.shrinkTo(Record[0]);
1076 break;
1077 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001078 Record.clear();
1079 }
1080
1081 return Error("Premature end of bitstream");
1082}
1083
1084
Chris Lattnerc453f762007-04-29 07:54:31 +00001085bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001086 TheModule = 0;
1087
Chris Lattnerc453f762007-04-29 07:54:31 +00001088 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001089 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1090
Chris Lattnerc453f762007-04-29 07:54:31 +00001091 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001092 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001093
1094 // Sniff for the signature.
1095 if (Stream.Read(8) != 'B' ||
1096 Stream.Read(8) != 'C' ||
1097 Stream.Read(4) != 0x0 ||
1098 Stream.Read(4) != 0xC ||
1099 Stream.Read(4) != 0xE ||
1100 Stream.Read(4) != 0xD)
1101 return Error("Invalid bitcode signature");
1102
1103 // We expect a number of well-defined blocks, though we don't necessarily
1104 // need to understand them all.
1105 while (!Stream.AtEndOfStream()) {
1106 unsigned Code = Stream.ReadCode();
1107
1108 if (Code != bitc::ENTER_SUBBLOCK)
1109 return Error("Invalid record at top-level");
1110
1111 unsigned BlockID = Stream.ReadSubBlockID();
1112
1113 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001114 switch (BlockID) {
1115 case bitc::BLOCKINFO_BLOCK_ID:
1116 if (Stream.ReadBlockInfoBlock())
1117 return Error("Malformed BlockInfoBlock");
1118 break;
1119 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001120 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001121 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001122 break;
1123 default:
1124 if (Stream.SkipBlock())
1125 return Error("Malformed block record");
1126 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001127 }
1128 }
1129
1130 return false;
1131}
Chris Lattnerc453f762007-04-29 07:54:31 +00001132
Chris Lattner48f84872007-05-01 04:59:48 +00001133
Chris Lattner980e5aa2007-05-01 05:52:21 +00001134/// ParseFunctionBody - Lazily parse the specified function body block.
1135bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001136 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001137 return Error("Malformed block record");
1138
1139 unsigned ModuleValueListSize = ValueList.size();
1140
1141 // Add all the function arguments to the value table.
1142 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1143 ValueList.push_back(I);
1144
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001145 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001146 BasicBlock *CurBB = 0;
1147 unsigned CurBBNo = 0;
1148
Chris Lattner980e5aa2007-05-01 05:52:21 +00001149 // Read all the records.
1150 SmallVector<uint64_t, 64> Record;
1151 while (1) {
1152 unsigned Code = Stream.ReadCode();
1153 if (Code == bitc::END_BLOCK) {
1154 if (Stream.ReadBlockEnd())
1155 return Error("Error at end of function block");
1156 break;
1157 }
1158
1159 if (Code == bitc::ENTER_SUBBLOCK) {
1160 switch (Stream.ReadSubBlockID()) {
1161 default: // Skip unknown content.
1162 if (Stream.SkipBlock())
1163 return Error("Malformed block record");
1164 break;
1165 case bitc::CONSTANTS_BLOCK_ID:
1166 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001167 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001168 break;
1169 case bitc::VALUE_SYMTAB_BLOCK_ID:
1170 if (ParseValueSymbolTable()) return true;
1171 break;
1172 }
1173 continue;
1174 }
1175
1176 if (Code == bitc::DEFINE_ABBREV) {
1177 Stream.ReadAbbrevRecord();
1178 continue;
1179 }
1180
1181 // Read a record.
1182 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001183 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001184 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001185 default: // Default behavior: reject
1186 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001187 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001188 if (Record.size() < 1 || Record[0] == 0)
1189 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001190 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001191 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001192 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1193 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001194 CurBB = FunctionBBs[0];
1195 continue;
1196
Chris Lattnerabfbf852007-05-06 00:21:25 +00001197 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1198 unsigned OpNum = 0;
1199 Value *LHS, *RHS;
1200 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1201 getValue(Record, OpNum, LHS->getType(), RHS) ||
1202 OpNum+1 != Record.size())
1203 return Error("Invalid BINOP record");
1204
1205 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1206 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001207 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001208 break;
1209 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001210 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1211 unsigned OpNum = 0;
1212 Value *Op;
1213 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1214 OpNum+2 != Record.size())
1215 return Error("Invalid CAST record");
1216
1217 const Type *ResTy = getTypeByID(Record[OpNum]);
1218 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1219 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001220 return Error("Invalid CAST record");
1221 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1222 break;
1223 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001224 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001225 unsigned OpNum = 0;
1226 Value *BasePtr;
1227 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001228 return Error("Invalid GEP record");
1229
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001230 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001231 while (OpNum != Record.size()) {
1232 Value *Op;
1233 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001234 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001235 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001236 }
1237
David Greeneb8f74792007-09-04 15:46:09 +00001238 I = new GetElementPtrInst(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001239 break;
1240 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001241
Chris Lattnerabfbf852007-05-06 00:21:25 +00001242 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1243 unsigned OpNum = 0;
1244 Value *TrueVal, *FalseVal, *Cond;
1245 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1246 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1247 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001248 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001249
1250 I = new SelectInst(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001251 break;
1252 }
1253
1254 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001255 unsigned OpNum = 0;
1256 Value *Vec, *Idx;
1257 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1258 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001259 return Error("Invalid EXTRACTELT record");
1260 I = new ExtractElementInst(Vec, Idx);
1261 break;
1262 }
1263
1264 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001265 unsigned OpNum = 0;
1266 Value *Vec, *Elt, *Idx;
1267 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1268 getValue(Record, OpNum,
1269 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1270 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001271 return Error("Invalid INSERTELT record");
1272 I = new InsertElementInst(Vec, Elt, Idx);
1273 break;
1274 }
1275
Chris Lattnerabfbf852007-05-06 00:21:25 +00001276 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1277 unsigned OpNum = 0;
1278 Value *Vec1, *Vec2, *Mask;
1279 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1280 getValue(Record, OpNum, Vec1->getType(), Vec2))
1281 return Error("Invalid SHUFFLEVEC record");
1282
1283 const Type *MaskTy =
1284 VectorType::get(Type::Int32Ty,
1285 cast<VectorType>(Vec1->getType())->getNumElements());
1286
1287 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001288 return Error("Invalid SHUFFLEVEC record");
1289 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1290 break;
1291 }
1292
1293 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001294 unsigned OpNum = 0;
1295 Value *LHS, *RHS;
1296 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1297 getValue(Record, OpNum, LHS->getType(), RHS) ||
1298 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001299 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001300
1301 if (LHS->getType()->isFPOrFPVector())
1302 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001303 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001304 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001305 break;
1306 }
1307
Chris Lattner231cbcb2007-05-02 04:27:25 +00001308 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1309 if (Record.size() == 0) {
1310 I = new ReturnInst();
1311 break;
Chris Lattner7337ab92007-05-06 00:00:00 +00001312 } else {
1313 unsigned OpNum = 0;
1314 Value *Op;
1315 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1316 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001317 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001318 I = new ReturnInst(Op);
1319 break;
1320 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001321 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001322 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001323 return Error("Invalid BR record");
1324 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1325 if (TrueDest == 0)
1326 return Error("Invalid BR record");
1327
1328 if (Record.size() == 1)
1329 I = new BranchInst(TrueDest);
1330 else {
1331 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1332 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1333 if (FalseDest == 0 || Cond == 0)
1334 return Error("Invalid BR record");
1335 I = new BranchInst(TrueDest, FalseDest, Cond);
1336 }
1337 break;
1338 }
1339 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1340 if (Record.size() < 3 || (Record.size() & 1) == 0)
1341 return Error("Invalid SWITCH record");
1342 const Type *OpTy = getTypeByID(Record[0]);
1343 Value *Cond = getFnValueByID(Record[1], OpTy);
1344 BasicBlock *Default = getBasicBlock(Record[2]);
1345 if (OpTy == 0 || Cond == 0 || Default == 0)
1346 return Error("Invalid SWITCH record");
1347 unsigned NumCases = (Record.size()-3)/2;
1348 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1349 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1350 ConstantInt *CaseVal =
1351 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1352 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1353 if (CaseVal == 0 || DestBB == 0) {
1354 delete SI;
1355 return Error("Invalid SWITCH record!");
1356 }
1357 SI->addCase(CaseVal, DestBB);
1358 }
1359 I = SI;
1360 break;
1361 }
1362
Duncan Sandsdc024672007-11-27 13:23:08 +00001363 case bitc::FUNC_CODE_INST_INVOKE: {
1364 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001365 if (Record.size() < 4) return Error("Invalid INVOKE record");
Duncan Sandsdc024672007-11-27 13:23:08 +00001366 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001367 unsigned CCInfo = Record[1];
1368 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1369 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001370
Chris Lattnera9bb7132007-05-08 05:38:01 +00001371 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001372 Value *Callee;
1373 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001374 return Error("Invalid INVOKE record");
1375
Chris Lattner7337ab92007-05-06 00:00:00 +00001376 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1377 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001378 dyn_cast<FunctionType>(CalleeTy->getElementType());
1379
1380 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001381 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1382 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001383 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001384
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001385 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001386 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1387 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1388 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001389 }
1390
Chris Lattner7337ab92007-05-06 00:00:00 +00001391 if (!FTy->isVarArg()) {
1392 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001393 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001394 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001395 // Read type/value pairs for varargs params.
1396 while (OpNum != Record.size()) {
1397 Value *Op;
1398 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1399 return Error("Invalid INVOKE record");
1400 Ops.push_back(Op);
1401 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001402 }
1403
David Greenef1355a52007-08-27 19:04:21 +00001404 I = new InvokeInst(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001405 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Duncan Sandsdc024672007-11-27 13:23:08 +00001406 cast<InvokeInst>(I)->setParamAttrs(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001407 break;
1408 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001409 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1410 I = new UnwindInst();
1411 break;
1412 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1413 I = new UnreachableInst();
1414 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001415 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001416 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001417 return Error("Invalid PHI record");
1418 const Type *Ty = getTypeByID(Record[0]);
1419 if (!Ty) return Error("Invalid PHI record");
1420
1421 PHINode *PN = new PHINode(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001422 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001423
Chris Lattner15e6d172007-05-04 19:11:41 +00001424 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1425 Value *V = getFnValueByID(Record[1+i], Ty);
1426 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001427 if (!V || !BB) return Error("Invalid PHI record");
1428 PN->addIncoming(V, BB);
1429 }
1430 I = PN;
1431 break;
1432 }
1433
1434 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1435 if (Record.size() < 3)
1436 return Error("Invalid MALLOC record");
1437 const PointerType *Ty =
1438 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1439 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1440 unsigned Align = Record[2];
1441 if (!Ty || !Size) return Error("Invalid MALLOC record");
1442 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1443 break;
1444 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001445 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1446 unsigned OpNum = 0;
1447 Value *Op;
1448 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1449 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001450 return Error("Invalid FREE record");
1451 I = new FreeInst(Op);
1452 break;
1453 }
1454 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1455 if (Record.size() < 3)
1456 return Error("Invalid ALLOCA record");
1457 const PointerType *Ty =
1458 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1459 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1460 unsigned Align = Record[2];
1461 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1462 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1463 break;
1464 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001465 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001466 unsigned OpNum = 0;
1467 Value *Op;
1468 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1469 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001470 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001471
1472 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001473 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001474 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001475 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1476 unsigned OpNum = 0;
1477 Value *Val, *Ptr;
1478 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1479 getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1480 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001481 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001482
1483 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001484 break;
1485 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001486 case bitc::FUNC_CODE_INST_CALL: {
1487 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1488 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001489 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001490
Duncan Sandsdc024672007-11-27 13:23:08 +00001491 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001492 unsigned CCInfo = Record[1];
1493
1494 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001495 Value *Callee;
1496 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1497 return Error("Invalid CALL record");
1498
1499 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001500 const FunctionType *FTy = 0;
1501 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001502 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001503 return Error("Invalid CALL record");
1504
1505 SmallVector<Value*, 16> Args;
1506 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001507 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001508 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1509 Args.push_back(getBasicBlock(Record[OpNum]));
1510 else
1511 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001512 if (Args.back() == 0) return Error("Invalid CALL record");
1513 }
1514
Chris Lattner0579f7f2007-05-03 22:04:19 +00001515 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001516 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001517 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001518 return Error("Invalid CALL record");
1519 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001520 while (OpNum != Record.size()) {
1521 Value *Op;
1522 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1523 return Error("Invalid CALL record");
1524 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001525 }
1526 }
1527
David Greene52eec542007-08-01 03:43:44 +00001528 I = new CallInst(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001529 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1530 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Duncan Sandsdc024672007-11-27 13:23:08 +00001531 cast<CallInst>(I)->setParamAttrs(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001532 break;
1533 }
1534 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1535 if (Record.size() < 3)
1536 return Error("Invalid VAARG record");
1537 const Type *OpTy = getTypeByID(Record[0]);
1538 Value *Op = getFnValueByID(Record[1], OpTy);
1539 const Type *ResTy = getTypeByID(Record[2]);
1540 if (!OpTy || !Op || !ResTy)
1541 return Error("Invalid VAARG record");
1542 I = new VAArgInst(Op, ResTy);
1543 break;
1544 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001545 }
1546
1547 // Add instruction to end of current BB. If there is no current BB, reject
1548 // this file.
1549 if (CurBB == 0) {
1550 delete I;
1551 return Error("Invalid instruction with no BB");
1552 }
1553 CurBB->getInstList().push_back(I);
1554
1555 // If this was a terminator instruction, move to the next block.
1556 if (isa<TerminatorInst>(I)) {
1557 ++CurBBNo;
1558 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1559 }
1560
1561 // Non-void values get registered in the value table for future use.
1562 if (I && I->getType() != Type::VoidTy)
1563 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001564 }
1565
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001566 // Check the function list for unresolved values.
1567 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1568 if (A->getParent() == 0) {
1569 // We found at least one unresolved value. Nuke them all to avoid leaks.
1570 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1571 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1572 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1573 delete A;
1574 }
1575 }
Chris Lattner35a04702007-05-04 03:50:29 +00001576 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001577 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001578 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001579
1580 // Trim the value list down to the size it was before we parsed this function.
1581 ValueList.shrinkTo(ModuleValueListSize);
1582 std::vector<BasicBlock*>().swap(FunctionBBs);
1583
Chris Lattner48f84872007-05-01 04:59:48 +00001584 return false;
1585}
1586
Chris Lattnerb348bb82007-05-18 04:02:46 +00001587//===----------------------------------------------------------------------===//
1588// ModuleProvider implementation
1589//===----------------------------------------------------------------------===//
1590
1591
1592bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1593 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001594 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001595
1596 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1597 DeferredFunctionInfo.find(F);
1598 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1599
1600 // Move the bit stream to the saved position of the deferred function body and
1601 // restore the real linkage type for the function.
1602 Stream.JumpToBit(DFII->second.first);
1603 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1604
1605 if (ParseFunctionBody(F)) {
1606 if (ErrInfo) *ErrInfo = ErrorString;
1607 return true;
1608 }
Chandler Carruth69940402007-08-04 01:51:18 +00001609
1610 // Upgrade any old intrinsic calls in the function.
1611 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1612 E = UpgradedIntrinsics.end(); I != E; ++I) {
1613 if (I->first != I->second) {
1614 for (Value::use_iterator UI = I->first->use_begin(),
1615 UE = I->first->use_end(); UI != UE; ) {
1616 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1617 UpgradeIntrinsicCall(CI, I->second);
1618 }
1619 }
1620 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001621
1622 return false;
1623}
1624
1625void BitcodeReader::dematerializeFunction(Function *F) {
1626 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001627 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001628 return;
1629
1630 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1631
1632 // Just forget the function body, we can remat it later.
1633 F->deleteBody();
1634 F->setLinkage(GlobalValue::GhostLinkage);
1635}
1636
1637
1638Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1639 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1640 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1641 ++I) {
1642 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001643 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001644 materializeFunction(F, ErrInfo))
1645 return 0;
1646 }
Chandler Carruth69940402007-08-04 01:51:18 +00001647
1648 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1649 // delete the old functions to clean up. We can't do this unless the entire
1650 // module is materialized because there could always be another function body
1651 // with calls to the old function.
1652 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1653 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1654 if (I->first != I->second) {
1655 for (Value::use_iterator UI = I->first->use_begin(),
1656 UE = I->first->use_end(); UI != UE; ) {
1657 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1658 UpgradeIntrinsicCall(CI, I->second);
1659 }
1660 ValueList.replaceUsesOfWith(I->first, I->second);
1661 I->first->eraseFromParent();
1662 }
1663 }
1664 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1665
Chris Lattnerb348bb82007-05-18 04:02:46 +00001666 return TheModule;
1667}
1668
1669
1670/// This method is provided by the parent ModuleProvde class and overriden
1671/// here. It simply releases the module from its provided and frees up our
1672/// state.
1673/// @brief Release our hold on the generated module
1674Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1675 // Since we're losing control of this Module, we must hand it back complete
1676 Module *M = ModuleProvider::releaseModule(ErrInfo);
1677 FreeState();
1678 return M;
1679}
1680
Chris Lattner48f84872007-05-01 04:59:48 +00001681
Chris Lattnerc453f762007-04-29 07:54:31 +00001682//===----------------------------------------------------------------------===//
1683// External interface
1684//===----------------------------------------------------------------------===//
1685
1686/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1687///
1688ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1689 std::string *ErrMsg) {
1690 BitcodeReader *R = new BitcodeReader(Buffer);
1691 if (R->ParseBitcode()) {
1692 if (ErrMsg)
1693 *ErrMsg = R->getErrorString();
1694
1695 // Don't let the BitcodeReader dtor delete 'Buffer'.
1696 R->releaseMemoryBuffer();
1697 delete R;
1698 return 0;
1699 }
1700 return R;
1701}
1702
1703/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1704/// If an error occurs, return null and fill in *ErrMsg if non-null.
1705Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1706 BitcodeReader *R;
1707 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1708 if (!R) return 0;
1709
Chris Lattnerb348bb82007-05-18 04:02:46 +00001710 // Read in the entire module.
1711 Module *M = R->materializeModule(ErrMsg);
1712
1713 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1714 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001715 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001716
1717 // If there was no error, tell ModuleProvider not to delete it when its dtor
1718 // is run.
1719 if (M)
1720 M = R->releaseModule(ErrMsg);
1721
Chris Lattnerc453f762007-04-29 07:54:31 +00001722 delete R;
1723 return M;
1724}