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/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"
27 void BitcodeReader::FreeState() {
30 std::vector<PATypeHolder>().swap(TypeList);
32 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
33 std::vector<BasicBlock*>().swap(FunctionBBs);
34 std::vector<Function*>().swap(FunctionsWithBodies);
35 DeferredFunctionInfo.clear();
38 //===----------------------------------------------------------------------===//
39 // Helper functions to implement forward reference resolution, etc.
40 //===----------------------------------------------------------------------===//
42 /// ConvertToString - Convert a string from a record into an std::string, return
44 template<typename StrTy>
45 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
47 if (Idx > Record.size())
50 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
51 Result += (char)Record[i];
55 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned 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;
69 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned 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;
78 static int GetDecodedCastOpcode(unsigned Val) {
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;
95 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
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;
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
125 ConstantPlaceHolder(const Type *Ty)
126 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
127 Op(UndefValue::get(Type::Int32Ty), this) {
132 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
135 // Insert a bunch of null values.
137 OperandList = &Uses[0];
141 if (Value *V = Uses[Idx]) {
142 assert(Ty == V->getType() && "Type mismatch in constant table!");
143 return cast<Constant>(V);
146 // Create and return a placeholder, which will later be RAUW'd.
147 Constant *C = new ConstantPlaceHolder(Ty);
148 Uses[Idx].init(C, this);
152 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
154 // Insert a bunch of null values.
156 OperandList = &Uses[0];
160 if (Value *V = Uses[Idx]) {
161 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
165 // No type specified, must be invalid reference.
166 if (Ty == 0) return 0;
168 // Create and return a placeholder, which will later be RAUW'd.
169 Value *V = new Argument(Ty);
170 Uses[Idx].init(V, this);
175 const 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;
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();
188 //===----------------------------------------------------------------------===//
189 // Functions for parsing blocks from the bitcode file
190 //===----------------------------------------------------------------------===//
192 bool BitcodeReader::ParseParamAttrBlock() {
193 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
194 return Error("Malformed block record");
196 if (!ParamAttrs.empty())
197 return Error("Multiple PARAMATTR blocks found!");
199 SmallVector<uint64_t, 64> Record;
201 ParamAttrsVector Attrs;
203 // Read all the records.
205 unsigned Code = Stream.ReadCode();
206 if (Code == bitc::END_BLOCK) {
207 if (Stream.ReadBlockEnd())
208 return Error("Error at end of PARAMATTR block");
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");
220 if (Code == bitc::DEFINE_ABBREV) {
221 Stream.ReadAbbrevRecord();
227 switch (Stream.ReadRecord(Code, Record)) {
228 default: // Default behavior: ignore.
230 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
231 if (Record.size() & 1)
232 return Error("Invalid ENTRY record");
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);
240 ParamAttrs.push_back(ParamAttrsList::get(Attrs));
249 bool BitcodeReader::ParseTypeTable() {
250 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
251 return Error("Malformed block record");
253 if (!TypeList.empty())
254 return Error("Multiple TYPE_BLOCKs found!");
256 SmallVector<uint64_t, 64> Record;
257 unsigned NumRecords = 0;
259 // Read all the records for this type table.
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");
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");
278 if (Code == bitc::DEFINE_ABBREV) {
279 Stream.ReadAbbrevRecord();
285 const Type *ResultTy = 0;
286 switch (Stream.ReadRecord(Code, Record)) {
287 default: // Default behavior: unknown type.
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]);
297 case bitc::TYPE_CODE_VOID: // VOID
298 ResultTy = Type::VoidTy;
300 case bitc::TYPE_CODE_FLOAT: // FLOAT
301 ResultTy = Type::FloatTy;
303 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
304 ResultTy = Type::DoubleTy;
306 case bitc::TYPE_CODE_LABEL: // LABEL
307 ResultTy = Type::LabelTy;
309 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
312 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
313 if (Record.size() < 1)
314 return Error("Invalid Integer type record");
316 ResultTy = IntegerType::get(Record[0]);
318 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
319 if (Record.size() < 1)
320 return Error("Invalid POINTER type record");
321 ResultTy = PointerType::get(getTypeByID(Record[0], true));
323 case bitc::TYPE_CODE_FUNCTION: {
324 // FUNCTION: [vararg, attrid, retty, paramty x N]
325 if (Record.size() < 3)
326 return Error("Invalid FUNCTION type record");
327 std::vector<const Type*> ArgTys;
328 for (unsigned i = 3, e = Record.size(); i != e; ++i)
329 ArgTys.push_back(getTypeByID(Record[i], true));
331 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
332 Record[0], getParamAttrs(Record[1]));
335 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
336 if (Record.size() < 1)
337 return Error("Invalid STRUCT type record");
338 std::vector<const Type*> EltTys;
339 for (unsigned i = 1, e = Record.size(); i != e; ++i)
340 EltTys.push_back(getTypeByID(Record[i], true));
341 ResultTy = StructType::get(EltTys, Record[0]);
344 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
345 if (Record.size() < 2)
346 return Error("Invalid ARRAY type record");
347 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
349 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
350 if (Record.size() < 2)
351 return Error("Invalid VECTOR type record");
352 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
356 if (NumRecords == TypeList.size()) {
357 // If this is a new type slot, just append it.
358 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
360 } else if (ResultTy == 0) {
361 // Otherwise, this was forward referenced, so an opaque type was created,
362 // but the result type is actually just an opaque. Leave the one we
363 // created previously.
366 // Otherwise, this was forward referenced, so an opaque type was created.
367 // Resolve the opaque type to the real type now.
368 assert(NumRecords < TypeList.size() && "Typelist imbalance");
369 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
371 // Don't directly push the new type on the Tab. Instead we want to replace
372 // the opaque type we previously inserted with the new concrete value. The
373 // refinement from the abstract (opaque) type to the new type causes all
374 // uses of the abstract type to use the concrete type (NewTy). This will
375 // also cause the opaque type to be deleted.
376 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
378 // This should have replaced the old opaque type with the new type in the
379 // value table... or with a preexisting type that was already in the
380 // system. Let's just make sure it did.
381 assert(TypeList[NumRecords-1].get() != OldTy &&
382 "refineAbstractType didn't work!");
388 bool BitcodeReader::ParseTypeSymbolTable() {
389 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
390 return Error("Malformed block record");
392 SmallVector<uint64_t, 64> Record;
394 // Read all the records for this type table.
395 std::string TypeName;
397 unsigned Code = Stream.ReadCode();
398 if (Code == bitc::END_BLOCK) {
399 if (Stream.ReadBlockEnd())
400 return Error("Error at end of type symbol table block");
404 if (Code == bitc::ENTER_SUBBLOCK) {
405 // No known subblocks, always skip them.
406 Stream.ReadSubBlockID();
407 if (Stream.SkipBlock())
408 return Error("Malformed block record");
412 if (Code == bitc::DEFINE_ABBREV) {
413 Stream.ReadAbbrevRecord();
419 switch (Stream.ReadRecord(Code, Record)) {
420 default: // Default behavior: unknown type.
422 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
423 if (ConvertToString(Record, 1, TypeName))
424 return Error("Invalid TST_ENTRY record");
425 unsigned TypeID = Record[0];
426 if (TypeID >= TypeList.size())
427 return Error("Invalid Type ID in TST_ENTRY record");
429 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
436 bool BitcodeReader::ParseValueSymbolTable() {
437 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
438 return Error("Malformed block record");
440 SmallVector<uint64_t, 64> Record;
442 // Read all the records for this value table.
443 SmallString<128> ValueName;
445 unsigned Code = Stream.ReadCode();
446 if (Code == bitc::END_BLOCK) {
447 if (Stream.ReadBlockEnd())
448 return Error("Error at end of value symbol table block");
451 if (Code == bitc::ENTER_SUBBLOCK) {
452 // No known subblocks, always skip them.
453 Stream.ReadSubBlockID();
454 if (Stream.SkipBlock())
455 return Error("Malformed block record");
459 if (Code == bitc::DEFINE_ABBREV) {
460 Stream.ReadAbbrevRecord();
466 switch (Stream.ReadRecord(Code, Record)) {
467 default: // Default behavior: unknown type.
469 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
470 if (ConvertToString(Record, 1, ValueName))
471 return Error("Invalid TST_ENTRY record");
472 unsigned ValueID = Record[0];
473 if (ValueID >= ValueList.size())
474 return Error("Invalid Value ID in VST_ENTRY record");
475 Value *V = ValueList[ValueID];
477 V->setName(&ValueName[0], ValueName.size());
481 case bitc::VST_CODE_BBENTRY: {
482 if (ConvertToString(Record, 1, ValueName))
483 return Error("Invalid VST_BBENTRY record");
484 BasicBlock *BB = getBasicBlock(Record[0]);
486 return Error("Invalid BB ID in VST_BBENTRY record");
488 BB->setName(&ValueName[0], ValueName.size());
496 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
497 /// the LSB for dense VBR encoding.
498 static uint64_t DecodeSignRotatedValue(uint64_t V) {
503 // There is no such thing as -0 with integers. "-0" really means MININT.
507 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
508 /// values and aliases that we can.
509 bool BitcodeReader::ResolveGlobalAndAliasInits() {
510 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
511 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
513 GlobalInitWorklist.swap(GlobalInits);
514 AliasInitWorklist.swap(AliasInits);
516 while (!GlobalInitWorklist.empty()) {
517 unsigned ValID = GlobalInitWorklist.back().second;
518 if (ValID >= ValueList.size()) {
519 // Not ready to resolve this yet, it requires something later in the file.
520 GlobalInits.push_back(GlobalInitWorklist.back());
522 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
523 GlobalInitWorklist.back().first->setInitializer(C);
525 return Error("Global variable initializer is not a constant!");
527 GlobalInitWorklist.pop_back();
530 while (!AliasInitWorklist.empty()) {
531 unsigned ValID = AliasInitWorklist.back().second;
532 if (ValID >= ValueList.size()) {
533 AliasInits.push_back(AliasInitWorklist.back());
535 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
536 AliasInitWorklist.back().first->setAliasee(C);
538 return Error("Alias initializer is not a constant!");
540 AliasInitWorklist.pop_back();
546 bool BitcodeReader::ParseConstants() {
547 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
548 return Error("Malformed block record");
550 SmallVector<uint64_t, 64> Record;
552 // Read all the records for this value table.
553 const Type *CurTy = Type::Int32Ty;
554 unsigned NextCstNo = ValueList.size();
556 unsigned Code = Stream.ReadCode();
557 if (Code == bitc::END_BLOCK) {
558 if (NextCstNo != ValueList.size())
559 return Error("Invalid constant reference!");
561 if (Stream.ReadBlockEnd())
562 return Error("Error at end of constants block");
566 if (Code == bitc::ENTER_SUBBLOCK) {
567 // No known subblocks, always skip them.
568 Stream.ReadSubBlockID();
569 if (Stream.SkipBlock())
570 return Error("Malformed block record");
574 if (Code == bitc::DEFINE_ABBREV) {
575 Stream.ReadAbbrevRecord();
582 switch (Stream.ReadRecord(Code, Record)) {
583 default: // Default behavior: unknown constant
584 case bitc::CST_CODE_UNDEF: // UNDEF
585 V = UndefValue::get(CurTy);
587 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
589 return Error("Malformed CST_SETTYPE record");
590 if (Record[0] >= TypeList.size())
591 return Error("Invalid Type ID in CST_SETTYPE record");
592 CurTy = TypeList[Record[0]];
593 continue; // Skip the ValueList manipulation.
594 case bitc::CST_CODE_NULL: // NULL
595 V = Constant::getNullValue(CurTy);
597 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
598 if (!isa<IntegerType>(CurTy) || Record.empty())
599 return Error("Invalid CST_INTEGER record");
600 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
602 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
603 if (!isa<IntegerType>(CurTy) || Record.empty())
604 return Error("Invalid WIDE_INTEGER record");
606 unsigned NumWords = Record.size();
607 SmallVector<uint64_t, 8> Words;
608 Words.resize(NumWords);
609 for (unsigned i = 0; i != NumWords; ++i)
610 Words[i] = DecodeSignRotatedValue(Record[i]);
611 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
612 NumWords, &Words[0]));
615 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
617 return Error("Invalid FLOAT record");
618 if (CurTy == Type::FloatTy)
619 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
620 else if (CurTy == Type::DoubleTy)
621 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
623 V = UndefValue::get(CurTy);
626 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
628 return Error("Invalid CST_AGGREGATE record");
630 unsigned Size = Record.size();
631 std::vector<Constant*> Elts;
633 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
634 for (unsigned i = 0; i != Size; ++i)
635 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
636 STy->getElementType(i)));
637 V = ConstantStruct::get(STy, Elts);
638 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
639 const Type *EltTy = ATy->getElementType();
640 for (unsigned i = 0; i != Size; ++i)
641 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
642 V = ConstantArray::get(ATy, Elts);
643 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
644 const Type *EltTy = VTy->getElementType();
645 for (unsigned i = 0; i != Size; ++i)
646 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
647 V = ConstantVector::get(Elts);
649 V = UndefValue::get(CurTy);
653 case bitc::CST_CODE_STRING: { // STRING: [values]
655 return Error("Invalid CST_AGGREGATE record");
657 const ArrayType *ATy = cast<ArrayType>(CurTy);
658 const Type *EltTy = ATy->getElementType();
660 unsigned Size = Record.size();
661 std::vector<Constant*> Elts;
662 for (unsigned i = 0; i != Size; ++i)
663 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
664 V = ConstantArray::get(ATy, Elts);
667 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
669 return Error("Invalid CST_AGGREGATE record");
671 const ArrayType *ATy = cast<ArrayType>(CurTy);
672 const Type *EltTy = ATy->getElementType();
674 unsigned Size = Record.size();
675 std::vector<Constant*> Elts;
676 for (unsigned i = 0; i != Size; ++i)
677 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
678 Elts.push_back(Constant::getNullValue(EltTy));
679 V = ConstantArray::get(ATy, Elts);
682 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
683 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
684 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
686 V = UndefValue::get(CurTy); // Unknown binop.
688 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
689 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
690 V = ConstantExpr::get(Opc, LHS, RHS);
694 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
695 if (Record.size() < 3) return Error("Invalid CE_CAST record");
696 int Opc = GetDecodedCastOpcode(Record[0]);
698 V = UndefValue::get(CurTy); // Unknown cast.
700 const Type *OpTy = getTypeByID(Record[1]);
701 if (!OpTy) return Error("Invalid CE_CAST record");
702 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
703 V = ConstantExpr::getCast(Opc, Op, CurTy);
707 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
708 if (Record.size() & 1) return Error("Invalid CE_GEP record");
709 SmallVector<Constant*, 16> Elts;
710 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
711 const Type *ElTy = getTypeByID(Record[i]);
712 if (!ElTy) return Error("Invalid CE_GEP record");
713 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
715 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
718 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
719 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
720 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
722 ValueList.getConstantFwdRef(Record[1],CurTy),
723 ValueList.getConstantFwdRef(Record[2],CurTy));
725 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
726 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
727 const VectorType *OpTy =
728 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
729 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
730 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
731 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
732 OpTy->getElementType());
733 V = ConstantExpr::getExtractElement(Op0, Op1);
736 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
737 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
738 if (Record.size() < 3 || OpTy == 0)
739 return Error("Invalid CE_INSERTELT record");
740 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
741 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
742 OpTy->getElementType());
743 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
744 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
747 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
748 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
749 if (Record.size() < 3 || OpTy == 0)
750 return Error("Invalid CE_INSERTELT record");
751 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
752 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
753 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
754 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
755 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
758 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
759 if (Record.size() < 4) return Error("Invalid CE_CMP record");
760 const Type *OpTy = getTypeByID(Record[0]);
761 if (OpTy == 0) return Error("Invalid CE_CMP record");
762 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
763 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
765 if (OpTy->isFloatingPoint())
766 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
768 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
771 case bitc::CST_CODE_INLINEASM: {
772 if (Record.size() < 2) return Error("Invalid INLINEASM record");
773 std::string AsmStr, ConstrStr;
774 bool HasSideEffects = Record[0];
775 unsigned AsmStrSize = Record[1];
776 if (2+AsmStrSize >= Record.size())
777 return Error("Invalid INLINEASM record");
778 unsigned ConstStrSize = Record[2+AsmStrSize];
779 if (3+AsmStrSize+ConstStrSize > Record.size())
780 return Error("Invalid INLINEASM record");
782 for (unsigned i = 0; i != AsmStrSize; ++i)
783 AsmStr += (char)Record[2+i];
784 for (unsigned i = 0; i != ConstStrSize; ++i)
785 ConstrStr += (char)Record[3+AsmStrSize+i];
786 const PointerType *PTy = cast<PointerType>(CurTy);
787 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
788 AsmStr, ConstrStr, HasSideEffects);
793 ValueList.AssignValue(V, NextCstNo);
798 /// RememberAndSkipFunctionBody - When we see the block for a function body,
799 /// remember where it is and then skip it. This lets us lazily deserialize the
801 bool BitcodeReader::RememberAndSkipFunctionBody() {
802 // Get the function we are talking about.
803 if (FunctionsWithBodies.empty())
804 return Error("Insufficient function protos");
806 Function *Fn = FunctionsWithBodies.back();
807 FunctionsWithBodies.pop_back();
809 // Save the current stream state.
810 uint64_t CurBit = Stream.GetCurrentBitNo();
811 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
813 // Set the functions linkage to GhostLinkage so we know it is lazily
815 Fn->setLinkage(GlobalValue::GhostLinkage);
817 // Skip over the function block for now.
818 if (Stream.SkipBlock())
819 return Error("Malformed block record");
823 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
824 // Reject multiple MODULE_BLOCK's in a single bitstream.
826 return Error("Multiple MODULE_BLOCKs in same stream");
828 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
829 return Error("Malformed block record");
831 // Otherwise, create the module.
832 TheModule = new Module(ModuleID);
834 SmallVector<uint64_t, 64> Record;
835 std::vector<std::string> SectionTable;
837 // Read all the records for this module.
838 while (!Stream.AtEndOfStream()) {
839 unsigned Code = Stream.ReadCode();
840 if (Code == bitc::END_BLOCK) {
841 if (Stream.ReadBlockEnd())
842 return Error("Error at end of module block");
844 // Patch the initializers for globals and aliases up.
845 ResolveGlobalAndAliasInits();
846 if (!GlobalInits.empty() || !AliasInits.empty())
847 return Error("Malformed global initializer set");
848 if (!FunctionsWithBodies.empty())
849 return Error("Too few function bodies found");
851 // Force deallocation of memory for these vectors to favor the client that
852 // want lazy deserialization.
853 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
854 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
855 std::vector<Function*>().swap(FunctionsWithBodies);
859 if (Code == bitc::ENTER_SUBBLOCK) {
860 switch (Stream.ReadSubBlockID()) {
861 default: // Skip unknown content.
862 if (Stream.SkipBlock())
863 return Error("Malformed block record");
865 case bitc::BLOCKINFO_BLOCK_ID:
866 if (Stream.ReadBlockInfoBlock())
867 return Error("Malformed BlockInfoBlock");
869 case bitc::PARAMATTR_BLOCK_ID:
870 if (ParseParamAttrBlock())
873 case bitc::TYPE_BLOCK_ID:
874 if (ParseTypeTable())
877 case bitc::TYPE_SYMTAB_BLOCK_ID:
878 if (ParseTypeSymbolTable())
881 case bitc::VALUE_SYMTAB_BLOCK_ID:
882 if (ParseValueSymbolTable())
885 case bitc::CONSTANTS_BLOCK_ID:
886 if (ParseConstants() || ResolveGlobalAndAliasInits())
889 case bitc::FUNCTION_BLOCK_ID:
890 // If this is the first function body we've seen, reverse the
891 // FunctionsWithBodies list.
892 if (!HasReversedFunctionsWithBodies) {
893 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
894 HasReversedFunctionsWithBodies = true;
897 if (RememberAndSkipFunctionBody())
904 if (Code == bitc::DEFINE_ABBREV) {
905 Stream.ReadAbbrevRecord();
910 switch (Stream.ReadRecord(Code, Record)) {
911 default: break; // Default behavior, ignore unknown content.
912 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
913 if (Record.size() < 1)
914 return Error("Malformed MODULE_CODE_VERSION");
915 // Only version #0 is supported so far.
917 return Error("Unknown bitstream version!");
919 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
921 if (ConvertToString(Record, 0, S))
922 return Error("Invalid MODULE_CODE_TRIPLE record");
923 TheModule->setTargetTriple(S);
926 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
928 if (ConvertToString(Record, 0, S))
929 return Error("Invalid MODULE_CODE_DATALAYOUT record");
930 TheModule->setDataLayout(S);
933 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
935 if (ConvertToString(Record, 0, S))
936 return Error("Invalid MODULE_CODE_ASM record");
937 TheModule->setModuleInlineAsm(S);
940 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
942 if (ConvertToString(Record, 0, S))
943 return Error("Invalid MODULE_CODE_DEPLIB record");
944 TheModule->addLibrary(S);
947 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
949 if (ConvertToString(Record, 0, S))
950 return Error("Invalid MODULE_CODE_SECTIONNAME record");
951 SectionTable.push_back(S);
954 // GLOBALVAR: [type, isconst, initid,
955 // linkage, alignment, section, visibility, threadlocal]
956 case bitc::MODULE_CODE_GLOBALVAR: {
957 if (Record.size() < 6)
958 return Error("Invalid MODULE_CODE_GLOBALVAR record");
959 const Type *Ty = getTypeByID(Record[0]);
960 if (!isa<PointerType>(Ty))
961 return Error("Global not a pointer type!");
962 Ty = cast<PointerType>(Ty)->getElementType();
964 bool isConstant = Record[1];
965 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
966 unsigned Alignment = (1 << Record[4]) >> 1;
969 if (Record[5]-1 >= SectionTable.size())
970 return Error("Invalid section ID");
971 Section = SectionTable[Record[5]-1];
973 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
974 if (Record.size() > 6)
975 Visibility = GetDecodedVisibility(Record[6]);
976 bool isThreadLocal = false;
977 if (Record.size() > 7)
978 isThreadLocal = Record[7];
980 GlobalVariable *NewGV =
981 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
982 NewGV->setAlignment(Alignment);
983 if (!Section.empty())
984 NewGV->setSection(Section);
985 NewGV->setVisibility(Visibility);
986 NewGV->setThreadLocal(isThreadLocal);
988 ValueList.push_back(NewGV);
990 // Remember which value to use for the global initializer.
991 if (unsigned InitID = Record[2])
992 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
995 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
996 // alignment, section, visibility]
997 case bitc::MODULE_CODE_FUNCTION: {
998 if (Record.size() < 8)
999 return Error("Invalid MODULE_CODE_FUNCTION record");
1000 const Type *Ty = getTypeByID(Record[0]);
1001 if (!isa<PointerType>(Ty))
1002 return Error("Function not a pointer type!");
1003 const FunctionType *FTy =
1004 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1006 return Error("Function not a pointer to function type!");
1008 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1011 Func->setCallingConv(Record[1]);
1012 bool isProto = Record[2];
1013 Func->setLinkage(GetDecodedLinkage(Record[3]));
1015 assert(Func->getFunctionType()->getParamAttrs() ==
1016 getParamAttrs(Record[4]));
1018 Func->setAlignment((1 << Record[5]) >> 1);
1020 if (Record[6]-1 >= SectionTable.size())
1021 return Error("Invalid section ID");
1022 Func->setSection(SectionTable[Record[6]-1]);
1024 Func->setVisibility(GetDecodedVisibility(Record[7]));
1026 ValueList.push_back(Func);
1028 // If this is a function with a body, remember the prototype we are
1029 // creating now, so that we can match up the body with them later.
1031 FunctionsWithBodies.push_back(Func);
1034 // ALIAS: [alias type, aliasee val#, linkage]
1035 case bitc::MODULE_CODE_ALIAS: {
1036 if (Record.size() < 3)
1037 return Error("Invalid MODULE_ALIAS record");
1038 const Type *Ty = getTypeByID(Record[0]);
1039 if (!isa<PointerType>(Ty))
1040 return Error("Function not a pointer type!");
1042 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1044 ValueList.push_back(NewGA);
1045 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1048 /// MODULE_CODE_PURGEVALS: [numvals]
1049 case bitc::MODULE_CODE_PURGEVALS:
1050 // Trim down the value list to the specified size.
1051 if (Record.size() < 1 || Record[0] > ValueList.size())
1052 return Error("Invalid MODULE_PURGEVALS record");
1053 ValueList.shrinkTo(Record[0]);
1059 return Error("Premature end of bitstream");
1063 bool BitcodeReader::ParseBitcode() {
1066 if (Buffer->getBufferSize() & 3)
1067 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1069 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1070 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1072 // Sniff for the signature.
1073 if (Stream.Read(8) != 'B' ||
1074 Stream.Read(8) != 'C' ||
1075 Stream.Read(4) != 0x0 ||
1076 Stream.Read(4) != 0xC ||
1077 Stream.Read(4) != 0xE ||
1078 Stream.Read(4) != 0xD)
1079 return Error("Invalid bitcode signature");
1081 // We expect a number of well-defined blocks, though we don't necessarily
1082 // need to understand them all.
1083 while (!Stream.AtEndOfStream()) {
1084 unsigned Code = Stream.ReadCode();
1086 if (Code != bitc::ENTER_SUBBLOCK)
1087 return Error("Invalid record at top-level");
1089 unsigned BlockID = Stream.ReadSubBlockID();
1091 // We only know the MODULE subblock ID.
1093 case bitc::BLOCKINFO_BLOCK_ID:
1094 if (Stream.ReadBlockInfoBlock())
1095 return Error("Malformed BlockInfoBlock");
1097 case bitc::MODULE_BLOCK_ID:
1098 if (ParseModule(Buffer->getBufferIdentifier()))
1102 if (Stream.SkipBlock())
1103 return Error("Malformed block record");
1112 /// ParseFunctionBody - Lazily parse the specified function body block.
1113 bool BitcodeReader::ParseFunctionBody(Function *F) {
1114 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1115 return Error("Malformed block record");
1117 unsigned ModuleValueListSize = ValueList.size();
1119 // Add all the function arguments to the value table.
1120 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1121 ValueList.push_back(I);
1123 unsigned NextValueNo = ValueList.size();
1124 BasicBlock *CurBB = 0;
1125 unsigned CurBBNo = 0;
1127 // Read all the records.
1128 SmallVector<uint64_t, 64> Record;
1130 unsigned Code = Stream.ReadCode();
1131 if (Code == bitc::END_BLOCK) {
1132 if (Stream.ReadBlockEnd())
1133 return Error("Error at end of function block");
1137 if (Code == bitc::ENTER_SUBBLOCK) {
1138 switch (Stream.ReadSubBlockID()) {
1139 default: // Skip unknown content.
1140 if (Stream.SkipBlock())
1141 return Error("Malformed block record");
1143 case bitc::CONSTANTS_BLOCK_ID:
1144 if (ParseConstants()) return true;
1145 NextValueNo = ValueList.size();
1147 case bitc::VALUE_SYMTAB_BLOCK_ID:
1148 if (ParseValueSymbolTable()) return true;
1154 if (Code == bitc::DEFINE_ABBREV) {
1155 Stream.ReadAbbrevRecord();
1162 switch (Stream.ReadRecord(Code, Record)) {
1163 default: // Default behavior: reject
1164 return Error("Unknown instruction");
1165 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1166 if (Record.size() < 1 || Record[0] == 0)
1167 return Error("Invalid DECLAREBLOCKS record");
1168 // Create all the basic blocks for the function.
1169 FunctionBBs.resize(Record[0]);
1170 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1171 FunctionBBs[i] = new BasicBlock("", F);
1172 CurBB = FunctionBBs[0];
1175 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1178 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1179 getValue(Record, OpNum, LHS->getType(), RHS) ||
1180 OpNum+1 != Record.size())
1181 return Error("Invalid BINOP record");
1183 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1184 if (Opc == -1) return Error("Invalid BINOP record");
1185 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1188 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1191 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1192 OpNum+2 != Record.size())
1193 return Error("Invalid CAST record");
1195 const Type *ResTy = getTypeByID(Record[OpNum]);
1196 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1197 if (Opc == -1 || ResTy == 0)
1198 return Error("Invalid CAST record");
1199 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1202 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1205 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1206 return Error("Invalid GEP record");
1208 SmallVector<Value*, 16> GEPIdx;
1209 while (OpNum != Record.size()) {
1211 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1212 return Error("Invalid GEP record");
1213 GEPIdx.push_back(Op);
1216 I = new GetElementPtrInst(BasePtr, &GEPIdx[0], GEPIdx.size());
1220 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1222 Value *TrueVal, *FalseVal, *Cond;
1223 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1224 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1225 getValue(Record, OpNum, Type::Int1Ty, Cond))
1226 return Error("Invalid SELECT record");
1228 I = new SelectInst(Cond, TrueVal, FalseVal);
1232 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1235 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1236 getValue(Record, OpNum, Type::Int32Ty, Idx))
1237 return Error("Invalid EXTRACTELT record");
1238 I = new ExtractElementInst(Vec, Idx);
1242 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1244 Value *Vec, *Elt, *Idx;
1245 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1246 getValue(Record, OpNum,
1247 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1248 getValue(Record, OpNum, Type::Int32Ty, Idx))
1249 return Error("Invalid INSERTELT record");
1250 I = new InsertElementInst(Vec, Elt, Idx);
1254 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1256 Value *Vec1, *Vec2, *Mask;
1257 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1258 getValue(Record, OpNum, Vec1->getType(), Vec2))
1259 return Error("Invalid SHUFFLEVEC record");
1261 const Type *MaskTy =
1262 VectorType::get(Type::Int32Ty,
1263 cast<VectorType>(Vec1->getType())->getNumElements());
1265 if (getValue(Record, OpNum, MaskTy, Mask))
1266 return Error("Invalid SHUFFLEVEC record");
1267 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1271 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1274 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1275 getValue(Record, OpNum, LHS->getType(), RHS) ||
1276 OpNum+1 != Record.size())
1277 return Error("Invalid CMP record");
1279 if (LHS->getType()->isFPOrFPVector())
1280 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1282 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1286 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1287 if (Record.size() == 0) {
1288 I = new ReturnInst();
1293 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1294 OpNum != Record.size())
1295 return Error("Invalid RET record");
1296 I = new ReturnInst(Op);
1299 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1300 if (Record.size() != 1 && Record.size() != 3)
1301 return Error("Invalid BR record");
1302 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1304 return Error("Invalid BR record");
1306 if (Record.size() == 1)
1307 I = new BranchInst(TrueDest);
1309 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1310 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1311 if (FalseDest == 0 || Cond == 0)
1312 return Error("Invalid BR record");
1313 I = new BranchInst(TrueDest, FalseDest, Cond);
1317 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1318 if (Record.size() < 3 || (Record.size() & 1) == 0)
1319 return Error("Invalid SWITCH record");
1320 const Type *OpTy = getTypeByID(Record[0]);
1321 Value *Cond = getFnValueByID(Record[1], OpTy);
1322 BasicBlock *Default = getBasicBlock(Record[2]);
1323 if (OpTy == 0 || Cond == 0 || Default == 0)
1324 return Error("Invalid SWITCH record");
1325 unsigned NumCases = (Record.size()-3)/2;
1326 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1327 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1328 ConstantInt *CaseVal =
1329 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1330 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1331 if (CaseVal == 0 || DestBB == 0) {
1333 return Error("Invalid SWITCH record!");
1335 SI->addCase(CaseVal, DestBB);
1341 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1342 if (Record.size() < 4) return Error("Invalid INVOKE record");
1343 unsigned CCInfo = Record[1];
1344 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1345 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1349 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1350 return Error("Invalid INVOKE record");
1352 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1353 const FunctionType *FTy = !CalleeTy ? 0 :
1354 dyn_cast<FunctionType>(CalleeTy->getElementType());
1356 // Check that the right number of fixed parameters are here.
1357 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1358 Record.size() < OpNum+FTy->getNumParams())
1359 return Error("Invalid INVOKE record");
1361 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1363 SmallVector<Value*, 16> Ops;
1364 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1365 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1366 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1369 if (!FTy->isVarArg()) {
1370 if (Record.size() != OpNum)
1371 return Error("Invalid INVOKE record");
1373 // Read type/value pairs for varargs params.
1374 while (OpNum != Record.size()) {
1376 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1377 return Error("Invalid INVOKE record");
1382 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1383 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1386 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1387 I = new UnwindInst();
1389 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1390 I = new UnreachableInst();
1392 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1393 if (Record.size() < 1 || ((Record.size()-1)&1))
1394 return Error("Invalid PHI record");
1395 const Type *Ty = getTypeByID(Record[0]);
1396 if (!Ty) return Error("Invalid PHI record");
1398 PHINode *PN = new PHINode(Ty);
1399 PN->reserveOperandSpace(Record.size()-1);
1401 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1402 Value *V = getFnValueByID(Record[1+i], Ty);
1403 BasicBlock *BB = getBasicBlock(Record[2+i]);
1404 if (!V || !BB) return Error("Invalid PHI record");
1405 PN->addIncoming(V, BB);
1411 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1412 if (Record.size() < 3)
1413 return Error("Invalid MALLOC record");
1414 const PointerType *Ty =
1415 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1416 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1417 unsigned Align = Record[2];
1418 if (!Ty || !Size) return Error("Invalid MALLOC record");
1419 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1422 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1425 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1426 OpNum != Record.size())
1427 return Error("Invalid FREE record");
1428 I = new FreeInst(Op);
1431 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1432 if (Record.size() < 3)
1433 return Error("Invalid ALLOCA record");
1434 const PointerType *Ty =
1435 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1436 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1437 unsigned Align = Record[2];
1438 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1439 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1442 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1445 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1446 OpNum+2 != Record.size())
1447 return Error("Invalid LOAD record");
1449 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1452 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1455 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1456 getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1457 OpNum+2 != Record.size())
1458 return Error("Invalid STORE record");
1460 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1463 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1464 if (Record.size() < 2)
1465 return Error("Invalid CALL record");
1467 unsigned CCInfo = Record[1];
1471 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1472 return Error("Invalid CALL record");
1474 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1475 const FunctionType *FTy = 0;
1476 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1477 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1478 return Error("Invalid CALL record");
1480 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1482 SmallVector<Value*, 16> Args;
1483 // Read the fixed params.
1484 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1485 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1486 if (Args.back() == 0) return Error("Invalid CALL record");
1489 // Read type/value pairs for varargs params.
1490 if (!FTy->isVarArg()) {
1491 if (OpNum != Record.size())
1492 return Error("Invalid CALL record");
1494 while (OpNum != Record.size()) {
1496 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1497 return Error("Invalid CALL record");
1502 I = new CallInst(Callee, Args.begin(), Args.end());
1503 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1504 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1507 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1508 if (Record.size() < 3)
1509 return Error("Invalid VAARG record");
1510 const Type *OpTy = getTypeByID(Record[0]);
1511 Value *Op = getFnValueByID(Record[1], OpTy);
1512 const Type *ResTy = getTypeByID(Record[2]);
1513 if (!OpTy || !Op || !ResTy)
1514 return Error("Invalid VAARG record");
1515 I = new VAArgInst(Op, ResTy);
1520 // Add instruction to end of current BB. If there is no current BB, reject
1524 return Error("Invalid instruction with no BB");
1526 CurBB->getInstList().push_back(I);
1528 // If this was a terminator instruction, move to the next block.
1529 if (isa<TerminatorInst>(I)) {
1531 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1534 // Non-void values get registered in the value table for future use.
1535 if (I && I->getType() != Type::VoidTy)
1536 ValueList.AssignValue(I, NextValueNo++);
1539 // Check the function list for unresolved values.
1540 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1541 if (A->getParent() == 0) {
1542 // We found at least one unresolved value. Nuke them all to avoid leaks.
1543 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1544 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1545 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1549 return Error("Never resolved value found in function!");
1553 // Trim the value list down to the size it was before we parsed this function.
1554 ValueList.shrinkTo(ModuleValueListSize);
1555 std::vector<BasicBlock*>().swap(FunctionBBs);
1560 //===----------------------------------------------------------------------===//
1561 // ModuleProvider implementation
1562 //===----------------------------------------------------------------------===//
1565 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1566 // If it already is material, ignore the request.
1567 if (!F->hasNotBeenReadFromBitcode()) return false;
1569 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1570 DeferredFunctionInfo.find(F);
1571 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1573 // Move the bit stream to the saved position of the deferred function body and
1574 // restore the real linkage type for the function.
1575 Stream.JumpToBit(DFII->second.first);
1576 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1578 if (ParseFunctionBody(F)) {
1579 if (ErrInfo) *ErrInfo = ErrorString;
1586 void BitcodeReader::dematerializeFunction(Function *F) {
1587 // If this function isn't materialized, or if it is a proto, this is a noop.
1588 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1591 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1593 // Just forget the function body, we can remat it later.
1595 F->setLinkage(GlobalValue::GhostLinkage);
1599 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1600 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1601 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1603 Function *F = I->first;
1604 if (F->hasNotBeenReadFromBitcode() &&
1605 materializeFunction(F, ErrInfo))
1612 /// This method is provided by the parent ModuleProvde class and overriden
1613 /// here. It simply releases the module from its provided and frees up our
1615 /// @brief Release our hold on the generated module
1616 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1617 // Since we're losing control of this Module, we must hand it back complete
1618 Module *M = ModuleProvider::releaseModule(ErrInfo);
1624 //===----------------------------------------------------------------------===//
1625 // External interface
1626 //===----------------------------------------------------------------------===//
1628 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1630 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1631 std::string *ErrMsg) {
1632 BitcodeReader *R = new BitcodeReader(Buffer);
1633 if (R->ParseBitcode()) {
1635 *ErrMsg = R->getErrorString();
1637 // Don't let the BitcodeReader dtor delete 'Buffer'.
1638 R->releaseMemoryBuffer();
1645 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1646 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1647 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1649 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1652 // Read in the entire module.
1653 Module *M = R->materializeModule(ErrMsg);
1655 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1656 // there was an error.
1657 R->releaseMemoryBuffer();
1659 // If there was no error, tell ModuleProvider not to delete it when its dtor
1662 M = R->releaseModule(ErrMsg);