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/AutoUpgrade.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/MemoryBuffer.h"
28 void BitcodeReader::FreeState() {
31 std::vector<PATypeHolder>().swap(TypeList);
34 std::vector<PAListPtr>().swap(ParamAttrs);
35 std::vector<BasicBlock*>().swap(FunctionBBs);
36 std::vector<Function*>().swap(FunctionsWithBodies);
37 DeferredFunctionInfo.clear();
40 //===----------------------------------------------------------------------===//
41 // Helper functions to implement forward reference resolution, etc.
42 //===----------------------------------------------------------------------===//
44 /// ConvertToString - Convert a string from a record into an std::string, return
46 template<typename StrTy>
47 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
49 if (Idx > Record.size())
52 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
53 Result += (char)Record[i];
57 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
59 default: // Map unknown/new linkages to external
60 case 0: return GlobalValue::ExternalLinkage;
61 case 1: return GlobalValue::WeakLinkage;
62 case 2: return GlobalValue::AppendingLinkage;
63 case 3: return GlobalValue::InternalLinkage;
64 case 4: return GlobalValue::LinkOnceLinkage;
65 case 5: return GlobalValue::DLLImportLinkage;
66 case 6: return GlobalValue::DLLExportLinkage;
67 case 7: return GlobalValue::ExternalWeakLinkage;
71 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
73 default: // Map unknown visibilities to default.
74 case 0: return GlobalValue::DefaultVisibility;
75 case 1: return GlobalValue::HiddenVisibility;
76 case 2: return GlobalValue::ProtectedVisibility;
80 static int GetDecodedCastOpcode(unsigned Val) {
83 case bitc::CAST_TRUNC : return Instruction::Trunc;
84 case bitc::CAST_ZEXT : return Instruction::ZExt;
85 case bitc::CAST_SEXT : return Instruction::SExt;
86 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
87 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
88 case bitc::CAST_UITOFP : return Instruction::UIToFP;
89 case bitc::CAST_SITOFP : return Instruction::SIToFP;
90 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
91 case bitc::CAST_FPEXT : return Instruction::FPExt;
92 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
93 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
94 case bitc::CAST_BITCAST : return Instruction::BitCast;
97 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
100 case bitc::BINOP_ADD: return Instruction::Add;
101 case bitc::BINOP_SUB: return Instruction::Sub;
102 case bitc::BINOP_MUL: return Instruction::Mul;
103 case bitc::BINOP_UDIV: return Instruction::UDiv;
104 case bitc::BINOP_SDIV:
105 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
106 case bitc::BINOP_UREM: return Instruction::URem;
107 case bitc::BINOP_SREM:
108 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
109 case bitc::BINOP_SHL: return Instruction::Shl;
110 case bitc::BINOP_LSHR: return Instruction::LShr;
111 case bitc::BINOP_ASHR: return Instruction::AShr;
112 case bitc::BINOP_AND: return Instruction::And;
113 case bitc::BINOP_OR: return Instruction::Or;
114 case bitc::BINOP_XOR: return Instruction::Xor;
120 /// @brief A class for maintaining the slot number definition
121 /// as a placeholder for the actual definition for forward constants defs.
122 class ConstantPlaceHolder : public ConstantExpr {
123 ConstantPlaceHolder(); // DO NOT IMPLEMENT
124 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
127 // allocate space for exactly one operand
128 void *operator new(size_t s) {
129 return User::operator new(s, 1);
131 explicit ConstantPlaceHolder(const Type *Ty)
132 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
133 Op(UndefValue::get(Type::Int32Ty), this) {
138 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
141 // Insert a bunch of null values.
143 OperandList = &Uses[0];
147 if (Value *V = Uses[Idx]) {
148 assert(Ty == V->getType() && "Type mismatch in constant table!");
149 return cast<Constant>(V);
152 // Create and return a placeholder, which will later be RAUW'd.
153 Constant *C = new ConstantPlaceHolder(Ty);
154 Uses[Idx].init(C, this);
158 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
160 // Insert a bunch of null values.
162 OperandList = &Uses[0];
166 if (Value *V = Uses[Idx]) {
167 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
171 // No type specified, must be invalid reference.
172 if (Ty == 0) return 0;
174 // Create and return a placeholder, which will later be RAUW'd.
175 Value *V = new Argument(Ty);
176 Uses[Idx].init(V, this);
181 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
182 // If the TypeID is in range, return it.
183 if (ID < TypeList.size())
184 return TypeList[ID].get();
185 if (!isTypeTable) return 0;
187 // The type table allows forward references. Push as many Opaque types as
188 // needed to get up to ID.
189 while (TypeList.size() <= ID)
190 TypeList.push_back(OpaqueType::get());
191 return TypeList.back().get();
194 //===----------------------------------------------------------------------===//
195 // Functions for parsing blocks from the bitcode file
196 //===----------------------------------------------------------------------===//
198 bool BitcodeReader::ParseParamAttrBlock() {
199 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
200 return Error("Malformed block record");
202 if (!ParamAttrs.empty())
203 return Error("Multiple PARAMATTR blocks found!");
205 SmallVector<uint64_t, 64> Record;
207 SmallVector<ParamAttrsWithIndex, 8> Attrs;
209 // Read all the records.
211 unsigned Code = Stream.ReadCode();
212 if (Code == bitc::END_BLOCK) {
213 if (Stream.ReadBlockEnd())
214 return Error("Error at end of PARAMATTR block");
218 if (Code == bitc::ENTER_SUBBLOCK) {
219 // No known subblocks, always skip them.
220 Stream.ReadSubBlockID();
221 if (Stream.SkipBlock())
222 return Error("Malformed block record");
226 if (Code == bitc::DEFINE_ABBREV) {
227 Stream.ReadAbbrevRecord();
233 switch (Stream.ReadRecord(Code, Record)) {
234 default: // Default behavior: ignore.
236 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
237 if (Record.size() & 1)
238 return Error("Invalid ENTRY record");
240 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
241 if (Record[i+1] != ParamAttr::None)
242 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
245 ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end()));
254 bool BitcodeReader::ParseTypeTable() {
255 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
256 return Error("Malformed block record");
258 if (!TypeList.empty())
259 return Error("Multiple TYPE_BLOCKs found!");
261 SmallVector<uint64_t, 64> Record;
262 unsigned NumRecords = 0;
264 // Read all the records for this type table.
266 unsigned Code = Stream.ReadCode();
267 if (Code == bitc::END_BLOCK) {
268 if (NumRecords != TypeList.size())
269 return Error("Invalid type forward reference in TYPE_BLOCK");
270 if (Stream.ReadBlockEnd())
271 return Error("Error at end of type table block");
275 if (Code == bitc::ENTER_SUBBLOCK) {
276 // No known subblocks, always skip them.
277 Stream.ReadSubBlockID();
278 if (Stream.SkipBlock())
279 return Error("Malformed block record");
283 if (Code == bitc::DEFINE_ABBREV) {
284 Stream.ReadAbbrevRecord();
290 const Type *ResultTy = 0;
291 switch (Stream.ReadRecord(Code, Record)) {
292 default: // Default behavior: unknown type.
295 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
296 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
297 // type list. This allows us to reserve space.
298 if (Record.size() < 1)
299 return Error("Invalid TYPE_CODE_NUMENTRY record");
300 TypeList.reserve(Record[0]);
302 case bitc::TYPE_CODE_VOID: // VOID
303 ResultTy = Type::VoidTy;
305 case bitc::TYPE_CODE_FLOAT: // FLOAT
306 ResultTy = Type::FloatTy;
308 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
309 ResultTy = Type::DoubleTy;
311 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
312 ResultTy = Type::X86_FP80Ty;
314 case bitc::TYPE_CODE_FP128: // FP128
315 ResultTy = Type::FP128Ty;
317 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
318 ResultTy = Type::PPC_FP128Ty;
320 case bitc::TYPE_CODE_LABEL: // LABEL
321 ResultTy = Type::LabelTy;
323 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
326 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
327 if (Record.size() < 1)
328 return Error("Invalid Integer type record");
330 ResultTy = IntegerType::get(Record[0]);
332 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
333 // [pointee type, address space]
334 if (Record.size() < 1)
335 return Error("Invalid POINTER type record");
336 unsigned AddressSpace = 0;
337 if (Record.size() == 2)
338 AddressSpace = Record[1];
339 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
342 case bitc::TYPE_CODE_FUNCTION: {
343 // FIXME: attrid is dead, remove it in LLVM 3.0
344 // FUNCTION: [vararg, attrid, retty, paramty x N]
345 if (Record.size() < 3)
346 return Error("Invalid FUNCTION type record");
347 std::vector<const Type*> ArgTys;
348 for (unsigned i = 3, e = Record.size(); i != e; ++i)
349 ArgTys.push_back(getTypeByID(Record[i], true));
351 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
355 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
356 if (Record.size() < 1)
357 return Error("Invalid STRUCT type record");
358 std::vector<const Type*> EltTys;
359 for (unsigned i = 1, e = Record.size(); i != e; ++i)
360 EltTys.push_back(getTypeByID(Record[i], true));
361 ResultTy = StructType::get(EltTys, Record[0]);
364 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
365 if (Record.size() < 2)
366 return Error("Invalid ARRAY type record");
367 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
369 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
370 if (Record.size() < 2)
371 return Error("Invalid VECTOR type record");
372 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
376 if (NumRecords == TypeList.size()) {
377 // If this is a new type slot, just append it.
378 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
380 } else if (ResultTy == 0) {
381 // Otherwise, this was forward referenced, so an opaque type was created,
382 // but the result type is actually just an opaque. Leave the one we
383 // created previously.
386 // Otherwise, this was forward referenced, so an opaque type was created.
387 // Resolve the opaque type to the real type now.
388 assert(NumRecords < TypeList.size() && "Typelist imbalance");
389 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
391 // Don't directly push the new type on the Tab. Instead we want to replace
392 // the opaque type we previously inserted with the new concrete value. The
393 // refinement from the abstract (opaque) type to the new type causes all
394 // uses of the abstract type to use the concrete type (NewTy). This will
395 // also cause the opaque type to be deleted.
396 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
398 // This should have replaced the old opaque type with the new type in the
399 // value table... or with a preexisting type that was already in the
400 // system. Let's just make sure it did.
401 assert(TypeList[NumRecords-1].get() != OldTy &&
402 "refineAbstractType didn't work!");
408 bool BitcodeReader::ParseTypeSymbolTable() {
409 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
410 return Error("Malformed block record");
412 SmallVector<uint64_t, 64> Record;
414 // Read all the records for this type table.
415 std::string TypeName;
417 unsigned Code = Stream.ReadCode();
418 if (Code == bitc::END_BLOCK) {
419 if (Stream.ReadBlockEnd())
420 return Error("Error at end of type symbol table block");
424 if (Code == bitc::ENTER_SUBBLOCK) {
425 // No known subblocks, always skip them.
426 Stream.ReadSubBlockID();
427 if (Stream.SkipBlock())
428 return Error("Malformed block record");
432 if (Code == bitc::DEFINE_ABBREV) {
433 Stream.ReadAbbrevRecord();
439 switch (Stream.ReadRecord(Code, Record)) {
440 default: // Default behavior: unknown type.
442 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
443 if (ConvertToString(Record, 1, TypeName))
444 return Error("Invalid TST_ENTRY record");
445 unsigned TypeID = Record[0];
446 if (TypeID >= TypeList.size())
447 return Error("Invalid Type ID in TST_ENTRY record");
449 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
456 bool BitcodeReader::ParseValueSymbolTable() {
457 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
458 return Error("Malformed block record");
460 SmallVector<uint64_t, 64> Record;
462 // Read all the records for this value table.
463 SmallString<128> ValueName;
465 unsigned Code = Stream.ReadCode();
466 if (Code == bitc::END_BLOCK) {
467 if (Stream.ReadBlockEnd())
468 return Error("Error at end of value symbol table block");
471 if (Code == bitc::ENTER_SUBBLOCK) {
472 // No known subblocks, always skip them.
473 Stream.ReadSubBlockID();
474 if (Stream.SkipBlock())
475 return Error("Malformed block record");
479 if (Code == bitc::DEFINE_ABBREV) {
480 Stream.ReadAbbrevRecord();
486 switch (Stream.ReadRecord(Code, Record)) {
487 default: // Default behavior: unknown type.
489 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
490 if (ConvertToString(Record, 1, ValueName))
491 return Error("Invalid TST_ENTRY record");
492 unsigned ValueID = Record[0];
493 if (ValueID >= ValueList.size())
494 return Error("Invalid Value ID in VST_ENTRY record");
495 Value *V = ValueList[ValueID];
497 V->setName(&ValueName[0], ValueName.size());
501 case bitc::VST_CODE_BBENTRY: {
502 if (ConvertToString(Record, 1, ValueName))
503 return Error("Invalid VST_BBENTRY record");
504 BasicBlock *BB = getBasicBlock(Record[0]);
506 return Error("Invalid BB ID in VST_BBENTRY record");
508 BB->setName(&ValueName[0], ValueName.size());
516 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
517 /// the LSB for dense VBR encoding.
518 static uint64_t DecodeSignRotatedValue(uint64_t V) {
523 // There is no such thing as -0 with integers. "-0" really means MININT.
527 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
528 /// values and aliases that we can.
529 bool BitcodeReader::ResolveGlobalAndAliasInits() {
530 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
531 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
533 GlobalInitWorklist.swap(GlobalInits);
534 AliasInitWorklist.swap(AliasInits);
536 while (!GlobalInitWorklist.empty()) {
537 unsigned ValID = GlobalInitWorklist.back().second;
538 if (ValID >= ValueList.size()) {
539 // Not ready to resolve this yet, it requires something later in the file.
540 GlobalInits.push_back(GlobalInitWorklist.back());
542 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
543 GlobalInitWorklist.back().first->setInitializer(C);
545 return Error("Global variable initializer is not a constant!");
547 GlobalInitWorklist.pop_back();
550 while (!AliasInitWorklist.empty()) {
551 unsigned ValID = AliasInitWorklist.back().second;
552 if (ValID >= ValueList.size()) {
553 AliasInits.push_back(AliasInitWorklist.back());
555 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
556 AliasInitWorklist.back().first->setAliasee(C);
558 return Error("Alias initializer is not a constant!");
560 AliasInitWorklist.pop_back();
566 bool BitcodeReader::ParseConstants() {
567 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
568 return Error("Malformed block record");
570 SmallVector<uint64_t, 64> Record;
572 // Read all the records for this value table.
573 const Type *CurTy = Type::Int32Ty;
574 unsigned NextCstNo = ValueList.size();
576 unsigned Code = Stream.ReadCode();
577 if (Code == bitc::END_BLOCK) {
578 if (NextCstNo != ValueList.size())
579 return Error("Invalid constant reference!");
581 if (Stream.ReadBlockEnd())
582 return Error("Error at end of constants block");
586 if (Code == bitc::ENTER_SUBBLOCK) {
587 // No known subblocks, always skip them.
588 Stream.ReadSubBlockID();
589 if (Stream.SkipBlock())
590 return Error("Malformed block record");
594 if (Code == bitc::DEFINE_ABBREV) {
595 Stream.ReadAbbrevRecord();
602 switch (Stream.ReadRecord(Code, Record)) {
603 default: // Default behavior: unknown constant
604 case bitc::CST_CODE_UNDEF: // UNDEF
605 V = UndefValue::get(CurTy);
607 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
609 return Error("Malformed CST_SETTYPE record");
610 if (Record[0] >= TypeList.size())
611 return Error("Invalid Type ID in CST_SETTYPE record");
612 CurTy = TypeList[Record[0]];
613 continue; // Skip the ValueList manipulation.
614 case bitc::CST_CODE_NULL: // NULL
615 V = Constant::getNullValue(CurTy);
617 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
618 if (!isa<IntegerType>(CurTy) || Record.empty())
619 return Error("Invalid CST_INTEGER record");
620 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
622 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
623 if (!isa<IntegerType>(CurTy) || Record.empty())
624 return Error("Invalid WIDE_INTEGER record");
626 unsigned NumWords = Record.size();
627 SmallVector<uint64_t, 8> Words;
628 Words.resize(NumWords);
629 for (unsigned i = 0; i != NumWords; ++i)
630 Words[i] = DecodeSignRotatedValue(Record[i]);
631 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
632 NumWords, &Words[0]));
635 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
637 return Error("Invalid FLOAT record");
638 if (CurTy == Type::FloatTy)
639 V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
640 else if (CurTy == Type::DoubleTy)
641 V = ConstantFP::get(APFloat(APInt(64, Record[0])));
642 else if (CurTy == Type::X86_FP80Ty)
643 V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
644 else if (CurTy == Type::FP128Ty)
645 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
646 else if (CurTy == Type::PPC_FP128Ty)
647 V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
649 V = UndefValue::get(CurTy);
653 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
655 return Error("Invalid CST_AGGREGATE record");
657 unsigned Size = Record.size();
658 std::vector<Constant*> Elts;
660 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
661 for (unsigned i = 0; i != Size; ++i)
662 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
663 STy->getElementType(i)));
664 V = ConstantStruct::get(STy, Elts);
665 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
666 const Type *EltTy = ATy->getElementType();
667 for (unsigned i = 0; i != Size; ++i)
668 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
669 V = ConstantArray::get(ATy, Elts);
670 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
671 const Type *EltTy = VTy->getElementType();
672 for (unsigned i = 0; i != Size; ++i)
673 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
674 V = ConstantVector::get(Elts);
676 V = UndefValue::get(CurTy);
680 case bitc::CST_CODE_STRING: { // STRING: [values]
682 return Error("Invalid CST_AGGREGATE record");
684 const ArrayType *ATy = cast<ArrayType>(CurTy);
685 const Type *EltTy = ATy->getElementType();
687 unsigned Size = Record.size();
688 std::vector<Constant*> Elts;
689 for (unsigned i = 0; i != Size; ++i)
690 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
691 V = ConstantArray::get(ATy, Elts);
694 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
696 return Error("Invalid CST_AGGREGATE record");
698 const ArrayType *ATy = cast<ArrayType>(CurTy);
699 const Type *EltTy = ATy->getElementType();
701 unsigned Size = Record.size();
702 std::vector<Constant*> Elts;
703 for (unsigned i = 0; i != Size; ++i)
704 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
705 Elts.push_back(Constant::getNullValue(EltTy));
706 V = ConstantArray::get(ATy, Elts);
709 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
710 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
711 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
713 V = UndefValue::get(CurTy); // Unknown binop.
715 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
716 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
717 V = ConstantExpr::get(Opc, LHS, RHS);
721 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
722 if (Record.size() < 3) return Error("Invalid CE_CAST record");
723 int Opc = GetDecodedCastOpcode(Record[0]);
725 V = UndefValue::get(CurTy); // Unknown cast.
727 const Type *OpTy = getTypeByID(Record[1]);
728 if (!OpTy) return Error("Invalid CE_CAST record");
729 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
730 V = ConstantExpr::getCast(Opc, Op, CurTy);
734 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
735 if (Record.size() & 1) return Error("Invalid CE_GEP record");
736 SmallVector<Constant*, 16> Elts;
737 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
738 const Type *ElTy = getTypeByID(Record[i]);
739 if (!ElTy) return Error("Invalid CE_GEP record");
740 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
742 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
745 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
746 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
747 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
749 ValueList.getConstantFwdRef(Record[1],CurTy),
750 ValueList.getConstantFwdRef(Record[2],CurTy));
752 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
753 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
754 const VectorType *OpTy =
755 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
756 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
757 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
758 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
759 OpTy->getElementType());
760 V = ConstantExpr::getExtractElement(Op0, Op1);
763 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
764 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
765 if (Record.size() < 3 || OpTy == 0)
766 return Error("Invalid CE_INSERTELT record");
767 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
768 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
769 OpTy->getElementType());
770 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
771 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
774 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
775 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
776 if (Record.size() < 3 || OpTy == 0)
777 return Error("Invalid CE_INSERTELT record");
778 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
779 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
780 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
781 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
782 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
785 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
786 if (Record.size() < 4) return Error("Invalid CE_CMP record");
787 const Type *OpTy = getTypeByID(Record[0]);
788 if (OpTy == 0) return Error("Invalid CE_CMP record");
789 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
790 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
792 if (OpTy->isFloatingPoint())
793 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
795 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
798 case bitc::CST_CODE_INLINEASM: {
799 if (Record.size() < 2) return Error("Invalid INLINEASM record");
800 std::string AsmStr, ConstrStr;
801 bool HasSideEffects = Record[0];
802 unsigned AsmStrSize = Record[1];
803 if (2+AsmStrSize >= Record.size())
804 return Error("Invalid INLINEASM record");
805 unsigned ConstStrSize = Record[2+AsmStrSize];
806 if (3+AsmStrSize+ConstStrSize > Record.size())
807 return Error("Invalid INLINEASM record");
809 for (unsigned i = 0; i != AsmStrSize; ++i)
810 AsmStr += (char)Record[2+i];
811 for (unsigned i = 0; i != ConstStrSize; ++i)
812 ConstrStr += (char)Record[3+AsmStrSize+i];
813 const PointerType *PTy = cast<PointerType>(CurTy);
814 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
815 AsmStr, ConstrStr, HasSideEffects);
820 ValueList.AssignValue(V, NextCstNo);
825 /// RememberAndSkipFunctionBody - When we see the block for a function body,
826 /// remember where it is and then skip it. This lets us lazily deserialize the
828 bool BitcodeReader::RememberAndSkipFunctionBody() {
829 // Get the function we are talking about.
830 if (FunctionsWithBodies.empty())
831 return Error("Insufficient function protos");
833 Function *Fn = FunctionsWithBodies.back();
834 FunctionsWithBodies.pop_back();
836 // Save the current stream state.
837 uint64_t CurBit = Stream.GetCurrentBitNo();
838 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
840 // Set the functions linkage to GhostLinkage so we know it is lazily
842 Fn->setLinkage(GlobalValue::GhostLinkage);
844 // Skip over the function block for now.
845 if (Stream.SkipBlock())
846 return Error("Malformed block record");
850 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
851 // Reject multiple MODULE_BLOCK's in a single bitstream.
853 return Error("Multiple MODULE_BLOCKs in same stream");
855 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
856 return Error("Malformed block record");
858 // Otherwise, create the module.
859 TheModule = new Module(ModuleID);
861 SmallVector<uint64_t, 64> Record;
862 std::vector<std::string> SectionTable;
863 std::vector<std::string> CollectorTable;
865 // Read all the records for this module.
866 while (!Stream.AtEndOfStream()) {
867 unsigned Code = Stream.ReadCode();
868 if (Code == bitc::END_BLOCK) {
869 if (Stream.ReadBlockEnd())
870 return Error("Error at end of module block");
872 // Patch the initializers for globals and aliases up.
873 ResolveGlobalAndAliasInits();
874 if (!GlobalInits.empty() || !AliasInits.empty())
875 return Error("Malformed global initializer set");
876 if (!FunctionsWithBodies.empty())
877 return Error("Too few function bodies found");
879 // Look for intrinsic functions which need to be upgraded at some point
880 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
883 if (UpgradeIntrinsicFunction(FI, NewFn))
884 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
887 // Force deallocation of memory for these vectors to favor the client that
888 // want lazy deserialization.
889 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
890 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
891 std::vector<Function*>().swap(FunctionsWithBodies);
895 if (Code == bitc::ENTER_SUBBLOCK) {
896 switch (Stream.ReadSubBlockID()) {
897 default: // Skip unknown content.
898 if (Stream.SkipBlock())
899 return Error("Malformed block record");
901 case bitc::BLOCKINFO_BLOCK_ID:
902 if (Stream.ReadBlockInfoBlock())
903 return Error("Malformed BlockInfoBlock");
905 case bitc::PARAMATTR_BLOCK_ID:
906 if (ParseParamAttrBlock())
909 case bitc::TYPE_BLOCK_ID:
910 if (ParseTypeTable())
913 case bitc::TYPE_SYMTAB_BLOCK_ID:
914 if (ParseTypeSymbolTable())
917 case bitc::VALUE_SYMTAB_BLOCK_ID:
918 if (ParseValueSymbolTable())
921 case bitc::CONSTANTS_BLOCK_ID:
922 if (ParseConstants() || ResolveGlobalAndAliasInits())
925 case bitc::FUNCTION_BLOCK_ID:
926 // If this is the first function body we've seen, reverse the
927 // FunctionsWithBodies list.
928 if (!HasReversedFunctionsWithBodies) {
929 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
930 HasReversedFunctionsWithBodies = true;
933 if (RememberAndSkipFunctionBody())
940 if (Code == bitc::DEFINE_ABBREV) {
941 Stream.ReadAbbrevRecord();
946 switch (Stream.ReadRecord(Code, Record)) {
947 default: break; // Default behavior, ignore unknown content.
948 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
949 if (Record.size() < 1)
950 return Error("Malformed MODULE_CODE_VERSION");
951 // Only version #0 is supported so far.
953 return Error("Unknown bitstream version!");
955 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
957 if (ConvertToString(Record, 0, S))
958 return Error("Invalid MODULE_CODE_TRIPLE record");
959 TheModule->setTargetTriple(S);
962 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
964 if (ConvertToString(Record, 0, S))
965 return Error("Invalid MODULE_CODE_DATALAYOUT record");
966 TheModule->setDataLayout(S);
969 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
971 if (ConvertToString(Record, 0, S))
972 return Error("Invalid MODULE_CODE_ASM record");
973 TheModule->setModuleInlineAsm(S);
976 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
978 if (ConvertToString(Record, 0, S))
979 return Error("Invalid MODULE_CODE_DEPLIB record");
980 TheModule->addLibrary(S);
983 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
985 if (ConvertToString(Record, 0, S))
986 return Error("Invalid MODULE_CODE_SECTIONNAME record");
987 SectionTable.push_back(S);
990 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
992 if (ConvertToString(Record, 0, S))
993 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
994 CollectorTable.push_back(S);
997 // GLOBALVAR: [pointer type, isconst, initid,
998 // linkage, alignment, section, visibility, threadlocal]
999 case bitc::MODULE_CODE_GLOBALVAR: {
1000 if (Record.size() < 6)
1001 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1002 const Type *Ty = getTypeByID(Record[0]);
1003 if (!isa<PointerType>(Ty))
1004 return Error("Global not a pointer type!");
1005 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1006 Ty = cast<PointerType>(Ty)->getElementType();
1008 bool isConstant = Record[1];
1009 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1010 unsigned Alignment = (1 << Record[4]) >> 1;
1011 std::string Section;
1013 if (Record[5]-1 >= SectionTable.size())
1014 return Error("Invalid section ID");
1015 Section = SectionTable[Record[5]-1];
1017 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1018 if (Record.size() > 6)
1019 Visibility = GetDecodedVisibility(Record[6]);
1020 bool isThreadLocal = false;
1021 if (Record.size() > 7)
1022 isThreadLocal = Record[7];
1024 GlobalVariable *NewGV =
1025 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1026 isThreadLocal, AddressSpace);
1027 NewGV->setAlignment(Alignment);
1028 if (!Section.empty())
1029 NewGV->setSection(Section);
1030 NewGV->setVisibility(Visibility);
1031 NewGV->setThreadLocal(isThreadLocal);
1033 ValueList.push_back(NewGV);
1035 // Remember which value to use for the global initializer.
1036 if (unsigned InitID = Record[2])
1037 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1040 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1041 // alignment, section, visibility, collector]
1042 case bitc::MODULE_CODE_FUNCTION: {
1043 if (Record.size() < 8)
1044 return Error("Invalid MODULE_CODE_FUNCTION record");
1045 const Type *Ty = getTypeByID(Record[0]);
1046 if (!isa<PointerType>(Ty))
1047 return Error("Function not a pointer type!");
1048 const FunctionType *FTy =
1049 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1051 return Error("Function not a pointer to function type!");
1053 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1056 Func->setCallingConv(Record[1]);
1057 bool isProto = Record[2];
1058 Func->setLinkage(GetDecodedLinkage(Record[3]));
1059 Func->setParamAttrs(getParamAttrs(Record[4]));
1061 Func->setAlignment((1 << Record[5]) >> 1);
1063 if (Record[6]-1 >= SectionTable.size())
1064 return Error("Invalid section ID");
1065 Func->setSection(SectionTable[Record[6]-1]);
1067 Func->setVisibility(GetDecodedVisibility(Record[7]));
1068 if (Record.size() > 8 && Record[8]) {
1069 if (Record[8]-1 > CollectorTable.size())
1070 return Error("Invalid collector ID");
1071 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1074 ValueList.push_back(Func);
1076 // If this is a function with a body, remember the prototype we are
1077 // creating now, so that we can match up the body with them later.
1079 FunctionsWithBodies.push_back(Func);
1082 // ALIAS: [alias type, aliasee val#, linkage]
1083 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1084 case bitc::MODULE_CODE_ALIAS: {
1085 if (Record.size() < 3)
1086 return Error("Invalid MODULE_ALIAS record");
1087 const Type *Ty = getTypeByID(Record[0]);
1088 if (!isa<PointerType>(Ty))
1089 return Error("Function not a pointer type!");
1091 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1093 // Old bitcode files didn't have visibility field.
1094 if (Record.size() > 3)
1095 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1096 ValueList.push_back(NewGA);
1097 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1100 /// MODULE_CODE_PURGEVALS: [numvals]
1101 case bitc::MODULE_CODE_PURGEVALS:
1102 // Trim down the value list to the specified size.
1103 if (Record.size() < 1 || Record[0] > ValueList.size())
1104 return Error("Invalid MODULE_PURGEVALS record");
1105 ValueList.shrinkTo(Record[0]);
1111 return Error("Premature end of bitstream");
1115 bool BitcodeReader::ParseBitcode() {
1118 if (Buffer->getBufferSize() & 3)
1119 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1121 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1122 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1124 // Sniff for the signature.
1125 if (Stream.Read(8) != 'B' ||
1126 Stream.Read(8) != 'C' ||
1127 Stream.Read(4) != 0x0 ||
1128 Stream.Read(4) != 0xC ||
1129 Stream.Read(4) != 0xE ||
1130 Stream.Read(4) != 0xD)
1131 return Error("Invalid bitcode signature");
1133 // We expect a number of well-defined blocks, though we don't necessarily
1134 // need to understand them all.
1135 while (!Stream.AtEndOfStream()) {
1136 unsigned Code = Stream.ReadCode();
1138 if (Code != bitc::ENTER_SUBBLOCK)
1139 return Error("Invalid record at top-level");
1141 unsigned BlockID = Stream.ReadSubBlockID();
1143 // We only know the MODULE subblock ID.
1145 case bitc::BLOCKINFO_BLOCK_ID:
1146 if (Stream.ReadBlockInfoBlock())
1147 return Error("Malformed BlockInfoBlock");
1149 case bitc::MODULE_BLOCK_ID:
1150 if (ParseModule(Buffer->getBufferIdentifier()))
1154 if (Stream.SkipBlock())
1155 return Error("Malformed block record");
1164 /// ParseFunctionBody - Lazily parse the specified function body block.
1165 bool BitcodeReader::ParseFunctionBody(Function *F) {
1166 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1167 return Error("Malformed block record");
1169 unsigned ModuleValueListSize = ValueList.size();
1171 // Add all the function arguments to the value table.
1172 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1173 ValueList.push_back(I);
1175 unsigned NextValueNo = ValueList.size();
1176 BasicBlock *CurBB = 0;
1177 unsigned CurBBNo = 0;
1179 // Read all the records.
1180 SmallVector<uint64_t, 64> Record;
1182 unsigned Code = Stream.ReadCode();
1183 if (Code == bitc::END_BLOCK) {
1184 if (Stream.ReadBlockEnd())
1185 return Error("Error at end of function block");
1189 if (Code == bitc::ENTER_SUBBLOCK) {
1190 switch (Stream.ReadSubBlockID()) {
1191 default: // Skip unknown content.
1192 if (Stream.SkipBlock())
1193 return Error("Malformed block record");
1195 case bitc::CONSTANTS_BLOCK_ID:
1196 if (ParseConstants()) return true;
1197 NextValueNo = ValueList.size();
1199 case bitc::VALUE_SYMTAB_BLOCK_ID:
1200 if (ParseValueSymbolTable()) return true;
1206 if (Code == bitc::DEFINE_ABBREV) {
1207 Stream.ReadAbbrevRecord();
1214 switch (Stream.ReadRecord(Code, Record)) {
1215 default: // Default behavior: reject
1216 return Error("Unknown instruction");
1217 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1218 if (Record.size() < 1 || Record[0] == 0)
1219 return Error("Invalid DECLAREBLOCKS record");
1220 // Create all the basic blocks for the function.
1221 FunctionBBs.resize(Record[0]);
1222 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1223 FunctionBBs[i] = BasicBlock::Create("", F);
1224 CurBB = FunctionBBs[0];
1227 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1230 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1231 getValue(Record, OpNum, LHS->getType(), RHS) ||
1232 OpNum+1 != Record.size())
1233 return Error("Invalid BINOP record");
1235 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1236 if (Opc == -1) return Error("Invalid BINOP record");
1237 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1240 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1243 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1244 OpNum+2 != Record.size())
1245 return Error("Invalid CAST record");
1247 const Type *ResTy = getTypeByID(Record[OpNum]);
1248 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1249 if (Opc == -1 || ResTy == 0)
1250 return Error("Invalid CAST record");
1251 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1254 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1257 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1258 return Error("Invalid GEP record");
1260 SmallVector<Value*, 16> GEPIdx;
1261 while (OpNum != Record.size()) {
1263 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1264 return Error("Invalid GEP record");
1265 GEPIdx.push_back(Op);
1268 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1272 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1274 Value *TrueVal, *FalseVal, *Cond;
1275 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1276 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1277 getValue(Record, OpNum, Type::Int1Ty, Cond))
1278 return Error("Invalid SELECT record");
1280 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1284 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1287 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1288 getValue(Record, OpNum, Type::Int32Ty, Idx))
1289 return Error("Invalid EXTRACTELT record");
1290 I = new ExtractElementInst(Vec, Idx);
1294 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1296 Value *Vec, *Elt, *Idx;
1297 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1298 getValue(Record, OpNum,
1299 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1300 getValue(Record, OpNum, Type::Int32Ty, Idx))
1301 return Error("Invalid INSERTELT record");
1302 I = InsertElementInst::Create(Vec, Elt, Idx);
1306 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1308 Value *Vec1, *Vec2, *Mask;
1309 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1310 getValue(Record, OpNum, Vec1->getType(), Vec2))
1311 return Error("Invalid SHUFFLEVEC record");
1313 const Type *MaskTy =
1314 VectorType::get(Type::Int32Ty,
1315 cast<VectorType>(Vec1->getType())->getNumElements());
1317 if (getValue(Record, OpNum, MaskTy, Mask))
1318 return Error("Invalid SHUFFLEVEC record");
1319 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1323 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1326 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1327 getValue(Record, OpNum, LHS->getType(), RHS) ||
1328 OpNum+1 != Record.size())
1329 return Error("Invalid CMP record");
1331 if (LHS->getType()->isFPOrFPVector())
1332 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1334 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1337 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1338 if (Record.size() != 2)
1339 return Error("Invalid GETRESULT record");
1342 getValueTypePair(Record, OpNum, NextValueNo, Op);
1343 unsigned Index = Record[1];
1344 I = new GetResultInst(Op, Index);
1348 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1350 unsigned Size = Record.size();
1352 I = ReturnInst::Create();
1356 SmallVector<Value *,4> Vs;
1359 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1360 return Error("Invalid RET record");
1362 } while(OpNum != Record.size());
1364 // SmallVector Vs has at least one element.
1365 I = ReturnInst::Create(&Vs[0], Vs.size());
1369 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1370 if (Record.size() != 1 && Record.size() != 3)
1371 return Error("Invalid BR record");
1372 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1374 return Error("Invalid BR record");
1376 if (Record.size() == 1)
1377 I = BranchInst::Create(TrueDest);
1379 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1380 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1381 if (FalseDest == 0 || Cond == 0)
1382 return Error("Invalid BR record");
1383 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1387 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1388 if (Record.size() < 3 || (Record.size() & 1) == 0)
1389 return Error("Invalid SWITCH record");
1390 const Type *OpTy = getTypeByID(Record[0]);
1391 Value *Cond = getFnValueByID(Record[1], OpTy);
1392 BasicBlock *Default = getBasicBlock(Record[2]);
1393 if (OpTy == 0 || Cond == 0 || Default == 0)
1394 return Error("Invalid SWITCH record");
1395 unsigned NumCases = (Record.size()-3)/2;
1396 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1397 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1398 ConstantInt *CaseVal =
1399 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1400 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1401 if (CaseVal == 0 || DestBB == 0) {
1403 return Error("Invalid SWITCH record!");
1405 SI->addCase(CaseVal, DestBB);
1411 case bitc::FUNC_CODE_INST_INVOKE: {
1412 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1413 if (Record.size() < 4) return Error("Invalid INVOKE record");
1414 PAListPtr PAL = getParamAttrs(Record[0]);
1415 unsigned CCInfo = Record[1];
1416 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1417 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1421 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1422 return Error("Invalid INVOKE record");
1424 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1425 const FunctionType *FTy = !CalleeTy ? 0 :
1426 dyn_cast<FunctionType>(CalleeTy->getElementType());
1428 // Check that the right number of fixed parameters are here.
1429 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1430 Record.size() < OpNum+FTy->getNumParams())
1431 return Error("Invalid INVOKE record");
1433 SmallVector<Value*, 16> Ops;
1434 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1435 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1436 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1439 if (!FTy->isVarArg()) {
1440 if (Record.size() != OpNum)
1441 return Error("Invalid INVOKE record");
1443 // Read type/value pairs for varargs params.
1444 while (OpNum != Record.size()) {
1446 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1447 return Error("Invalid INVOKE record");
1452 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
1453 cast<InvokeInst>(I)->setCallingConv(CCInfo);
1454 cast<InvokeInst>(I)->setParamAttrs(PAL);
1457 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1458 I = new UnwindInst();
1460 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1461 I = new UnreachableInst();
1463 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1464 if (Record.size() < 1 || ((Record.size()-1)&1))
1465 return Error("Invalid PHI record");
1466 const Type *Ty = getTypeByID(Record[0]);
1467 if (!Ty) return Error("Invalid PHI record");
1469 PHINode *PN = PHINode::Create(Ty);
1470 PN->reserveOperandSpace((Record.size()-1)/2);
1472 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1473 Value *V = getFnValueByID(Record[1+i], Ty);
1474 BasicBlock *BB = getBasicBlock(Record[2+i]);
1475 if (!V || !BB) return Error("Invalid PHI record");
1476 PN->addIncoming(V, BB);
1482 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1483 if (Record.size() < 3)
1484 return Error("Invalid MALLOC record");
1485 const PointerType *Ty =
1486 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1487 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1488 unsigned Align = Record[2];
1489 if (!Ty || !Size) return Error("Invalid MALLOC record");
1490 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1493 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1496 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1497 OpNum != Record.size())
1498 return Error("Invalid FREE record");
1499 I = new FreeInst(Op);
1502 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1503 if (Record.size() < 3)
1504 return Error("Invalid ALLOCA record");
1505 const PointerType *Ty =
1506 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1507 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1508 unsigned Align = Record[2];
1509 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1510 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1513 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1516 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1517 OpNum+2 != Record.size())
1518 return Error("Invalid LOAD record");
1520 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1523 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1526 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1527 getValue(Record, OpNum,
1528 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1529 OpNum+2 != Record.size())
1530 return Error("Invalid STORE record");
1532 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1535 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1536 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1539 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1540 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
1541 OpNum+2 != Record.size())
1542 return Error("Invalid STORE record");
1544 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1547 case bitc::FUNC_CODE_INST_CALL: {
1548 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1549 if (Record.size() < 3)
1550 return Error("Invalid CALL record");
1552 PAListPtr PAL = getParamAttrs(Record[0]);
1553 unsigned CCInfo = Record[1];
1557 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1558 return Error("Invalid CALL record");
1560 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1561 const FunctionType *FTy = 0;
1562 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1563 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1564 return Error("Invalid CALL record");
1566 SmallVector<Value*, 16> Args;
1567 // Read the fixed params.
1568 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1569 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1570 Args.push_back(getBasicBlock(Record[OpNum]));
1572 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1573 if (Args.back() == 0) return Error("Invalid CALL record");
1576 // Read type/value pairs for varargs params.
1577 if (!FTy->isVarArg()) {
1578 if (OpNum != Record.size())
1579 return Error("Invalid CALL record");
1581 while (OpNum != Record.size()) {
1583 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1584 return Error("Invalid CALL record");
1589 I = CallInst::Create(Callee, Args.begin(), Args.end());
1590 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1591 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1592 cast<CallInst>(I)->setParamAttrs(PAL);
1595 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1596 if (Record.size() < 3)
1597 return Error("Invalid VAARG record");
1598 const Type *OpTy = getTypeByID(Record[0]);
1599 Value *Op = getFnValueByID(Record[1], OpTy);
1600 const Type *ResTy = getTypeByID(Record[2]);
1601 if (!OpTy || !Op || !ResTy)
1602 return Error("Invalid VAARG record");
1603 I = new VAArgInst(Op, ResTy);
1608 // Add instruction to end of current BB. If there is no current BB, reject
1612 return Error("Invalid instruction with no BB");
1614 CurBB->getInstList().push_back(I);
1616 // If this was a terminator instruction, move to the next block.
1617 if (isa<TerminatorInst>(I)) {
1619 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1622 // Non-void values get registered in the value table for future use.
1623 if (I && I->getType() != Type::VoidTy)
1624 ValueList.AssignValue(I, NextValueNo++);
1627 // Check the function list for unresolved values.
1628 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1629 if (A->getParent() == 0) {
1630 // We found at least one unresolved value. Nuke them all to avoid leaks.
1631 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1632 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1633 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1637 return Error("Never resolved value found in function!");
1641 // Trim the value list down to the size it was before we parsed this function.
1642 ValueList.shrinkTo(ModuleValueListSize);
1643 std::vector<BasicBlock*>().swap(FunctionBBs);
1648 //===----------------------------------------------------------------------===//
1649 // ModuleProvider implementation
1650 //===----------------------------------------------------------------------===//
1653 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1654 // If it already is material, ignore the request.
1655 if (!F->hasNotBeenReadFromBitcode()) return false;
1657 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1658 DeferredFunctionInfo.find(F);
1659 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1661 // Move the bit stream to the saved position of the deferred function body and
1662 // restore the real linkage type for the function.
1663 Stream.JumpToBit(DFII->second.first);
1664 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1666 if (ParseFunctionBody(F)) {
1667 if (ErrInfo) *ErrInfo = ErrorString;
1671 // Upgrade any old intrinsic calls in the function.
1672 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1673 E = UpgradedIntrinsics.end(); I != E; ++I) {
1674 if (I->first != I->second) {
1675 for (Value::use_iterator UI = I->first->use_begin(),
1676 UE = I->first->use_end(); UI != UE; ) {
1677 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1678 UpgradeIntrinsicCall(CI, I->second);
1686 void BitcodeReader::dematerializeFunction(Function *F) {
1687 // If this function isn't materialized, or if it is a proto, this is a noop.
1688 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1691 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1693 // Just forget the function body, we can remat it later.
1695 F->setLinkage(GlobalValue::GhostLinkage);
1699 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1700 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1701 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1703 Function *F = I->first;
1704 if (F->hasNotBeenReadFromBitcode() &&
1705 materializeFunction(F, ErrInfo))
1709 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1710 // delete the old functions to clean up. We can't do this unless the entire
1711 // module is materialized because there could always be another function body
1712 // with calls to the old function.
1713 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1714 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1715 if (I->first != I->second) {
1716 for (Value::use_iterator UI = I->first->use_begin(),
1717 UE = I->first->use_end(); UI != UE; ) {
1718 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1719 UpgradeIntrinsicCall(CI, I->second);
1721 ValueList.replaceUsesOfWith(I->first, I->second);
1722 I->first->eraseFromParent();
1725 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1731 /// This method is provided by the parent ModuleProvde class and overriden
1732 /// here. It simply releases the module from its provided and frees up our
1734 /// @brief Release our hold on the generated module
1735 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1736 // Since we're losing control of this Module, we must hand it back complete
1737 Module *M = ModuleProvider::releaseModule(ErrInfo);
1743 //===----------------------------------------------------------------------===//
1744 // External interface
1745 //===----------------------------------------------------------------------===//
1747 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1749 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1750 std::string *ErrMsg) {
1751 BitcodeReader *R = new BitcodeReader(Buffer);
1752 if (R->ParseBitcode()) {
1754 *ErrMsg = R->getErrorString();
1756 // Don't let the BitcodeReader dtor delete 'Buffer'.
1757 R->releaseMemoryBuffer();
1764 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1765 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1766 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1768 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1771 // Read in the entire module.
1772 Module *M = R->materializeModule(ErrMsg);
1774 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1775 // there was an error.
1776 R->releaseMemoryBuffer();
1778 // If there was no error, tell ModuleProvider not to delete it when its dtor
1781 M = R->releaseModule(ErrMsg);