blob: 9c1f49e865dc298d2ab955f817995149d8a8ff70 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
14#include "llvm/Bitcode/ReaderWriter.h"
15#include "BitcodeReader.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/InlineAsm.h"
19#include "llvm/Instructions.h"
20#include "llvm/Module.h"
21#include "llvm/ParameterAttributes.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/Support/MathExtras.h"
24#include "llvm/Support/MemoryBuffer.h"
25using namespace llvm;
26
27void BitcodeReader::FreeState() {
28 delete Buffer;
29 Buffer = 0;
30 std::vector<PATypeHolder>().swap(TypeList);
31 ValueList.clear();
32 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
33 std::vector<BasicBlock*>().swap(FunctionBBs);
34 std::vector<Function*>().swap(FunctionsWithBodies);
35 DeferredFunctionInfo.clear();
36}
37
38//===----------------------------------------------------------------------===//
39// Helper functions to implement forward reference resolution, etc.
40//===----------------------------------------------------------------------===//
41
42/// ConvertToString - Convert a string from a record into an std::string, return
43/// true on failure.
44template<typename StrTy>
45static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
46 StrTy &Result) {
47 if (Idx > Record.size())
48 return true;
49
50 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
51 Result += (char)Record[i];
52 return false;
53}
54
55static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
56 switch (Val) {
57 default: // Map unknown/new linkages to external
58 case 0: return GlobalValue::ExternalLinkage;
59 case 1: return GlobalValue::WeakLinkage;
60 case 2: return GlobalValue::AppendingLinkage;
61 case 3: return GlobalValue::InternalLinkage;
62 case 4: return GlobalValue::LinkOnceLinkage;
63 case 5: return GlobalValue::DLLImportLinkage;
64 case 6: return GlobalValue::DLLExportLinkage;
65 case 7: return GlobalValue::ExternalWeakLinkage;
66 }
67}
68
69static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
70 switch (Val) {
71 default: // Map unknown visibilities to default.
72 case 0: return GlobalValue::DefaultVisibility;
73 case 1: return GlobalValue::HiddenVisibility;
74 case 2: return GlobalValue::ProtectedVisibility;
75 }
76}
77
78static int GetDecodedCastOpcode(unsigned Val) {
79 switch (Val) {
80 default: return -1;
81 case bitc::CAST_TRUNC : return Instruction::Trunc;
82 case bitc::CAST_ZEXT : return Instruction::ZExt;
83 case bitc::CAST_SEXT : return Instruction::SExt;
84 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
85 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
86 case bitc::CAST_UITOFP : return Instruction::UIToFP;
87 case bitc::CAST_SITOFP : return Instruction::SIToFP;
88 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
89 case bitc::CAST_FPEXT : return Instruction::FPExt;
90 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
91 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
92 case bitc::CAST_BITCAST : return Instruction::BitCast;
93 }
94}
95static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
96 switch (Val) {
97 default: return -1;
98 case bitc::BINOP_ADD: return Instruction::Add;
99 case bitc::BINOP_SUB: return Instruction::Sub;
100 case bitc::BINOP_MUL: return Instruction::Mul;
101 case bitc::BINOP_UDIV: return Instruction::UDiv;
102 case bitc::BINOP_SDIV:
103 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
104 case bitc::BINOP_UREM: return Instruction::URem;
105 case bitc::BINOP_SREM:
106 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
107 case bitc::BINOP_SHL: return Instruction::Shl;
108 case bitc::BINOP_LSHR: return Instruction::LShr;
109 case bitc::BINOP_ASHR: return Instruction::AShr;
110 case bitc::BINOP_AND: return Instruction::And;
111 case bitc::BINOP_OR: return Instruction::Or;
112 case bitc::BINOP_XOR: return Instruction::Xor;
113 }
114}
115
116
117namespace {
118 /// @brief A class for maintaining the slot number definition
119 /// as a placeholder for the actual definition for forward constants defs.
120 class ConstantPlaceHolder : public ConstantExpr {
121 ConstantPlaceHolder(); // DO NOT IMPLEMENT
122 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
123 public:
124 Use Op;
125 ConstantPlaceHolder(const Type *Ty)
126 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
127 Op(UndefValue::get(Type::Int32Ty), this) {
128 }
129 };
130}
131
132Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
133 const Type *Ty) {
134 if (Idx >= size()) {
135 // Insert a bunch of null values.
136 Uses.resize(Idx+1);
137 OperandList = &Uses[0];
138 NumOperands = Idx+1;
139 }
140
141 if (Value *V = Uses[Idx]) {
142 assert(Ty == V->getType() && "Type mismatch in constant table!");
143 return cast<Constant>(V);
144 }
145
146 // Create and return a placeholder, which will later be RAUW'd.
147 Constant *C = new ConstantPlaceHolder(Ty);
148 Uses[Idx].init(C, this);
149 return C;
150}
151
152Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
153 if (Idx >= size()) {
154 // Insert a bunch of null values.
155 Uses.resize(Idx+1);
156 OperandList = &Uses[0];
157 NumOperands = Idx+1;
158 }
159
160 if (Value *V = Uses[Idx]) {
161 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
162 return V;
163 }
164
165 // No type specified, must be invalid reference.
166 if (Ty == 0) return 0;
167
168 // Create and return a placeholder, which will later be RAUW'd.
169 Value *V = new Argument(Ty);
170 Uses[Idx].init(V, this);
171 return V;
172}
173
174
175const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
176 // If the TypeID is in range, return it.
177 if (ID < TypeList.size())
178 return TypeList[ID].get();
179 if (!isTypeTable) return 0;
180
181 // The type table allows forward references. Push as many Opaque types as
182 // needed to get up to ID.
183 while (TypeList.size() <= ID)
184 TypeList.push_back(OpaqueType::get());
185 return TypeList.back().get();
186}
187
188//===----------------------------------------------------------------------===//
189// Functions for parsing blocks from the bitcode file
190//===----------------------------------------------------------------------===//
191
192bool BitcodeReader::ParseParamAttrBlock() {
193 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
194 return Error("Malformed block record");
195
196 if (!ParamAttrs.empty())
197 return Error("Multiple PARAMATTR blocks found!");
198
199 SmallVector<uint64_t, 64> Record;
200
201 ParamAttrsVector Attrs;
202
203 // Read all the records.
204 while (1) {
205 unsigned Code = Stream.ReadCode();
206 if (Code == bitc::END_BLOCK) {
207 if (Stream.ReadBlockEnd())
208 return Error("Error at end of PARAMATTR block");
209 return false;
210 }
211
212 if (Code == bitc::ENTER_SUBBLOCK) {
213 // No known subblocks, always skip them.
214 Stream.ReadSubBlockID();
215 if (Stream.SkipBlock())
216 return Error("Malformed block record");
217 continue;
218 }
219
220 if (Code == bitc::DEFINE_ABBREV) {
221 Stream.ReadAbbrevRecord();
222 continue;
223 }
224
225 // Read a record.
226 Record.clear();
227 switch (Stream.ReadRecord(Code, Record)) {
228 default: // Default behavior: ignore.
229 break;
230 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
231 if (Record.size() & 1)
232 return Error("Invalid ENTRY record");
233
234 ParamAttrsWithIndex PAWI;
235 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
236 PAWI.index = Record[i];
237 PAWI.attrs = Record[i+1];
238 Attrs.push_back(PAWI);
239 }
240 ParamAttrs.push_back(ParamAttrsList::get(Attrs));
241 Attrs.clear();
242 break;
243 }
244 }
245 }
246}
247
248
249bool BitcodeReader::ParseTypeTable() {
250 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
251 return Error("Malformed block record");
252
253 if (!TypeList.empty())
254 return Error("Multiple TYPE_BLOCKs found!");
255
256 SmallVector<uint64_t, 64> Record;
257 unsigned NumRecords = 0;
258
259 // Read all the records for this type table.
260 while (1) {
261 unsigned Code = Stream.ReadCode();
262 if (Code == bitc::END_BLOCK) {
263 if (NumRecords != TypeList.size())
264 return Error("Invalid type forward reference in TYPE_BLOCK");
265 if (Stream.ReadBlockEnd())
266 return Error("Error at end of type table block");
267 return false;
268 }
269
270 if (Code == bitc::ENTER_SUBBLOCK) {
271 // No known subblocks, always skip them.
272 Stream.ReadSubBlockID();
273 if (Stream.SkipBlock())
274 return Error("Malformed block record");
275 continue;
276 }
277
278 if (Code == bitc::DEFINE_ABBREV) {
279 Stream.ReadAbbrevRecord();
280 continue;
281 }
282
283 // Read a record.
284 Record.clear();
285 const Type *ResultTy = 0;
286 switch (Stream.ReadRecord(Code, Record)) {
287 default: // Default behavior: unknown type.
288 ResultTy = 0;
289 break;
290 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
291 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
292 // type list. This allows us to reserve space.
293 if (Record.size() < 1)
294 return Error("Invalid TYPE_CODE_NUMENTRY record");
295 TypeList.reserve(Record[0]);
296 continue;
297 case bitc::TYPE_CODE_VOID: // VOID
298 ResultTy = Type::VoidTy;
299 break;
300 case bitc::TYPE_CODE_FLOAT: // FLOAT
301 ResultTy = Type::FloatTy;
302 break;
303 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
304 ResultTy = Type::DoubleTy;
305 break;
Dale Johannesenf325d9f2007-08-03 01:03:46 +0000306 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
307 ResultTy = Type::X86_FP80Ty;
308 break;
309 case bitc::TYPE_CODE_FP128: // FP128
310 ResultTy = Type::FP128Ty;
311 break;
312 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
313 ResultTy = Type::PPC_FP128Ty;
314 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 case bitc::TYPE_CODE_LABEL: // LABEL
316 ResultTy = Type::LabelTy;
317 break;
318 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
319 ResultTy = 0;
320 break;
321 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
322 if (Record.size() < 1)
323 return Error("Invalid Integer type record");
324
325 ResultTy = IntegerType::get(Record[0]);
326 break;
327 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
328 if (Record.size() < 1)
329 return Error("Invalid POINTER type record");
330 ResultTy = PointerType::get(getTypeByID(Record[0], true));
331 break;
332 case bitc::TYPE_CODE_FUNCTION: {
333 // FUNCTION: [vararg, attrid, retty, paramty x N]
334 if (Record.size() < 3)
335 return Error("Invalid FUNCTION type record");
336 std::vector<const Type*> ArgTys;
337 for (unsigned i = 3, e = Record.size(); i != e; ++i)
338 ArgTys.push_back(getTypeByID(Record[i], true));
339
340 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
341 Record[0], getParamAttrs(Record[1]));
342 break;
343 }
344 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
345 if (Record.size() < 1)
346 return Error("Invalid STRUCT type record");
347 std::vector<const Type*> EltTys;
348 for (unsigned i = 1, e = Record.size(); i != e; ++i)
349 EltTys.push_back(getTypeByID(Record[i], true));
350 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
388 // value table... or with a preexisting type that was already in the
389 // system. Let's just make sure it did.
390 assert(TypeList[NumRecords-1].get() != OldTy &&
391 "refineAbstractType didn't work!");
392 }
393 }
394}
395
396
397bool BitcodeReader::ParseTypeSymbolTable() {
398 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
399 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();
407 if (Code == bitc::END_BLOCK) {
408 if (Stream.ReadBlockEnd())
409 return Error("Error at end of type symbol table block");
410 return false;
411 }
412
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
421 if (Code == bitc::DEFINE_ABBREV) {
422 Stream.ReadAbbrevRecord();
423 continue;
424 }
425
426 // Read a record.
427 Record.clear();
428 switch (Stream.ReadRecord(Code, Record)) {
429 default: // Default behavior: unknown type.
430 break;
431 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
432 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
445bool BitcodeReader::ParseValueSymbolTable() {
446 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
447 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();
455 if (Code == bitc::END_BLOCK) {
456 if (Stream.ReadBlockEnd())
457 return Error("Error at end of value symbol table block");
458 return false;
459 }
460 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;
478 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
479 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;
489 }
490 case bitc::VST_CODE_BBENTRY: {
491 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;
500 }
501 }
502 }
503}
504
505/// 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
516/// 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()) {
526 unsigned ValID = GlobalInitWorklist.back().second;
527 if (ValID >= ValueList.size()) {
528 // Not ready to resolve this yet, it requires something later in the file.
529 GlobalInits.push_back(GlobalInitWorklist.back());
530 } 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]))
545 AliasInitWorklist.back().first->setAliasee(C);
546 else
547 return Error("Alias initializer is not a constant!");
548 }
549 AliasInitWorklist.pop_back();
550 }
551 return false;
552}
553
554
555bool BitcodeReader::ParseConstants() {
556 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
557 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;
563 unsigned NextCstNo = ValueList.size();
564 while (1) {
565 unsigned Code = Stream.ReadCode();
566 if (Code == bitc::END_BLOCK) {
567 if (NextCstNo != ValueList.size())
568 return Error("Invalid constant reference!");
569
570 if (Stream.ReadBlockEnd())
571 return Error("Error at end of constants block");
572 return false;
573 }
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]];
602 continue; // Skip the ValueList manipulation.
603 case bitc::CST_CODE_NULL: // NULL
604 V = Constant::getNullValue(CurTy);
605 break;
606 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
607 if (!isa<IntegerType>(CurTy) || Record.empty())
608 return Error("Invalid CST_INTEGER record");
609 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
610 break;
611 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
612 if (!isa<IntegerType>(CurTy) || Record.empty())
613 return Error("Invalid WIDE_INTEGER record");
614
615 unsigned NumWords = Record.size();
616 SmallVector<uint64_t, 8> Words;
617 Words.resize(NumWords);
618 for (unsigned i = 0; i != NumWords; ++i)
619 Words[i] = DecodeSignRotatedValue(Record[i]);
620 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
621 NumWords, &Words[0]));
622 break;
623 }
624 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
625 if (Record.empty())
626 return Error("Invalid FLOAT record");
627 if (CurTy == Type::FloatTy)
628 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
629 else if (CurTy == Type::DoubleTy)
630 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
631 else
632 V = UndefValue::get(CurTy);
633 break;
634
635 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
636 if (Record.empty())
637 return Error("Invalid CST_AGGREGATE record");
638
639 unsigned Size = Record.size();
640 std::vector<Constant*> Elts;
641
642 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
643 for (unsigned i = 0; i != Size; ++i)
644 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
645 STy->getElementType(i)));
646 V = ConstantStruct::get(STy, Elts);
647 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
648 const Type *EltTy = ATy->getElementType();
649 for (unsigned i = 0; i != Size; ++i)
650 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
651 V = ConstantArray::get(ATy, Elts);
652 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
653 const Type *EltTy = VTy->getElementType();
654 for (unsigned i = 0; i != Size; ++i)
655 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
656 V = ConstantVector::get(Elts);
657 } else {
658 V = UndefValue::get(CurTy);
659 }
660 break;
661 }
662 case bitc::CST_CODE_STRING: { // STRING: [values]
663 if (Record.empty())
664 return Error("Invalid CST_AGGREGATE record");
665
666 const ArrayType *ATy = cast<ArrayType>(CurTy);
667 const Type *EltTy = ATy->getElementType();
668
669 unsigned Size = Record.size();
670 std::vector<Constant*> Elts;
671 for (unsigned i = 0; i != Size; ++i)
672 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
673 V = ConstantArray::get(ATy, Elts);
674 break;
675 }
676 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
677 if (Record.empty())
678 return Error("Invalid CST_AGGREGATE record");
679
680 const ArrayType *ATy = cast<ArrayType>(CurTy);
681 const Type *EltTy = ATy->getElementType();
682
683 unsigned Size = Record.size();
684 std::vector<Constant*> Elts;
685 for (unsigned i = 0; i != Size; ++i)
686 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
687 Elts.push_back(Constant::getNullValue(EltTy));
688 V = ConstantArray::get(ATy, Elts);
689 break;
690 }
691 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
692 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
693 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
694 if (Opc < 0) {
695 V = UndefValue::get(CurTy); // Unknown binop.
696 } else {
697 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
698 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
699 V = ConstantExpr::get(Opc, LHS, RHS);
700 }
701 break;
702 }
703 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
704 if (Record.size() < 3) return Error("Invalid CE_CAST record");
705 int Opc = GetDecodedCastOpcode(Record[0]);
706 if (Opc < 0) {
707 V = UndefValue::get(CurTy); // Unknown cast.
708 } else {
709 const Type *OpTy = getTypeByID(Record[1]);
710 if (!OpTy) return Error("Invalid CE_CAST record");
711 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
712 V = ConstantExpr::getCast(Opc, Op, CurTy);
713 }
714 break;
715 }
716 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
717 if (Record.size() & 1) return Error("Invalid CE_GEP record");
718 SmallVector<Constant*, 16> Elts;
719 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
720 const Type *ElTy = getTypeByID(Record[i]);
721 if (!ElTy) return Error("Invalid CE_GEP record");
722 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
723 }
724 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
725 break;
726 }
727 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
728 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
729 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
730 Type::Int1Ty),
731 ValueList.getConstantFwdRef(Record[1],CurTy),
732 ValueList.getConstantFwdRef(Record[2],CurTy));
733 break;
734 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
735 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
736 const VectorType *OpTy =
737 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
738 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
739 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
740 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
741 OpTy->getElementType());
742 V = ConstantExpr::getExtractElement(Op0, Op1);
743 break;
744 }
745 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
746 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
747 if (Record.size() < 3 || OpTy == 0)
748 return Error("Invalid CE_INSERTELT record");
749 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
750 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
751 OpTy->getElementType());
752 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
753 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
754 break;
755 }
756 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
757 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
758 if (Record.size() < 3 || OpTy == 0)
759 return Error("Invalid CE_INSERTELT record");
760 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
761 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
762 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
763 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
764 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
765 break;
766 }
767 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
768 if (Record.size() < 4) return Error("Invalid CE_CMP record");
769 const Type *OpTy = getTypeByID(Record[0]);
770 if (OpTy == 0) return Error("Invalid CE_CMP record");
771 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
772 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
773
774 if (OpTy->isFloatingPoint())
775 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
776 else
777 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
778 break;
779 }
780 case bitc::CST_CODE_INLINEASM: {
781 if (Record.size() < 2) return Error("Invalid INLINEASM record");
782 std::string AsmStr, ConstrStr;
783 bool HasSideEffects = Record[0];
784 unsigned AsmStrSize = Record[1];
785 if (2+AsmStrSize >= Record.size())
786 return Error("Invalid INLINEASM record");
787 unsigned ConstStrSize = Record[2+AsmStrSize];
788 if (3+AsmStrSize+ConstStrSize > Record.size())
789 return Error("Invalid INLINEASM record");
790
791 for (unsigned i = 0; i != AsmStrSize; ++i)
792 AsmStr += (char)Record[2+i];
793 for (unsigned i = 0; i != ConstStrSize; ++i)
794 ConstrStr += (char)Record[3+AsmStrSize+i];
795 const PointerType *PTy = cast<PointerType>(CurTy);
796 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
797 AsmStr, ConstrStr, HasSideEffects);
798 break;
799 }
800 }
801
802 ValueList.AssignValue(V, NextCstNo);
803 ++NextCstNo;
804 }
805}
806
807/// RememberAndSkipFunctionBody - When we see the block for a function body,
808/// remember where it is and then skip it. This lets us lazily deserialize the
809/// functions.
810bool BitcodeReader::RememberAndSkipFunctionBody() {
811 // Get the function we are talking about.
812 if (FunctionsWithBodies.empty())
813 return Error("Insufficient function protos");
814
815 Function *Fn = FunctionsWithBodies.back();
816 FunctionsWithBodies.pop_back();
817
818 // Save the current stream state.
819 uint64_t CurBit = Stream.GetCurrentBitNo();
820 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
821
822 // Set the functions linkage to GhostLinkage so we know it is lazily
823 // deserialized.
824 Fn->setLinkage(GlobalValue::GhostLinkage);
825
826 // Skip over the function block for now.
827 if (Stream.SkipBlock())
828 return Error("Malformed block record");
829 return false;
830}
831
832bool BitcodeReader::ParseModule(const std::string &ModuleID) {
833 // Reject multiple MODULE_BLOCK's in a single bitstream.
834 if (TheModule)
835 return Error("Multiple MODULE_BLOCKs in same stream");
836
837 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
838 return Error("Malformed block record");
839
840 // Otherwise, create the module.
841 TheModule = new Module(ModuleID);
842
843 SmallVector<uint64_t, 64> Record;
844 std::vector<std::string> SectionTable;
845
846 // Read all the records for this module.
847 while (!Stream.AtEndOfStream()) {
848 unsigned Code = Stream.ReadCode();
849 if (Code == bitc::END_BLOCK) {
850 if (Stream.ReadBlockEnd())
851 return Error("Error at end of module block");
852
853 // Patch the initializers for globals and aliases up.
854 ResolveGlobalAndAliasInits();
855 if (!GlobalInits.empty() || !AliasInits.empty())
856 return Error("Malformed global initializer set");
857 if (!FunctionsWithBodies.empty())
858 return Error("Too few function bodies found");
859
860 // Force deallocation of memory for these vectors to favor the client that
861 // want lazy deserialization.
862 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
863 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
864 std::vector<Function*>().swap(FunctionsWithBodies);
865 return false;
866 }
867
868 if (Code == bitc::ENTER_SUBBLOCK) {
869 switch (Stream.ReadSubBlockID()) {
870 default: // Skip unknown content.
871 if (Stream.SkipBlock())
872 return Error("Malformed block record");
873 break;
874 case bitc::BLOCKINFO_BLOCK_ID:
875 if (Stream.ReadBlockInfoBlock())
876 return Error("Malformed BlockInfoBlock");
877 break;
878 case bitc::PARAMATTR_BLOCK_ID:
879 if (ParseParamAttrBlock())
880 return true;
881 break;
882 case bitc::TYPE_BLOCK_ID:
883 if (ParseTypeTable())
884 return true;
885 break;
886 case bitc::TYPE_SYMTAB_BLOCK_ID:
887 if (ParseTypeSymbolTable())
888 return true;
889 break;
890 case bitc::VALUE_SYMTAB_BLOCK_ID:
891 if (ParseValueSymbolTable())
892 return true;
893 break;
894 case bitc::CONSTANTS_BLOCK_ID:
895 if (ParseConstants() || ResolveGlobalAndAliasInits())
896 return true;
897 break;
898 case bitc::FUNCTION_BLOCK_ID:
899 // If this is the first function body we've seen, reverse the
900 // FunctionsWithBodies list.
901 if (!HasReversedFunctionsWithBodies) {
902 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
903 HasReversedFunctionsWithBodies = true;
904 }
905
906 if (RememberAndSkipFunctionBody())
907 return true;
908 break;
909 }
910 continue;
911 }
912
913 if (Code == bitc::DEFINE_ABBREV) {
914 Stream.ReadAbbrevRecord();
915 continue;
916 }
917
918 // Read a record.
919 switch (Stream.ReadRecord(Code, Record)) {
920 default: break; // Default behavior, ignore unknown content.
921 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
922 if (Record.size() < 1)
923 return Error("Malformed MODULE_CODE_VERSION");
924 // Only version #0 is supported so far.
925 if (Record[0] != 0)
926 return Error("Unknown bitstream version!");
927 break;
928 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
929 std::string S;
930 if (ConvertToString(Record, 0, S))
931 return Error("Invalid MODULE_CODE_TRIPLE record");
932 TheModule->setTargetTriple(S);
933 break;
934 }
935 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
936 std::string S;
937 if (ConvertToString(Record, 0, S))
938 return Error("Invalid MODULE_CODE_DATALAYOUT record");
939 TheModule->setDataLayout(S);
940 break;
941 }
942 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
943 std::string S;
944 if (ConvertToString(Record, 0, S))
945 return Error("Invalid MODULE_CODE_ASM record");
946 TheModule->setModuleInlineAsm(S);
947 break;
948 }
949 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
950 std::string S;
951 if (ConvertToString(Record, 0, S))
952 return Error("Invalid MODULE_CODE_DEPLIB record");
953 TheModule->addLibrary(S);
954 break;
955 }
956 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
957 std::string S;
958 if (ConvertToString(Record, 0, S))
959 return Error("Invalid MODULE_CODE_SECTIONNAME record");
960 SectionTable.push_back(S);
961 break;
962 }
963 // GLOBALVAR: [type, isconst, initid,
964 // linkage, alignment, section, visibility, threadlocal]
965 case bitc::MODULE_CODE_GLOBALVAR: {
966 if (Record.size() < 6)
967 return Error("Invalid MODULE_CODE_GLOBALVAR record");
968 const Type *Ty = getTypeByID(Record[0]);
969 if (!isa<PointerType>(Ty))
970 return Error("Global not a pointer type!");
971 Ty = cast<PointerType>(Ty)->getElementType();
972
973 bool isConstant = Record[1];
974 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
975 unsigned Alignment = (1 << Record[4]) >> 1;
976 std::string Section;
977 if (Record[5]) {
978 if (Record[5]-1 >= SectionTable.size())
979 return Error("Invalid section ID");
980 Section = SectionTable[Record[5]-1];
981 }
982 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
983 if (Record.size() > 6)
984 Visibility = GetDecodedVisibility(Record[6]);
985 bool isThreadLocal = false;
986 if (Record.size() > 7)
987 isThreadLocal = Record[7];
988
989 GlobalVariable *NewGV =
990 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
991 NewGV->setAlignment(Alignment);
992 if (!Section.empty())
993 NewGV->setSection(Section);
994 NewGV->setVisibility(Visibility);
995 NewGV->setThreadLocal(isThreadLocal);
996
997 ValueList.push_back(NewGV);
998
999 // Remember which value to use for the global initializer.
1000 if (unsigned InitID = Record[2])
1001 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1002 break;
1003 }
1004 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1005 // alignment, section, visibility]
1006 case bitc::MODULE_CODE_FUNCTION: {
1007 if (Record.size() < 8)
1008 return Error("Invalid MODULE_CODE_FUNCTION record");
1009 const Type *Ty = getTypeByID(Record[0]);
1010 if (!isa<PointerType>(Ty))
1011 return Error("Function not a pointer type!");
1012 const FunctionType *FTy =
1013 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1014 if (!FTy)
1015 return Error("Function not a pointer to function type!");
1016
1017 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1018 "", TheModule);
1019
1020 Func->setCallingConv(Record[1]);
1021 bool isProto = Record[2];
1022 Func->setLinkage(GetDecodedLinkage(Record[3]));
1023
1024 assert(Func->getFunctionType()->getParamAttrs() ==
1025 getParamAttrs(Record[4]));
1026
1027 Func->setAlignment((1 << Record[5]) >> 1);
1028 if (Record[6]) {
1029 if (Record[6]-1 >= SectionTable.size())
1030 return Error("Invalid section ID");
1031 Func->setSection(SectionTable[Record[6]-1]);
1032 }
1033 Func->setVisibility(GetDecodedVisibility(Record[7]));
1034
1035 ValueList.push_back(Func);
1036
1037 // If this is a function with a body, remember the prototype we are
1038 // creating now, so that we can match up the body with them later.
1039 if (!isProto)
1040 FunctionsWithBodies.push_back(Func);
1041 break;
1042 }
1043 // ALIAS: [alias type, aliasee val#, linkage]
1044 case bitc::MODULE_CODE_ALIAS: {
1045 if (Record.size() < 3)
1046 return Error("Invalid MODULE_ALIAS record");
1047 const Type *Ty = getTypeByID(Record[0]);
1048 if (!isa<PointerType>(Ty))
1049 return Error("Function not a pointer type!");
1050
1051 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1052 "", 0, TheModule);
1053 ValueList.push_back(NewGA);
1054 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1055 break;
1056 }
1057 /// MODULE_CODE_PURGEVALS: [numvals]
1058 case bitc::MODULE_CODE_PURGEVALS:
1059 // Trim down the value list to the specified size.
1060 if (Record.size() < 1 || Record[0] > ValueList.size())
1061 return Error("Invalid MODULE_PURGEVALS record");
1062 ValueList.shrinkTo(Record[0]);
1063 break;
1064 }
1065 Record.clear();
1066 }
1067
1068 return Error("Premature end of bitstream");
1069}
1070
1071
1072bool BitcodeReader::ParseBitcode() {
1073 TheModule = 0;
1074
1075 if (Buffer->getBufferSize() & 3)
1076 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1077
1078 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1079 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1080
1081 // Sniff for the signature.
1082 if (Stream.Read(8) != 'B' ||
1083 Stream.Read(8) != 'C' ||
1084 Stream.Read(4) != 0x0 ||
1085 Stream.Read(4) != 0xC ||
1086 Stream.Read(4) != 0xE ||
1087 Stream.Read(4) != 0xD)
1088 return Error("Invalid bitcode signature");
1089
1090 // We expect a number of well-defined blocks, though we don't necessarily
1091 // need to understand them all.
1092 while (!Stream.AtEndOfStream()) {
1093 unsigned Code = Stream.ReadCode();
1094
1095 if (Code != bitc::ENTER_SUBBLOCK)
1096 return Error("Invalid record at top-level");
1097
1098 unsigned BlockID = Stream.ReadSubBlockID();
1099
1100 // We only know the MODULE subblock ID.
1101 switch (BlockID) {
1102 case bitc::BLOCKINFO_BLOCK_ID:
1103 if (Stream.ReadBlockInfoBlock())
1104 return Error("Malformed BlockInfoBlock");
1105 break;
1106 case bitc::MODULE_BLOCK_ID:
1107 if (ParseModule(Buffer->getBufferIdentifier()))
1108 return true;
1109 break;
1110 default:
1111 if (Stream.SkipBlock())
1112 return Error("Malformed block record");
1113 break;
1114 }
1115 }
1116
1117 return false;
1118}
1119
1120
1121/// ParseFunctionBody - Lazily parse the specified function body block.
1122bool BitcodeReader::ParseFunctionBody(Function *F) {
1123 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1124 return Error("Malformed block record");
1125
1126 unsigned ModuleValueListSize = ValueList.size();
1127
1128 // Add all the function arguments to the value table.
1129 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1130 ValueList.push_back(I);
1131
1132 unsigned NextValueNo = ValueList.size();
1133 BasicBlock *CurBB = 0;
1134 unsigned CurBBNo = 0;
1135
1136 // Read all the records.
1137 SmallVector<uint64_t, 64> Record;
1138 while (1) {
1139 unsigned Code = Stream.ReadCode();
1140 if (Code == bitc::END_BLOCK) {
1141 if (Stream.ReadBlockEnd())
1142 return Error("Error at end of function block");
1143 break;
1144 }
1145
1146 if (Code == bitc::ENTER_SUBBLOCK) {
1147 switch (Stream.ReadSubBlockID()) {
1148 default: // Skip unknown content.
1149 if (Stream.SkipBlock())
1150 return Error("Malformed block record");
1151 break;
1152 case bitc::CONSTANTS_BLOCK_ID:
1153 if (ParseConstants()) return true;
1154 NextValueNo = ValueList.size();
1155 break;
1156 case bitc::VALUE_SYMTAB_BLOCK_ID:
1157 if (ParseValueSymbolTable()) return true;
1158 break;
1159 }
1160 continue;
1161 }
1162
1163 if (Code == bitc::DEFINE_ABBREV) {
1164 Stream.ReadAbbrevRecord();
1165 continue;
1166 }
1167
1168 // Read a record.
1169 Record.clear();
1170 Instruction *I = 0;
1171 switch (Stream.ReadRecord(Code, Record)) {
1172 default: // Default behavior: reject
1173 return Error("Unknown instruction");
1174 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1175 if (Record.size() < 1 || Record[0] == 0)
1176 return Error("Invalid DECLAREBLOCKS record");
1177 // Create all the basic blocks for the function.
1178 FunctionBBs.resize(Record[0]);
1179 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1180 FunctionBBs[i] = new BasicBlock("", F);
1181 CurBB = FunctionBBs[0];
1182 continue;
1183
1184 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1185 unsigned OpNum = 0;
1186 Value *LHS, *RHS;
1187 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1188 getValue(Record, OpNum, LHS->getType(), RHS) ||
1189 OpNum+1 != Record.size())
1190 return Error("Invalid BINOP record");
1191
1192 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1193 if (Opc == -1) return Error("Invalid BINOP record");
1194 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1195 break;
1196 }
1197 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1198 unsigned OpNum = 0;
1199 Value *Op;
1200 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1201 OpNum+2 != Record.size())
1202 return Error("Invalid CAST record");
1203
1204 const Type *ResTy = getTypeByID(Record[OpNum]);
1205 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1206 if (Opc == -1 || ResTy == 0)
1207 return Error("Invalid CAST record");
1208 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1209 break;
1210 }
1211 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1212 unsigned OpNum = 0;
1213 Value *BasePtr;
1214 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1215 return Error("Invalid GEP record");
1216
1217 SmallVector<Value*, 16> GEPIdx;
1218 while (OpNum != Record.size()) {
1219 Value *Op;
1220 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1221 return Error("Invalid GEP record");
1222 GEPIdx.push_back(Op);
1223 }
1224
1225 I = new GetElementPtrInst(BasePtr, &GEPIdx[0], GEPIdx.size());
1226 break;
1227 }
1228
1229 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1230 unsigned OpNum = 0;
1231 Value *TrueVal, *FalseVal, *Cond;
1232 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1233 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1234 getValue(Record, OpNum, Type::Int1Ty, Cond))
1235 return Error("Invalid SELECT record");
1236
1237 I = new SelectInst(Cond, TrueVal, FalseVal);
1238 break;
1239 }
1240
1241 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1242 unsigned OpNum = 0;
1243 Value *Vec, *Idx;
1244 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1245 getValue(Record, OpNum, Type::Int32Ty, Idx))
1246 return Error("Invalid EXTRACTELT record");
1247 I = new ExtractElementInst(Vec, Idx);
1248 break;
1249 }
1250
1251 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1252 unsigned OpNum = 0;
1253 Value *Vec, *Elt, *Idx;
1254 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1255 getValue(Record, OpNum,
1256 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1257 getValue(Record, OpNum, Type::Int32Ty, Idx))
1258 return Error("Invalid INSERTELT record");
1259 I = new InsertElementInst(Vec, Elt, Idx);
1260 break;
1261 }
1262
1263 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1264 unsigned OpNum = 0;
1265 Value *Vec1, *Vec2, *Mask;
1266 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1267 getValue(Record, OpNum, Vec1->getType(), Vec2))
1268 return Error("Invalid SHUFFLEVEC record");
1269
1270 const Type *MaskTy =
1271 VectorType::get(Type::Int32Ty,
1272 cast<VectorType>(Vec1->getType())->getNumElements());
1273
1274 if (getValue(Record, OpNum, MaskTy, Mask))
1275 return Error("Invalid SHUFFLEVEC record");
1276 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1277 break;
1278 }
1279
1280 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1281 unsigned OpNum = 0;
1282 Value *LHS, *RHS;
1283 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1284 getValue(Record, OpNum, LHS->getType(), RHS) ||
1285 OpNum+1 != Record.size())
1286 return Error("Invalid CMP record");
1287
1288 if (LHS->getType()->isFPOrFPVector())
1289 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1290 else
1291 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1292 break;
1293 }
1294
1295 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1296 if (Record.size() == 0) {
1297 I = new ReturnInst();
1298 break;
1299 } else {
1300 unsigned OpNum = 0;
1301 Value *Op;
1302 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1303 OpNum != Record.size())
1304 return Error("Invalid RET record");
1305 I = new ReturnInst(Op);
1306 break;
1307 }
1308 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1309 if (Record.size() != 1 && Record.size() != 3)
1310 return Error("Invalid BR record");
1311 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1312 if (TrueDest == 0)
1313 return Error("Invalid BR record");
1314
1315 if (Record.size() == 1)
1316 I = new BranchInst(TrueDest);
1317 else {
1318 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1319 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1320 if (FalseDest == 0 || Cond == 0)
1321 return Error("Invalid BR record");
1322 I = new BranchInst(TrueDest, FalseDest, Cond);
1323 }
1324 break;
1325 }
1326 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1327 if (Record.size() < 3 || (Record.size() & 1) == 0)
1328 return Error("Invalid SWITCH record");
1329 const Type *OpTy = getTypeByID(Record[0]);
1330 Value *Cond = getFnValueByID(Record[1], OpTy);
1331 BasicBlock *Default = getBasicBlock(Record[2]);
1332 if (OpTy == 0 || Cond == 0 || Default == 0)
1333 return Error("Invalid SWITCH record");
1334 unsigned NumCases = (Record.size()-3)/2;
1335 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1336 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1337 ConstantInt *CaseVal =
1338 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1339 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1340 if (CaseVal == 0 || DestBB == 0) {
1341 delete SI;
1342 return Error("Invalid SWITCH record!");
1343 }
1344 SI->addCase(CaseVal, DestBB);
1345 }
1346 I = SI;
1347 break;
1348 }
1349
1350 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1351 if (Record.size() < 4) return Error("Invalid INVOKE record");
1352 unsigned CCInfo = Record[1];
1353 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1354 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1355
1356 unsigned OpNum = 4;
1357 Value *Callee;
1358 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1359 return Error("Invalid INVOKE record");
1360
1361 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1362 const FunctionType *FTy = !CalleeTy ? 0 :
1363 dyn_cast<FunctionType>(CalleeTy->getElementType());
1364
1365 // Check that the right number of fixed parameters are here.
1366 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1367 Record.size() < OpNum+FTy->getNumParams())
1368 return Error("Invalid INVOKE record");
1369
1370 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1371
1372 SmallVector<Value*, 16> Ops;
1373 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1374 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1375 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1376 }
1377
1378 if (!FTy->isVarArg()) {
1379 if (Record.size() != OpNum)
1380 return Error("Invalid INVOKE record");
1381 } else {
1382 // Read type/value pairs for varargs params.
1383 while (OpNum != Record.size()) {
1384 Value *Op;
1385 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1386 return Error("Invalid INVOKE record");
1387 Ops.push_back(Op);
1388 }
1389 }
1390
1391 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1392 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1393 break;
1394 }
1395 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1396 I = new UnwindInst();
1397 break;
1398 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1399 I = new UnreachableInst();
1400 break;
1401 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1402 if (Record.size() < 1 || ((Record.size()-1)&1))
1403 return Error("Invalid PHI record");
1404 const Type *Ty = getTypeByID(Record[0]);
1405 if (!Ty) return Error("Invalid PHI record");
1406
1407 PHINode *PN = new PHINode(Ty);
1408 PN->reserveOperandSpace(Record.size()-1);
1409
1410 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1411 Value *V = getFnValueByID(Record[1+i], Ty);
1412 BasicBlock *BB = getBasicBlock(Record[2+i]);
1413 if (!V || !BB) return Error("Invalid PHI record");
1414 PN->addIncoming(V, BB);
1415 }
1416 I = PN;
1417 break;
1418 }
1419
1420 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1421 if (Record.size() < 3)
1422 return Error("Invalid MALLOC record");
1423 const PointerType *Ty =
1424 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1425 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1426 unsigned Align = Record[2];
1427 if (!Ty || !Size) return Error("Invalid MALLOC record");
1428 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1429 break;
1430 }
1431 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1432 unsigned OpNum = 0;
1433 Value *Op;
1434 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1435 OpNum != Record.size())
1436 return Error("Invalid FREE record");
1437 I = new FreeInst(Op);
1438 break;
1439 }
1440 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1441 if (Record.size() < 3)
1442 return Error("Invalid ALLOCA record");
1443 const PointerType *Ty =
1444 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1445 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1446 unsigned Align = Record[2];
1447 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1448 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1449 break;
1450 }
1451 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1452 unsigned OpNum = 0;
1453 Value *Op;
1454 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1455 OpNum+2 != Record.size())
1456 return Error("Invalid LOAD record");
1457
1458 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1459 break;
1460 }
1461 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1462 unsigned OpNum = 0;
1463 Value *Val, *Ptr;
1464 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1465 getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1466 OpNum+2 != Record.size())
1467 return Error("Invalid STORE record");
1468
1469 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1470 break;
1471 }
1472 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1473 if (Record.size() < 2)
1474 return Error("Invalid CALL record");
1475
1476 unsigned CCInfo = Record[1];
1477
1478 unsigned OpNum = 2;
1479 Value *Callee;
1480 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1481 return Error("Invalid CALL record");
1482
1483 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1484 const FunctionType *FTy = 0;
1485 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1486 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1487 return Error("Invalid CALL record");
1488
1489 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1490
1491 SmallVector<Value*, 16> Args;
1492 // Read the fixed params.
1493 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1494 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1495 if (Args.back() == 0) return Error("Invalid CALL record");
1496 }
1497
1498 // Read type/value pairs for varargs params.
1499 if (!FTy->isVarArg()) {
1500 if (OpNum != Record.size())
1501 return Error("Invalid CALL record");
1502 } else {
1503 while (OpNum != Record.size()) {
1504 Value *Op;
1505 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1506 return Error("Invalid CALL record");
1507 Args.push_back(Op);
1508 }
1509 }
1510
David Greeneb1c4a7b2007-08-01 03:43:44 +00001511 I = new CallInst(Callee, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1513 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1514 break;
1515 }
1516 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1517 if (Record.size() < 3)
1518 return Error("Invalid VAARG record");
1519 const Type *OpTy = getTypeByID(Record[0]);
1520 Value *Op = getFnValueByID(Record[1], OpTy);
1521 const Type *ResTy = getTypeByID(Record[2]);
1522 if (!OpTy || !Op || !ResTy)
1523 return Error("Invalid VAARG record");
1524 I = new VAArgInst(Op, ResTy);
1525 break;
1526 }
1527 }
1528
1529 // Add instruction to end of current BB. If there is no current BB, reject
1530 // this file.
1531 if (CurBB == 0) {
1532 delete I;
1533 return Error("Invalid instruction with no BB");
1534 }
1535 CurBB->getInstList().push_back(I);
1536
1537 // If this was a terminator instruction, move to the next block.
1538 if (isa<TerminatorInst>(I)) {
1539 ++CurBBNo;
1540 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1541 }
1542
1543 // Non-void values get registered in the value table for future use.
1544 if (I && I->getType() != Type::VoidTy)
1545 ValueList.AssignValue(I, NextValueNo++);
1546 }
1547
1548 // Check the function list for unresolved values.
1549 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1550 if (A->getParent() == 0) {
1551 // We found at least one unresolved value. Nuke them all to avoid leaks.
1552 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1553 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1554 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1555 delete A;
1556 }
1557 }
1558 return Error("Never resolved value found in function!");
1559 }
1560 }
1561
1562 // Trim the value list down to the size it was before we parsed this function.
1563 ValueList.shrinkTo(ModuleValueListSize);
1564 std::vector<BasicBlock*>().swap(FunctionBBs);
1565
1566 return false;
1567}
1568
1569//===----------------------------------------------------------------------===//
1570// ModuleProvider implementation
1571//===----------------------------------------------------------------------===//
1572
1573
1574bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1575 // If it already is material, ignore the request.
1576 if (!F->hasNotBeenReadFromBitcode()) return false;
1577
1578 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1579 DeferredFunctionInfo.find(F);
1580 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1581
1582 // Move the bit stream to the saved position of the deferred function body and
1583 // restore the real linkage type for the function.
1584 Stream.JumpToBit(DFII->second.first);
1585 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1586
1587 if (ParseFunctionBody(F)) {
1588 if (ErrInfo) *ErrInfo = ErrorString;
1589 return true;
1590 }
1591
1592 return false;
1593}
1594
1595void BitcodeReader::dematerializeFunction(Function *F) {
1596 // If this function isn't materialized, or if it is a proto, this is a noop.
1597 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1598 return;
1599
1600 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1601
1602 // Just forget the function body, we can remat it later.
1603 F->deleteBody();
1604 F->setLinkage(GlobalValue::GhostLinkage);
1605}
1606
1607
1608Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1609 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1610 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1611 ++I) {
1612 Function *F = I->first;
1613 if (F->hasNotBeenReadFromBitcode() &&
1614 materializeFunction(F, ErrInfo))
1615 return 0;
1616 }
1617 return TheModule;
1618}
1619
1620
1621/// This method is provided by the parent ModuleProvde class and overriden
1622/// here. It simply releases the module from its provided and frees up our
1623/// state.
1624/// @brief Release our hold on the generated module
1625Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1626 // Since we're losing control of this Module, we must hand it back complete
1627 Module *M = ModuleProvider::releaseModule(ErrInfo);
1628 FreeState();
1629 return M;
1630}
1631
1632
1633//===----------------------------------------------------------------------===//
1634// External interface
1635//===----------------------------------------------------------------------===//
1636
1637/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1638///
1639ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1640 std::string *ErrMsg) {
1641 BitcodeReader *R = new BitcodeReader(Buffer);
1642 if (R->ParseBitcode()) {
1643 if (ErrMsg)
1644 *ErrMsg = R->getErrorString();
1645
1646 // Don't let the BitcodeReader dtor delete 'Buffer'.
1647 R->releaseMemoryBuffer();
1648 delete R;
1649 return 0;
1650 }
1651 return R;
1652}
1653
1654/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1655/// If an error occurs, return null and fill in *ErrMsg if non-null.
1656Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1657 BitcodeReader *R;
1658 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1659 if (!R) return 0;
1660
1661 // Read in the entire module.
1662 Module *M = R->materializeModule(ErrMsg);
1663
1664 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1665 // there was an error.
1666 R->releaseMemoryBuffer();
1667
1668 // If there was no error, tell ModuleProvider not to delete it when its dtor
1669 // is run.
1670 if (M)
1671 M = R->releaseModule(ErrMsg);
1672
1673 delete R;
1674 return M;
1675}