1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/ParamAttrsList.h"
22 #include "llvm/AutoUpgrade.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/MemoryBuffer.h"
28 void BitcodeReader::FreeState() {
31 std::vector<PATypeHolder>().swap(TypeList);
33 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
34 std::vector<BasicBlock*>().swap(FunctionBBs);
35 std::vector<Function*>().swap(FunctionsWithBodies);
36 DeferredFunctionInfo.clear();
39 //===----------------------------------------------------------------------===//
40 // Helper functions to implement forward reference resolution, etc.
41 //===----------------------------------------------------------------------===//
43 /// ConvertToString - Convert a string from a record into an std::string, return
45 template<typename StrTy>
46 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
48 if (Idx > Record.size())
51 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
52 Result += (char)Record[i];
56 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
58 default: // Map unknown/new linkages to external
59 case 0: return GlobalValue::ExternalLinkage;
60 case 1: return GlobalValue::WeakLinkage;
61 case 2: return GlobalValue::AppendingLinkage;
62 case 3: return GlobalValue::InternalLinkage;
63 case 4: return GlobalValue::LinkOnceLinkage;
64 case 5: return GlobalValue::DLLImportLinkage;
65 case 6: return GlobalValue::DLLExportLinkage;
66 case 7: return GlobalValue::ExternalWeakLinkage;
70 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
72 default: // Map unknown visibilities to default.
73 case 0: return GlobalValue::DefaultVisibility;
74 case 1: return GlobalValue::HiddenVisibility;
75 case 2: return GlobalValue::ProtectedVisibility;
79 static int GetDecodedCastOpcode(unsigned Val) {
82 case bitc::CAST_TRUNC : return Instruction::Trunc;
83 case bitc::CAST_ZEXT : return Instruction::ZExt;
84 case bitc::CAST_SEXT : return Instruction::SExt;
85 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
86 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
87 case bitc::CAST_UITOFP : return Instruction::UIToFP;
88 case bitc::CAST_SITOFP : return Instruction::SIToFP;
89 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
90 case bitc::CAST_FPEXT : return Instruction::FPExt;
91 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
92 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
93 case bitc::CAST_BITCAST : return Instruction::BitCast;
96 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
99 case bitc::BINOP_ADD: return Instruction::Add;
100 case bitc::BINOP_SUB: return Instruction::Sub;
101 case bitc::BINOP_MUL: return Instruction::Mul;
102 case bitc::BINOP_UDIV: return Instruction::UDiv;
103 case bitc::BINOP_SDIV:
104 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
105 case bitc::BINOP_UREM: return Instruction::URem;
106 case bitc::BINOP_SREM:
107 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
108 case bitc::BINOP_SHL: return Instruction::Shl;
109 case bitc::BINOP_LSHR: return Instruction::LShr;
110 case bitc::BINOP_ASHR: return Instruction::AShr;
111 case bitc::BINOP_AND: return Instruction::And;
112 case bitc::BINOP_OR: return Instruction::Or;
113 case bitc::BINOP_XOR: return Instruction::Xor;
119 /// @brief A class for maintaining the slot number definition
120 /// as a placeholder for the actual definition for forward constants defs.
121 class ConstantPlaceHolder : public ConstantExpr {
122 ConstantPlaceHolder(); // DO NOT IMPLEMENT
123 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
126 explicit ConstantPlaceHolder(const Type *Ty)
127 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
128 Op(UndefValue::get(Type::Int32Ty), this) {
133 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
136 // Insert a bunch of null values.
138 OperandList = &Uses[0];
142 if (Value *V = Uses[Idx]) {
143 assert(Ty == V->getType() && "Type mismatch in constant table!");
144 return cast<Constant>(V);
147 // Create and return a placeholder, which will later be RAUW'd.
148 Constant *C = new ConstantPlaceHolder(Ty);
149 Uses[Idx].init(C, this);
153 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
155 // Insert a bunch of null values.
157 OperandList = &Uses[0];
161 if (Value *V = Uses[Idx]) {
162 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
166 // No type specified, must be invalid reference.
167 if (Ty == 0) return 0;
169 // Create and return a placeholder, which will later be RAUW'd.
170 Value *V = new Argument(Ty);
171 Uses[Idx].init(V, this);
176 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
177 // If the TypeID is in range, return it.
178 if (ID < TypeList.size())
179 return TypeList[ID].get();
180 if (!isTypeTable) return 0;
182 // The type table allows forward references. Push as many Opaque types as
183 // needed to get up to ID.
184 while (TypeList.size() <= ID)
185 TypeList.push_back(OpaqueType::get());
186 return TypeList.back().get();
189 //===----------------------------------------------------------------------===//
190 // Functions for parsing blocks from the bitcode file
191 //===----------------------------------------------------------------------===//
193 bool BitcodeReader::ParseParamAttrBlock() {
194 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
195 return Error("Malformed block record");
197 if (!ParamAttrs.empty())
198 return Error("Multiple PARAMATTR blocks found!");
200 SmallVector<uint64_t, 64> Record;
202 ParamAttrsVector Attrs;
204 // Read all the records.
206 unsigned Code = Stream.ReadCode();
207 if (Code == bitc::END_BLOCK) {
208 if (Stream.ReadBlockEnd())
209 return Error("Error at end of PARAMATTR block");
213 if (Code == bitc::ENTER_SUBBLOCK) {
214 // No known subblocks, always skip them.
215 Stream.ReadSubBlockID();
216 if (Stream.SkipBlock())
217 return Error("Malformed block record");
221 if (Code == bitc::DEFINE_ABBREV) {
222 Stream.ReadAbbrevRecord();
228 switch (Stream.ReadRecord(Code, Record)) {
229 default: // Default behavior: ignore.
231 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
232 if (Record.size() & 1)
233 return Error("Invalid ENTRY record");
235 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
236 if (Record[i+1] != ParamAttr::None)
237 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
239 ParamAttrs.push_back(Attrs.empty() ? NULL : ParamAttrsList::get(Attrs));
248 bool BitcodeReader::ParseTypeTable() {
249 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
250 return Error("Malformed block record");
252 if (!TypeList.empty())
253 return Error("Multiple TYPE_BLOCKs found!");
255 SmallVector<uint64_t, 64> Record;
256 unsigned NumRecords = 0;
258 // Read all the records for this type table.
260 unsigned Code = Stream.ReadCode();
261 if (Code == bitc::END_BLOCK) {
262 if (NumRecords != TypeList.size())
263 return Error("Invalid type forward reference in TYPE_BLOCK");
264 if (Stream.ReadBlockEnd())
265 return Error("Error at end of type table block");
269 if (Code == bitc::ENTER_SUBBLOCK) {
270 // No known subblocks, always skip them.
271 Stream.ReadSubBlockID();
272 if (Stream.SkipBlock())
273 return Error("Malformed block record");
277 if (Code == bitc::DEFINE_ABBREV) {
278 Stream.ReadAbbrevRecord();
284 const Type *ResultTy = 0;
285 switch (Stream.ReadRecord(Code, Record)) {
286 default: // Default behavior: unknown type.
289 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
290 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
291 // type list. This allows us to reserve space.
292 if (Record.size() < 1)
293 return Error("Invalid TYPE_CODE_NUMENTRY record");
294 TypeList.reserve(Record[0]);
296 case bitc::TYPE_CODE_VOID: // VOID
297 ResultTy = Type::VoidTy;
299 case bitc::TYPE_CODE_FLOAT: // FLOAT
300 ResultTy = Type::FloatTy;
302 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
303 ResultTy = Type::DoubleTy;
305 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
306 ResultTy = Type::X86_FP80Ty;
308 case bitc::TYPE_CODE_FP128: // FP128
309 ResultTy = Type::FP128Ty;
311 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
312 ResultTy = Type::PPC_FP128Ty;
314 case bitc::TYPE_CODE_LABEL: // LABEL
315 ResultTy = Type::LabelTy;
317 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
320 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
321 if (Record.size() < 1)
322 return Error("Invalid Integer type record");
324 ResultTy = IntegerType::get(Record[0]);
326 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
327 // [pointee type, address space]
328 if (Record.size() < 1)
329 return Error("Invalid POINTER type record");
330 unsigned AddressSpace = 0;
331 if (Record.size() == 2)
332 AddressSpace = Record[1];
333 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
336 case bitc::TYPE_CODE_FUNCTION: {
337 // FIXME: attrid is dead, remove it in LLVM 3.0
338 // FUNCTION: [vararg, attrid, retty, paramty x N]
339 if (Record.size() < 3)
340 return Error("Invalid FUNCTION type record");
341 std::vector<const Type*> ArgTys;
342 for (unsigned i = 3, e = Record.size(); i != e; ++i)
343 ArgTys.push_back(getTypeByID(Record[i], true));
345 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
349 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
350 if (Record.size() < 1)
351 return Error("Invalid STRUCT type record");
352 std::vector<const Type*> EltTys;
353 for (unsigned i = 1, e = Record.size(); i != e; ++i)
354 EltTys.push_back(getTypeByID(Record[i], true));
355 ResultTy = StructType::get(EltTys, Record[0]);
358 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
359 if (Record.size() < 2)
360 return Error("Invalid ARRAY type record");
361 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
363 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
364 if (Record.size() < 2)
365 return Error("Invalid VECTOR type record");
366 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
370 if (NumRecords == TypeList.size()) {
371 // If this is a new type slot, just append it.
372 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
374 } else if (ResultTy == 0) {
375 // Otherwise, this was forward referenced, so an opaque type was created,
376 // but the result type is actually just an opaque. Leave the one we
377 // created previously.
380 // Otherwise, this was forward referenced, so an opaque type was created.
381 // Resolve the opaque type to the real type now.
382 assert(NumRecords < TypeList.size() && "Typelist imbalance");
383 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
385 // Don't directly push the new type on the Tab. Instead we want to replace
386 // the opaque type we previously inserted with the new concrete value. The
387 // refinement from the abstract (opaque) type to the new type causes all
388 // uses of the abstract type to use the concrete type (NewTy). This will
389 // also cause the opaque type to be deleted.
390 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
392 // This should have replaced the old opaque type with the new type in the
393 // value table... or with a preexisting type that was already in the
394 // system. Let's just make sure it did.
395 assert(TypeList[NumRecords-1].get() != OldTy &&
396 "refineAbstractType didn't work!");
402 bool BitcodeReader::ParseTypeSymbolTable() {
403 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
404 return Error("Malformed block record");
406 SmallVector<uint64_t, 64> Record;
408 // Read all the records for this type table.
409 std::string TypeName;
411 unsigned Code = Stream.ReadCode();
412 if (Code == bitc::END_BLOCK) {
413 if (Stream.ReadBlockEnd())
414 return Error("Error at end of type symbol table block");
418 if (Code == bitc::ENTER_SUBBLOCK) {
419 // No known subblocks, always skip them.
420 Stream.ReadSubBlockID();
421 if (Stream.SkipBlock())
422 return Error("Malformed block record");
426 if (Code == bitc::DEFINE_ABBREV) {
427 Stream.ReadAbbrevRecord();
433 switch (Stream.ReadRecord(Code, Record)) {
434 default: // Default behavior: unknown type.
436 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
437 if (ConvertToString(Record, 1, TypeName))
438 return Error("Invalid TST_ENTRY record");
439 unsigned TypeID = Record[0];
440 if (TypeID >= TypeList.size())
441 return Error("Invalid Type ID in TST_ENTRY record");
443 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
450 bool BitcodeReader::ParseValueSymbolTable() {
451 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
452 return Error("Malformed block record");
454 SmallVector<uint64_t, 64> Record;
456 // Read all the records for this value table.
457 SmallString<128> ValueName;
459 unsigned Code = Stream.ReadCode();
460 if (Code == bitc::END_BLOCK) {
461 if (Stream.ReadBlockEnd())
462 return Error("Error at end of value symbol table block");
465 if (Code == bitc::ENTER_SUBBLOCK) {
466 // No known subblocks, always skip them.
467 Stream.ReadSubBlockID();
468 if (Stream.SkipBlock())
469 return Error("Malformed block record");
473 if (Code == bitc::DEFINE_ABBREV) {
474 Stream.ReadAbbrevRecord();
480 switch (Stream.ReadRecord(Code, Record)) {
481 default: // Default behavior: unknown type.
483 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
484 if (ConvertToString(Record, 1, ValueName))
485 return Error("Invalid TST_ENTRY record");
486 unsigned ValueID = Record[0];
487 if (ValueID >= ValueList.size())
488 return Error("Invalid Value ID in VST_ENTRY record");
489 Value *V = ValueList[ValueID];
491 V->setName(&ValueName[0], ValueName.size());
495 case bitc::VST_CODE_BBENTRY: {
496 if (ConvertToString(Record, 1, ValueName))
497 return Error("Invalid VST_BBENTRY record");
498 BasicBlock *BB = getBasicBlock(Record[0]);
500 return Error("Invalid BB ID in VST_BBENTRY record");
502 BB->setName(&ValueName[0], ValueName.size());
510 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
511 /// the LSB for dense VBR encoding.
512 static uint64_t DecodeSignRotatedValue(uint64_t V) {
517 // There is no such thing as -0 with integers. "-0" really means MININT.
521 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
522 /// values and aliases that we can.
523 bool BitcodeReader::ResolveGlobalAndAliasInits() {
524 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
525 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
527 GlobalInitWorklist.swap(GlobalInits);
528 AliasInitWorklist.swap(AliasInits);
530 while (!GlobalInitWorklist.empty()) {
531 unsigned ValID = GlobalInitWorklist.back().second;
532 if (ValID >= ValueList.size()) {
533 // Not ready to resolve this yet, it requires something later in the file.
534 GlobalInits.push_back(GlobalInitWorklist.back());
536 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
537 GlobalInitWorklist.back().first->setInitializer(C);
539 return Error("Global variable initializer is not a constant!");
541 GlobalInitWorklist.pop_back();
544 while (!AliasInitWorklist.empty()) {
545 unsigned ValID = AliasInitWorklist.back().second;
546 if (ValID >= ValueList.size()) {
547 AliasInits.push_back(AliasInitWorklist.back());
549 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
550 AliasInitWorklist.back().first->setAliasee(C);
552 return Error("Alias initializer is not a constant!");
554 AliasInitWorklist.pop_back();
560 bool BitcodeReader::ParseConstants() {
561 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
562 return Error("Malformed block record");
564 SmallVector<uint64_t, 64> Record;
566 // Read all the records for this value table.
567 const Type *CurTy = Type::Int32Ty;
568 unsigned NextCstNo = ValueList.size();
570 unsigned Code = Stream.ReadCode();
571 if (Code == bitc::END_BLOCK) {
572 if (NextCstNo != ValueList.size())
573 return Error("Invalid constant reference!");
575 if (Stream.ReadBlockEnd())
576 return Error("Error at end of constants block");
580 if (Code == bitc::ENTER_SUBBLOCK) {
581 // No known subblocks, always skip them.
582 Stream.ReadSubBlockID();
583 if (Stream.SkipBlock())
584 return Error("Malformed block record");
588 if (Code == bitc::DEFINE_ABBREV) {
589 Stream.ReadAbbrevRecord();
596 switch (Stream.ReadRecord(Code, Record)) {
597 default: // Default behavior: unknown constant
598 case bitc::CST_CODE_UNDEF: // UNDEF
599 V = UndefValue::get(CurTy);
601 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
603 return Error("Malformed CST_SETTYPE record");
604 if (Record[0] >= TypeList.size())
605 return Error("Invalid Type ID in CST_SETTYPE record");
606 CurTy = TypeList[Record[0]];
607 continue; // Skip the ValueList manipulation.
608 case bitc::CST_CODE_NULL: // NULL
609 V = Constant::getNullValue(CurTy);
611 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
612 if (!isa<IntegerType>(CurTy) || Record.empty())
613 return Error("Invalid CST_INTEGER record");
614 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
616 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
617 if (!isa<IntegerType>(CurTy) || Record.empty())
618 return Error("Invalid WIDE_INTEGER record");
620 unsigned NumWords = Record.size();
621 SmallVector<uint64_t, 8> Words;
622 Words.resize(NumWords);
623 for (unsigned i = 0; i != NumWords; ++i)
624 Words[i] = DecodeSignRotatedValue(Record[i]);
625 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
626 NumWords, &Words[0]));
629 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
631 return Error("Invalid FLOAT record");
632 if (CurTy == Type::FloatTy)
633 V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
634 else if (CurTy == Type::DoubleTy)
635 V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
636 else if (CurTy == Type::X86_FP80Ty)
637 V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
638 else if (CurTy == Type::FP128Ty)
639 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true));
640 else if (CurTy == Type::PPC_FP128Ty)
641 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
643 V = UndefValue::get(CurTy);
647 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
649 return Error("Invalid CST_AGGREGATE record");
651 unsigned Size = Record.size();
652 std::vector<Constant*> Elts;
654 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
655 for (unsigned i = 0; i != Size; ++i)
656 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
657 STy->getElementType(i)));
658 V = ConstantStruct::get(STy, Elts);
659 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
660 const Type *EltTy = ATy->getElementType();
661 for (unsigned i = 0; i != Size; ++i)
662 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
663 V = ConstantArray::get(ATy, Elts);
664 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
665 const Type *EltTy = VTy->getElementType();
666 for (unsigned i = 0; i != Size; ++i)
667 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
668 V = ConstantVector::get(Elts);
670 V = UndefValue::get(CurTy);
674 case bitc::CST_CODE_STRING: { // STRING: [values]
676 return Error("Invalid CST_AGGREGATE record");
678 const ArrayType *ATy = cast<ArrayType>(CurTy);
679 const Type *EltTy = ATy->getElementType();
681 unsigned Size = Record.size();
682 std::vector<Constant*> Elts;
683 for (unsigned i = 0; i != Size; ++i)
684 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
685 V = ConstantArray::get(ATy, Elts);
688 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
690 return Error("Invalid CST_AGGREGATE record");
692 const ArrayType *ATy = cast<ArrayType>(CurTy);
693 const Type *EltTy = ATy->getElementType();
695 unsigned Size = Record.size();
696 std::vector<Constant*> Elts;
697 for (unsigned i = 0; i != Size; ++i)
698 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
699 Elts.push_back(Constant::getNullValue(EltTy));
700 V = ConstantArray::get(ATy, Elts);
703 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
704 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
705 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
707 V = UndefValue::get(CurTy); // Unknown binop.
709 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
710 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
711 V = ConstantExpr::get(Opc, LHS, RHS);
715 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
716 if (Record.size() < 3) return Error("Invalid CE_CAST record");
717 int Opc = GetDecodedCastOpcode(Record[0]);
719 V = UndefValue::get(CurTy); // Unknown cast.
721 const Type *OpTy = getTypeByID(Record[1]);
722 if (!OpTy) return Error("Invalid CE_CAST record");
723 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
724 V = ConstantExpr::getCast(Opc, Op, CurTy);
728 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
729 if (Record.size() & 1) return Error("Invalid CE_GEP record");
730 SmallVector<Constant*, 16> Elts;
731 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
732 const Type *ElTy = getTypeByID(Record[i]);
733 if (!ElTy) return Error("Invalid CE_GEP record");
734 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
736 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
739 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
740 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
741 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
743 ValueList.getConstantFwdRef(Record[1],CurTy),
744 ValueList.getConstantFwdRef(Record[2],CurTy));
746 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
747 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
748 const VectorType *OpTy =
749 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
750 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
751 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
752 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
753 OpTy->getElementType());
754 V = ConstantExpr::getExtractElement(Op0, Op1);
757 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
758 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
759 if (Record.size() < 3 || OpTy == 0)
760 return Error("Invalid CE_INSERTELT record");
761 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
762 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
763 OpTy->getElementType());
764 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
765 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
768 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
769 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
770 if (Record.size() < 3 || OpTy == 0)
771 return Error("Invalid CE_INSERTELT record");
772 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
773 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
774 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
775 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
776 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
779 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
780 if (Record.size() < 4) return Error("Invalid CE_CMP record");
781 const Type *OpTy = getTypeByID(Record[0]);
782 if (OpTy == 0) return Error("Invalid CE_CMP record");
783 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
784 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
786 if (OpTy->isFloatingPoint())
787 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
789 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
792 case bitc::CST_CODE_INLINEASM: {
793 if (Record.size() < 2) return Error("Invalid INLINEASM record");
794 std::string AsmStr, ConstrStr;
795 bool HasSideEffects = Record[0];
796 unsigned AsmStrSize = Record[1];
797 if (2+AsmStrSize >= Record.size())
798 return Error("Invalid INLINEASM record");
799 unsigned ConstStrSize = Record[2+AsmStrSize];
800 if (3+AsmStrSize+ConstStrSize > Record.size())
801 return Error("Invalid INLINEASM record");
803 for (unsigned i = 0; i != AsmStrSize; ++i)
804 AsmStr += (char)Record[2+i];
805 for (unsigned i = 0; i != ConstStrSize; ++i)
806 ConstrStr += (char)Record[3+AsmStrSize+i];
807 const PointerType *PTy = cast<PointerType>(CurTy);
808 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
809 AsmStr, ConstrStr, HasSideEffects);
814 ValueList.AssignValue(V, NextCstNo);
819 /// RememberAndSkipFunctionBody - When we see the block for a function body,
820 /// remember where it is and then skip it. This lets us lazily deserialize the
822 bool BitcodeReader::RememberAndSkipFunctionBody() {
823 // Get the function we are talking about.
824 if (FunctionsWithBodies.empty())
825 return Error("Insufficient function protos");
827 Function *Fn = FunctionsWithBodies.back();
828 FunctionsWithBodies.pop_back();
830 // Save the current stream state.
831 uint64_t CurBit = Stream.GetCurrentBitNo();
832 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
834 // Set the functions linkage to GhostLinkage so we know it is lazily
836 Fn->setLinkage(GlobalValue::GhostLinkage);
838 // Skip over the function block for now.
839 if (Stream.SkipBlock())
840 return Error("Malformed block record");
844 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
845 // Reject multiple MODULE_BLOCK's in a single bitstream.
847 return Error("Multiple MODULE_BLOCKs in same stream");
849 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
850 return Error("Malformed block record");
852 // Otherwise, create the module.
853 TheModule = new Module(ModuleID);
855 SmallVector<uint64_t, 64> Record;
856 std::vector<std::string> SectionTable;
857 std::vector<std::string> CollectorTable;
859 // Read all the records for this module.
860 while (!Stream.AtEndOfStream()) {
861 unsigned Code = Stream.ReadCode();
862 if (Code == bitc::END_BLOCK) {
863 if (Stream.ReadBlockEnd())
864 return Error("Error at end of module block");
866 // Patch the initializers for globals and aliases up.
867 ResolveGlobalAndAliasInits();
868 if (!GlobalInits.empty() || !AliasInits.empty())
869 return Error("Malformed global initializer set");
870 if (!FunctionsWithBodies.empty())
871 return Error("Too few function bodies found");
873 // Look for intrinsic functions which need to be upgraded at some point
874 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
877 if (UpgradeIntrinsicFunction(FI, NewFn))
878 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
881 // Force deallocation of memory for these vectors to favor the client that
882 // want lazy deserialization.
883 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
884 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
885 std::vector<Function*>().swap(FunctionsWithBodies);
889 if (Code == bitc::ENTER_SUBBLOCK) {
890 switch (Stream.ReadSubBlockID()) {
891 default: // Skip unknown content.
892 if (Stream.SkipBlock())
893 return Error("Malformed block record");
895 case bitc::BLOCKINFO_BLOCK_ID:
896 if (Stream.ReadBlockInfoBlock())
897 return Error("Malformed BlockInfoBlock");
899 case bitc::PARAMATTR_BLOCK_ID:
900 if (ParseParamAttrBlock())
903 case bitc::TYPE_BLOCK_ID:
904 if (ParseTypeTable())
907 case bitc::TYPE_SYMTAB_BLOCK_ID:
908 if (ParseTypeSymbolTable())
911 case bitc::VALUE_SYMTAB_BLOCK_ID:
912 if (ParseValueSymbolTable())
915 case bitc::CONSTANTS_BLOCK_ID:
916 if (ParseConstants() || ResolveGlobalAndAliasInits())
919 case bitc::FUNCTION_BLOCK_ID:
920 // If this is the first function body we've seen, reverse the
921 // FunctionsWithBodies list.
922 if (!HasReversedFunctionsWithBodies) {
923 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
924 HasReversedFunctionsWithBodies = true;
927 if (RememberAndSkipFunctionBody())
934 if (Code == bitc::DEFINE_ABBREV) {
935 Stream.ReadAbbrevRecord();
940 switch (Stream.ReadRecord(Code, Record)) {
941 default: break; // Default behavior, ignore unknown content.
942 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
943 if (Record.size() < 1)
944 return Error("Malformed MODULE_CODE_VERSION");
945 // Only version #0 is supported so far.
947 return Error("Unknown bitstream version!");
949 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
951 if (ConvertToString(Record, 0, S))
952 return Error("Invalid MODULE_CODE_TRIPLE record");
953 TheModule->setTargetTriple(S);
956 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
958 if (ConvertToString(Record, 0, S))
959 return Error("Invalid MODULE_CODE_DATALAYOUT record");
960 TheModule->setDataLayout(S);
963 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
965 if (ConvertToString(Record, 0, S))
966 return Error("Invalid MODULE_CODE_ASM record");
967 TheModule->setModuleInlineAsm(S);
970 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
972 if (ConvertToString(Record, 0, S))
973 return Error("Invalid MODULE_CODE_DEPLIB record");
974 TheModule->addLibrary(S);
977 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
979 if (ConvertToString(Record, 0, S))
980 return Error("Invalid MODULE_CODE_SECTIONNAME record");
981 SectionTable.push_back(S);
984 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
986 if (ConvertToString(Record, 0, S))
987 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
988 CollectorTable.push_back(S);
991 // GLOBALVAR: [pointer type, isconst, initid,
992 // linkage, alignment, section, visibility, threadlocal]
993 case bitc::MODULE_CODE_GLOBALVAR: {
994 if (Record.size() < 6)
995 return Error("Invalid MODULE_CODE_GLOBALVAR record");
996 const Type *Ty = getTypeByID(Record[0]);
997 if (!isa<PointerType>(Ty))
998 return Error("Global not a pointer type!");
999 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1000 Ty = cast<PointerType>(Ty)->getElementType();
1002 bool isConstant = Record[1];
1003 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1004 unsigned Alignment = (1 << Record[4]) >> 1;
1005 std::string Section;
1007 if (Record[5]-1 >= SectionTable.size())
1008 return Error("Invalid section ID");
1009 Section = SectionTable[Record[5]-1];
1011 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1012 if (Record.size() > 6)
1013 Visibility = GetDecodedVisibility(Record[6]);
1014 bool isThreadLocal = false;
1015 if (Record.size() > 7)
1016 isThreadLocal = Record[7];
1018 GlobalVariable *NewGV =
1019 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1020 isThreadLocal, AddressSpace);
1021 NewGV->setAlignment(Alignment);
1022 if (!Section.empty())
1023 NewGV->setSection(Section);
1024 NewGV->setVisibility(Visibility);
1025 NewGV->setThreadLocal(isThreadLocal);
1027 ValueList.push_back(NewGV);
1029 // Remember which value to use for the global initializer.
1030 if (unsigned InitID = Record[2])
1031 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1034 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1035 // alignment, section, visibility, collector]
1036 case bitc::MODULE_CODE_FUNCTION: {
1037 if (Record.size() < 8)
1038 return Error("Invalid MODULE_CODE_FUNCTION record");
1039 const Type *Ty = getTypeByID(Record[0]);
1040 if (!isa<PointerType>(Ty))
1041 return Error("Function not a pointer type!");
1042 const FunctionType *FTy =
1043 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1045 return Error("Function not a pointer to function type!");
1047 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1050 Func->setCallingConv(Record[1]);
1051 bool isProto = Record[2];
1052 Func->setLinkage(GetDecodedLinkage(Record[3]));
1053 const ParamAttrsList *PAL = getParamAttrs(Record[4]);
1054 Func->setParamAttrs(PAL);
1056 Func->setAlignment((1 << Record[5]) >> 1);
1058 if (Record[6]-1 >= SectionTable.size())
1059 return Error("Invalid section ID");
1060 Func->setSection(SectionTable[Record[6]-1]);
1062 Func->setVisibility(GetDecodedVisibility(Record[7]));
1063 if (Record.size() > 8 && Record[8]) {
1064 if (Record[8]-1 > CollectorTable.size())
1065 return Error("Invalid collector ID");
1066 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1069 ValueList.push_back(Func);
1071 // If this is a function with a body, remember the prototype we are
1072 // creating now, so that we can match up the body with them later.
1074 FunctionsWithBodies.push_back(Func);
1077 // ALIAS: [alias type, aliasee val#, linkage]
1078 case bitc::MODULE_CODE_ALIAS: {
1079 if (Record.size() < 3)
1080 return Error("Invalid MODULE_ALIAS record");
1081 const Type *Ty = getTypeByID(Record[0]);
1082 if (!isa<PointerType>(Ty))
1083 return Error("Function not a pointer type!");
1085 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1087 ValueList.push_back(NewGA);
1088 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1091 /// MODULE_CODE_PURGEVALS: [numvals]
1092 case bitc::MODULE_CODE_PURGEVALS:
1093 // Trim down the value list to the specified size.
1094 if (Record.size() < 1 || Record[0] > ValueList.size())
1095 return Error("Invalid MODULE_PURGEVALS record");
1096 ValueList.shrinkTo(Record[0]);
1102 return Error("Premature end of bitstream");
1106 bool BitcodeReader::ParseBitcode() {
1109 if (Buffer->getBufferSize() & 3)
1110 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1112 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1113 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1115 // Sniff for the signature.
1116 if (Stream.Read(8) != 'B' ||
1117 Stream.Read(8) != 'C' ||
1118 Stream.Read(4) != 0x0 ||
1119 Stream.Read(4) != 0xC ||
1120 Stream.Read(4) != 0xE ||
1121 Stream.Read(4) != 0xD)
1122 return Error("Invalid bitcode signature");
1124 // We expect a number of well-defined blocks, though we don't necessarily
1125 // need to understand them all.
1126 while (!Stream.AtEndOfStream()) {
1127 unsigned Code = Stream.ReadCode();
1129 if (Code != bitc::ENTER_SUBBLOCK)
1130 return Error("Invalid record at top-level");
1132 unsigned BlockID = Stream.ReadSubBlockID();
1134 // We only know the MODULE subblock ID.
1136 case bitc::BLOCKINFO_BLOCK_ID:
1137 if (Stream.ReadBlockInfoBlock())
1138 return Error("Malformed BlockInfoBlock");
1140 case bitc::MODULE_BLOCK_ID:
1141 if (ParseModule(Buffer->getBufferIdentifier()))
1145 if (Stream.SkipBlock())
1146 return Error("Malformed block record");
1155 /// ParseFunctionBody - Lazily parse the specified function body block.
1156 bool BitcodeReader::ParseFunctionBody(Function *F) {
1157 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1158 return Error("Malformed block record");
1160 unsigned ModuleValueListSize = ValueList.size();
1162 // Add all the function arguments to the value table.
1163 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1164 ValueList.push_back(I);
1166 unsigned NextValueNo = ValueList.size();
1167 BasicBlock *CurBB = 0;
1168 unsigned CurBBNo = 0;
1170 // Read all the records.
1171 SmallVector<uint64_t, 64> Record;
1173 unsigned Code = Stream.ReadCode();
1174 if (Code == bitc::END_BLOCK) {
1175 if (Stream.ReadBlockEnd())
1176 return Error("Error at end of function block");
1180 if (Code == bitc::ENTER_SUBBLOCK) {
1181 switch (Stream.ReadSubBlockID()) {
1182 default: // Skip unknown content.
1183 if (Stream.SkipBlock())
1184 return Error("Malformed block record");
1186 case bitc::CONSTANTS_BLOCK_ID:
1187 if (ParseConstants()) return true;
1188 NextValueNo = ValueList.size();
1190 case bitc::VALUE_SYMTAB_BLOCK_ID:
1191 if (ParseValueSymbolTable()) return true;
1197 if (Code == bitc::DEFINE_ABBREV) {
1198 Stream.ReadAbbrevRecord();
1205 switch (Stream.ReadRecord(Code, Record)) {
1206 default: // Default behavior: reject
1207 return Error("Unknown instruction");
1208 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1209 if (Record.size() < 1 || Record[0] == 0)
1210 return Error("Invalid DECLAREBLOCKS record");
1211 // Create all the basic blocks for the function.
1212 FunctionBBs.resize(Record[0]);
1213 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1214 FunctionBBs[i] = new BasicBlock("", F);
1215 CurBB = FunctionBBs[0];
1218 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1221 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1222 getValue(Record, OpNum, LHS->getType(), RHS) ||
1223 OpNum+1 != Record.size())
1224 return Error("Invalid BINOP record");
1226 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1227 if (Opc == -1) return Error("Invalid BINOP record");
1228 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1231 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1234 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1235 OpNum+2 != Record.size())
1236 return Error("Invalid CAST record");
1238 const Type *ResTy = getTypeByID(Record[OpNum]);
1239 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1240 if (Opc == -1 || ResTy == 0)
1241 return Error("Invalid CAST record");
1242 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1245 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1248 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1249 return Error("Invalid GEP record");
1251 SmallVector<Value*, 16> GEPIdx;
1252 while (OpNum != Record.size()) {
1254 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1255 return Error("Invalid GEP record");
1256 GEPIdx.push_back(Op);
1259 I = new GetElementPtrInst(BasePtr, GEPIdx.begin(), GEPIdx.end());
1263 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1265 Value *TrueVal, *FalseVal, *Cond;
1266 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1267 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1268 getValue(Record, OpNum, Type::Int1Ty, Cond))
1269 return Error("Invalid SELECT record");
1271 I = new SelectInst(Cond, TrueVal, FalseVal);
1275 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1278 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1279 getValue(Record, OpNum, Type::Int32Ty, Idx))
1280 return Error("Invalid EXTRACTELT record");
1281 I = new ExtractElementInst(Vec, Idx);
1285 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1287 Value *Vec, *Elt, *Idx;
1288 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1289 getValue(Record, OpNum,
1290 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1291 getValue(Record, OpNum, Type::Int32Ty, Idx))
1292 return Error("Invalid INSERTELT record");
1293 I = new InsertElementInst(Vec, Elt, Idx);
1297 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1299 Value *Vec1, *Vec2, *Mask;
1300 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1301 getValue(Record, OpNum, Vec1->getType(), Vec2))
1302 return Error("Invalid SHUFFLEVEC record");
1304 const Type *MaskTy =
1305 VectorType::get(Type::Int32Ty,
1306 cast<VectorType>(Vec1->getType())->getNumElements());
1308 if (getValue(Record, OpNum, MaskTy, Mask))
1309 return Error("Invalid SHUFFLEVEC record");
1310 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1314 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1317 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1318 getValue(Record, OpNum, LHS->getType(), RHS) ||
1319 OpNum+1 != Record.size())
1320 return Error("Invalid CMP record");
1322 if (LHS->getType()->isFPOrFPVector())
1323 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1325 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1328 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1329 if (Record.size() != 2)
1330 return Error("Invalid GETRESULT record");
1333 getValueTypePair(Record, OpNum, NextValueNo, Op);
1334 unsigned Index = Record[1];
1335 I = new GetResultInst(Op, Index);
1339 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1340 if (Record.empty()) {
1341 I = new ReturnInst();
1346 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1347 OpNum != Record.size())
1348 return Error("Invalid RET record");
1349 I = new ReturnInst(Op);
1352 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1353 if (Record.size() != 1 && Record.size() != 3)
1354 return Error("Invalid BR record");
1355 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1357 return Error("Invalid BR record");
1359 if (Record.size() == 1)
1360 I = new BranchInst(TrueDest);
1362 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1363 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1364 if (FalseDest == 0 || Cond == 0)
1365 return Error("Invalid BR record");
1366 I = new BranchInst(TrueDest, FalseDest, Cond);
1370 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1371 if (Record.size() < 3 || (Record.size() & 1) == 0)
1372 return Error("Invalid SWITCH record");
1373 const Type *OpTy = getTypeByID(Record[0]);
1374 Value *Cond = getFnValueByID(Record[1], OpTy);
1375 BasicBlock *Default = getBasicBlock(Record[2]);
1376 if (OpTy == 0 || Cond == 0 || Default == 0)
1377 return Error("Invalid SWITCH record");
1378 unsigned NumCases = (Record.size()-3)/2;
1379 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1380 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1381 ConstantInt *CaseVal =
1382 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1383 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1384 if (CaseVal == 0 || DestBB == 0) {
1386 return Error("Invalid SWITCH record!");
1388 SI->addCase(CaseVal, DestBB);
1394 case bitc::FUNC_CODE_INST_INVOKE: {
1395 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1396 if (Record.size() < 4) return Error("Invalid INVOKE record");
1397 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
1398 unsigned CCInfo = Record[1];
1399 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1400 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1404 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1405 return Error("Invalid INVOKE record");
1407 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1408 const FunctionType *FTy = !CalleeTy ? 0 :
1409 dyn_cast<FunctionType>(CalleeTy->getElementType());
1411 // Check that the right number of fixed parameters are here.
1412 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1413 Record.size() < OpNum+FTy->getNumParams())
1414 return Error("Invalid INVOKE record");
1416 SmallVector<Value*, 16> Ops;
1417 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1418 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1419 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1422 if (!FTy->isVarArg()) {
1423 if (Record.size() != OpNum)
1424 return Error("Invalid INVOKE record");
1426 // Read type/value pairs for varargs params.
1427 while (OpNum != Record.size()) {
1429 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1430 return Error("Invalid INVOKE record");
1435 I = new InvokeInst(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
1436 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1437 cast<InvokeInst>(I)->setParamAttrs(PAL);
1440 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1441 I = new UnwindInst();
1443 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1444 I = new UnreachableInst();
1446 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1447 if (Record.size() < 1 || ((Record.size()-1)&1))
1448 return Error("Invalid PHI record");
1449 const Type *Ty = getTypeByID(Record[0]);
1450 if (!Ty) return Error("Invalid PHI record");
1452 PHINode *PN = new PHINode(Ty);
1453 PN->reserveOperandSpace(Record.size()-1);
1455 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1456 Value *V = getFnValueByID(Record[1+i], Ty);
1457 BasicBlock *BB = getBasicBlock(Record[2+i]);
1458 if (!V || !BB) return Error("Invalid PHI record");
1459 PN->addIncoming(V, BB);
1465 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1466 if (Record.size() < 3)
1467 return Error("Invalid MALLOC record");
1468 const PointerType *Ty =
1469 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1470 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1471 unsigned Align = Record[2];
1472 if (!Ty || !Size) return Error("Invalid MALLOC record");
1473 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1476 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1479 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1480 OpNum != Record.size())
1481 return Error("Invalid FREE record");
1482 I = new FreeInst(Op);
1485 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1486 if (Record.size() < 3)
1487 return Error("Invalid ALLOCA record");
1488 const PointerType *Ty =
1489 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1490 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1491 unsigned Align = Record[2];
1492 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1493 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1496 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1499 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1500 OpNum+2 != Record.size())
1501 return Error("Invalid LOAD record");
1503 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1506 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1509 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1510 getValue(Record, OpNum,
1511 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1512 OpNum+2 != Record.size())
1513 return Error("Invalid STORE record");
1515 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1518 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1519 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1522 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1523 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
1524 OpNum+2 != Record.size())
1525 return Error("Invalid STORE record");
1527 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1530 case bitc::FUNC_CODE_INST_CALL: {
1531 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1532 if (Record.size() < 3)
1533 return Error("Invalid CALL record");
1535 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
1536 unsigned CCInfo = Record[1];
1540 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1541 return Error("Invalid CALL record");
1543 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1544 const FunctionType *FTy = 0;
1545 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1546 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1547 return Error("Invalid CALL record");
1549 SmallVector<Value*, 16> Args;
1550 // Read the fixed params.
1551 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1552 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1553 Args.push_back(getBasicBlock(Record[OpNum]));
1555 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1556 if (Args.back() == 0) return Error("Invalid CALL record");
1559 // Read type/value pairs for varargs params.
1560 if (!FTy->isVarArg()) {
1561 if (OpNum != Record.size())
1562 return Error("Invalid CALL record");
1564 while (OpNum != Record.size()) {
1566 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1567 return Error("Invalid CALL record");
1572 I = new CallInst(Callee, Args.begin(), Args.end());
1573 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1574 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1575 cast<CallInst>(I)->setParamAttrs(PAL);
1578 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1579 if (Record.size() < 3)
1580 return Error("Invalid VAARG record");
1581 const Type *OpTy = getTypeByID(Record[0]);
1582 Value *Op = getFnValueByID(Record[1], OpTy);
1583 const Type *ResTy = getTypeByID(Record[2]);
1584 if (!OpTy || !Op || !ResTy)
1585 return Error("Invalid VAARG record");
1586 I = new VAArgInst(Op, ResTy);
1591 // Add instruction to end of current BB. If there is no current BB, reject
1595 return Error("Invalid instruction with no BB");
1597 CurBB->getInstList().push_back(I);
1599 // If this was a terminator instruction, move to the next block.
1600 if (isa<TerminatorInst>(I)) {
1602 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1605 // Non-void values get registered in the value table for future use.
1606 if (I && I->getType() != Type::VoidTy)
1607 ValueList.AssignValue(I, NextValueNo++);
1610 // Check the function list for unresolved values.
1611 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1612 if (A->getParent() == 0) {
1613 // We found at least one unresolved value. Nuke them all to avoid leaks.
1614 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1615 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1616 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1620 return Error("Never resolved value found in function!");
1624 // Trim the value list down to the size it was before we parsed this function.
1625 ValueList.shrinkTo(ModuleValueListSize);
1626 std::vector<BasicBlock*>().swap(FunctionBBs);
1631 //===----------------------------------------------------------------------===//
1632 // ModuleProvider implementation
1633 //===----------------------------------------------------------------------===//
1636 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1637 // If it already is material, ignore the request.
1638 if (!F->hasNotBeenReadFromBitcode()) return false;
1640 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1641 DeferredFunctionInfo.find(F);
1642 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1644 // Move the bit stream to the saved position of the deferred function body and
1645 // restore the real linkage type for the function.
1646 Stream.JumpToBit(DFII->second.first);
1647 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1649 if (ParseFunctionBody(F)) {
1650 if (ErrInfo) *ErrInfo = ErrorString;
1654 // Upgrade any old intrinsic calls in the function.
1655 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1656 E = UpgradedIntrinsics.end(); I != E; ++I) {
1657 if (I->first != I->second) {
1658 for (Value::use_iterator UI = I->first->use_begin(),
1659 UE = I->first->use_end(); UI != UE; ) {
1660 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1661 UpgradeIntrinsicCall(CI, I->second);
1669 void BitcodeReader::dematerializeFunction(Function *F) {
1670 // If this function isn't materialized, or if it is a proto, this is a noop.
1671 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1674 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1676 // Just forget the function body, we can remat it later.
1678 F->setLinkage(GlobalValue::GhostLinkage);
1682 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1683 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1684 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1686 Function *F = I->first;
1687 if (F->hasNotBeenReadFromBitcode() &&
1688 materializeFunction(F, ErrInfo))
1692 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1693 // delete the old functions to clean up. We can't do this unless the entire
1694 // module is materialized because there could always be another function body
1695 // with calls to the old function.
1696 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1697 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1698 if (I->first != I->second) {
1699 for (Value::use_iterator UI = I->first->use_begin(),
1700 UE = I->first->use_end(); UI != UE; ) {
1701 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1702 UpgradeIntrinsicCall(CI, I->second);
1704 ValueList.replaceUsesOfWith(I->first, I->second);
1705 I->first->eraseFromParent();
1708 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1714 /// This method is provided by the parent ModuleProvde class and overriden
1715 /// here. It simply releases the module from its provided and frees up our
1717 /// @brief Release our hold on the generated module
1718 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1719 // Since we're losing control of this Module, we must hand it back complete
1720 Module *M = ModuleProvider::releaseModule(ErrInfo);
1726 //===----------------------------------------------------------------------===//
1727 // External interface
1728 //===----------------------------------------------------------------------===//
1730 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1732 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1733 std::string *ErrMsg) {
1734 BitcodeReader *R = new BitcodeReader(Buffer);
1735 if (R->ParseBitcode()) {
1737 *ErrMsg = R->getErrorString();
1739 // Don't let the BitcodeReader dtor delete 'Buffer'.
1740 R->releaseMemoryBuffer();
1747 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1748 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1749 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1751 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1754 // Read in the entire module.
1755 Module *M = R->materializeModule(ErrMsg);
1757 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1758 // there was an error.
1759 R->releaseMemoryBuffer();
1761 // If there was no error, tell ModuleProvider not to delete it when its dtor
1764 M = R->releaseModule(ErrMsg);