blob: 78cd1de20527a995ca175cf08e89dcec2ce455cf [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnercaee0dc2007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Chris Lattnera7c49aa2007-05-01 07:01:57 +000019#include "llvm/Instructions.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Chandler Carruth69940402007-08-04 01:51:18 +000021#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000022#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000023#include "llvm/ADT/SmallVector.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000025#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000026#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000027using namespace llvm;
28
Chris Lattnerb348bb82007-05-18 04:02:46 +000029void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000030 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000031 Buffer = 0;
32 std::vector<PATypeHolder>().swap(TypeList);
33 ValueList.clear();
Chris Lattner461edd92008-03-12 02:25:52 +000034
Chris Lattner58d74912008-03-12 17:45:29 +000035 std::vector<PAListPtr>().swap(ParamAttrs);
Chris Lattnerb348bb82007-05-18 04:02:46 +000036 std::vector<BasicBlock*>().swap(FunctionBBs);
37 std::vector<Function*>().swap(FunctionsWithBodies);
38 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000039}
40
Chris Lattner48c85b82007-05-04 03:30:17 +000041//===----------------------------------------------------------------------===//
42// Helper functions to implement forward reference resolution, etc.
43//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000044
Chris Lattnercaee0dc2007-04-22 06:23:29 +000045/// ConvertToString - Convert a string from a record into an std::string, return
46/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000047template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000048static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000049 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000050 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000051 return true;
52
Chris Lattner15e6d172007-05-04 19:11:41 +000053 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
54 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000055 return false;
56}
57
58static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
59 switch (Val) {
60 default: // Map unknown/new linkages to external
61 case 0: return GlobalValue::ExternalLinkage;
62 case 1: return GlobalValue::WeakLinkage;
63 case 2: return GlobalValue::AppendingLinkage;
64 case 3: return GlobalValue::InternalLinkage;
65 case 4: return GlobalValue::LinkOnceLinkage;
66 case 5: return GlobalValue::DLLImportLinkage;
67 case 6: return GlobalValue::DLLExportLinkage;
68 case 7: return GlobalValue::ExternalWeakLinkage;
69 }
70}
71
72static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
73 switch (Val) {
74 default: // Map unknown visibilities to default.
75 case 0: return GlobalValue::DefaultVisibility;
76 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000077 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000078 }
79}
80
Chris Lattnerf581c3b2007-04-24 07:07:11 +000081static int GetDecodedCastOpcode(unsigned Val) {
82 switch (Val) {
83 default: return -1;
84 case bitc::CAST_TRUNC : return Instruction::Trunc;
85 case bitc::CAST_ZEXT : return Instruction::ZExt;
86 case bitc::CAST_SEXT : return Instruction::SExt;
87 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
88 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
89 case bitc::CAST_UITOFP : return Instruction::UIToFP;
90 case bitc::CAST_SITOFP : return Instruction::SIToFP;
91 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
92 case bitc::CAST_FPEXT : return Instruction::FPExt;
93 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
94 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
95 case bitc::CAST_BITCAST : return Instruction::BitCast;
96 }
97}
98static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
99 switch (Val) {
100 default: return -1;
101 case bitc::BINOP_ADD: return Instruction::Add;
102 case bitc::BINOP_SUB: return Instruction::Sub;
103 case bitc::BINOP_MUL: return Instruction::Mul;
104 case bitc::BINOP_UDIV: return Instruction::UDiv;
105 case bitc::BINOP_SDIV:
106 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
107 case bitc::BINOP_UREM: return Instruction::URem;
108 case bitc::BINOP_SREM:
109 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
110 case bitc::BINOP_SHL: return Instruction::Shl;
111 case bitc::BINOP_LSHR: return Instruction::LShr;
112 case bitc::BINOP_ASHR: return Instruction::AShr;
113 case bitc::BINOP_AND: return Instruction::And;
114 case bitc::BINOP_OR: return Instruction::Or;
115 case bitc::BINOP_XOR: return Instruction::Xor;
116 }
117}
118
Gabor Greifefe65362008-05-10 08:32:32 +0000119namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000120namespace {
121 /// @brief A class for maintaining the slot number definition
122 /// as a placeholder for the actual definition for forward constants defs.
123 class ConstantPlaceHolder : public ConstantExpr {
124 ConstantPlaceHolder(); // DO NOT IMPLEMENT
125 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000126 public:
127 // allocate space for exactly one operand
128 void *operator new(size_t s) {
129 return User::operator new(s, 1);
130 }
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000131 explicit ConstantPlaceHolder(const Type *Ty)
Gabor Greifefe65362008-05-10 08:32:32 +0000132 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
133 Op<0>() = UndefValue::get(Type::Int32Ty);
Chris Lattner522b7b12007-04-24 05:48:56 +0000134 }
Gabor Greifefe65362008-05-10 08:32:32 +0000135 /// Provide fast operand accessors
136 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000137 };
138}
139
Gabor Greifefe65362008-05-10 08:32:32 +0000140
141 // FIXME: can we inherit this from ConstantExpr?
142template <>
143struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
144};
145
146DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
147}
148
149void BitcodeReaderValueList::resize(unsigned Desired) {
150 if (Desired > Capacity) {
151 // Since we expect many values to come from the bitcode file we better
152 // allocate the double amount, so that the array size grows exponentially
153 // at each reallocation. Also, add a small amount of 100 extra elements
154 // each time, to reallocate less frequently when the array is still small.
155 //
156 Capacity = Desired * 2 + 100;
157 Use *New = allocHungoffUses(Capacity);
158 Use *Old = OperandList;
159 unsigned Ops = getNumOperands();
160 for (int i(Ops - 1); i >= 0; --i)
161 New[i] = Old[i].get();
162 OperandList = New;
163 if (Old) Use::zap(Old, Old + Ops, true);
164 }
165}
166
Chris Lattner522b7b12007-04-24 05:48:56 +0000167Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
168 const Type *Ty) {
169 if (Idx >= size()) {
170 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000171 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000172 NumOperands = Idx+1;
173 }
174
Gabor Greifefe65362008-05-10 08:32:32 +0000175 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000176 assert(Ty == V->getType() && "Type mismatch in constant table!");
177 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000178 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000179
180 // Create and return a placeholder, which will later be RAUW'd.
181 Constant *C = new ConstantPlaceHolder(Ty);
Gabor Greifefe65362008-05-10 08:32:32 +0000182 OperandList[Idx].init(C, this);
Chris Lattner522b7b12007-04-24 05:48:56 +0000183 return C;
184}
185
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000186Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
187 if (Idx >= size()) {
188 // Insert a bunch of null values.
Gabor Greifefe65362008-05-10 08:32:32 +0000189 resize(Idx + 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000190 NumOperands = Idx+1;
191 }
192
Gabor Greifefe65362008-05-10 08:32:32 +0000193 if (Value *V = OperandList[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000194 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
195 return V;
196 }
197
Chris Lattner01ff65f2007-05-02 05:16:49 +0000198 // No type specified, must be invalid reference.
199 if (Ty == 0) return 0;
200
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000201 // Create and return a placeholder, which will later be RAUW'd.
202 Value *V = new Argument(Ty);
Gabor Greifefe65362008-05-10 08:32:32 +0000203 OperandList[Idx].init(V, this);
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000204 return V;
205}
206
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000207
208const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
209 // If the TypeID is in range, return it.
210 if (ID < TypeList.size())
211 return TypeList[ID].get();
212 if (!isTypeTable) return 0;
213
214 // The type table allows forward references. Push as many Opaque types as
215 // needed to get up to ID.
216 while (TypeList.size() <= ID)
217 TypeList.push_back(OpaqueType::get());
218 return TypeList.back().get();
219}
220
Chris Lattner48c85b82007-05-04 03:30:17 +0000221//===----------------------------------------------------------------------===//
222// Functions for parsing blocks from the bitcode file
223//===----------------------------------------------------------------------===//
224
225bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000226 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000227 return Error("Malformed block record");
228
229 if (!ParamAttrs.empty())
230 return Error("Multiple PARAMATTR blocks found!");
231
232 SmallVector<uint64_t, 64> Record;
233
Chris Lattner58d74912008-03-12 17:45:29 +0000234 SmallVector<ParamAttrsWithIndex, 8> Attrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000235
236 // Read all the records.
237 while (1) {
238 unsigned Code = Stream.ReadCode();
239 if (Code == bitc::END_BLOCK) {
240 if (Stream.ReadBlockEnd())
241 return Error("Error at end of PARAMATTR block");
242 return false;
243 }
244
245 if (Code == bitc::ENTER_SUBBLOCK) {
246 // No known subblocks, always skip them.
247 Stream.ReadSubBlockID();
248 if (Stream.SkipBlock())
249 return Error("Malformed block record");
250 continue;
251 }
252
253 if (Code == bitc::DEFINE_ABBREV) {
254 Stream.ReadAbbrevRecord();
255 continue;
256 }
257
258 // Read a record.
259 Record.clear();
260 switch (Stream.ReadRecord(Code, Record)) {
261 default: // Default behavior: ignore.
262 break;
263 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
264 if (Record.size() & 1)
265 return Error("Invalid ENTRY record");
266
Chris Lattner48c85b82007-05-04 03:30:17 +0000267 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Duncan Sands5e41f652007-11-20 14:09:29 +0000268 if (Record[i+1] != ParamAttr::None)
269 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
Chris Lattner48c85b82007-05-04 03:30:17 +0000270 }
Chris Lattner461edd92008-03-12 02:25:52 +0000271
Chris Lattner58d74912008-03-12 17:45:29 +0000272 ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000273 Attrs.clear();
274 break;
275 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000276 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000277 }
278}
279
280
Chris Lattner86697142007-05-01 05:01:34 +0000281bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000282 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000283 return Error("Malformed block record");
284
285 if (!TypeList.empty())
286 return Error("Multiple TYPE_BLOCKs found!");
287
288 SmallVector<uint64_t, 64> Record;
289 unsigned NumRecords = 0;
290
291 // Read all the records for this type table.
292 while (1) {
293 unsigned Code = Stream.ReadCode();
294 if (Code == bitc::END_BLOCK) {
295 if (NumRecords != TypeList.size())
296 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000297 if (Stream.ReadBlockEnd())
298 return Error("Error at end of type table block");
299 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000300 }
301
302 if (Code == bitc::ENTER_SUBBLOCK) {
303 // No known subblocks, always skip them.
304 Stream.ReadSubBlockID();
305 if (Stream.SkipBlock())
306 return Error("Malformed block record");
307 continue;
308 }
309
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000310 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000311 Stream.ReadAbbrevRecord();
312 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000313 }
314
315 // Read a record.
316 Record.clear();
317 const Type *ResultTy = 0;
318 switch (Stream.ReadRecord(Code, Record)) {
319 default: // Default behavior: unknown type.
320 ResultTy = 0;
321 break;
322 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
323 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
324 // type list. This allows us to reserve space.
325 if (Record.size() < 1)
326 return Error("Invalid TYPE_CODE_NUMENTRY record");
327 TypeList.reserve(Record[0]);
328 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000329 case bitc::TYPE_CODE_VOID: // VOID
330 ResultTy = Type::VoidTy;
331 break;
332 case bitc::TYPE_CODE_FLOAT: // FLOAT
333 ResultTy = Type::FloatTy;
334 break;
335 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
336 ResultTy = Type::DoubleTy;
337 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000338 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
339 ResultTy = Type::X86_FP80Ty;
340 break;
341 case bitc::TYPE_CODE_FP128: // FP128
342 ResultTy = Type::FP128Ty;
343 break;
344 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
345 ResultTy = Type::PPC_FP128Ty;
346 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000347 case bitc::TYPE_CODE_LABEL: // LABEL
348 ResultTy = Type::LabelTy;
349 break;
350 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
351 ResultTy = 0;
352 break;
353 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
354 if (Record.size() < 1)
355 return Error("Invalid Integer type record");
356
357 ResultTy = IntegerType::get(Record[0]);
358 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000359 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
360 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000361 if (Record.size() < 1)
362 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000363 unsigned AddressSpace = 0;
364 if (Record.size() == 2)
365 AddressSpace = Record[1];
366 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000367 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000368 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000369 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000370 // FIXME: attrid is dead, remove it in LLVM 3.0
371 // FUNCTION: [vararg, attrid, retty, paramty x N]
372 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000373 return Error("Invalid FUNCTION type record");
374 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000375 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000376 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000377
Chris Lattnera1afde72007-11-27 17:48:06 +0000378 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000379 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000380 break;
381 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000382 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000383 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000384 return Error("Invalid STRUCT type record");
385 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000386 for (unsigned i = 1, e = Record.size(); i != e; ++i)
387 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000388 ResultTy = StructType::get(EltTys, Record[0]);
389 break;
390 }
391 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
392 if (Record.size() < 2)
393 return Error("Invalid ARRAY type record");
394 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
395 break;
396 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
397 if (Record.size() < 2)
398 return Error("Invalid VECTOR type record");
399 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
400 break;
401 }
402
403 if (NumRecords == TypeList.size()) {
404 // If this is a new type slot, just append it.
405 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
406 ++NumRecords;
407 } else if (ResultTy == 0) {
408 // Otherwise, this was forward referenced, so an opaque type was created,
409 // but the result type is actually just an opaque. Leave the one we
410 // created previously.
411 ++NumRecords;
412 } else {
413 // Otherwise, this was forward referenced, so an opaque type was created.
414 // Resolve the opaque type to the real type now.
415 assert(NumRecords < TypeList.size() && "Typelist imbalance");
416 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
417
418 // Don't directly push the new type on the Tab. Instead we want to replace
419 // the opaque type we previously inserted with the new concrete value. The
420 // refinement from the abstract (opaque) type to the new type causes all
421 // uses of the abstract type to use the concrete type (NewTy). This will
422 // also cause the opaque type to be deleted.
423 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
424
425 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000426 // value table... or with a preexisting type that was already in the
427 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000428 assert(TypeList[NumRecords-1].get() != OldTy &&
429 "refineAbstractType didn't work!");
430 }
431 }
432}
433
434
Chris Lattner86697142007-05-01 05:01:34 +0000435bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000436 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000437 return Error("Malformed block record");
438
439 SmallVector<uint64_t, 64> Record;
440
441 // Read all the records for this type table.
442 std::string TypeName;
443 while (1) {
444 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000445 if (Code == bitc::END_BLOCK) {
446 if (Stream.ReadBlockEnd())
447 return Error("Error at end of type symbol table block");
448 return false;
449 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000450
451 if (Code == bitc::ENTER_SUBBLOCK) {
452 // No known subblocks, always skip them.
453 Stream.ReadSubBlockID();
454 if (Stream.SkipBlock())
455 return Error("Malformed block record");
456 continue;
457 }
458
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000459 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000460 Stream.ReadAbbrevRecord();
461 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000462 }
463
464 // Read a record.
465 Record.clear();
466 switch (Stream.ReadRecord(Code, Record)) {
467 default: // Default behavior: unknown type.
468 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000469 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000470 if (ConvertToString(Record, 1, TypeName))
471 return Error("Invalid TST_ENTRY record");
472 unsigned TypeID = Record[0];
473 if (TypeID >= TypeList.size())
474 return Error("Invalid Type ID in TST_ENTRY record");
475
476 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
477 TypeName.clear();
478 break;
479 }
480 }
481}
482
Chris Lattner86697142007-05-01 05:01:34 +0000483bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000484 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000485 return Error("Malformed block record");
486
487 SmallVector<uint64_t, 64> Record;
488
489 // Read all the records for this value table.
490 SmallString<128> ValueName;
491 while (1) {
492 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000493 if (Code == bitc::END_BLOCK) {
494 if (Stream.ReadBlockEnd())
495 return Error("Error at end of value symbol table block");
496 return false;
497 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000498 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 switch (Stream.ReadRecord(Code, Record)) {
514 default: // Default behavior: unknown type.
515 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000516 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000517 if (ConvertToString(Record, 1, ValueName))
518 return Error("Invalid TST_ENTRY record");
519 unsigned ValueID = Record[0];
520 if (ValueID >= ValueList.size())
521 return Error("Invalid Value ID in VST_ENTRY record");
522 Value *V = ValueList[ValueID];
523
524 V->setName(&ValueName[0], ValueName.size());
525 ValueName.clear();
526 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000527 }
528 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000529 if (ConvertToString(Record, 1, ValueName))
530 return Error("Invalid VST_BBENTRY record");
531 BasicBlock *BB = getBasicBlock(Record[0]);
532 if (BB == 0)
533 return Error("Invalid BB ID in VST_BBENTRY record");
534
535 BB->setName(&ValueName[0], ValueName.size());
536 ValueName.clear();
537 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000538 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000539 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000540 }
541}
542
Chris Lattner0eef0802007-04-24 04:04:35 +0000543/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
544/// the LSB for dense VBR encoding.
545static uint64_t DecodeSignRotatedValue(uint64_t V) {
546 if ((V & 1) == 0)
547 return V >> 1;
548 if (V != 1)
549 return -(V >> 1);
550 // There is no such thing as -0 with integers. "-0" really means MININT.
551 return 1ULL << 63;
552}
553
Chris Lattner07d98b42007-04-26 02:46:40 +0000554/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
555/// values and aliases that we can.
556bool BitcodeReader::ResolveGlobalAndAliasInits() {
557 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
558 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
559
560 GlobalInitWorklist.swap(GlobalInits);
561 AliasInitWorklist.swap(AliasInits);
562
563 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000564 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000565 if (ValID >= ValueList.size()) {
566 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000567 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000568 } else {
569 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
570 GlobalInitWorklist.back().first->setInitializer(C);
571 else
572 return Error("Global variable initializer is not a constant!");
573 }
574 GlobalInitWorklist.pop_back();
575 }
576
577 while (!AliasInitWorklist.empty()) {
578 unsigned ValID = AliasInitWorklist.back().second;
579 if (ValID >= ValueList.size()) {
580 AliasInits.push_back(AliasInitWorklist.back());
581 } else {
582 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000583 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000584 else
585 return Error("Alias initializer is not a constant!");
586 }
587 AliasInitWorklist.pop_back();
588 }
589 return false;
590}
591
592
Chris Lattner86697142007-05-01 05:01:34 +0000593bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000594 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000595 return Error("Malformed block record");
596
597 SmallVector<uint64_t, 64> Record;
598
599 // Read all the records for this value table.
600 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000601 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000602 while (1) {
603 unsigned Code = Stream.ReadCode();
604 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000605 if (NextCstNo != ValueList.size())
606 return Error("Invalid constant reference!");
607
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000608 if (Stream.ReadBlockEnd())
609 return Error("Error at end of constants block");
610 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000611 }
612
613 if (Code == bitc::ENTER_SUBBLOCK) {
614 // No known subblocks, always skip them.
615 Stream.ReadSubBlockID();
616 if (Stream.SkipBlock())
617 return Error("Malformed block record");
618 continue;
619 }
620
621 if (Code == bitc::DEFINE_ABBREV) {
622 Stream.ReadAbbrevRecord();
623 continue;
624 }
625
626 // Read a record.
627 Record.clear();
628 Value *V = 0;
629 switch (Stream.ReadRecord(Code, Record)) {
630 default: // Default behavior: unknown constant
631 case bitc::CST_CODE_UNDEF: // UNDEF
632 V = UndefValue::get(CurTy);
633 break;
634 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
635 if (Record.empty())
636 return Error("Malformed CST_SETTYPE record");
637 if (Record[0] >= TypeList.size())
638 return Error("Invalid Type ID in CST_SETTYPE record");
639 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000640 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000641 case bitc::CST_CODE_NULL: // NULL
642 V = Constant::getNullValue(CurTy);
643 break;
644 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000645 if (!isa<IntegerType>(CurTy) || Record.empty())
646 return Error("Invalid CST_INTEGER record");
647 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
648 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000649 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
650 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000651 return Error("Invalid WIDE_INTEGER record");
652
Chris Lattner15e6d172007-05-04 19:11:41 +0000653 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000654 SmallVector<uint64_t, 8> Words;
655 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000656 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000657 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000658 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000659 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000660 break;
661 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000662 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000663 if (Record.empty())
664 return Error("Invalid FLOAT record");
665 if (CurTy == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000666 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000667 else if (CurTy == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000668 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000669 else if (CurTy == Type::X86_FP80Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000670 V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000671 else if (CurTy == Type::FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000672 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000673 else if (CurTy == Type::PPC_FP128Ty)
Chris Lattner02a260a2008-04-20 00:41:09 +0000674 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000675 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000676 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000677 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000678 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000679
Chris Lattner15e6d172007-05-04 19:11:41 +0000680 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
681 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000682 return Error("Invalid CST_AGGREGATE record");
683
Chris Lattner15e6d172007-05-04 19:11:41 +0000684 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000685 std::vector<Constant*> Elts;
686
687 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
688 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000689 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000690 STy->getElementType(i)));
691 V = ConstantStruct::get(STy, Elts);
692 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
693 const Type *EltTy = ATy->getElementType();
694 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000695 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000696 V = ConstantArray::get(ATy, Elts);
697 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
698 const Type *EltTy = VTy->getElementType();
699 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000700 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000701 V = ConstantVector::get(Elts);
702 } else {
703 V = UndefValue::get(CurTy);
704 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000705 break;
706 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000707 case bitc::CST_CODE_STRING: { // STRING: [values]
708 if (Record.empty())
709 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000710
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000711 const ArrayType *ATy = cast<ArrayType>(CurTy);
712 const Type *EltTy = ATy->getElementType();
713
714 unsigned Size = Record.size();
715 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000716 for (unsigned i = 0; i != Size; ++i)
717 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
718 V = ConstantArray::get(ATy, Elts);
719 break;
720 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000721 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
722 if (Record.empty())
723 return Error("Invalid CST_AGGREGATE record");
724
725 const ArrayType *ATy = cast<ArrayType>(CurTy);
726 const Type *EltTy = ATy->getElementType();
727
728 unsigned Size = Record.size();
729 std::vector<Constant*> Elts;
730 for (unsigned i = 0; i != Size; ++i)
731 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
732 Elts.push_back(Constant::getNullValue(EltTy));
733 V = ConstantArray::get(ATy, Elts);
734 break;
735 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000736 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
737 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
738 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000739 if (Opc < 0) {
740 V = UndefValue::get(CurTy); // Unknown binop.
741 } else {
742 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
743 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
744 V = ConstantExpr::get(Opc, LHS, RHS);
745 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000746 break;
747 }
748 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
749 if (Record.size() < 3) return Error("Invalid CE_CAST record");
750 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000751 if (Opc < 0) {
752 V = UndefValue::get(CurTy); // Unknown cast.
753 } else {
754 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000755 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000756 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
757 V = ConstantExpr::getCast(Opc, Op, CurTy);
758 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000759 break;
760 }
761 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000762 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000763 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000764 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000765 const Type *ElTy = getTypeByID(Record[i]);
766 if (!ElTy) return Error("Invalid CE_GEP record");
767 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
768 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000769 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
770 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000771 }
772 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
773 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
774 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
775 Type::Int1Ty),
776 ValueList.getConstantFwdRef(Record[1],CurTy),
777 ValueList.getConstantFwdRef(Record[2],CurTy));
778 break;
779 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
780 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
781 const VectorType *OpTy =
782 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
783 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
784 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
785 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
786 OpTy->getElementType());
787 V = ConstantExpr::getExtractElement(Op0, Op1);
788 break;
789 }
790 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
791 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
792 if (Record.size() < 3 || OpTy == 0)
793 return Error("Invalid CE_INSERTELT record");
794 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
795 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
796 OpTy->getElementType());
797 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
798 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
799 break;
800 }
801 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
802 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
803 if (Record.size() < 3 || OpTy == 0)
804 return Error("Invalid CE_INSERTELT record");
805 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
806 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
807 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
808 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
809 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
810 break;
811 }
812 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
813 if (Record.size() < 4) return Error("Invalid CE_CMP record");
814 const Type *OpTy = getTypeByID(Record[0]);
815 if (OpTy == 0) return Error("Invalid CE_CMP record");
816 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
817 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
818
819 if (OpTy->isFloatingPoint())
820 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
821 else
822 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
823 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000824 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000825 case bitc::CST_CODE_INLINEASM: {
826 if (Record.size() < 2) return Error("Invalid INLINEASM record");
827 std::string AsmStr, ConstrStr;
828 bool HasSideEffects = Record[0];
829 unsigned AsmStrSize = Record[1];
830 if (2+AsmStrSize >= Record.size())
831 return Error("Invalid INLINEASM record");
832 unsigned ConstStrSize = Record[2+AsmStrSize];
833 if (3+AsmStrSize+ConstStrSize > Record.size())
834 return Error("Invalid INLINEASM record");
835
836 for (unsigned i = 0; i != AsmStrSize; ++i)
837 AsmStr += (char)Record[2+i];
838 for (unsigned i = 0; i != ConstStrSize; ++i)
839 ConstrStr += (char)Record[3+AsmStrSize+i];
840 const PointerType *PTy = cast<PointerType>(CurTy);
841 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
842 AsmStr, ConstrStr, HasSideEffects);
843 break;
844 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000845 }
846
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000847 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000848 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000849 }
850}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000851
Chris Lattner980e5aa2007-05-01 05:52:21 +0000852/// RememberAndSkipFunctionBody - When we see the block for a function body,
853/// remember where it is and then skip it. This lets us lazily deserialize the
854/// functions.
855bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000856 // Get the function we are talking about.
857 if (FunctionsWithBodies.empty())
858 return Error("Insufficient function protos");
859
860 Function *Fn = FunctionsWithBodies.back();
861 FunctionsWithBodies.pop_back();
862
863 // Save the current stream state.
864 uint64_t CurBit = Stream.GetCurrentBitNo();
865 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
866
867 // Set the functions linkage to GhostLinkage so we know it is lazily
868 // deserialized.
869 Fn->setLinkage(GlobalValue::GhostLinkage);
870
871 // Skip over the function block for now.
872 if (Stream.SkipBlock())
873 return Error("Malformed block record");
874 return false;
875}
876
Chris Lattner86697142007-05-01 05:01:34 +0000877bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000878 // Reject multiple MODULE_BLOCK's in a single bitstream.
879 if (TheModule)
880 return Error("Multiple MODULE_BLOCKs in same stream");
881
Chris Lattnere17b6582007-05-05 00:17:00 +0000882 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000883 return Error("Malformed block record");
884
885 // Otherwise, create the module.
886 TheModule = new Module(ModuleID);
887
888 SmallVector<uint64_t, 64> Record;
889 std::vector<std::string> SectionTable;
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000890 std::vector<std::string> CollectorTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000891
892 // Read all the records for this module.
893 while (!Stream.AtEndOfStream()) {
894 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000895 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000896 if (Stream.ReadBlockEnd())
897 return Error("Error at end of module block");
898
899 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000900 ResolveGlobalAndAliasInits();
901 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000902 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000903 if (!FunctionsWithBodies.empty())
904 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000905
Chandler Carruth69940402007-08-04 01:51:18 +0000906 // Look for intrinsic functions which need to be upgraded at some point
907 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
908 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +0000909 Function* NewFn;
910 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +0000911 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
912 }
913
Chris Lattner980e5aa2007-05-01 05:52:21 +0000914 // Force deallocation of memory for these vectors to favor the client that
915 // want lazy deserialization.
916 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
917 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
918 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000919 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000920 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000921
922 if (Code == bitc::ENTER_SUBBLOCK) {
923 switch (Stream.ReadSubBlockID()) {
924 default: // Skip unknown content.
925 if (Stream.SkipBlock())
926 return Error("Malformed block record");
927 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000928 case bitc::BLOCKINFO_BLOCK_ID:
929 if (Stream.ReadBlockInfoBlock())
930 return Error("Malformed BlockInfoBlock");
931 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000932 case bitc::PARAMATTR_BLOCK_ID:
933 if (ParseParamAttrBlock())
934 return true;
935 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000936 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000937 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000938 return true;
939 break;
940 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000941 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000942 return true;
943 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000944 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000945 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000946 return true;
947 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000948 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000949 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000950 return true;
951 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000952 case bitc::FUNCTION_BLOCK_ID:
953 // If this is the first function body we've seen, reverse the
954 // FunctionsWithBodies list.
955 if (!HasReversedFunctionsWithBodies) {
956 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
957 HasReversedFunctionsWithBodies = true;
958 }
959
Chris Lattner980e5aa2007-05-01 05:52:21 +0000960 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000961 return true;
962 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000963 }
964 continue;
965 }
966
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000967 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000968 Stream.ReadAbbrevRecord();
969 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000970 }
971
972 // Read a record.
973 switch (Stream.ReadRecord(Code, Record)) {
974 default: break; // Default behavior, ignore unknown content.
975 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
976 if (Record.size() < 1)
977 return Error("Malformed MODULE_CODE_VERSION");
978 // Only version #0 is supported so far.
979 if (Record[0] != 0)
980 return Error("Unknown bitstream version!");
981 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000982 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000983 std::string S;
984 if (ConvertToString(Record, 0, S))
985 return Error("Invalid MODULE_CODE_TRIPLE record");
986 TheModule->setTargetTriple(S);
987 break;
988 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000989 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000990 std::string S;
991 if (ConvertToString(Record, 0, S))
992 return Error("Invalid MODULE_CODE_DATALAYOUT record");
993 TheModule->setDataLayout(S);
994 break;
995 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000996 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000997 std::string S;
998 if (ConvertToString(Record, 0, S))
999 return Error("Invalid MODULE_CODE_ASM record");
1000 TheModule->setModuleInlineAsm(S);
1001 break;
1002 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001003 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001004 std::string S;
1005 if (ConvertToString(Record, 0, S))
1006 return Error("Invalid MODULE_CODE_DEPLIB record");
1007 TheModule->addLibrary(S);
1008 break;
1009 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001010 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001011 std::string S;
1012 if (ConvertToString(Record, 0, S))
1013 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1014 SectionTable.push_back(S);
1015 break;
1016 }
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001017 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
1018 std::string S;
1019 if (ConvertToString(Record, 0, S))
1020 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
1021 CollectorTable.push_back(S);
1022 break;
1023 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001024 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001025 // linkage, alignment, section, visibility, threadlocal]
1026 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001027 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001028 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1029 const Type *Ty = getTypeByID(Record[0]);
1030 if (!isa<PointerType>(Ty))
1031 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001032 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001033 Ty = cast<PointerType>(Ty)->getElementType();
1034
1035 bool isConstant = Record[1];
1036 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1037 unsigned Alignment = (1 << Record[4]) >> 1;
1038 std::string Section;
1039 if (Record[5]) {
1040 if (Record[5]-1 >= SectionTable.size())
1041 return Error("Invalid section ID");
1042 Section = SectionTable[Record[5]-1];
1043 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001044 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001045 if (Record.size() > 6)
1046 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001047 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001048 if (Record.size() > 7)
1049 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001050
1051 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001052 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1053 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001054 NewGV->setAlignment(Alignment);
1055 if (!Section.empty())
1056 NewGV->setSection(Section);
1057 NewGV->setVisibility(Visibility);
1058 NewGV->setThreadLocal(isThreadLocal);
1059
Chris Lattner0b2482a2007-04-23 21:26:05 +00001060 ValueList.push_back(NewGV);
1061
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001062 // Remember which value to use for the global initializer.
1063 if (unsigned InitID = Record[2])
1064 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001065 break;
1066 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001067 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001068 // alignment, section, visibility, collector]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001069 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001070 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001071 return Error("Invalid MODULE_CODE_FUNCTION record");
1072 const Type *Ty = getTypeByID(Record[0]);
1073 if (!isa<PointerType>(Ty))
1074 return Error("Function not a pointer type!");
1075 const FunctionType *FTy =
1076 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1077 if (!FTy)
1078 return Error("Function not a pointer to function type!");
1079
Gabor Greif051a9502008-04-06 20:25:17 +00001080 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1081 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001082
1083 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001084 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001085 Func->setLinkage(GetDecodedLinkage(Record[3]));
Chris Lattner58d74912008-03-12 17:45:29 +00001086 Func->setParamAttrs(getParamAttrs(Record[4]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001087
1088 Func->setAlignment((1 << Record[5]) >> 1);
1089 if (Record[6]) {
1090 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001091 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001092 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001093 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001094 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001095 if (Record.size() > 8 && Record[8]) {
1096 if (Record[8]-1 > CollectorTable.size())
1097 return Error("Invalid collector ID");
1098 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1099 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001100
Chris Lattner0b2482a2007-04-23 21:26:05 +00001101 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001102
1103 // If this is a function with a body, remember the prototype we are
1104 // creating now, so that we can match up the body with them later.
1105 if (!isProto)
1106 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001107 break;
1108 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001109 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001110 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001111 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001112 if (Record.size() < 3)
1113 return Error("Invalid MODULE_ALIAS record");
1114 const Type *Ty = getTypeByID(Record[0]);
1115 if (!isa<PointerType>(Ty))
1116 return Error("Function not a pointer type!");
1117
1118 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1119 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001120 // Old bitcode files didn't have visibility field.
1121 if (Record.size() > 3)
1122 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001123 ValueList.push_back(NewGA);
1124 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1125 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001126 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001127 /// MODULE_CODE_PURGEVALS: [numvals]
1128 case bitc::MODULE_CODE_PURGEVALS:
1129 // Trim down the value list to the specified size.
1130 if (Record.size() < 1 || Record[0] > ValueList.size())
1131 return Error("Invalid MODULE_PURGEVALS record");
1132 ValueList.shrinkTo(Record[0]);
1133 break;
1134 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001135 Record.clear();
1136 }
1137
1138 return Error("Premature end of bitstream");
1139}
1140
1141
Chris Lattnerc453f762007-04-29 07:54:31 +00001142bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001143 TheModule = 0;
1144
Chris Lattnerc453f762007-04-29 07:54:31 +00001145 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001146 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1147
Chris Lattnerc453f762007-04-29 07:54:31 +00001148 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001149 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001150
1151 // Sniff for the signature.
1152 if (Stream.Read(8) != 'B' ||
1153 Stream.Read(8) != 'C' ||
1154 Stream.Read(4) != 0x0 ||
1155 Stream.Read(4) != 0xC ||
1156 Stream.Read(4) != 0xE ||
1157 Stream.Read(4) != 0xD)
1158 return Error("Invalid bitcode signature");
1159
1160 // We expect a number of well-defined blocks, though we don't necessarily
1161 // need to understand them all.
1162 while (!Stream.AtEndOfStream()) {
1163 unsigned Code = Stream.ReadCode();
1164
1165 if (Code != bitc::ENTER_SUBBLOCK)
1166 return Error("Invalid record at top-level");
1167
1168 unsigned BlockID = Stream.ReadSubBlockID();
1169
1170 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001171 switch (BlockID) {
1172 case bitc::BLOCKINFO_BLOCK_ID:
1173 if (Stream.ReadBlockInfoBlock())
1174 return Error("Malformed BlockInfoBlock");
1175 break;
1176 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001177 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001178 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001179 break;
1180 default:
1181 if (Stream.SkipBlock())
1182 return Error("Malformed block record");
1183 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001184 }
1185 }
1186
1187 return false;
1188}
Chris Lattnerc453f762007-04-29 07:54:31 +00001189
Chris Lattner48f84872007-05-01 04:59:48 +00001190
Chris Lattner980e5aa2007-05-01 05:52:21 +00001191/// ParseFunctionBody - Lazily parse the specified function body block.
1192bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001193 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001194 return Error("Malformed block record");
1195
1196 unsigned ModuleValueListSize = ValueList.size();
1197
1198 // Add all the function arguments to the value table.
1199 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1200 ValueList.push_back(I);
1201
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001202 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001203 BasicBlock *CurBB = 0;
1204 unsigned CurBBNo = 0;
1205
Chris Lattner980e5aa2007-05-01 05:52:21 +00001206 // Read all the records.
1207 SmallVector<uint64_t, 64> Record;
1208 while (1) {
1209 unsigned Code = Stream.ReadCode();
1210 if (Code == bitc::END_BLOCK) {
1211 if (Stream.ReadBlockEnd())
1212 return Error("Error at end of function block");
1213 break;
1214 }
1215
1216 if (Code == bitc::ENTER_SUBBLOCK) {
1217 switch (Stream.ReadSubBlockID()) {
1218 default: // Skip unknown content.
1219 if (Stream.SkipBlock())
1220 return Error("Malformed block record");
1221 break;
1222 case bitc::CONSTANTS_BLOCK_ID:
1223 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001224 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001225 break;
1226 case bitc::VALUE_SYMTAB_BLOCK_ID:
1227 if (ParseValueSymbolTable()) return true;
1228 break;
1229 }
1230 continue;
1231 }
1232
1233 if (Code == bitc::DEFINE_ABBREV) {
1234 Stream.ReadAbbrevRecord();
1235 continue;
1236 }
1237
1238 // Read a record.
1239 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001240 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001241 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001242 default: // Default behavior: reject
1243 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001244 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001245 if (Record.size() < 1 || Record[0] == 0)
1246 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001247 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001248 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001249 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greif051a9502008-04-06 20:25:17 +00001250 FunctionBBs[i] = BasicBlock::Create("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001251 CurBB = FunctionBBs[0];
1252 continue;
1253
Chris Lattnerabfbf852007-05-06 00:21:25 +00001254 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1255 unsigned OpNum = 0;
1256 Value *LHS, *RHS;
1257 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1258 getValue(Record, OpNum, LHS->getType(), RHS) ||
1259 OpNum+1 != Record.size())
1260 return Error("Invalid BINOP record");
1261
1262 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1263 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001264 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001265 break;
1266 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001267 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1268 unsigned OpNum = 0;
1269 Value *Op;
1270 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1271 OpNum+2 != Record.size())
1272 return Error("Invalid CAST record");
1273
1274 const Type *ResTy = getTypeByID(Record[OpNum]);
1275 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1276 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001277 return Error("Invalid CAST record");
1278 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1279 break;
1280 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001281 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001282 unsigned OpNum = 0;
1283 Value *BasePtr;
1284 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001285 return Error("Invalid GEP record");
1286
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001287 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001288 while (OpNum != Record.size()) {
1289 Value *Op;
1290 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001291 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001292 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001293 }
1294
Gabor Greif051a9502008-04-06 20:25:17 +00001295 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001296 break;
1297 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001298
Chris Lattnerabfbf852007-05-06 00:21:25 +00001299 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1300 unsigned OpNum = 0;
1301 Value *TrueVal, *FalseVal, *Cond;
1302 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1303 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1304 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001305 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001306
Gabor Greif051a9502008-04-06 20:25:17 +00001307 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001308 break;
1309 }
1310
1311 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001312 unsigned OpNum = 0;
1313 Value *Vec, *Idx;
1314 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1315 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001316 return Error("Invalid EXTRACTELT record");
1317 I = new ExtractElementInst(Vec, Idx);
1318 break;
1319 }
1320
1321 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001322 unsigned OpNum = 0;
1323 Value *Vec, *Elt, *Idx;
1324 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1325 getValue(Record, OpNum,
1326 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1327 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001328 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00001329 I = InsertElementInst::Create(Vec, Elt, Idx);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001330 break;
1331 }
1332
Chris Lattnerabfbf852007-05-06 00:21:25 +00001333 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1334 unsigned OpNum = 0;
1335 Value *Vec1, *Vec2, *Mask;
1336 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1337 getValue(Record, OpNum, Vec1->getType(), Vec2))
1338 return Error("Invalid SHUFFLEVEC record");
1339
1340 const Type *MaskTy =
1341 VectorType::get(Type::Int32Ty,
1342 cast<VectorType>(Vec1->getType())->getNumElements());
1343
1344 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001345 return Error("Invalid SHUFFLEVEC record");
1346 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1347 break;
1348 }
1349
1350 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001351 unsigned OpNum = 0;
1352 Value *LHS, *RHS;
1353 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1354 getValue(Record, OpNum, LHS->getType(), RHS) ||
1355 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001356 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001357
1358 if (LHS->getType()->isFPOrFPVector())
1359 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001360 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001361 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001362 break;
1363 }
Devang Patel197be3d2008-02-22 02:49:49 +00001364 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1365 if (Record.size() != 2)
1366 return Error("Invalid GETRESULT record");
1367 unsigned OpNum = 0;
1368 Value *Op;
1369 getValueTypePair(Record, OpNum, NextValueNo, Op);
1370 unsigned Index = Record[1];
1371 I = new GetResultInst(Op, Index);
1372 break;
1373 }
Chris Lattner01ff65f2007-05-02 05:16:49 +00001374
Chris Lattner231cbcb2007-05-02 04:27:25 +00001375 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00001376 {
1377 unsigned Size = Record.size();
1378 if (Size == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00001379 I = ReturnInst::Create();
Devang Pateld9d99ff2008-02-26 01:29:32 +00001380 break;
1381 } else {
1382 unsigned OpNum = 0;
Devang Patelf4511cd2008-02-26 19:38:17 +00001383 SmallVector<Value *,4> Vs;
Devang Pateld9d99ff2008-02-26 01:29:32 +00001384 do {
1385 Value *Op = NULL;
1386 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1387 return Error("Invalid RET record");
1388 Vs.push_back(Op);
1389 } while(OpNum != Record.size());
1390
Devang Patelf4511cd2008-02-26 19:38:17 +00001391 // SmallVector Vs has at least one element.
Gabor Greif051a9502008-04-06 20:25:17 +00001392 I = ReturnInst::Create(&Vs[0], Vs.size());
Devang Pateld9d99ff2008-02-26 01:29:32 +00001393 break;
1394 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001395 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001396 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001397 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001398 return Error("Invalid BR record");
1399 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1400 if (TrueDest == 0)
1401 return Error("Invalid BR record");
1402
1403 if (Record.size() == 1)
Gabor Greif051a9502008-04-06 20:25:17 +00001404 I = BranchInst::Create(TrueDest);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001405 else {
1406 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1407 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1408 if (FalseDest == 0 || Cond == 0)
1409 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00001410 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001411 }
1412 break;
1413 }
1414 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1415 if (Record.size() < 3 || (Record.size() & 1) == 0)
1416 return Error("Invalid SWITCH record");
1417 const Type *OpTy = getTypeByID(Record[0]);
1418 Value *Cond = getFnValueByID(Record[1], OpTy);
1419 BasicBlock *Default = getBasicBlock(Record[2]);
1420 if (OpTy == 0 || Cond == 0 || Default == 0)
1421 return Error("Invalid SWITCH record");
1422 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00001423 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001424 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1425 ConstantInt *CaseVal =
1426 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1427 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1428 if (CaseVal == 0 || DestBB == 0) {
1429 delete SI;
1430 return Error("Invalid SWITCH record!");
1431 }
1432 SI->addCase(CaseVal, DestBB);
1433 }
1434 I = SI;
1435 break;
1436 }
1437
Duncan Sandsdc024672007-11-27 13:23:08 +00001438 case bitc::FUNC_CODE_INST_INVOKE: {
1439 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001440 if (Record.size() < 4) return Error("Invalid INVOKE record");
Chris Lattner58d74912008-03-12 17:45:29 +00001441 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001442 unsigned CCInfo = Record[1];
1443 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1444 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001445
Chris Lattnera9bb7132007-05-08 05:38:01 +00001446 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001447 Value *Callee;
1448 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001449 return Error("Invalid INVOKE record");
1450
Chris Lattner7337ab92007-05-06 00:00:00 +00001451 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1452 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001453 dyn_cast<FunctionType>(CalleeTy->getElementType());
1454
1455 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001456 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1457 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001458 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001459
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001460 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001461 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1462 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1463 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001464 }
1465
Chris Lattner7337ab92007-05-06 00:00:00 +00001466 if (!FTy->isVarArg()) {
1467 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001468 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001469 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001470 // Read type/value pairs for varargs params.
1471 while (OpNum != Record.size()) {
1472 Value *Op;
1473 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1474 return Error("Invalid INVOKE record");
1475 Ops.push_back(Op);
1476 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001477 }
1478
Gabor Greif051a9502008-04-06 20:25:17 +00001479 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001480 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Duncan Sandsdc024672007-11-27 13:23:08 +00001481 cast<InvokeInst>(I)->setParamAttrs(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001482 break;
1483 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001484 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1485 I = new UnwindInst();
1486 break;
1487 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1488 I = new UnreachableInst();
1489 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001490 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001491 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001492 return Error("Invalid PHI record");
1493 const Type *Ty = getTypeByID(Record[0]);
1494 if (!Ty) return Error("Invalid PHI record");
1495
Gabor Greif051a9502008-04-06 20:25:17 +00001496 PHINode *PN = PHINode::Create(Ty);
Chris Lattner86941612008-04-13 00:14:42 +00001497 PN->reserveOperandSpace((Record.size()-1)/2);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001498
Chris Lattner15e6d172007-05-04 19:11:41 +00001499 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1500 Value *V = getFnValueByID(Record[1+i], Ty);
1501 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001502 if (!V || !BB) return Error("Invalid PHI record");
1503 PN->addIncoming(V, BB);
1504 }
1505 I = PN;
1506 break;
1507 }
1508
1509 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1510 if (Record.size() < 3)
1511 return Error("Invalid MALLOC record");
1512 const PointerType *Ty =
1513 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1514 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1515 unsigned Align = Record[2];
1516 if (!Ty || !Size) return Error("Invalid MALLOC record");
1517 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1518 break;
1519 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001520 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1521 unsigned OpNum = 0;
1522 Value *Op;
1523 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1524 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001525 return Error("Invalid FREE record");
1526 I = new FreeInst(Op);
1527 break;
1528 }
1529 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1530 if (Record.size() < 3)
1531 return Error("Invalid ALLOCA record");
1532 const PointerType *Ty =
1533 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1534 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1535 unsigned Align = Record[2];
1536 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1537 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1538 break;
1539 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001540 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001541 unsigned OpNum = 0;
1542 Value *Op;
1543 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1544 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001545 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001546
1547 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001548 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001549 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001550 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1551 unsigned OpNum = 0;
1552 Value *Val, *Ptr;
1553 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1554 getValue(Record, OpNum,
1555 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1556 OpNum+2 != Record.size())
1557 return Error("Invalid STORE record");
1558
1559 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1560 break;
1561 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001562 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001563 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001564 unsigned OpNum = 0;
1565 Value *Val, *Ptr;
1566 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001567 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001568 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001569 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001570
1571 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001572 break;
1573 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001574 case bitc::FUNC_CODE_INST_CALL: {
1575 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1576 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001577 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001578
Chris Lattner58d74912008-03-12 17:45:29 +00001579 PAListPtr PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001580 unsigned CCInfo = Record[1];
1581
1582 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001583 Value *Callee;
1584 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1585 return Error("Invalid CALL record");
1586
1587 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001588 const FunctionType *FTy = 0;
1589 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001590 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001591 return Error("Invalid CALL record");
1592
1593 SmallVector<Value*, 16> Args;
1594 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001595 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001596 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1597 Args.push_back(getBasicBlock(Record[OpNum]));
1598 else
1599 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001600 if (Args.back() == 0) return Error("Invalid CALL record");
1601 }
1602
Chris Lattner0579f7f2007-05-03 22:04:19 +00001603 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001604 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001605 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001606 return Error("Invalid CALL record");
1607 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001608 while (OpNum != Record.size()) {
1609 Value *Op;
1610 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1611 return Error("Invalid CALL record");
1612 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001613 }
1614 }
1615
Gabor Greif051a9502008-04-06 20:25:17 +00001616 I = CallInst::Create(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001617 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1618 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Duncan Sandsdc024672007-11-27 13:23:08 +00001619 cast<CallInst>(I)->setParamAttrs(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001620 break;
1621 }
1622 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1623 if (Record.size() < 3)
1624 return Error("Invalid VAARG record");
1625 const Type *OpTy = getTypeByID(Record[0]);
1626 Value *Op = getFnValueByID(Record[1], OpTy);
1627 const Type *ResTy = getTypeByID(Record[2]);
1628 if (!OpTy || !Op || !ResTy)
1629 return Error("Invalid VAARG record");
1630 I = new VAArgInst(Op, ResTy);
1631 break;
1632 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001633 }
1634
1635 // Add instruction to end of current BB. If there is no current BB, reject
1636 // this file.
1637 if (CurBB == 0) {
1638 delete I;
1639 return Error("Invalid instruction with no BB");
1640 }
1641 CurBB->getInstList().push_back(I);
1642
1643 // If this was a terminator instruction, move to the next block.
1644 if (isa<TerminatorInst>(I)) {
1645 ++CurBBNo;
1646 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1647 }
1648
1649 // Non-void values get registered in the value table for future use.
1650 if (I && I->getType() != Type::VoidTy)
1651 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001652 }
1653
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001654 // Check the function list for unresolved values.
1655 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1656 if (A->getParent() == 0) {
1657 // We found at least one unresolved value. Nuke them all to avoid leaks.
1658 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1659 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1660 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1661 delete A;
1662 }
1663 }
Chris Lattner35a04702007-05-04 03:50:29 +00001664 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001665 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001666 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001667
1668 // Trim the value list down to the size it was before we parsed this function.
1669 ValueList.shrinkTo(ModuleValueListSize);
1670 std::vector<BasicBlock*>().swap(FunctionBBs);
1671
Chris Lattner48f84872007-05-01 04:59:48 +00001672 return false;
1673}
1674
Chris Lattnerb348bb82007-05-18 04:02:46 +00001675//===----------------------------------------------------------------------===//
1676// ModuleProvider implementation
1677//===----------------------------------------------------------------------===//
1678
1679
1680bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1681 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001682 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001683
1684 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1685 DeferredFunctionInfo.find(F);
1686 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1687
1688 // Move the bit stream to the saved position of the deferred function body and
1689 // restore the real linkage type for the function.
1690 Stream.JumpToBit(DFII->second.first);
1691 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1692
1693 if (ParseFunctionBody(F)) {
1694 if (ErrInfo) *ErrInfo = ErrorString;
1695 return true;
1696 }
Chandler Carruth69940402007-08-04 01:51:18 +00001697
1698 // Upgrade any old intrinsic calls in the function.
1699 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1700 E = UpgradedIntrinsics.end(); I != E; ++I) {
1701 if (I->first != I->second) {
1702 for (Value::use_iterator UI = I->first->use_begin(),
1703 UE = I->first->use_end(); UI != UE; ) {
1704 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1705 UpgradeIntrinsicCall(CI, I->second);
1706 }
1707 }
1708 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001709
1710 return false;
1711}
1712
1713void BitcodeReader::dematerializeFunction(Function *F) {
1714 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001715 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001716 return;
1717
1718 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1719
1720 // Just forget the function body, we can remat it later.
1721 F->deleteBody();
1722 F->setLinkage(GlobalValue::GhostLinkage);
1723}
1724
1725
1726Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1727 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1728 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1729 ++I) {
1730 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001731 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001732 materializeFunction(F, ErrInfo))
1733 return 0;
1734 }
Chandler Carruth69940402007-08-04 01:51:18 +00001735
1736 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1737 // delete the old functions to clean up. We can't do this unless the entire
1738 // module is materialized because there could always be another function body
1739 // with calls to the old function.
1740 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1741 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1742 if (I->first != I->second) {
1743 for (Value::use_iterator UI = I->first->use_begin(),
1744 UE = I->first->use_end(); UI != UE; ) {
1745 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1746 UpgradeIntrinsicCall(CI, I->second);
1747 }
1748 ValueList.replaceUsesOfWith(I->first, I->second);
1749 I->first->eraseFromParent();
1750 }
1751 }
1752 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1753
Chris Lattnerb348bb82007-05-18 04:02:46 +00001754 return TheModule;
1755}
1756
1757
1758/// This method is provided by the parent ModuleProvde class and overriden
1759/// here. It simply releases the module from its provided and frees up our
1760/// state.
1761/// @brief Release our hold on the generated module
1762Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1763 // Since we're losing control of this Module, we must hand it back complete
1764 Module *M = ModuleProvider::releaseModule(ErrInfo);
1765 FreeState();
1766 return M;
1767}
1768
Chris Lattner48f84872007-05-01 04:59:48 +00001769
Chris Lattnerc453f762007-04-29 07:54:31 +00001770//===----------------------------------------------------------------------===//
1771// External interface
1772//===----------------------------------------------------------------------===//
1773
1774/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1775///
1776ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1777 std::string *ErrMsg) {
1778 BitcodeReader *R = new BitcodeReader(Buffer);
1779 if (R->ParseBitcode()) {
1780 if (ErrMsg)
1781 *ErrMsg = R->getErrorString();
1782
1783 // Don't let the BitcodeReader dtor delete 'Buffer'.
1784 R->releaseMemoryBuffer();
1785 delete R;
1786 return 0;
1787 }
1788 return R;
1789}
1790
1791/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1792/// If an error occurs, return null and fill in *ErrMsg if non-null.
1793Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1794 BitcodeReader *R;
1795 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1796 if (!R) return 0;
1797
Chris Lattnerb348bb82007-05-18 04:02:46 +00001798 // Read in the entire module.
1799 Module *M = R->materializeModule(ErrMsg);
1800
1801 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1802 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001803 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001804
1805 // If there was no error, tell ModuleProvider not to delete it when its dtor
1806 // is run.
1807 if (M)
1808 M = R->releaseModule(ErrMsg);
1809
Chris Lattnerc453f762007-04-29 07:54:31 +00001810 delete R;
1811 return M;
1812}