1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitcodeReader class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "BitcodeReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ParameterAttributes.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/MemoryBuffer.h"
26 BitcodeReader::~BitcodeReader() {
30 //===----------------------------------------------------------------------===//
31 // Helper functions to implement forward reference resolution, etc.
32 //===----------------------------------------------------------------------===//
34 /// ConvertToString - Convert a string from a record into an std::string, return
36 template<typename StrTy>
37 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
39 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
42 for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
43 Result += (char)Record[Idx+i+1];
47 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
49 default: // Map unknown/new linkages to external
50 case 0: return GlobalValue::ExternalLinkage;
51 case 1: return GlobalValue::WeakLinkage;
52 case 2: return GlobalValue::AppendingLinkage;
53 case 3: return GlobalValue::InternalLinkage;
54 case 4: return GlobalValue::LinkOnceLinkage;
55 case 5: return GlobalValue::DLLImportLinkage;
56 case 6: return GlobalValue::DLLExportLinkage;
57 case 7: return GlobalValue::ExternalWeakLinkage;
61 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
63 default: // Map unknown visibilities to default.
64 case 0: return GlobalValue::DefaultVisibility;
65 case 1: return GlobalValue::HiddenVisibility;
66 case 2: return GlobalValue::ProtectedVisibility;
70 static int GetDecodedCastOpcode(unsigned Val) {
73 case bitc::CAST_TRUNC : return Instruction::Trunc;
74 case bitc::CAST_ZEXT : return Instruction::ZExt;
75 case bitc::CAST_SEXT : return Instruction::SExt;
76 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
77 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
78 case bitc::CAST_UITOFP : return Instruction::UIToFP;
79 case bitc::CAST_SITOFP : return Instruction::SIToFP;
80 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
81 case bitc::CAST_FPEXT : return Instruction::FPExt;
82 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
83 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
84 case bitc::CAST_BITCAST : return Instruction::BitCast;
87 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
90 case bitc::BINOP_ADD: return Instruction::Add;
91 case bitc::BINOP_SUB: return Instruction::Sub;
92 case bitc::BINOP_MUL: return Instruction::Mul;
93 case bitc::BINOP_UDIV: return Instruction::UDiv;
94 case bitc::BINOP_SDIV:
95 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
96 case bitc::BINOP_UREM: return Instruction::URem;
97 case bitc::BINOP_SREM:
98 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
99 case bitc::BINOP_SHL: return Instruction::Shl;
100 case bitc::BINOP_LSHR: return Instruction::LShr;
101 case bitc::BINOP_ASHR: return Instruction::AShr;
102 case bitc::BINOP_AND: return Instruction::And;
103 case bitc::BINOP_OR: return Instruction::Or;
104 case bitc::BINOP_XOR: return Instruction::Xor;
110 /// @brief A class for maintaining the slot number definition
111 /// as a placeholder for the actual definition for forward constants defs.
112 class ConstantPlaceHolder : public ConstantExpr {
113 ConstantPlaceHolder(); // DO NOT IMPLEMENT
114 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
117 ConstantPlaceHolder(const Type *Ty)
118 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
119 Op(UndefValue::get(Type::Int32Ty), this) {
124 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
127 // Insert a bunch of null values.
129 OperandList = &Uses[0];
133 if (Value *V = Uses[Idx]) {
134 assert(Ty == V->getType() && "Type mismatch in constant table!");
135 return cast<Constant>(V);
138 // Create and return a placeholder, which will later be RAUW'd.
139 Constant *C = new ConstantPlaceHolder(Ty);
140 Uses[Idx].init(C, this);
144 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
146 // Insert a bunch of null values.
148 OperandList = &Uses[0];
152 if (Value *V = Uses[Idx]) {
153 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
157 // No type specified, must be invalid reference.
158 if (Ty == 0) return 0;
160 // Create and return a placeholder, which will later be RAUW'd.
161 Value *V = new Argument(Ty);
162 Uses[Idx].init(V, this);
167 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
168 // If the TypeID is in range, return it.
169 if (ID < TypeList.size())
170 return TypeList[ID].get();
171 if (!isTypeTable) return 0;
173 // The type table allows forward references. Push as many Opaque types as
174 // needed to get up to ID.
175 while (TypeList.size() <= ID)
176 TypeList.push_back(OpaqueType::get());
177 return TypeList.back().get();
180 //===----------------------------------------------------------------------===//
181 // Functions for parsing blocks from the bitcode file
182 //===----------------------------------------------------------------------===//
184 bool BitcodeReader::ParseParamAttrBlock() {
185 if (Stream.EnterSubBlock())
186 return Error("Malformed block record");
188 if (!ParamAttrs.empty())
189 return Error("Multiple PARAMATTR blocks found!");
191 SmallVector<uint64_t, 64> Record;
193 ParamAttrsVector Attrs;
195 // Read all the records.
197 unsigned Code = Stream.ReadCode();
198 if (Code == bitc::END_BLOCK) {
199 if (Stream.ReadBlockEnd())
200 return Error("Error at end of PARAMATTR block");
204 if (Code == bitc::ENTER_SUBBLOCK) {
205 // No known subblocks, always skip them.
206 Stream.ReadSubBlockID();
207 if (Stream.SkipBlock())
208 return Error("Malformed block record");
212 if (Code == bitc::DEFINE_ABBREV) {
213 Stream.ReadAbbrevRecord();
219 switch (Stream.ReadRecord(Code, Record)) {
220 default: // Default behavior: ignore.
222 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
223 if (Record.size() & 1)
224 return Error("Invalid ENTRY record");
226 ParamAttrsWithIndex PAWI;
227 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
228 PAWI.index = Record[i];
229 PAWI.attrs = Record[i+1];
230 Attrs.push_back(PAWI);
232 ParamAttrs.push_back(ParamAttrsList::get(Attrs));
241 bool BitcodeReader::ParseTypeTable() {
242 if (Stream.EnterSubBlock())
243 return Error("Malformed block record");
245 if (!TypeList.empty())
246 return Error("Multiple TYPE_BLOCKs found!");
248 SmallVector<uint64_t, 64> Record;
249 unsigned NumRecords = 0;
251 // Read all the records for this type table.
253 unsigned Code = Stream.ReadCode();
254 if (Code == bitc::END_BLOCK) {
255 if (NumRecords != TypeList.size())
256 return Error("Invalid type forward reference in TYPE_BLOCK");
257 if (Stream.ReadBlockEnd())
258 return Error("Error at end of type table block");
262 if (Code == bitc::ENTER_SUBBLOCK) {
263 // No known subblocks, always skip them.
264 Stream.ReadSubBlockID();
265 if (Stream.SkipBlock())
266 return Error("Malformed block record");
270 if (Code == bitc::DEFINE_ABBREV) {
271 Stream.ReadAbbrevRecord();
277 const Type *ResultTy = 0;
278 switch (Stream.ReadRecord(Code, Record)) {
279 default: // Default behavior: unknown type.
282 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
283 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
284 // type list. This allows us to reserve space.
285 if (Record.size() < 1)
286 return Error("Invalid TYPE_CODE_NUMENTRY record");
287 TypeList.reserve(Record[0]);
289 case bitc::TYPE_CODE_VOID: // VOID
290 ResultTy = Type::VoidTy;
292 case bitc::TYPE_CODE_FLOAT: // FLOAT
293 ResultTy = Type::FloatTy;
295 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
296 ResultTy = Type::DoubleTy;
298 case bitc::TYPE_CODE_LABEL: // LABEL
299 ResultTy = Type::LabelTy;
301 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
304 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
305 if (Record.size() < 1)
306 return Error("Invalid Integer type record");
308 ResultTy = IntegerType::get(Record[0]);
310 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
311 if (Record.size() < 1)
312 return Error("Invalid POINTER type record");
313 ResultTy = PointerType::get(getTypeByID(Record[0], true));
315 case bitc::TYPE_CODE_FUNCTION: {
316 // FUNCTION: [vararg, attrid, retty, #pararms, paramty N]
317 if (Record.size() < 4 || Record.size() < Record[3]+4)
318 return Error("Invalid FUNCTION type record");
319 std::vector<const Type*> ArgTys;
320 for (unsigned i = 0, e = Record[3]; i != e; ++i)
321 ArgTys.push_back(getTypeByID(Record[4+i], true));
323 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
324 Record[0], getParamAttrs(Record[1]));
327 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
328 if (Record.size() < 2 || Record.size() < Record[1]+2)
329 return Error("Invalid STRUCT type record");
330 std::vector<const Type*> EltTys;
331 for (unsigned i = 0, e = Record[1]; i != e; ++i)
332 EltTys.push_back(getTypeByID(Record[2+i], true));
333 ResultTy = StructType::get(EltTys, Record[0]);
336 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
337 if (Record.size() < 2)
338 return Error("Invalid ARRAY type record");
339 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
341 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
342 if (Record.size() < 2)
343 return Error("Invalid VECTOR type record");
344 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
348 if (NumRecords == TypeList.size()) {
349 // If this is a new type slot, just append it.
350 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
352 } else if (ResultTy == 0) {
353 // Otherwise, this was forward referenced, so an opaque type was created,
354 // but the result type is actually just an opaque. Leave the one we
355 // created previously.
358 // Otherwise, this was forward referenced, so an opaque type was created.
359 // Resolve the opaque type to the real type now.
360 assert(NumRecords < TypeList.size() && "Typelist imbalance");
361 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
363 // Don't directly push the new type on the Tab. Instead we want to replace
364 // the opaque type we previously inserted with the new concrete value. The
365 // refinement from the abstract (opaque) type to the new type causes all
366 // uses of the abstract type to use the concrete type (NewTy). This will
367 // also cause the opaque type to be deleted.
368 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
370 // This should have replaced the old opaque type with the new type in the
371 // value table... or with a preexisting type that was already in the
372 // system. Let's just make sure it did.
373 assert(TypeList[NumRecords-1].get() != OldTy &&
374 "refineAbstractType didn't work!");
380 bool BitcodeReader::ParseTypeSymbolTable() {
381 if (Stream.EnterSubBlock())
382 return Error("Malformed block record");
384 SmallVector<uint64_t, 64> Record;
386 // Read all the records for this type table.
387 std::string TypeName;
389 unsigned Code = Stream.ReadCode();
390 if (Code == bitc::END_BLOCK) {
391 if (Stream.ReadBlockEnd())
392 return Error("Error at end of type symbol table block");
396 if (Code == bitc::ENTER_SUBBLOCK) {
397 // No known subblocks, always skip them.
398 Stream.ReadSubBlockID();
399 if (Stream.SkipBlock())
400 return Error("Malformed block record");
404 if (Code == bitc::DEFINE_ABBREV) {
405 Stream.ReadAbbrevRecord();
411 switch (Stream.ReadRecord(Code, Record)) {
412 default: // Default behavior: unknown type.
414 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
415 if (ConvertToString(Record, 1, TypeName))
416 return Error("Invalid TST_ENTRY record");
417 unsigned TypeID = Record[0];
418 if (TypeID >= TypeList.size())
419 return Error("Invalid Type ID in TST_ENTRY record");
421 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
428 bool BitcodeReader::ParseValueSymbolTable() {
429 if (Stream.EnterSubBlock())
430 return Error("Malformed block record");
432 SmallVector<uint64_t, 64> Record;
434 // Read all the records for this value table.
435 SmallString<128> ValueName;
437 unsigned Code = Stream.ReadCode();
438 if (Code == bitc::END_BLOCK) {
439 if (Stream.ReadBlockEnd())
440 return Error("Error at end of value symbol table block");
443 if (Code == bitc::ENTER_SUBBLOCK) {
444 // No known subblocks, always skip them.
445 Stream.ReadSubBlockID();
446 if (Stream.SkipBlock())
447 return Error("Malformed block record");
451 if (Code == bitc::DEFINE_ABBREV) {
452 Stream.ReadAbbrevRecord();
458 switch (Stream.ReadRecord(Code, Record)) {
459 default: // Default behavior: unknown type.
461 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namelen, namechar x N]
462 if (ConvertToString(Record, 1, ValueName))
463 return Error("Invalid TST_ENTRY record");
464 unsigned ValueID = Record[0];
465 if (ValueID >= ValueList.size())
466 return Error("Invalid Value ID in VST_ENTRY record");
467 Value *V = ValueList[ValueID];
469 V->setName(&ValueName[0], ValueName.size());
473 case bitc::VST_CODE_BBENTRY: {
474 if (ConvertToString(Record, 1, ValueName))
475 return Error("Invalid VST_BBENTRY record");
476 BasicBlock *BB = getBasicBlock(Record[0]);
478 return Error("Invalid BB ID in VST_BBENTRY record");
480 BB->setName(&ValueName[0], ValueName.size());
488 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
489 /// the LSB for dense VBR encoding.
490 static uint64_t DecodeSignRotatedValue(uint64_t V) {
495 // There is no such thing as -0 with integers. "-0" really means MININT.
499 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
500 /// values and aliases that we can.
501 bool BitcodeReader::ResolveGlobalAndAliasInits() {
502 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
503 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
505 GlobalInitWorklist.swap(GlobalInits);
506 AliasInitWorklist.swap(AliasInits);
508 while (!GlobalInitWorklist.empty()) {
509 unsigned ValID = GlobalInitWorklist.back().second;
510 if (ValID >= ValueList.size()) {
511 // Not ready to resolve this yet, it requires something later in the file.
512 GlobalInits.push_back(GlobalInitWorklist.back());
514 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
515 GlobalInitWorklist.back().first->setInitializer(C);
517 return Error("Global variable initializer is not a constant!");
519 GlobalInitWorklist.pop_back();
522 while (!AliasInitWorklist.empty()) {
523 unsigned ValID = AliasInitWorklist.back().second;
524 if (ValID >= ValueList.size()) {
525 AliasInits.push_back(AliasInitWorklist.back());
527 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
528 AliasInitWorklist.back().first->setAliasee(C);
530 return Error("Alias initializer is not a constant!");
532 AliasInitWorklist.pop_back();
538 bool BitcodeReader::ParseConstants() {
539 if (Stream.EnterSubBlock())
540 return Error("Malformed block record");
542 SmallVector<uint64_t, 64> Record;
544 // Read all the records for this value table.
545 const Type *CurTy = Type::Int32Ty;
546 unsigned NextCstNo = ValueList.size();
548 unsigned Code = Stream.ReadCode();
549 if (Code == bitc::END_BLOCK) {
550 if (NextCstNo != ValueList.size())
551 return Error("Invalid constant reference!");
553 if (Stream.ReadBlockEnd())
554 return Error("Error at end of constants block");
558 if (Code == bitc::ENTER_SUBBLOCK) {
559 // No known subblocks, always skip them.
560 Stream.ReadSubBlockID();
561 if (Stream.SkipBlock())
562 return Error("Malformed block record");
566 if (Code == bitc::DEFINE_ABBREV) {
567 Stream.ReadAbbrevRecord();
574 switch (Stream.ReadRecord(Code, Record)) {
575 default: // Default behavior: unknown constant
576 case bitc::CST_CODE_UNDEF: // UNDEF
577 V = UndefValue::get(CurTy);
579 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
581 return Error("Malformed CST_SETTYPE record");
582 if (Record[0] >= TypeList.size())
583 return Error("Invalid Type ID in CST_SETTYPE record");
584 CurTy = TypeList[Record[0]];
585 continue; // Skip the ValueList manipulation.
586 case bitc::CST_CODE_NULL: // NULL
587 V = Constant::getNullValue(CurTy);
589 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
590 if (!isa<IntegerType>(CurTy) || Record.empty())
591 return Error("Invalid CST_INTEGER record");
592 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
594 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
595 if (!isa<IntegerType>(CurTy) || Record.empty() ||
596 Record.size() < Record[0]+1)
597 return Error("Invalid WIDE_INTEGER record");
599 unsigned NumWords = Record[0];
600 SmallVector<uint64_t, 8> Words;
601 Words.resize(NumWords);
602 for (unsigned i = 0; i != NumWords; ++i)
603 Words[i] = DecodeSignRotatedValue(Record[i+1]);
604 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
605 NumWords, &Words[0]));
608 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
610 return Error("Invalid FLOAT record");
611 if (CurTy == Type::FloatTy)
612 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
613 else if (CurTy == Type::DoubleTy)
614 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
616 V = UndefValue::get(CurTy);
619 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
620 if (Record.empty() || Record.size() < Record[0]+1)
621 return Error("Invalid CST_AGGREGATE record");
623 unsigned Size = Record[0];
624 std::vector<Constant*> Elts;
626 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
627 for (unsigned i = 0; i != Size; ++i)
628 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
629 STy->getElementType(i)));
630 V = ConstantStruct::get(STy, Elts);
631 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
632 const Type *EltTy = ATy->getElementType();
633 for (unsigned i = 0; i != Size; ++i)
634 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
635 V = ConstantArray::get(ATy, Elts);
636 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
637 const Type *EltTy = VTy->getElementType();
638 for (unsigned i = 0; i != Size; ++i)
639 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
640 V = ConstantVector::get(Elts);
642 V = UndefValue::get(CurTy);
647 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
648 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
649 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
651 V = UndefValue::get(CurTy); // Unknown binop.
653 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
654 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
655 V = ConstantExpr::get(Opc, LHS, RHS);
659 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
660 if (Record.size() < 3) return Error("Invalid CE_CAST record");
661 int Opc = GetDecodedCastOpcode(Record[0]);
663 V = UndefValue::get(CurTy); // Unknown cast.
665 const Type *OpTy = getTypeByID(Record[1]);
666 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
667 V = ConstantExpr::getCast(Opc, Op, CurTy);
671 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
672 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
673 SmallVector<Constant*, 16> Elts;
674 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
675 const Type *ElTy = getTypeByID(Record[i]);
676 if (!ElTy) return Error("Invalid CE_GEP record");
677 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
679 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
682 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
683 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
684 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
686 ValueList.getConstantFwdRef(Record[1],CurTy),
687 ValueList.getConstantFwdRef(Record[2],CurTy));
689 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
690 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
691 const VectorType *OpTy =
692 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
693 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
694 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
695 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
696 OpTy->getElementType());
697 V = ConstantExpr::getExtractElement(Op0, Op1);
700 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
701 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
702 if (Record.size() < 3 || OpTy == 0)
703 return Error("Invalid CE_INSERTELT record");
704 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
705 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
706 OpTy->getElementType());
707 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
708 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
711 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
712 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
713 if (Record.size() < 3 || OpTy == 0)
714 return Error("Invalid CE_INSERTELT record");
715 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
716 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
717 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
718 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
719 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
722 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
723 if (Record.size() < 4) return Error("Invalid CE_CMP record");
724 const Type *OpTy = getTypeByID(Record[0]);
725 if (OpTy == 0) return Error("Invalid CE_CMP record");
726 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
727 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
729 if (OpTy->isFloatingPoint())
730 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
732 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
737 ValueList.AssignValue(V, NextCstNo);
742 /// RememberAndSkipFunctionBody - When we see the block for a function body,
743 /// remember where it is and then skip it. This lets us lazily deserialize the
745 bool BitcodeReader::RememberAndSkipFunctionBody() {
746 // Get the function we are talking about.
747 if (FunctionsWithBodies.empty())
748 return Error("Insufficient function protos");
750 Function *Fn = FunctionsWithBodies.back();
751 FunctionsWithBodies.pop_back();
753 // Save the current stream state.
754 uint64_t CurBit = Stream.GetCurrentBitNo();
755 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
757 // Set the functions linkage to GhostLinkage so we know it is lazily
759 Fn->setLinkage(GlobalValue::GhostLinkage);
761 // Skip over the function block for now.
762 if (Stream.SkipBlock())
763 return Error("Malformed block record");
767 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
768 // Reject multiple MODULE_BLOCK's in a single bitstream.
770 return Error("Multiple MODULE_BLOCKs in same stream");
772 if (Stream.EnterSubBlock())
773 return Error("Malformed block record");
775 // Otherwise, create the module.
776 TheModule = new Module(ModuleID);
778 SmallVector<uint64_t, 64> Record;
779 std::vector<std::string> SectionTable;
781 // Read all the records for this module.
782 while (!Stream.AtEndOfStream()) {
783 unsigned Code = Stream.ReadCode();
784 if (Code == bitc::END_BLOCK) {
785 if (Stream.ReadBlockEnd())
786 return Error("Error at end of module block");
788 // Patch the initializers for globals and aliases up.
789 ResolveGlobalAndAliasInits();
790 if (!GlobalInits.empty() || !AliasInits.empty())
791 return Error("Malformed global initializer set");
792 if (!FunctionsWithBodies.empty())
793 return Error("Too few function bodies found");
795 // Force deallocation of memory for these vectors to favor the client that
796 // want lazy deserialization.
797 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
798 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
799 std::vector<Function*>().swap(FunctionsWithBodies);
803 if (Code == bitc::ENTER_SUBBLOCK) {
804 switch (Stream.ReadSubBlockID()) {
805 default: // Skip unknown content.
806 if (Stream.SkipBlock())
807 return Error("Malformed block record");
809 case bitc::PARAMATTR_BLOCK_ID:
810 if (ParseParamAttrBlock())
813 case bitc::TYPE_BLOCK_ID:
814 if (ParseTypeTable())
817 case bitc::TYPE_SYMTAB_BLOCK_ID:
818 if (ParseTypeSymbolTable())
821 case bitc::VALUE_SYMTAB_BLOCK_ID:
822 if (ParseValueSymbolTable())
825 case bitc::CONSTANTS_BLOCK_ID:
826 if (ParseConstants() || ResolveGlobalAndAliasInits())
829 case bitc::FUNCTION_BLOCK_ID:
830 // If this is the first function body we've seen, reverse the
831 // FunctionsWithBodies list.
832 if (!HasReversedFunctionsWithBodies) {
833 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
834 HasReversedFunctionsWithBodies = true;
837 if (RememberAndSkipFunctionBody())
844 if (Code == bitc::DEFINE_ABBREV) {
845 Stream.ReadAbbrevRecord();
850 switch (Stream.ReadRecord(Code, Record)) {
851 default: break; // Default behavior, ignore unknown content.
852 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
853 if (Record.size() < 1)
854 return Error("Malformed MODULE_CODE_VERSION");
855 // Only version #0 is supported so far.
857 return Error("Unknown bitstream version!");
859 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
861 if (ConvertToString(Record, 0, S))
862 return Error("Invalid MODULE_CODE_TRIPLE record");
863 TheModule->setTargetTriple(S);
866 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
868 if (ConvertToString(Record, 0, S))
869 return Error("Invalid MODULE_CODE_DATALAYOUT record");
870 TheModule->setDataLayout(S);
873 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
875 if (ConvertToString(Record, 0, S))
876 return Error("Invalid MODULE_CODE_ASM record");
877 TheModule->setModuleInlineAsm(S);
880 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
882 if (ConvertToString(Record, 0, S))
883 return Error("Invalid MODULE_CODE_DEPLIB record");
884 TheModule->addLibrary(S);
887 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
889 if (ConvertToString(Record, 0, S))
890 return Error("Invalid MODULE_CODE_SECTIONNAME record");
891 SectionTable.push_back(S);
894 // GLOBALVAR: [type, isconst, initid,
895 // linkage, alignment, section, visibility, threadlocal]
896 case bitc::MODULE_CODE_GLOBALVAR: {
897 if (Record.size() < 6)
898 return Error("Invalid MODULE_CODE_GLOBALVAR record");
899 const Type *Ty = getTypeByID(Record[0]);
900 if (!isa<PointerType>(Ty))
901 return Error("Global not a pointer type!");
902 Ty = cast<PointerType>(Ty)->getElementType();
904 bool isConstant = Record[1];
905 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
906 unsigned Alignment = (1 << Record[4]) >> 1;
909 if (Record[5]-1 >= SectionTable.size())
910 return Error("Invalid section ID");
911 Section = SectionTable[Record[5]-1];
913 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
914 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
915 bool isThreadLocal = false;
916 if (Record.size() >= 7) isThreadLocal = Record[7];
918 GlobalVariable *NewGV =
919 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
920 NewGV->setAlignment(Alignment);
921 if (!Section.empty())
922 NewGV->setSection(Section);
923 NewGV->setVisibility(Visibility);
924 NewGV->setThreadLocal(isThreadLocal);
926 ValueList.push_back(NewGV);
928 // Remember which value to use for the global initializer.
929 if (unsigned InitID = Record[2])
930 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
933 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
935 case bitc::MODULE_CODE_FUNCTION: {
936 if (Record.size() < 7)
937 return Error("Invalid MODULE_CODE_FUNCTION record");
938 const Type *Ty = getTypeByID(Record[0]);
939 if (!isa<PointerType>(Ty))
940 return Error("Function not a pointer type!");
941 const FunctionType *FTy =
942 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
944 return Error("Function not a pointer to function type!");
946 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
949 Func->setCallingConv(Record[1]);
950 bool isProto = Record[2];
951 Func->setLinkage(GetDecodedLinkage(Record[3]));
952 Func->setAlignment((1 << Record[4]) >> 1);
954 if (Record[5]-1 >= SectionTable.size())
955 return Error("Invalid section ID");
956 Func->setSection(SectionTable[Record[5]-1]);
958 Func->setVisibility(GetDecodedVisibility(Record[6]));
960 ValueList.push_back(Func);
962 // If this is a function with a body, remember the prototype we are
963 // creating now, so that we can match up the body with them later.
965 FunctionsWithBodies.push_back(Func);
968 // ALIAS: [alias type, aliasee val#, linkage]
969 case bitc::MODULE_CODE_ALIAS: {
970 if (Record.size() < 3)
971 return Error("Invalid MODULE_ALIAS record");
972 const Type *Ty = getTypeByID(Record[0]);
973 if (!isa<PointerType>(Ty))
974 return Error("Function not a pointer type!");
976 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
978 ValueList.push_back(NewGA);
979 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
982 /// MODULE_CODE_PURGEVALS: [numvals]
983 case bitc::MODULE_CODE_PURGEVALS:
984 // Trim down the value list to the specified size.
985 if (Record.size() < 1 || Record[0] > ValueList.size())
986 return Error("Invalid MODULE_PURGEVALS record");
987 ValueList.shrinkTo(Record[0]);
993 return Error("Premature end of bitstream");
997 bool BitcodeReader::ParseBitcode() {
1000 if (Buffer->getBufferSize() & 3)
1001 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1003 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1004 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1006 // Sniff for the signature.
1007 if (Stream.Read(8) != 'B' ||
1008 Stream.Read(8) != 'C' ||
1009 Stream.Read(4) != 0x0 ||
1010 Stream.Read(4) != 0xC ||
1011 Stream.Read(4) != 0xE ||
1012 Stream.Read(4) != 0xD)
1013 return Error("Invalid bitcode signature");
1015 // We expect a number of well-defined blocks, though we don't necessarily
1016 // need to understand them all.
1017 while (!Stream.AtEndOfStream()) {
1018 unsigned Code = Stream.ReadCode();
1020 if (Code != bitc::ENTER_SUBBLOCK)
1021 return Error("Invalid record at top-level");
1023 unsigned BlockID = Stream.ReadSubBlockID();
1025 // We only know the MODULE subblock ID.
1026 if (BlockID == bitc::MODULE_BLOCK_ID) {
1027 if (ParseModule(Buffer->getBufferIdentifier()))
1029 } else if (Stream.SkipBlock()) {
1030 return Error("Malformed block record");
1038 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1039 // If it already is material, ignore the request.
1040 if (!F->hasNotBeenReadFromBytecode()) return false;
1042 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1043 DeferredFunctionInfo.find(F);
1044 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1046 // Move the bit stream to the saved position of the deferred function body and
1047 // restore the real linkage type for the function.
1048 Stream.JumpToBit(DFII->second.first);
1049 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1050 DeferredFunctionInfo.erase(DFII);
1052 if (ParseFunctionBody(F)) {
1053 if (ErrInfo) *ErrInfo = ErrorString;
1060 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1061 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1062 DeferredFunctionInfo.begin();
1063 while (!DeferredFunctionInfo.empty()) {
1064 Function *F = (*I++).first;
1065 assert(F->hasNotBeenReadFromBytecode() &&
1066 "Deserialized function found in map!");
1067 if (materializeFunction(F, ErrInfo))
1074 /// ParseFunctionBody - Lazily parse the specified function body block.
1075 bool BitcodeReader::ParseFunctionBody(Function *F) {
1076 if (Stream.EnterSubBlock())
1077 return Error("Malformed block record");
1079 unsigned ModuleValueListSize = ValueList.size();
1081 // Add all the function arguments to the value table.
1082 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1083 ValueList.push_back(I);
1085 unsigned NextValueNo = ValueList.size();
1086 BasicBlock *CurBB = 0;
1087 unsigned CurBBNo = 0;
1089 // Read all the records.
1090 SmallVector<uint64_t, 64> Record;
1092 unsigned Code = Stream.ReadCode();
1093 if (Code == bitc::END_BLOCK) {
1094 if (Stream.ReadBlockEnd())
1095 return Error("Error at end of function block");
1099 if (Code == bitc::ENTER_SUBBLOCK) {
1100 switch (Stream.ReadSubBlockID()) {
1101 default: // Skip unknown content.
1102 if (Stream.SkipBlock())
1103 return Error("Malformed block record");
1105 case bitc::CONSTANTS_BLOCK_ID:
1106 if (ParseConstants()) return true;
1107 NextValueNo = ValueList.size();
1109 case bitc::VALUE_SYMTAB_BLOCK_ID:
1110 if (ParseValueSymbolTable()) return true;
1116 if (Code == bitc::DEFINE_ABBREV) {
1117 Stream.ReadAbbrevRecord();
1124 switch (Stream.ReadRecord(Code, Record)) {
1125 default: // Default behavior: reject
1126 return Error("Unknown instruction");
1127 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1128 if (Record.size() < 1 || Record[0] == 0)
1129 return Error("Invalid DECLAREBLOCKS record");
1130 // Create all the basic blocks for the function.
1131 FunctionBBs.resize(Record[0]);
1132 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1133 FunctionBBs[i] = new BasicBlock("", F);
1134 CurBB = FunctionBBs[0];
1137 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
1138 if (Record.size() < 4) return Error("Invalid BINOP record");
1139 const Type *Ty = getTypeByID(Record[1]);
1140 int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1141 Value *LHS = getFnValueByID(Record[2], Ty);
1142 Value *RHS = getFnValueByID(Record[3], Ty);
1143 if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1144 return Error("Invalid BINOP record");
1145 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1148 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
1149 if (Record.size() < 4) return Error("Invalid CAST record");
1150 int Opc = GetDecodedCastOpcode(Record[0]);
1151 const Type *ResTy = getTypeByID(Record[1]);
1152 const Type *OpTy = getTypeByID(Record[2]);
1153 Value *Op = getFnValueByID(Record[3], OpTy);
1154 if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1155 return Error("Invalid CAST record");
1156 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1159 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n, n x operands]
1160 if (Record.size() < 2 || (Record.size() & 1))
1161 return Error("Invalid GEP record");
1162 const Type *OpTy = getTypeByID(Record[0]);
1163 Value *Op = getFnValueByID(Record[1], OpTy);
1164 if (OpTy == 0 || Op == 0)
1165 return Error("Invalid GEP record");
1167 SmallVector<Value*, 16> GEPIdx;
1168 for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
1169 const Type *IdxTy = getTypeByID(Record[i*2]);
1170 Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
1171 if (IdxTy == 0 || Idx == 0)
1172 return Error("Invalid GEP record");
1173 GEPIdx.push_back(Idx);
1176 I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
1180 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
1181 if (Record.size() < 4) return Error("Invalid SELECT record");
1182 const Type *Ty = getTypeByID(Record[0]);
1183 Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
1184 Value *LHS = getFnValueByID(Record[2], Ty);
1185 Value *RHS = getFnValueByID(Record[3], Ty);
1186 if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
1187 return Error("Invalid SELECT record");
1188 I = new SelectInst(Cond, LHS, RHS);
1192 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1193 if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
1194 const Type *OpTy = getTypeByID(Record[0]);
1195 Value *Vec = getFnValueByID(Record[1], OpTy);
1196 Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
1197 if (OpTy == 0 || Vec == 0 || Idx == 0)
1198 return Error("Invalid EXTRACTELT record");
1199 I = new ExtractElementInst(Vec, Idx);
1203 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1204 if (Record.size() < 4) return Error("Invalid INSERTELT record");
1205 const VectorType *OpTy =
1206 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1207 if (OpTy == 0) return Error("Invalid INSERTELT record");
1208 Value *Vec = getFnValueByID(Record[1], OpTy);
1209 Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
1210 Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
1211 if (Vec == 0 || Elt == 0 || Idx == 0)
1212 return Error("Invalid INSERTELT record");
1213 I = new InsertElementInst(Vec, Elt, Idx);
1217 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
1218 if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
1219 const VectorType *OpTy =
1220 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1221 if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
1222 Value *Vec1 = getFnValueByID(Record[1], OpTy);
1223 Value *Vec2 = getFnValueByID(Record[2], OpTy);
1224 Value *Mask = getFnValueByID(Record[3],
1225 VectorType::get(Type::Int32Ty,
1226 OpTy->getNumElements()));
1227 if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
1228 return Error("Invalid SHUFFLEVEC record");
1229 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1233 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1234 if (Record.size() < 4) return Error("Invalid CMP record");
1235 const Type *OpTy = getTypeByID(Record[0]);
1236 Value *LHS = getFnValueByID(Record[1], OpTy);
1237 Value *RHS = getFnValueByID(Record[2], OpTy);
1238 if (OpTy == 0 || LHS == 0 || RHS == 0)
1239 return Error("Invalid CMP record");
1240 if (OpTy->isFPOrFPVector())
1241 I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
1243 I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
1247 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1248 if (Record.size() == 0) {
1249 I = new ReturnInst();
1252 if (Record.size() == 2) {
1253 const Type *OpTy = getTypeByID(Record[0]);
1254 Value *Op = getFnValueByID(Record[1], OpTy);
1256 return Error("Invalid RET record");
1257 I = new ReturnInst(Op);
1260 return Error("Invalid RET record");
1261 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1262 if (Record.size() != 1 && Record.size() != 3)
1263 return Error("Invalid BR record");
1264 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1266 return Error("Invalid BR record");
1268 if (Record.size() == 1)
1269 I = new BranchInst(TrueDest);
1271 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1272 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1273 if (FalseDest == 0 || Cond == 0)
1274 return Error("Invalid BR record");
1275 I = new BranchInst(TrueDest, FalseDest, Cond);
1279 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1280 if (Record.size() < 3 || (Record.size() & 1) == 0)
1281 return Error("Invalid SWITCH record");
1282 const Type *OpTy = getTypeByID(Record[0]);
1283 Value *Cond = getFnValueByID(Record[1], OpTy);
1284 BasicBlock *Default = getBasicBlock(Record[2]);
1285 if (OpTy == 0 || Cond == 0 || Default == 0)
1286 return Error("Invalid SWITCH record");
1287 unsigned NumCases = (Record.size()-3)/2;
1288 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1289 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1290 ConstantInt *CaseVal =
1291 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1292 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1293 if (CaseVal == 0 || DestBB == 0) {
1295 return Error("Invalid SWITCH record!");
1297 SI->addCase(CaseVal, DestBB);
1303 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1304 if (Record.size() < 5)
1305 return Error("Invalid INVOKE record");
1306 unsigned CCInfo = Record[0];
1307 const PointerType *CalleeTy =
1308 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
1309 Value *Callee = getFnValueByID(Record[2], CalleeTy);
1310 BasicBlock *NormalBB = getBasicBlock(Record[3]);
1311 BasicBlock *UnwindBB = getBasicBlock(Record[4]);
1312 if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
1313 return Error("Invalid INVOKE record");
1315 const FunctionType *FTy =
1316 dyn_cast<FunctionType>(CalleeTy->getElementType());
1318 // Check that the right number of fixed parameters are here.
1319 if (FTy == 0 || Record.size() < 5+FTy->getNumParams())
1320 return Error("Invalid INVOKE record");
1322 SmallVector<Value*, 16> Ops;
1323 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1324 Ops.push_back(getFnValueByID(Record[5+i], FTy->getParamType(i)));
1325 if (Ops.back() == 0)
1326 return Error("Invalid INVOKE record");
1329 unsigned FirstVarargParam = 5+FTy->getNumParams();
1330 if (FTy->isVarArg()) {
1331 // Read type/value pairs for varargs params.
1332 if ((Record.size()-FirstVarargParam) & 1)
1333 return Error("Invalid INVOKE record");
1335 for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
1336 const Type *ArgTy = getTypeByID(Record[i]);
1337 Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
1338 if (Ops.back() == 0 || ArgTy == 0)
1339 return Error("Invalid INVOKE record");
1342 if (Record.size() != FirstVarargParam)
1343 return Error("Invalid INVOKE record");
1346 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1347 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1350 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1351 I = new UnwindInst();
1353 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1354 I = new UnreachableInst();
1356 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
1357 if (Record.size() < 2 || Record.size() < 2+Record[1] || (Record[1]&1))
1358 return Error("Invalid PHI record");
1359 const Type *Ty = getTypeByID(Record[0]);
1360 if (!Ty) return Error("Invalid PHI record");
1362 PHINode *PN = new PHINode(Ty);
1363 PN->reserveOperandSpace(Record[1]);
1365 for (unsigned i = 0, e = Record[1]; i != e; i += 2) {
1366 Value *V = getFnValueByID(Record[2+i], Ty);
1367 BasicBlock *BB = getBasicBlock(Record[3+i]);
1368 if (!V || !BB) return Error("Invalid PHI record");
1369 PN->addIncoming(V, BB);
1375 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1376 if (Record.size() < 3)
1377 return Error("Invalid MALLOC record");
1378 const PointerType *Ty =
1379 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1380 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1381 unsigned Align = Record[2];
1382 if (!Ty || !Size) return Error("Invalid MALLOC record");
1383 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1386 case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
1387 if (Record.size() < 2)
1388 return Error("Invalid FREE record");
1389 const Type *OpTy = getTypeByID(Record[0]);
1390 Value *Op = getFnValueByID(Record[1], OpTy);
1392 return Error("Invalid FREE record");
1393 I = new FreeInst(Op);
1396 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1397 if (Record.size() < 3)
1398 return Error("Invalid ALLOCA record");
1399 const PointerType *Ty =
1400 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1401 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1402 unsigned Align = Record[2];
1403 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1404 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1407 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1408 if (Record.size() < 4)
1409 return Error("Invalid LOAD record");
1410 const Type *OpTy = getTypeByID(Record[0]);
1411 Value *Op = getFnValueByID(Record[1], OpTy);
1413 return Error("Invalid LOAD record");
1414 I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
1417 case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
1418 if (Record.size() < 5)
1419 return Error("Invalid LOAD record");
1420 const PointerType *OpTy =
1421 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1422 Value *Op = getFnValueByID(Record[1], OpTy ? OpTy->getElementType() : 0);
1423 Value *Ptr = getFnValueByID(Record[2], OpTy);
1424 if (!OpTy || !Op || !Ptr)
1425 return Error("Invalid STORE record");
1426 I = new StoreInst(Op, Ptr, (1 << Record[3]) >> 1, Record[4]);
1429 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1430 if (Record.size() < 3)
1431 return Error("Invalid CALL record");
1432 unsigned CCInfo = Record[0];
1433 const PointerType *OpTy =
1434 dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
1435 const FunctionType *FTy = 0;
1436 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1437 Value *Callee = getFnValueByID(Record[2], OpTy);
1438 if (!FTy || !Callee || Record.size() < FTy->getNumParams()+3)
1439 return Error("Invalid CALL record");
1441 SmallVector<Value*, 16> Args;
1442 // Read the fixed params.
1443 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1444 Args.push_back(getFnValueByID(Record[i+3], FTy->getParamType(i)));
1445 if (Args.back() == 0) return Error("Invalid CALL record");
1449 // Read type/value pairs for varargs params.
1450 unsigned NextArg = FTy->getNumParams()+3;
1451 if (!FTy->isVarArg()) {
1452 if (NextArg != Record.size())
1453 return Error("Invalid CALL record");
1455 if ((Record.size()-NextArg) & 1)
1456 return Error("Invalid CALL record");
1457 for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
1458 Args.push_back(getFnValueByID(Record[NextArg+1],
1459 getTypeByID(Record[NextArg])));
1460 if (Args.back() == 0) return Error("Invalid CALL record");
1464 I = new CallInst(Callee, &Args[0], Args.size());
1465 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1466 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1469 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1470 if (Record.size() < 3)
1471 return Error("Invalid VAARG record");
1472 const Type *OpTy = getTypeByID(Record[0]);
1473 Value *Op = getFnValueByID(Record[1], OpTy);
1474 const Type *ResTy = getTypeByID(Record[2]);
1475 if (!OpTy || !Op || !ResTy)
1476 return Error("Invalid VAARG record");
1477 I = new VAArgInst(Op, ResTy);
1482 // Add instruction to end of current BB. If there is no current BB, reject
1486 return Error("Invalid instruction with no BB");
1488 CurBB->getInstList().push_back(I);
1490 // If this was a terminator instruction, move to the next block.
1491 if (isa<TerminatorInst>(I)) {
1493 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1496 // Non-void values get registered in the value table for future use.
1497 if (I && I->getType() != Type::VoidTy)
1498 ValueList.AssignValue(I, NextValueNo++);
1501 // Check the function list for unresolved values.
1502 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1503 if (A->getParent() == 0) {
1504 // We found at least one unresolved value. Nuke them all to avoid leaks.
1505 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1506 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1507 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1512 return Error("Never resolved value found in function!");
1515 // Trim the value list down to the size it was before we parsed this function.
1516 ValueList.shrinkTo(ModuleValueListSize);
1517 std::vector<BasicBlock*>().swap(FunctionBBs);
1523 //===----------------------------------------------------------------------===//
1524 // External interface
1525 //===----------------------------------------------------------------------===//
1527 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1529 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1530 std::string *ErrMsg) {
1531 BitcodeReader *R = new BitcodeReader(Buffer);
1532 if (R->ParseBitcode()) {
1534 *ErrMsg = R->getErrorString();
1536 // Don't let the BitcodeReader dtor delete 'Buffer'.
1537 R->releaseMemoryBuffer();
1544 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1545 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1546 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1548 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1551 // Read the whole module, get a pointer to it, tell ModuleProvider not to
1552 // delete it when its dtor is run.
1553 Module *M = R->releaseModule(ErrMsg);
1555 // Don't let the BitcodeReader dtor delete 'Buffer'.
1556 R->releaseMemoryBuffer();