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/IntrinsicInst.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/AutoUpgrade.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/OperandTraits.h"
30 void BitcodeReader::FreeState() {
34 std::vector<Type*>().swap(TypeList);
38 std::vector<AttrListPtr>().swap(MAttributes);
39 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
45 //===----------------------------------------------------------------------===//
46 // Helper functions to implement forward reference resolution, etc.
47 //===----------------------------------------------------------------------===//
49 /// ConvertToString - Convert a string from a record into an std::string, return
51 template<typename StrTy>
52 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
54 if (Idx > Record.size())
57 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58 Result += (char)Record[i];
62 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
64 default: // Map unknown/new linkages to external
65 case 0: return GlobalValue::ExternalLinkage;
66 case 1: return GlobalValue::WeakAnyLinkage;
67 case 2: return GlobalValue::AppendingLinkage;
68 case 3: return GlobalValue::InternalLinkage;
69 case 4: return GlobalValue::LinkOnceAnyLinkage;
70 case 5: return GlobalValue::DLLImportLinkage;
71 case 6: return GlobalValue::DLLExportLinkage;
72 case 7: return GlobalValue::ExternalWeakLinkage;
73 case 8: return GlobalValue::CommonLinkage;
74 case 9: return GlobalValue::PrivateLinkage;
75 case 10: return GlobalValue::WeakODRLinkage;
76 case 11: return GlobalValue::LinkOnceODRLinkage;
77 case 12: return GlobalValue::AvailableExternallyLinkage;
78 case 13: return GlobalValue::LinkerPrivateLinkage;
79 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
80 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
84 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
86 default: // Map unknown visibilities to default.
87 case 0: return GlobalValue::DefaultVisibility;
88 case 1: return GlobalValue::HiddenVisibility;
89 case 2: return GlobalValue::ProtectedVisibility;
93 static int GetDecodedCastOpcode(unsigned Val) {
96 case bitc::CAST_TRUNC : return Instruction::Trunc;
97 case bitc::CAST_ZEXT : return Instruction::ZExt;
98 case bitc::CAST_SEXT : return Instruction::SExt;
99 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
100 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
101 case bitc::CAST_UITOFP : return Instruction::UIToFP;
102 case bitc::CAST_SITOFP : return Instruction::SIToFP;
103 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
104 case bitc::CAST_FPEXT : return Instruction::FPExt;
105 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
106 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
107 case bitc::CAST_BITCAST : return Instruction::BitCast;
110 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
113 case bitc::BINOP_ADD:
114 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
115 case bitc::BINOP_SUB:
116 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
117 case bitc::BINOP_MUL:
118 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
119 case bitc::BINOP_UDIV: return Instruction::UDiv;
120 case bitc::BINOP_SDIV:
121 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
122 case bitc::BINOP_UREM: return Instruction::URem;
123 case bitc::BINOP_SREM:
124 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
125 case bitc::BINOP_SHL: return Instruction::Shl;
126 case bitc::BINOP_LSHR: return Instruction::LShr;
127 case bitc::BINOP_ASHR: return Instruction::AShr;
128 case bitc::BINOP_AND: return Instruction::And;
129 case bitc::BINOP_OR: return Instruction::Or;
130 case bitc::BINOP_XOR: return Instruction::Xor;
134 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
136 default: return AtomicRMWInst::BAD_BINOP;
137 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
138 case bitc::RMW_ADD: return AtomicRMWInst::Add;
139 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
140 case bitc::RMW_AND: return AtomicRMWInst::And;
141 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
142 case bitc::RMW_OR: return AtomicRMWInst::Or;
143 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
144 case bitc::RMW_MAX: return AtomicRMWInst::Max;
145 case bitc::RMW_MIN: return AtomicRMWInst::Min;
146 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
147 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
151 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
153 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
154 case bitc::ORDERING_UNORDERED: return Unordered;
155 case bitc::ORDERING_MONOTONIC: return Monotonic;
156 case bitc::ORDERING_ACQUIRE: return Acquire;
157 case bitc::ORDERING_RELEASE: return Release;
158 case bitc::ORDERING_ACQREL: return AcquireRelease;
159 default: // Map unknown orderings to sequentially-consistent.
160 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
164 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
166 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
167 default: // Map unknown scopes to cross-thread.
168 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
174 /// @brief A class for maintaining the slot number definition
175 /// as a placeholder for the actual definition for forward constants defs.
176 class ConstantPlaceHolder : public ConstantExpr {
177 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
179 // allocate space for exactly one operand
180 void *operator new(size_t s) {
181 return User::operator new(s, 1);
183 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
184 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
185 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
188 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
189 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
190 static bool classof(const Value *V) {
191 return isa<ConstantExpr>(V) &&
192 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
196 /// Provide fast operand accessors
197 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
201 // FIXME: can we inherit this from ConstantExpr?
203 struct OperandTraits<ConstantPlaceHolder> :
204 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
209 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
218 WeakVH &OldV = ValuePtrs[Idx];
224 // Handle constants and non-constants (e.g. instrs) differently for
226 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
227 ResolveConstants.push_back(std::make_pair(PHC, Idx));
230 // If there was a forward reference to this value, replace it.
231 Value *PrevVal = OldV;
232 OldV->replaceAllUsesWith(V);
238 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
243 if (Value *V = ValuePtrs[Idx]) {
244 assert(Ty == V->getType() && "Type mismatch in constant table!");
245 return cast<Constant>(V);
248 // Create and return a placeholder, which will later be RAUW'd.
249 Constant *C = new ConstantPlaceHolder(Ty, Context);
254 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
258 if (Value *V = ValuePtrs[Idx]) {
259 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
263 // No type specified, must be invalid reference.
264 if (Ty == 0) return 0;
266 // Create and return a placeholder, which will later be RAUW'd.
267 Value *V = new Argument(Ty);
272 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
273 /// resolves any forward references. The idea behind this is that we sometimes
274 /// get constants (such as large arrays) which reference *many* forward ref
275 /// constants. Replacing each of these causes a lot of thrashing when
276 /// building/reuniquing the constant. Instead of doing this, we look at all the
277 /// uses and rewrite all the place holders at once for any constant that uses
279 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
280 // Sort the values by-pointer so that they are efficient to look up with a
282 std::sort(ResolveConstants.begin(), ResolveConstants.end());
284 SmallVector<Constant*, 64> NewOps;
286 while (!ResolveConstants.empty()) {
287 Value *RealVal = operator[](ResolveConstants.back().second);
288 Constant *Placeholder = ResolveConstants.back().first;
289 ResolveConstants.pop_back();
291 // Loop over all users of the placeholder, updating them to reference the
292 // new value. If they reference more than one placeholder, update them all
294 while (!Placeholder->use_empty()) {
295 Value::use_iterator UI = Placeholder->use_begin();
298 // If the using object isn't uniqued, just update the operands. This
299 // handles instructions and initializers for global variables.
300 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
301 UI.getUse().set(RealVal);
305 // Otherwise, we have a constant that uses the placeholder. Replace that
306 // constant with a new constant that has *all* placeholder uses updated.
307 Constant *UserC = cast<Constant>(U);
308 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
311 if (!isa<ConstantPlaceHolder>(*I)) {
312 // Not a placeholder reference.
314 } else if (*I == Placeholder) {
315 // Common case is that it just references this one placeholder.
318 // Otherwise, look up the placeholder in ResolveConstants.
319 ResolveConstantsTy::iterator It =
320 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
321 std::pair<Constant*, unsigned>(cast<Constant>(*I),
323 assert(It != ResolveConstants.end() && It->first == *I);
324 NewOp = operator[](It->second);
327 NewOps.push_back(cast<Constant>(NewOp));
330 // Make the new constant.
332 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
333 NewC = ConstantArray::get(UserCA->getType(), NewOps);
334 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
335 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
336 } else if (isa<ConstantVector>(UserC)) {
337 NewC = ConstantVector::get(NewOps);
339 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
340 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
343 UserC->replaceAllUsesWith(NewC);
344 UserC->destroyConstant();
348 // Update all ValueHandles, they should be the only users at this point.
349 Placeholder->replaceAllUsesWith(RealVal);
354 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
363 WeakVH &OldV = MDValuePtrs[Idx];
369 // If there was a forward reference to this value, replace it.
370 MDNode *PrevVal = cast<MDNode>(OldV);
371 OldV->replaceAllUsesWith(V);
372 MDNode::deleteTemporary(PrevVal);
373 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
375 MDValuePtrs[Idx] = V;
378 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
382 if (Value *V = MDValuePtrs[Idx]) {
383 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
387 // Create and return a placeholder, which will later be RAUW'd.
388 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
389 MDValuePtrs[Idx] = V;
393 Type *BitcodeReader::getTypeByID(unsigned ID) {
394 // The type table size is always specified correctly.
395 if (ID >= TypeList.size())
398 if (Type *Ty = TypeList[ID])
401 // If we have a forward reference, the only possible case is when it is to a
402 // named struct. Just create a placeholder for now.
403 return TypeList[ID] = StructType::create(Context);
406 /// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable.
407 Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) {
408 if (ID >= TypeList.size())
409 TypeList.resize(ID+1);
415 //===----------------------------------------------------------------------===//
416 // Functions for parsing blocks from the bitcode file
417 //===----------------------------------------------------------------------===//
419 bool BitcodeReader::ParseAttributeBlock() {
420 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
421 return Error("Malformed block record");
423 if (!MAttributes.empty())
424 return Error("Multiple PARAMATTR blocks found!");
426 SmallVector<uint64_t, 64> Record;
428 SmallVector<AttributeWithIndex, 8> Attrs;
430 // Read all the records.
432 unsigned Code = Stream.ReadCode();
433 if (Code == bitc::END_BLOCK) {
434 if (Stream.ReadBlockEnd())
435 return Error("Error at end of PARAMATTR block");
439 if (Code == bitc::ENTER_SUBBLOCK) {
440 // No known subblocks, always skip them.
441 Stream.ReadSubBlockID();
442 if (Stream.SkipBlock())
443 return Error("Malformed block record");
447 if (Code == bitc::DEFINE_ABBREV) {
448 Stream.ReadAbbrevRecord();
454 switch (Stream.ReadRecord(Code, Record)) {
455 default: // Default behavior: ignore.
457 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
458 if (Record.size() & 1)
459 return Error("Invalid ENTRY record");
461 // FIXME : Remove this autoupgrade code in LLVM 3.0.
462 // If Function attributes are using index 0 then transfer them
463 // to index ~0. Index 0 is used for return value attributes but used to be
464 // used for function attributes.
465 Attributes RetAttribute = Attribute::None;
466 Attributes FnAttribute = Attribute::None;
467 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
468 // FIXME: remove in LLVM 3.0
469 // The alignment is stored as a 16-bit raw value from bits 31--16.
470 // We shift the bits above 31 down by 11 bits.
472 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
473 if (Alignment && !isPowerOf2_32(Alignment))
474 return Error("Alignment is not a power of two.");
476 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
478 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
479 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
480 Record[i+1] = ReconstitutedAttr;
483 RetAttribute = Record[i+1];
484 else if (Record[i] == ~0U)
485 FnAttribute = Record[i+1];
488 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
489 Attribute::ReadOnly|Attribute::ReadNone);
491 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
492 (RetAttribute & OldRetAttrs) != 0) {
493 if (FnAttribute == Attribute::None) { // add a slot so they get added.
494 Record.push_back(~0U);
498 FnAttribute |= RetAttribute & OldRetAttrs;
499 RetAttribute &= ~OldRetAttrs;
502 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
503 if (Record[i] == 0) {
504 if (RetAttribute != Attribute::None)
505 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
506 } else if (Record[i] == ~0U) {
507 if (FnAttribute != Attribute::None)
508 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
509 } else if (Record[i+1] != Attribute::None)
510 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
513 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
521 bool BitcodeReader::ParseTypeTable() {
522 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
523 return Error("Malformed block record");
525 return ParseTypeTableBody();
528 bool BitcodeReader::ParseTypeTableBody() {
529 if (!TypeList.empty())
530 return Error("Multiple TYPE_BLOCKs found!");
532 SmallVector<uint64_t, 64> Record;
533 unsigned NumRecords = 0;
535 SmallString<64> TypeName;
537 // Read all the records for this type table.
539 unsigned Code = Stream.ReadCode();
540 if (Code == bitc::END_BLOCK) {
541 if (NumRecords != TypeList.size())
542 return Error("Invalid type forward reference in TYPE_BLOCK");
543 if (Stream.ReadBlockEnd())
544 return Error("Error at end of type table block");
548 if (Code == bitc::ENTER_SUBBLOCK) {
549 // No known subblocks, always skip them.
550 Stream.ReadSubBlockID();
551 if (Stream.SkipBlock())
552 return Error("Malformed block record");
556 if (Code == bitc::DEFINE_ABBREV) {
557 Stream.ReadAbbrevRecord();
564 switch (Stream.ReadRecord(Code, Record)) {
565 default: return Error("unknown type in type table");
566 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
567 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
568 // type list. This allows us to reserve space.
569 if (Record.size() < 1)
570 return Error("Invalid TYPE_CODE_NUMENTRY record");
571 TypeList.resize(Record[0]);
573 case bitc::TYPE_CODE_VOID: // VOID
574 ResultTy = Type::getVoidTy(Context);
576 case bitc::TYPE_CODE_FLOAT: // FLOAT
577 ResultTy = Type::getFloatTy(Context);
579 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
580 ResultTy = Type::getDoubleTy(Context);
582 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
583 ResultTy = Type::getX86_FP80Ty(Context);
585 case bitc::TYPE_CODE_FP128: // FP128
586 ResultTy = Type::getFP128Ty(Context);
588 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
589 ResultTy = Type::getPPC_FP128Ty(Context);
591 case bitc::TYPE_CODE_LABEL: // LABEL
592 ResultTy = Type::getLabelTy(Context);
594 case bitc::TYPE_CODE_METADATA: // METADATA
595 ResultTy = Type::getMetadataTy(Context);
597 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
598 ResultTy = Type::getX86_MMXTy(Context);
600 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
601 if (Record.size() < 1)
602 return Error("Invalid Integer type record");
604 ResultTy = IntegerType::get(Context, Record[0]);
606 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
607 // [pointee type, address space]
608 if (Record.size() < 1)
609 return Error("Invalid POINTER type record");
610 unsigned AddressSpace = 0;
611 if (Record.size() == 2)
612 AddressSpace = Record[1];
613 ResultTy = getTypeByID(Record[0]);
614 if (ResultTy == 0) return Error("invalid element type in pointer type");
615 ResultTy = PointerType::get(ResultTy, AddressSpace);
618 case bitc::TYPE_CODE_FUNCTION_OLD: {
619 // FIXME: attrid is dead, remove it in LLVM 3.0
620 // FUNCTION: [vararg, attrid, retty, paramty x N]
621 if (Record.size() < 3)
622 return Error("Invalid FUNCTION type record");
623 std::vector<Type*> ArgTys;
624 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
625 if (Type *T = getTypeByID(Record[i]))
631 ResultTy = getTypeByID(Record[2]);
632 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
633 return Error("invalid type in function type");
635 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
638 case bitc::TYPE_CODE_FUNCTION: {
639 // FUNCTION: [vararg, retty, paramty x N]
640 if (Record.size() < 2)
641 return Error("Invalid FUNCTION type record");
642 std::vector<Type*> ArgTys;
643 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
644 if (Type *T = getTypeByID(Record[i]))
650 ResultTy = getTypeByID(Record[1]);
651 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
652 return Error("invalid type in function type");
654 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
657 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
658 if (Record.size() < 1)
659 return Error("Invalid STRUCT type record");
660 std::vector<Type*> EltTys;
661 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
662 if (Type *T = getTypeByID(Record[i]))
667 if (EltTys.size() != Record.size()-1)
668 return Error("invalid type in struct type");
669 ResultTy = StructType::get(Context, EltTys, Record[0]);
672 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
673 if (ConvertToString(Record, 0, TypeName))
674 return Error("Invalid STRUCT_NAME record");
677 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
678 if (Record.size() < 1)
679 return Error("Invalid STRUCT type record");
681 if (NumRecords >= TypeList.size())
682 return Error("invalid TYPE table");
684 // Check to see if this was forward referenced, if so fill in the temp.
685 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
687 Res->setName(TypeName);
688 TypeList[NumRecords] = 0;
689 } else // Otherwise, create a new struct.
690 Res = StructType::create(Context, TypeName);
693 SmallVector<Type*, 8> EltTys;
694 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
695 if (Type *T = getTypeByID(Record[i]))
700 if (EltTys.size() != Record.size()-1)
701 return Error("invalid STRUCT type record");
702 Res->setBody(EltTys, Record[0]);
706 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
707 if (Record.size() != 1)
708 return Error("Invalid OPAQUE type record");
710 if (NumRecords >= TypeList.size())
711 return Error("invalid TYPE table");
713 // Check to see if this was forward referenced, if so fill in the temp.
714 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
716 Res->setName(TypeName);
717 TypeList[NumRecords] = 0;
718 } else // Otherwise, create a new struct with no body.
719 Res = StructType::create(Context, TypeName);
724 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
725 if (Record.size() < 2)
726 return Error("Invalid ARRAY type record");
727 if ((ResultTy = getTypeByID(Record[1])))
728 ResultTy = ArrayType::get(ResultTy, Record[0]);
730 return Error("Invalid ARRAY type element");
732 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
733 if (Record.size() < 2)
734 return Error("Invalid VECTOR type record");
735 if ((ResultTy = getTypeByID(Record[1])))
736 ResultTy = VectorType::get(ResultTy, Record[0]);
738 return Error("Invalid ARRAY type element");
742 if (NumRecords >= TypeList.size())
743 return Error("invalid TYPE table");
744 assert(ResultTy && "Didn't read a type?");
745 assert(TypeList[NumRecords] == 0 && "Already read type?");
746 TypeList[NumRecords++] = ResultTy;
750 // FIXME: Remove in LLVM 3.1
751 bool BitcodeReader::ParseOldTypeTable() {
752 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_OLD))
753 return Error("Malformed block record");
755 if (!TypeList.empty())
756 return Error("Multiple TYPE_BLOCKs found!");
759 // While horrible, we have no good ordering of types in the bc file. Just
760 // iteratively parse types out of the bc file in multiple passes until we get
761 // them all. Do this by saving a cursor for the start of the type block.
762 BitstreamCursor StartOfTypeBlockCursor(Stream);
764 unsigned NumTypesRead = 0;
766 SmallVector<uint64_t, 64> Record;
768 unsigned NextTypeID = 0;
769 bool ReadAnyTypes = false;
771 // Read all the records for this type table.
773 unsigned Code = Stream.ReadCode();
774 if (Code == bitc::END_BLOCK) {
775 if (NextTypeID != TypeList.size())
776 return Error("Invalid type forward reference in TYPE_BLOCK_ID_OLD");
778 // If we haven't read all of the types yet, iterate again.
779 if (NumTypesRead != TypeList.size()) {
780 // If we didn't successfully read any types in this pass, then we must
781 // have an unhandled forward reference.
783 return Error("Obsolete bitcode contains unhandled recursive type");
785 Stream = StartOfTypeBlockCursor;
789 if (Stream.ReadBlockEnd())
790 return Error("Error at end of type table block");
794 if (Code == bitc::ENTER_SUBBLOCK) {
795 // No known subblocks, always skip them.
796 Stream.ReadSubBlockID();
797 if (Stream.SkipBlock())
798 return Error("Malformed block record");
802 if (Code == bitc::DEFINE_ABBREV) {
803 Stream.ReadAbbrevRecord();
810 switch (Stream.ReadRecord(Code, Record)) {
811 default: return Error("unknown type in type table");
812 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
813 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
814 // type list. This allows us to reserve space.
815 if (Record.size() < 1)
816 return Error("Invalid TYPE_CODE_NUMENTRY record");
817 TypeList.resize(Record[0]);
819 case bitc::TYPE_CODE_VOID: // VOID
820 ResultTy = Type::getVoidTy(Context);
822 case bitc::TYPE_CODE_FLOAT: // FLOAT
823 ResultTy = Type::getFloatTy(Context);
825 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
826 ResultTy = Type::getDoubleTy(Context);
828 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
829 ResultTy = Type::getX86_FP80Ty(Context);
831 case bitc::TYPE_CODE_FP128: // FP128
832 ResultTy = Type::getFP128Ty(Context);
834 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
835 ResultTy = Type::getPPC_FP128Ty(Context);
837 case bitc::TYPE_CODE_LABEL: // LABEL
838 ResultTy = Type::getLabelTy(Context);
840 case bitc::TYPE_CODE_METADATA: // METADATA
841 ResultTy = Type::getMetadataTy(Context);
843 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
844 ResultTy = Type::getX86_MMXTy(Context);
846 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
847 if (Record.size() < 1)
848 return Error("Invalid Integer type record");
849 ResultTy = IntegerType::get(Context, Record[0]);
851 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
852 if (NextTypeID < TypeList.size() && TypeList[NextTypeID] == 0)
853 ResultTy = StructType::create(Context);
855 case bitc::TYPE_CODE_STRUCT_OLD: {// STRUCT_OLD
856 if (NextTypeID >= TypeList.size()) break;
857 // If we already read it, don't reprocess.
858 if (TypeList[NextTypeID] &&
859 !cast<StructType>(TypeList[NextTypeID])->isOpaque())
863 if (TypeList[NextTypeID] == 0)
864 TypeList[NextTypeID] = StructType::create(Context);
866 std::vector<Type*> EltTys;
867 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
868 if (Type *Elt = getTypeByIDOrNull(Record[i]))
869 EltTys.push_back(Elt);
874 if (EltTys.size() != Record.size()-1)
875 break; // Not all elements are ready.
877 cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]);
878 ResultTy = TypeList[NextTypeID];
879 TypeList[NextTypeID] = 0;
882 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
883 // [pointee type, address space]
884 if (Record.size() < 1)
885 return Error("Invalid POINTER type record");
886 unsigned AddressSpace = 0;
887 if (Record.size() == 2)
888 AddressSpace = Record[1];
889 if ((ResultTy = getTypeByIDOrNull(Record[0])))
890 ResultTy = PointerType::get(ResultTy, AddressSpace);
893 case bitc::TYPE_CODE_FUNCTION_OLD: {
894 // FIXME: attrid is dead, remove it in LLVM 3.0
895 // FUNCTION: [vararg, attrid, retty, paramty x N]
896 if (Record.size() < 3)
897 return Error("Invalid FUNCTION type record");
898 std::vector<Type*> ArgTys;
899 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
900 if (Type *Elt = getTypeByIDOrNull(Record[i]))
901 ArgTys.push_back(Elt);
905 if (ArgTys.size()+3 != Record.size())
906 break; // Something was null.
907 if ((ResultTy = getTypeByIDOrNull(Record[2])))
908 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
911 case bitc::TYPE_CODE_FUNCTION: {
912 // FUNCTION: [vararg, retty, paramty x N]
913 if (Record.size() < 2)
914 return Error("Invalid FUNCTION type record");
915 std::vector<Type*> ArgTys;
916 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
917 if (Type *Elt = getTypeByIDOrNull(Record[i]))
918 ArgTys.push_back(Elt);
922 if (ArgTys.size()+2 != Record.size())
923 break; // Something was null.
924 if ((ResultTy = getTypeByIDOrNull(Record[1])))
925 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
928 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
929 if (Record.size() < 2)
930 return Error("Invalid ARRAY type record");
931 if ((ResultTy = getTypeByIDOrNull(Record[1])))
932 ResultTy = ArrayType::get(ResultTy, Record[0]);
934 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
935 if (Record.size() < 2)
936 return Error("Invalid VECTOR type record");
937 if ((ResultTy = getTypeByIDOrNull(Record[1])))
938 ResultTy = VectorType::get(ResultTy, Record[0]);
942 if (NextTypeID >= TypeList.size())
943 return Error("invalid TYPE table");
945 if (ResultTy && TypeList[NextTypeID] == 0) {
949 TypeList[NextTypeID] = ResultTy;
957 bool BitcodeReader::ParseOldTypeSymbolTable() {
958 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID_OLD))
959 return Error("Malformed block record");
961 SmallVector<uint64_t, 64> Record;
963 // Read all the records for this type table.
964 std::string TypeName;
966 unsigned Code = Stream.ReadCode();
967 if (Code == bitc::END_BLOCK) {
968 if (Stream.ReadBlockEnd())
969 return Error("Error at end of type symbol table block");
973 if (Code == bitc::ENTER_SUBBLOCK) {
974 // No known subblocks, always skip them.
975 Stream.ReadSubBlockID();
976 if (Stream.SkipBlock())
977 return Error("Malformed block record");
981 if (Code == bitc::DEFINE_ABBREV) {
982 Stream.ReadAbbrevRecord();
988 switch (Stream.ReadRecord(Code, Record)) {
989 default: // Default behavior: unknown type.
991 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
992 if (ConvertToString(Record, 1, TypeName))
993 return Error("Invalid TST_ENTRY record");
994 unsigned TypeID = Record[0];
995 if (TypeID >= TypeList.size())
996 return Error("Invalid Type ID in TST_ENTRY record");
998 // Only apply the type name to a struct type with no name.
999 if (StructType *STy = dyn_cast<StructType>(TypeList[TypeID]))
1000 if (!STy->isLiteral() && !STy->hasName())
1001 STy->setName(TypeName);
1008 bool BitcodeReader::ParseValueSymbolTable() {
1009 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1010 return Error("Malformed block record");
1012 SmallVector<uint64_t, 64> Record;
1014 // Read all the records for this value table.
1015 SmallString<128> ValueName;
1017 unsigned Code = Stream.ReadCode();
1018 if (Code == bitc::END_BLOCK) {
1019 if (Stream.ReadBlockEnd())
1020 return Error("Error at end of value symbol table block");
1023 if (Code == bitc::ENTER_SUBBLOCK) {
1024 // No known subblocks, always skip them.
1025 Stream.ReadSubBlockID();
1026 if (Stream.SkipBlock())
1027 return Error("Malformed block record");
1031 if (Code == bitc::DEFINE_ABBREV) {
1032 Stream.ReadAbbrevRecord();
1038 switch (Stream.ReadRecord(Code, Record)) {
1039 default: // Default behavior: unknown type.
1041 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1042 if (ConvertToString(Record, 1, ValueName))
1043 return Error("Invalid VST_ENTRY record");
1044 unsigned ValueID = Record[0];
1045 if (ValueID >= ValueList.size())
1046 return Error("Invalid Value ID in VST_ENTRY record");
1047 Value *V = ValueList[ValueID];
1049 V->setName(StringRef(ValueName.data(), ValueName.size()));
1053 case bitc::VST_CODE_BBENTRY: {
1054 if (ConvertToString(Record, 1, ValueName))
1055 return Error("Invalid VST_BBENTRY record");
1056 BasicBlock *BB = getBasicBlock(Record[0]);
1058 return Error("Invalid BB ID in VST_BBENTRY record");
1060 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1068 bool BitcodeReader::ParseMetadata() {
1069 unsigned NextMDValueNo = MDValueList.size();
1071 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1072 return Error("Malformed block record");
1074 SmallVector<uint64_t, 64> Record;
1076 // Read all the records.
1078 unsigned Code = Stream.ReadCode();
1079 if (Code == bitc::END_BLOCK) {
1080 if (Stream.ReadBlockEnd())
1081 return Error("Error at end of PARAMATTR block");
1085 if (Code == bitc::ENTER_SUBBLOCK) {
1086 // No known subblocks, always skip them.
1087 Stream.ReadSubBlockID();
1088 if (Stream.SkipBlock())
1089 return Error("Malformed block record");
1093 if (Code == bitc::DEFINE_ABBREV) {
1094 Stream.ReadAbbrevRecord();
1098 bool IsFunctionLocal = false;
1101 Code = Stream.ReadRecord(Code, Record);
1103 default: // Default behavior: ignore.
1105 case bitc::METADATA_NAME: {
1106 // Read named of the named metadata.
1107 unsigned NameLength = Record.size();
1108 SmallString<8> Name;
1109 Name.resize(NameLength);
1110 for (unsigned i = 0; i != NameLength; ++i)
1111 Name[i] = Record[i];
1113 Code = Stream.ReadCode();
1115 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1116 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
1117 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1119 // Read named metadata elements.
1120 unsigned Size = Record.size();
1121 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1122 for (unsigned i = 0; i != Size; ++i) {
1123 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1125 return Error("Malformed metadata record");
1126 NMD->addOperand(MD);
1130 case bitc::METADATA_FN_NODE:
1131 IsFunctionLocal = true;
1133 case bitc::METADATA_NODE: {
1134 if (Record.size() % 2 == 1)
1135 return Error("Invalid METADATA_NODE record");
1137 unsigned Size = Record.size();
1138 SmallVector<Value*, 8> Elts;
1139 for (unsigned i = 0; i != Size; i += 2) {
1140 Type *Ty = getTypeByID(Record[i]);
1141 if (!Ty) return Error("Invalid METADATA_NODE record");
1142 if (Ty->isMetadataTy())
1143 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1144 else if (!Ty->isVoidTy())
1145 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1147 Elts.push_back(NULL);
1149 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1150 IsFunctionLocal = false;
1151 MDValueList.AssignValue(V, NextMDValueNo++);
1154 case bitc::METADATA_STRING: {
1155 unsigned MDStringLength = Record.size();
1156 SmallString<8> String;
1157 String.resize(MDStringLength);
1158 for (unsigned i = 0; i != MDStringLength; ++i)
1159 String[i] = Record[i];
1160 Value *V = MDString::get(Context,
1161 StringRef(String.data(), String.size()));
1162 MDValueList.AssignValue(V, NextMDValueNo++);
1165 case bitc::METADATA_KIND: {
1166 unsigned RecordLength = Record.size();
1167 if (Record.empty() || RecordLength < 2)
1168 return Error("Invalid METADATA_KIND record");
1169 SmallString<8> Name;
1170 Name.resize(RecordLength-1);
1171 unsigned Kind = Record[0];
1172 for (unsigned i = 1; i != RecordLength; ++i)
1173 Name[i-1] = Record[i];
1175 unsigned NewKind = TheModule->getMDKindID(Name.str());
1176 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1177 return Error("Conflicting METADATA_KIND records");
1184 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
1185 /// the LSB for dense VBR encoding.
1186 static uint64_t DecodeSignRotatedValue(uint64_t V) {
1191 // There is no such thing as -0 with integers. "-0" really means MININT.
1195 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1196 /// values and aliases that we can.
1197 bool BitcodeReader::ResolveGlobalAndAliasInits() {
1198 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1199 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1201 GlobalInitWorklist.swap(GlobalInits);
1202 AliasInitWorklist.swap(AliasInits);
1204 while (!GlobalInitWorklist.empty()) {
1205 unsigned ValID = GlobalInitWorklist.back().second;
1206 if (ValID >= ValueList.size()) {
1207 // Not ready to resolve this yet, it requires something later in the file.
1208 GlobalInits.push_back(GlobalInitWorklist.back());
1210 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1211 GlobalInitWorklist.back().first->setInitializer(C);
1213 return Error("Global variable initializer is not a constant!");
1215 GlobalInitWorklist.pop_back();
1218 while (!AliasInitWorklist.empty()) {
1219 unsigned ValID = AliasInitWorklist.back().second;
1220 if (ValID >= ValueList.size()) {
1221 AliasInits.push_back(AliasInitWorklist.back());
1223 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1224 AliasInitWorklist.back().first->setAliasee(C);
1226 return Error("Alias initializer is not a constant!");
1228 AliasInitWorklist.pop_back();
1233 bool BitcodeReader::ParseConstants() {
1234 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1235 return Error("Malformed block record");
1237 SmallVector<uint64_t, 64> Record;
1239 // Read all the records for this value table.
1240 Type *CurTy = Type::getInt32Ty(Context);
1241 unsigned NextCstNo = ValueList.size();
1243 unsigned Code = Stream.ReadCode();
1244 if (Code == bitc::END_BLOCK)
1247 if (Code == bitc::ENTER_SUBBLOCK) {
1248 // No known subblocks, always skip them.
1249 Stream.ReadSubBlockID();
1250 if (Stream.SkipBlock())
1251 return Error("Malformed block record");
1255 if (Code == bitc::DEFINE_ABBREV) {
1256 Stream.ReadAbbrevRecord();
1263 unsigned BitCode = Stream.ReadRecord(Code, Record);
1265 default: // Default behavior: unknown constant
1266 case bitc::CST_CODE_UNDEF: // UNDEF
1267 V = UndefValue::get(CurTy);
1269 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1271 return Error("Malformed CST_SETTYPE record");
1272 if (Record[0] >= TypeList.size())
1273 return Error("Invalid Type ID in CST_SETTYPE record");
1274 CurTy = TypeList[Record[0]];
1275 continue; // Skip the ValueList manipulation.
1276 case bitc::CST_CODE_NULL: // NULL
1277 V = Constant::getNullValue(CurTy);
1279 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1280 if (!CurTy->isIntegerTy() || Record.empty())
1281 return Error("Invalid CST_INTEGER record");
1282 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
1284 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1285 if (!CurTy->isIntegerTy() || Record.empty())
1286 return Error("Invalid WIDE_INTEGER record");
1288 unsigned NumWords = Record.size();
1289 SmallVector<uint64_t, 8> Words;
1290 Words.resize(NumWords);
1291 for (unsigned i = 0; i != NumWords; ++i)
1292 Words[i] = DecodeSignRotatedValue(Record[i]);
1293 V = ConstantInt::get(Context,
1294 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
1298 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1300 return Error("Invalid FLOAT record");
1301 if (CurTy->isFloatTy())
1302 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1303 else if (CurTy->isDoubleTy())
1304 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1305 else if (CurTy->isX86_FP80Ty()) {
1306 // Bits are not stored the same way as a normal i80 APInt, compensate.
1307 uint64_t Rearrange[2];
1308 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1309 Rearrange[1] = Record[0] >> 48;
1310 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1311 } else if (CurTy->isFP128Ty())
1312 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1313 else if (CurTy->isPPC_FP128Ty())
1314 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1316 V = UndefValue::get(CurTy);
1320 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1322 return Error("Invalid CST_AGGREGATE record");
1324 unsigned Size = Record.size();
1325 std::vector<Constant*> Elts;
1327 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1328 for (unsigned i = 0; i != Size; ++i)
1329 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1330 STy->getElementType(i)));
1331 V = ConstantStruct::get(STy, Elts);
1332 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1333 Type *EltTy = ATy->getElementType();
1334 for (unsigned i = 0; i != Size; ++i)
1335 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1336 V = ConstantArray::get(ATy, Elts);
1337 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1338 Type *EltTy = VTy->getElementType();
1339 for (unsigned i = 0; i != Size; ++i)
1340 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1341 V = ConstantVector::get(Elts);
1343 V = UndefValue::get(CurTy);
1347 case bitc::CST_CODE_STRING: { // STRING: [values]
1349 return Error("Invalid CST_AGGREGATE record");
1351 ArrayType *ATy = cast<ArrayType>(CurTy);
1352 Type *EltTy = ATy->getElementType();
1354 unsigned Size = Record.size();
1355 std::vector<Constant*> Elts;
1356 for (unsigned i = 0; i != Size; ++i)
1357 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1358 V = ConstantArray::get(ATy, Elts);
1361 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1363 return Error("Invalid CST_AGGREGATE record");
1365 ArrayType *ATy = cast<ArrayType>(CurTy);
1366 Type *EltTy = ATy->getElementType();
1368 unsigned Size = Record.size();
1369 std::vector<Constant*> Elts;
1370 for (unsigned i = 0; i != Size; ++i)
1371 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1372 Elts.push_back(Constant::getNullValue(EltTy));
1373 V = ConstantArray::get(ATy, Elts);
1376 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1377 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1378 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1380 V = UndefValue::get(CurTy); // Unknown binop.
1382 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1383 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1385 if (Record.size() >= 4) {
1386 if (Opc == Instruction::Add ||
1387 Opc == Instruction::Sub ||
1388 Opc == Instruction::Mul ||
1389 Opc == Instruction::Shl) {
1390 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1391 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1392 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1393 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1394 } else if (Opc == Instruction::SDiv ||
1395 Opc == Instruction::UDiv ||
1396 Opc == Instruction::LShr ||
1397 Opc == Instruction::AShr) {
1398 if (Record[3] & (1 << bitc::PEO_EXACT))
1399 Flags |= SDivOperator::IsExact;
1402 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1406 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1407 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1408 int Opc = GetDecodedCastOpcode(Record[0]);
1410 V = UndefValue::get(CurTy); // Unknown cast.
1412 Type *OpTy = getTypeByID(Record[1]);
1413 if (!OpTy) return Error("Invalid CE_CAST record");
1414 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1415 V = ConstantExpr::getCast(Opc, Op, CurTy);
1419 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1420 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1421 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1422 SmallVector<Constant*, 16> Elts;
1423 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1424 Type *ElTy = getTypeByID(Record[i]);
1425 if (!ElTy) return Error("Invalid CE_GEP record");
1426 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1428 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1429 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1431 bitc::CST_CODE_CE_INBOUNDS_GEP);
1434 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1435 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1436 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1437 Type::getInt1Ty(Context)),
1438 ValueList.getConstantFwdRef(Record[1],CurTy),
1439 ValueList.getConstantFwdRef(Record[2],CurTy));
1441 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1442 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1444 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1445 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1446 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1447 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1448 V = ConstantExpr::getExtractElement(Op0, Op1);
1451 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1452 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1453 if (Record.size() < 3 || OpTy == 0)
1454 return Error("Invalid CE_INSERTELT record");
1455 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1456 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1457 OpTy->getElementType());
1458 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1459 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1462 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1463 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1464 if (Record.size() < 3 || OpTy == 0)
1465 return Error("Invalid CE_SHUFFLEVEC record");
1466 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1467 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1468 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1469 OpTy->getNumElements());
1470 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1471 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1474 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1475 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1477 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1478 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1479 return Error("Invalid CE_SHUFVEC_EX record");
1480 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1481 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1482 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1483 RTy->getNumElements());
1484 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1485 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1488 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1489 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1490 Type *OpTy = getTypeByID(Record[0]);
1491 if (OpTy == 0) return Error("Invalid CE_CMP record");
1492 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1493 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1495 if (OpTy->isFPOrFPVectorTy())
1496 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1498 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1501 case bitc::CST_CODE_INLINEASM: {
1502 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1503 std::string AsmStr, ConstrStr;
1504 bool HasSideEffects = Record[0] & 1;
1505 bool IsAlignStack = Record[0] >> 1;
1506 unsigned AsmStrSize = Record[1];
1507 if (2+AsmStrSize >= Record.size())
1508 return Error("Invalid INLINEASM record");
1509 unsigned ConstStrSize = Record[2+AsmStrSize];
1510 if (3+AsmStrSize+ConstStrSize > Record.size())
1511 return Error("Invalid INLINEASM record");
1513 for (unsigned i = 0; i != AsmStrSize; ++i)
1514 AsmStr += (char)Record[2+i];
1515 for (unsigned i = 0; i != ConstStrSize; ++i)
1516 ConstrStr += (char)Record[3+AsmStrSize+i];
1517 PointerType *PTy = cast<PointerType>(CurTy);
1518 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1519 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1522 case bitc::CST_CODE_BLOCKADDRESS:{
1523 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1524 Type *FnTy = getTypeByID(Record[0]);
1525 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1527 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1528 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1530 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1531 Type::getInt8Ty(Context),
1532 false, GlobalValue::InternalLinkage,
1534 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1540 ValueList.AssignValue(V, NextCstNo);
1544 if (NextCstNo != ValueList.size())
1545 return Error("Invalid constant reference!");
1547 if (Stream.ReadBlockEnd())
1548 return Error("Error at end of constants block");
1550 // Once all the constants have been read, go through and resolve forward
1552 ValueList.ResolveConstantForwardRefs();
1556 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1557 /// remember where it is and then skip it. This lets us lazily deserialize the
1559 bool BitcodeReader::RememberAndSkipFunctionBody() {
1560 // Get the function we are talking about.
1561 if (FunctionsWithBodies.empty())
1562 return Error("Insufficient function protos");
1564 Function *Fn = FunctionsWithBodies.back();
1565 FunctionsWithBodies.pop_back();
1567 // Save the current stream state.
1568 uint64_t CurBit = Stream.GetCurrentBitNo();
1569 DeferredFunctionInfo[Fn] = CurBit;
1571 // Skip over the function block for now.
1572 if (Stream.SkipBlock())
1573 return Error("Malformed block record");
1577 bool BitcodeReader::ParseModule() {
1578 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1579 return Error("Malformed block record");
1581 SmallVector<uint64_t, 64> Record;
1582 std::vector<std::string> SectionTable;
1583 std::vector<std::string> GCTable;
1585 // Read all the records for this module.
1586 while (!Stream.AtEndOfStream()) {
1587 unsigned Code = Stream.ReadCode();
1588 if (Code == bitc::END_BLOCK) {
1589 if (Stream.ReadBlockEnd())
1590 return Error("Error at end of module block");
1592 // Patch the initializers for globals and aliases up.
1593 ResolveGlobalAndAliasInits();
1594 if (!GlobalInits.empty() || !AliasInits.empty())
1595 return Error("Malformed global initializer set");
1596 if (!FunctionsWithBodies.empty())
1597 return Error("Too few function bodies found");
1599 // Look for intrinsic functions which need to be upgraded at some point
1600 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1603 if (UpgradeIntrinsicFunction(FI, NewFn))
1604 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1607 // Look for global variables which need to be renamed.
1608 for (Module::global_iterator
1609 GI = TheModule->global_begin(), GE = TheModule->global_end();
1611 UpgradeGlobalVariable(GI);
1613 // Force deallocation of memory for these vectors to favor the client that
1614 // want lazy deserialization.
1615 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1616 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1617 std::vector<Function*>().swap(FunctionsWithBodies);
1621 if (Code == bitc::ENTER_SUBBLOCK) {
1622 switch (Stream.ReadSubBlockID()) {
1623 default: // Skip unknown content.
1624 if (Stream.SkipBlock())
1625 return Error("Malformed block record");
1627 case bitc::BLOCKINFO_BLOCK_ID:
1628 if (Stream.ReadBlockInfoBlock())
1629 return Error("Malformed BlockInfoBlock");
1631 case bitc::PARAMATTR_BLOCK_ID:
1632 if (ParseAttributeBlock())
1635 case bitc::TYPE_BLOCK_ID_NEW:
1636 if (ParseTypeTable())
1639 case bitc::TYPE_BLOCK_ID_OLD:
1640 if (ParseOldTypeTable())
1643 case bitc::TYPE_SYMTAB_BLOCK_ID_OLD:
1644 if (ParseOldTypeSymbolTable())
1647 case bitc::VALUE_SYMTAB_BLOCK_ID:
1648 if (ParseValueSymbolTable())
1651 case bitc::CONSTANTS_BLOCK_ID:
1652 if (ParseConstants() || ResolveGlobalAndAliasInits())
1655 case bitc::METADATA_BLOCK_ID:
1656 if (ParseMetadata())
1659 case bitc::FUNCTION_BLOCK_ID:
1660 // If this is the first function body we've seen, reverse the
1661 // FunctionsWithBodies list.
1662 if (!HasReversedFunctionsWithBodies) {
1663 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1664 HasReversedFunctionsWithBodies = true;
1667 if (RememberAndSkipFunctionBody())
1674 if (Code == bitc::DEFINE_ABBREV) {
1675 Stream.ReadAbbrevRecord();
1680 switch (Stream.ReadRecord(Code, Record)) {
1681 default: break; // Default behavior, ignore unknown content.
1682 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1683 if (Record.size() < 1)
1684 return Error("Malformed MODULE_CODE_VERSION");
1685 // Only version #0 is supported so far.
1687 return Error("Unknown bitstream version!");
1689 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1691 if (ConvertToString(Record, 0, S))
1692 return Error("Invalid MODULE_CODE_TRIPLE record");
1693 TheModule->setTargetTriple(S);
1696 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1698 if (ConvertToString(Record, 0, S))
1699 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1700 TheModule->setDataLayout(S);
1703 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1705 if (ConvertToString(Record, 0, S))
1706 return Error("Invalid MODULE_CODE_ASM record");
1707 TheModule->setModuleInlineAsm(S);
1710 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1712 if (ConvertToString(Record, 0, S))
1713 return Error("Invalid MODULE_CODE_DEPLIB record");
1714 TheModule->addLibrary(S);
1717 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1719 if (ConvertToString(Record, 0, S))
1720 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1721 SectionTable.push_back(S);
1724 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1726 if (ConvertToString(Record, 0, S))
1727 return Error("Invalid MODULE_CODE_GCNAME record");
1728 GCTable.push_back(S);
1731 // GLOBALVAR: [pointer type, isconst, initid,
1732 // linkage, alignment, section, visibility, threadlocal,
1734 case bitc::MODULE_CODE_GLOBALVAR: {
1735 if (Record.size() < 6)
1736 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1737 Type *Ty = getTypeByID(Record[0]);
1738 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1739 if (!Ty->isPointerTy())
1740 return Error("Global not a pointer type!");
1741 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1742 Ty = cast<PointerType>(Ty)->getElementType();
1744 bool isConstant = Record[1];
1745 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1746 unsigned Alignment = (1 << Record[4]) >> 1;
1747 std::string Section;
1749 if (Record[5]-1 >= SectionTable.size())
1750 return Error("Invalid section ID");
1751 Section = SectionTable[Record[5]-1];
1753 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1754 if (Record.size() > 6)
1755 Visibility = GetDecodedVisibility(Record[6]);
1756 bool isThreadLocal = false;
1757 if (Record.size() > 7)
1758 isThreadLocal = Record[7];
1760 bool UnnamedAddr = false;
1761 if (Record.size() > 8)
1762 UnnamedAddr = Record[8];
1764 GlobalVariable *NewGV =
1765 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1766 isThreadLocal, AddressSpace);
1767 NewGV->setAlignment(Alignment);
1768 if (!Section.empty())
1769 NewGV->setSection(Section);
1770 NewGV->setVisibility(Visibility);
1771 NewGV->setThreadLocal(isThreadLocal);
1772 NewGV->setUnnamedAddr(UnnamedAddr);
1774 ValueList.push_back(NewGV);
1776 // Remember which value to use for the global initializer.
1777 if (unsigned InitID = Record[2])
1778 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1781 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1782 // alignment, section, visibility, gc, unnamed_addr]
1783 case bitc::MODULE_CODE_FUNCTION: {
1784 if (Record.size() < 8)
1785 return Error("Invalid MODULE_CODE_FUNCTION record");
1786 Type *Ty = getTypeByID(Record[0]);
1787 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1788 if (!Ty->isPointerTy())
1789 return Error("Function not a pointer type!");
1791 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1793 return Error("Function not a pointer to function type!");
1795 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1798 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1799 bool isProto = Record[2];
1800 Func->setLinkage(GetDecodedLinkage(Record[3]));
1801 Func->setAttributes(getAttributes(Record[4]));
1803 Func->setAlignment((1 << Record[5]) >> 1);
1805 if (Record[6]-1 >= SectionTable.size())
1806 return Error("Invalid section ID");
1807 Func->setSection(SectionTable[Record[6]-1]);
1809 Func->setVisibility(GetDecodedVisibility(Record[7]));
1810 if (Record.size() > 8 && Record[8]) {
1811 if (Record[8]-1 > GCTable.size())
1812 return Error("Invalid GC ID");
1813 Func->setGC(GCTable[Record[8]-1].c_str());
1815 bool UnnamedAddr = false;
1816 if (Record.size() > 9)
1817 UnnamedAddr = Record[9];
1818 Func->setUnnamedAddr(UnnamedAddr);
1819 ValueList.push_back(Func);
1821 // If this is a function with a body, remember the prototype we are
1822 // creating now, so that we can match up the body with them later.
1824 FunctionsWithBodies.push_back(Func);
1827 // ALIAS: [alias type, aliasee val#, linkage]
1828 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1829 case bitc::MODULE_CODE_ALIAS: {
1830 if (Record.size() < 3)
1831 return Error("Invalid MODULE_ALIAS record");
1832 Type *Ty = getTypeByID(Record[0]);
1833 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1834 if (!Ty->isPointerTy())
1835 return Error("Function not a pointer type!");
1837 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1839 // Old bitcode files didn't have visibility field.
1840 if (Record.size() > 3)
1841 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1842 ValueList.push_back(NewGA);
1843 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1846 /// MODULE_CODE_PURGEVALS: [numvals]
1847 case bitc::MODULE_CODE_PURGEVALS:
1848 // Trim down the value list to the specified size.
1849 if (Record.size() < 1 || Record[0] > ValueList.size())
1850 return Error("Invalid MODULE_PURGEVALS record");
1851 ValueList.shrinkTo(Record[0]);
1857 return Error("Premature end of bitstream");
1860 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1863 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1864 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1866 if (Buffer->getBufferSize() & 3) {
1867 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1868 return Error("Invalid bitcode signature");
1870 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1873 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1874 // The magic number is 0x0B17C0DE stored in little endian.
1875 if (isBitcodeWrapper(BufPtr, BufEnd))
1876 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1877 return Error("Invalid bitcode wrapper header");
1879 StreamFile.init(BufPtr, BufEnd);
1880 Stream.init(StreamFile);
1882 // Sniff for the signature.
1883 if (Stream.Read(8) != 'B' ||
1884 Stream.Read(8) != 'C' ||
1885 Stream.Read(4) != 0x0 ||
1886 Stream.Read(4) != 0xC ||
1887 Stream.Read(4) != 0xE ||
1888 Stream.Read(4) != 0xD)
1889 return Error("Invalid bitcode signature");
1891 // We expect a number of well-defined blocks, though we don't necessarily
1892 // need to understand them all.
1893 while (!Stream.AtEndOfStream()) {
1894 unsigned Code = Stream.ReadCode();
1896 if (Code != bitc::ENTER_SUBBLOCK) {
1898 // The ranlib in xcode 4 will align archive members by appending newlines
1899 // to the end of them. If this file size is a multiple of 4 but not 8, we
1900 // have to read and ignore these final 4 bytes :-(
1901 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1902 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1903 Stream.AtEndOfStream())
1906 return Error("Invalid record at top-level");
1909 unsigned BlockID = Stream.ReadSubBlockID();
1911 // We only know the MODULE subblock ID.
1913 case bitc::BLOCKINFO_BLOCK_ID:
1914 if (Stream.ReadBlockInfoBlock())
1915 return Error("Malformed BlockInfoBlock");
1917 case bitc::MODULE_BLOCK_ID:
1918 // Reject multiple MODULE_BLOCK's in a single bitstream.
1920 return Error("Multiple MODULE_BLOCKs in same stream");
1926 if (Stream.SkipBlock())
1927 return Error("Malformed block record");
1935 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1936 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1937 return Error("Malformed block record");
1939 SmallVector<uint64_t, 64> Record;
1941 // Read all the records for this module.
1942 while (!Stream.AtEndOfStream()) {
1943 unsigned Code = Stream.ReadCode();
1944 if (Code == bitc::END_BLOCK) {
1945 if (Stream.ReadBlockEnd())
1946 return Error("Error at end of module block");
1951 if (Code == bitc::ENTER_SUBBLOCK) {
1952 switch (Stream.ReadSubBlockID()) {
1953 default: // Skip unknown content.
1954 if (Stream.SkipBlock())
1955 return Error("Malformed block record");
1961 if (Code == bitc::DEFINE_ABBREV) {
1962 Stream.ReadAbbrevRecord();
1967 switch (Stream.ReadRecord(Code, Record)) {
1968 default: break; // Default behavior, ignore unknown content.
1969 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1970 if (Record.size() < 1)
1971 return Error("Malformed MODULE_CODE_VERSION");
1972 // Only version #0 is supported so far.
1974 return Error("Unknown bitstream version!");
1976 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1978 if (ConvertToString(Record, 0, S))
1979 return Error("Invalid MODULE_CODE_TRIPLE record");
1987 return Error("Premature end of bitstream");
1990 bool BitcodeReader::ParseTriple(std::string &Triple) {
1991 if (Buffer->getBufferSize() & 3)
1992 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1994 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1995 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1997 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1998 // The magic number is 0x0B17C0DE stored in little endian.
1999 if (isBitcodeWrapper(BufPtr, BufEnd))
2000 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
2001 return Error("Invalid bitcode wrapper header");
2003 StreamFile.init(BufPtr, BufEnd);
2004 Stream.init(StreamFile);
2006 // Sniff for the signature.
2007 if (Stream.Read(8) != 'B' ||
2008 Stream.Read(8) != 'C' ||
2009 Stream.Read(4) != 0x0 ||
2010 Stream.Read(4) != 0xC ||
2011 Stream.Read(4) != 0xE ||
2012 Stream.Read(4) != 0xD)
2013 return Error("Invalid bitcode signature");
2015 // We expect a number of well-defined blocks, though we don't necessarily
2016 // need to understand them all.
2017 while (!Stream.AtEndOfStream()) {
2018 unsigned Code = Stream.ReadCode();
2020 if (Code != bitc::ENTER_SUBBLOCK)
2021 return Error("Invalid record at top-level");
2023 unsigned BlockID = Stream.ReadSubBlockID();
2025 // We only know the MODULE subblock ID.
2027 case bitc::MODULE_BLOCK_ID:
2028 if (ParseModuleTriple(Triple))
2032 if (Stream.SkipBlock())
2033 return Error("Malformed block record");
2041 /// ParseMetadataAttachment - Parse metadata attachments.
2042 bool BitcodeReader::ParseMetadataAttachment() {
2043 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2044 return Error("Malformed block record");
2046 SmallVector<uint64_t, 64> Record;
2048 unsigned Code = Stream.ReadCode();
2049 if (Code == bitc::END_BLOCK) {
2050 if (Stream.ReadBlockEnd())
2051 return Error("Error at end of PARAMATTR block");
2054 if (Code == bitc::DEFINE_ABBREV) {
2055 Stream.ReadAbbrevRecord();
2058 // Read a metadata attachment record.
2060 switch (Stream.ReadRecord(Code, Record)) {
2061 default: // Default behavior: ignore.
2063 case bitc::METADATA_ATTACHMENT: {
2064 unsigned RecordLength = Record.size();
2065 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2066 return Error ("Invalid METADATA_ATTACHMENT reader!");
2067 Instruction *Inst = InstructionList[Record[0]];
2068 for (unsigned i = 1; i != RecordLength; i = i+2) {
2069 unsigned Kind = Record[i];
2070 DenseMap<unsigned, unsigned>::iterator I =
2071 MDKindMap.find(Kind);
2072 if (I == MDKindMap.end())
2073 return Error("Invalid metadata kind ID");
2074 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2075 Inst->setMetadata(I->second, cast<MDNode>(Node));
2084 /// ParseFunctionBody - Lazily parse the specified function body block.
2085 bool BitcodeReader::ParseFunctionBody(Function *F) {
2086 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2087 return Error("Malformed block record");
2089 InstructionList.clear();
2090 unsigned ModuleValueListSize = ValueList.size();
2091 unsigned ModuleMDValueListSize = MDValueList.size();
2093 // Add all the function arguments to the value table.
2094 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2095 ValueList.push_back(I);
2097 unsigned NextValueNo = ValueList.size();
2098 BasicBlock *CurBB = 0;
2099 unsigned CurBBNo = 0;
2103 // Read all the records.
2104 SmallVector<uint64_t, 64> Record;
2106 unsigned Code = Stream.ReadCode();
2107 if (Code == bitc::END_BLOCK) {
2108 if (Stream.ReadBlockEnd())
2109 return Error("Error at end of function block");
2113 if (Code == bitc::ENTER_SUBBLOCK) {
2114 switch (Stream.ReadSubBlockID()) {
2115 default: // Skip unknown content.
2116 if (Stream.SkipBlock())
2117 return Error("Malformed block record");
2119 case bitc::CONSTANTS_BLOCK_ID:
2120 if (ParseConstants()) return true;
2121 NextValueNo = ValueList.size();
2123 case bitc::VALUE_SYMTAB_BLOCK_ID:
2124 if (ParseValueSymbolTable()) return true;
2126 case bitc::METADATA_ATTACHMENT_ID:
2127 if (ParseMetadataAttachment()) return true;
2129 case bitc::METADATA_BLOCK_ID:
2130 if (ParseMetadata()) return true;
2136 if (Code == bitc::DEFINE_ABBREV) {
2137 Stream.ReadAbbrevRecord();
2144 unsigned BitCode = Stream.ReadRecord(Code, Record);
2146 default: // Default behavior: reject
2147 return Error("Unknown instruction");
2148 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2149 if (Record.size() < 1 || Record[0] == 0)
2150 return Error("Invalid DECLAREBLOCKS record");
2151 // Create all the basic blocks for the function.
2152 FunctionBBs.resize(Record[0]);
2153 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2154 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2155 CurBB = FunctionBBs[0];
2158 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2159 // This record indicates that the last instruction is at the same
2160 // location as the previous instruction with a location.
2163 // Get the last instruction emitted.
2164 if (CurBB && !CurBB->empty())
2166 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2167 !FunctionBBs[CurBBNo-1]->empty())
2168 I = &FunctionBBs[CurBBNo-1]->back();
2170 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2171 I->setDebugLoc(LastLoc);
2175 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2176 I = 0; // Get the last instruction emitted.
2177 if (CurBB && !CurBB->empty())
2179 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2180 !FunctionBBs[CurBBNo-1]->empty())
2181 I = &FunctionBBs[CurBBNo-1]->back();
2182 if (I == 0 || Record.size() < 4)
2183 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2185 unsigned Line = Record[0], Col = Record[1];
2186 unsigned ScopeID = Record[2], IAID = Record[3];
2188 MDNode *Scope = 0, *IA = 0;
2189 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2190 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2191 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2192 I->setDebugLoc(LastLoc);
2197 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2200 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2201 getValue(Record, OpNum, LHS->getType(), RHS) ||
2202 OpNum+1 > Record.size())
2203 return Error("Invalid BINOP record");
2205 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2206 if (Opc == -1) return Error("Invalid BINOP record");
2207 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2208 InstructionList.push_back(I);
2209 if (OpNum < Record.size()) {
2210 if (Opc == Instruction::Add ||
2211 Opc == Instruction::Sub ||
2212 Opc == Instruction::Mul ||
2213 Opc == Instruction::Shl) {
2214 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2215 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2216 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2217 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2218 } else if (Opc == Instruction::SDiv ||
2219 Opc == Instruction::UDiv ||
2220 Opc == Instruction::LShr ||
2221 Opc == Instruction::AShr) {
2222 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2223 cast<BinaryOperator>(I)->setIsExact(true);
2228 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2231 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2232 OpNum+2 != Record.size())
2233 return Error("Invalid CAST record");
2235 Type *ResTy = getTypeByID(Record[OpNum]);
2236 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2237 if (Opc == -1 || ResTy == 0)
2238 return Error("Invalid CAST record");
2239 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2240 InstructionList.push_back(I);
2243 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2244 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2247 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2248 return Error("Invalid GEP record");
2250 SmallVector<Value*, 16> GEPIdx;
2251 while (OpNum != Record.size()) {
2253 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2254 return Error("Invalid GEP record");
2255 GEPIdx.push_back(Op);
2258 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2259 InstructionList.push_back(I);
2260 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2261 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2265 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2266 // EXTRACTVAL: [opty, opval, n x indices]
2269 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2270 return Error("Invalid EXTRACTVAL record");
2272 SmallVector<unsigned, 4> EXTRACTVALIdx;
2273 for (unsigned RecSize = Record.size();
2274 OpNum != RecSize; ++OpNum) {
2275 uint64_t Index = Record[OpNum];
2276 if ((unsigned)Index != Index)
2277 return Error("Invalid EXTRACTVAL index");
2278 EXTRACTVALIdx.push_back((unsigned)Index);
2281 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2282 InstructionList.push_back(I);
2286 case bitc::FUNC_CODE_INST_INSERTVAL: {
2287 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2290 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2291 return Error("Invalid INSERTVAL record");
2293 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2294 return Error("Invalid INSERTVAL record");
2296 SmallVector<unsigned, 4> INSERTVALIdx;
2297 for (unsigned RecSize = Record.size();
2298 OpNum != RecSize; ++OpNum) {
2299 uint64_t Index = Record[OpNum];
2300 if ((unsigned)Index != Index)
2301 return Error("Invalid INSERTVAL index");
2302 INSERTVALIdx.push_back((unsigned)Index);
2305 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2306 InstructionList.push_back(I);
2310 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2311 // obsolete form of select
2312 // handles select i1 ... in old bitcode
2314 Value *TrueVal, *FalseVal, *Cond;
2315 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2316 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2317 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2318 return Error("Invalid SELECT record");
2320 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2321 InstructionList.push_back(I);
2325 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2326 // new form of select
2327 // handles select i1 or select [N x i1]
2329 Value *TrueVal, *FalseVal, *Cond;
2330 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2331 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2332 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2333 return Error("Invalid SELECT record");
2335 // select condition can be either i1 or [N x i1]
2336 if (VectorType* vector_type =
2337 dyn_cast<VectorType>(Cond->getType())) {
2339 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2340 return Error("Invalid SELECT condition type");
2343 if (Cond->getType() != Type::getInt1Ty(Context))
2344 return Error("Invalid SELECT condition type");
2347 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2348 InstructionList.push_back(I);
2352 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2355 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2356 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2357 return Error("Invalid EXTRACTELT record");
2358 I = ExtractElementInst::Create(Vec, Idx);
2359 InstructionList.push_back(I);
2363 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2365 Value *Vec, *Elt, *Idx;
2366 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2367 getValue(Record, OpNum,
2368 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2369 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2370 return Error("Invalid INSERTELT record");
2371 I = InsertElementInst::Create(Vec, Elt, Idx);
2372 InstructionList.push_back(I);
2376 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2378 Value *Vec1, *Vec2, *Mask;
2379 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2380 getValue(Record, OpNum, Vec1->getType(), Vec2))
2381 return Error("Invalid SHUFFLEVEC record");
2383 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2384 return Error("Invalid SHUFFLEVEC record");
2385 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2386 InstructionList.push_back(I);
2390 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2391 // Old form of ICmp/FCmp returning bool
2392 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2393 // both legal on vectors but had different behaviour.
2394 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2395 // FCmp/ICmp returning bool or vector of bool
2399 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2400 getValue(Record, OpNum, LHS->getType(), RHS) ||
2401 OpNum+1 != Record.size())
2402 return Error("Invalid CMP record");
2404 if (LHS->getType()->isFPOrFPVectorTy())
2405 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2407 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2408 InstructionList.push_back(I);
2412 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2414 unsigned Size = Record.size();
2416 I = ReturnInst::Create(Context);
2417 InstructionList.push_back(I);
2423 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2424 return Error("Invalid RET record");
2425 if (OpNum != Record.size())
2426 return Error("Invalid RET record");
2428 I = ReturnInst::Create(Context, Op);
2429 InstructionList.push_back(I);
2432 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2433 if (Record.size() != 1 && Record.size() != 3)
2434 return Error("Invalid BR record");
2435 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2437 return Error("Invalid BR record");
2439 if (Record.size() == 1) {
2440 I = BranchInst::Create(TrueDest);
2441 InstructionList.push_back(I);
2444 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2445 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2446 if (FalseDest == 0 || Cond == 0)
2447 return Error("Invalid BR record");
2448 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2449 InstructionList.push_back(I);
2453 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2454 if (Record.size() < 3 || (Record.size() & 1) == 0)
2455 return Error("Invalid SWITCH record");
2456 Type *OpTy = getTypeByID(Record[0]);
2457 Value *Cond = getFnValueByID(Record[1], OpTy);
2458 BasicBlock *Default = getBasicBlock(Record[2]);
2459 if (OpTy == 0 || Cond == 0 || Default == 0)
2460 return Error("Invalid SWITCH record");
2461 unsigned NumCases = (Record.size()-3)/2;
2462 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2463 InstructionList.push_back(SI);
2464 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2465 ConstantInt *CaseVal =
2466 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2467 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2468 if (CaseVal == 0 || DestBB == 0) {
2470 return Error("Invalid SWITCH record!");
2472 SI->addCase(CaseVal, DestBB);
2477 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2478 if (Record.size() < 2)
2479 return Error("Invalid INDIRECTBR record");
2480 Type *OpTy = getTypeByID(Record[0]);
2481 Value *Address = getFnValueByID(Record[1], OpTy);
2482 if (OpTy == 0 || Address == 0)
2483 return Error("Invalid INDIRECTBR record");
2484 unsigned NumDests = Record.size()-2;
2485 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2486 InstructionList.push_back(IBI);
2487 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2488 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2489 IBI->addDestination(DestBB);
2492 return Error("Invalid INDIRECTBR record!");
2499 case bitc::FUNC_CODE_INST_INVOKE: {
2500 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2501 if (Record.size() < 4) return Error("Invalid INVOKE record");
2502 AttrListPtr PAL = getAttributes(Record[0]);
2503 unsigned CCInfo = Record[1];
2504 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2505 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2509 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2510 return Error("Invalid INVOKE record");
2512 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2513 FunctionType *FTy = !CalleeTy ? 0 :
2514 dyn_cast<FunctionType>(CalleeTy->getElementType());
2516 // Check that the right number of fixed parameters are here.
2517 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2518 Record.size() < OpNum+FTy->getNumParams())
2519 return Error("Invalid INVOKE record");
2521 SmallVector<Value*, 16> Ops;
2522 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2523 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2524 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2527 if (!FTy->isVarArg()) {
2528 if (Record.size() != OpNum)
2529 return Error("Invalid INVOKE record");
2531 // Read type/value pairs for varargs params.
2532 while (OpNum != Record.size()) {
2534 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2535 return Error("Invalid INVOKE record");
2540 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2541 InstructionList.push_back(I);
2542 cast<InvokeInst>(I)->setCallingConv(
2543 static_cast<CallingConv::ID>(CCInfo));
2544 cast<InvokeInst>(I)->setAttributes(PAL);
2547 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2550 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2551 return Error("Invalid RESUME record");
2552 I = ResumeInst::Create(Val);
2553 InstructionList.push_back(I);
2556 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2557 I = new UnwindInst(Context);
2558 InstructionList.push_back(I);
2560 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2561 I = new UnreachableInst(Context);
2562 InstructionList.push_back(I);
2564 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2565 if (Record.size() < 1 || ((Record.size()-1)&1))
2566 return Error("Invalid PHI record");
2567 Type *Ty = getTypeByID(Record[0]);
2568 if (!Ty) return Error("Invalid PHI record");
2570 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2571 InstructionList.push_back(PN);
2573 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2574 Value *V = getFnValueByID(Record[1+i], Ty);
2575 BasicBlock *BB = getBasicBlock(Record[2+i]);
2576 if (!V || !BB) return Error("Invalid PHI record");
2577 PN->addIncoming(V, BB);
2583 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2584 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2586 if (Record.size() < 4)
2587 return Error("Invalid LANDINGPAD record");
2588 Type *Ty = getTypeByID(Record[Idx++]);
2589 if (!Ty) return Error("Invalid LANDINGPAD record");
2591 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2592 return Error("Invalid LANDINGPAD record");
2594 bool IsCleanup = !!Record[Idx++];
2595 unsigned NumClauses = Record[Idx++];
2596 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2597 LP->setCleanup(IsCleanup);
2598 for (unsigned J = 0; J != NumClauses; ++J) {
2599 LandingPadInst::ClauseType CT =
2600 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2603 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2605 return Error("Invalid LANDINGPAD record");
2608 assert((CT != LandingPadInst::Catch ||
2609 !isa<ArrayType>(Val->getType())) &&
2610 "Catch clause has a invalid type!");
2611 assert((CT != LandingPadInst::Filter ||
2612 isa<ArrayType>(Val->getType())) &&
2613 "Filter clause has invalid type!");
2618 InstructionList.push_back(I);
2622 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2623 if (Record.size() != 4)
2624 return Error("Invalid ALLOCA record");
2626 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2627 Type *OpTy = getTypeByID(Record[1]);
2628 Value *Size = getFnValueByID(Record[2], OpTy);
2629 unsigned Align = Record[3];
2630 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2631 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2632 InstructionList.push_back(I);
2635 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2638 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2639 OpNum+2 != Record.size())
2640 return Error("Invalid LOAD record");
2642 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2643 InstructionList.push_back(I);
2646 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2647 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2650 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2651 OpNum+4 != Record.size())
2652 return Error("Invalid LOADATOMIC record");
2655 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2656 if (Ordering == NotAtomic || Ordering == Release ||
2657 Ordering == AcquireRelease)
2658 return Error("Invalid LOADATOMIC record");
2659 if (Ordering != NotAtomic && Record[OpNum] == 0)
2660 return Error("Invalid LOADATOMIC record");
2661 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2663 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2664 Ordering, SynchScope);
2665 InstructionList.push_back(I);
2668 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2671 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2672 getValue(Record, OpNum,
2673 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2674 OpNum+2 != Record.size())
2675 return Error("Invalid STORE record");
2677 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2678 InstructionList.push_back(I);
2681 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2682 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2685 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2686 getValue(Record, OpNum,
2687 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2688 OpNum+4 != Record.size())
2689 return Error("Invalid STOREATOMIC record");
2691 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2692 if (Ordering == NotAtomic || Ordering == Acquire ||
2693 Ordering == AcquireRelease)
2694 return Error("Invalid STOREATOMIC record");
2695 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2696 if (Ordering != NotAtomic && Record[OpNum] == 0)
2697 return Error("Invalid STOREATOMIC record");
2699 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2700 Ordering, SynchScope);
2701 InstructionList.push_back(I);
2704 case bitc::FUNC_CODE_INST_CMPXCHG: {
2705 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2707 Value *Ptr, *Cmp, *New;
2708 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2709 getValue(Record, OpNum,
2710 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2711 getValue(Record, OpNum,
2712 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2713 OpNum+3 != Record.size())
2714 return Error("Invalid CMPXCHG record");
2715 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2716 if (Ordering == NotAtomic || Ordering == Unordered)
2717 return Error("Invalid CMPXCHG record");
2718 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2719 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2720 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2721 InstructionList.push_back(I);
2724 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2725 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2728 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2729 getValue(Record, OpNum,
2730 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2731 OpNum+4 != Record.size())
2732 return Error("Invalid ATOMICRMW record");
2733 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2734 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2735 Operation > AtomicRMWInst::LAST_BINOP)
2736 return Error("Invalid ATOMICRMW record");
2737 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2738 if (Ordering == NotAtomic || Ordering == Unordered)
2739 return Error("Invalid ATOMICRMW record");
2740 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2741 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2742 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2743 InstructionList.push_back(I);
2746 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2747 if (2 != Record.size())
2748 return Error("Invalid FENCE record");
2749 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2750 if (Ordering == NotAtomic || Ordering == Unordered ||
2751 Ordering == Monotonic)
2752 return Error("Invalid FENCE record");
2753 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2754 I = new FenceInst(Context, Ordering, SynchScope);
2755 InstructionList.push_back(I);
2758 case bitc::FUNC_CODE_INST_CALL: {
2759 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2760 if (Record.size() < 3)
2761 return Error("Invalid CALL record");
2763 AttrListPtr PAL = getAttributes(Record[0]);
2764 unsigned CCInfo = Record[1];
2768 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2769 return Error("Invalid CALL record");
2771 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2772 FunctionType *FTy = 0;
2773 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2774 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2775 return Error("Invalid CALL record");
2777 SmallVector<Value*, 16> Args;
2778 // Read the fixed params.
2779 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2780 if (FTy->getParamType(i)->isLabelTy())
2781 Args.push_back(getBasicBlock(Record[OpNum]));
2783 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2784 if (Args.back() == 0) return Error("Invalid CALL record");
2787 // Read type/value pairs for varargs params.
2788 if (!FTy->isVarArg()) {
2789 if (OpNum != Record.size())
2790 return Error("Invalid CALL record");
2792 while (OpNum != Record.size()) {
2794 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2795 return Error("Invalid CALL record");
2800 I = CallInst::Create(Callee, Args);
2801 InstructionList.push_back(I);
2802 cast<CallInst>(I)->setCallingConv(
2803 static_cast<CallingConv::ID>(CCInfo>>1));
2804 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2805 cast<CallInst>(I)->setAttributes(PAL);
2808 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2809 if (Record.size() < 3)
2810 return Error("Invalid VAARG record");
2811 Type *OpTy = getTypeByID(Record[0]);
2812 Value *Op = getFnValueByID(Record[1], OpTy);
2813 Type *ResTy = getTypeByID(Record[2]);
2814 if (!OpTy || !Op || !ResTy)
2815 return Error("Invalid VAARG record");
2816 I = new VAArgInst(Op, ResTy);
2817 InstructionList.push_back(I);
2822 // Add instruction to end of current BB. If there is no current BB, reject
2826 return Error("Invalid instruction with no BB");
2828 CurBB->getInstList().push_back(I);
2830 // If this was a terminator instruction, move to the next block.
2831 if (isa<TerminatorInst>(I)) {
2833 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2836 // Non-void values get registered in the value table for future use.
2837 if (I && !I->getType()->isVoidTy())
2838 ValueList.AssignValue(I, NextValueNo++);
2841 // Check the function list for unresolved values.
2842 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2843 if (A->getParent() == 0) {
2844 // We found at least one unresolved value. Nuke them all to avoid leaks.
2845 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2846 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2847 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2851 return Error("Never resolved value found in function!");
2855 // FIXME: Check for unresolved forward-declared metadata references
2856 // and clean up leaks.
2858 // See if anything took the address of blocks in this function. If so,
2859 // resolve them now.
2860 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2861 BlockAddrFwdRefs.find(F);
2862 if (BAFRI != BlockAddrFwdRefs.end()) {
2863 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2864 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2865 unsigned BlockIdx = RefList[i].first;
2866 if (BlockIdx >= FunctionBBs.size())
2867 return Error("Invalid blockaddress block #");
2869 GlobalVariable *FwdRef = RefList[i].second;
2870 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2871 FwdRef->eraseFromParent();
2874 BlockAddrFwdRefs.erase(BAFRI);
2877 // Trim the value list down to the size it was before we parsed this function.
2878 ValueList.shrinkTo(ModuleValueListSize);
2879 MDValueList.shrinkTo(ModuleMDValueListSize);
2880 std::vector<BasicBlock*>().swap(FunctionBBs);
2884 //===----------------------------------------------------------------------===//
2885 // GVMaterializer implementation
2886 //===----------------------------------------------------------------------===//
2889 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2890 if (const Function *F = dyn_cast<Function>(GV)) {
2891 return F->isDeclaration() &&
2892 DeferredFunctionInfo.count(const_cast<Function*>(F));
2897 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2898 Function *F = dyn_cast<Function>(GV);
2899 // If it's not a function or is already material, ignore the request.
2900 if (!F || !F->isMaterializable()) return false;
2902 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2903 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2905 // Move the bit stream to the saved position of the deferred function body.
2906 Stream.JumpToBit(DFII->second);
2908 if (ParseFunctionBody(F)) {
2909 if (ErrInfo) *ErrInfo = ErrorString;
2913 // Upgrade any old intrinsic calls in the function.
2914 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2915 E = UpgradedIntrinsics.end(); I != E; ++I) {
2916 if (I->first != I->second) {
2917 for (Value::use_iterator UI = I->first->use_begin(),
2918 UE = I->first->use_end(); UI != UE; ) {
2919 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2920 UpgradeIntrinsicCall(CI, I->second);
2928 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2929 const Function *F = dyn_cast<Function>(GV);
2930 if (!F || F->isDeclaration())
2932 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2935 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2936 Function *F = dyn_cast<Function>(GV);
2937 // If this function isn't dematerializable, this is a noop.
2938 if (!F || !isDematerializable(F))
2941 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2943 // Just forget the function body, we can remat it later.
2948 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2949 assert(M == TheModule &&
2950 "Can only Materialize the Module this BitcodeReader is attached to.");
2951 // Iterate over the module, deserializing any functions that are still on
2953 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2955 if (F->isMaterializable() &&
2956 Materialize(F, ErrInfo))
2959 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2960 // delete the old functions to clean up. We can't do this unless the entire
2961 // module is materialized because there could always be another function body
2962 // with calls to the old function.
2963 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2964 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2965 if (I->first != I->second) {
2966 for (Value::use_iterator UI = I->first->use_begin(),
2967 UE = I->first->use_end(); UI != UE; ) {
2968 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2969 UpgradeIntrinsicCall(CI, I->second);
2971 if (!I->first->use_empty())
2972 I->first->replaceAllUsesWith(I->second);
2973 I->first->eraseFromParent();
2976 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2978 // Upgrade to new EH scheme. N.B. This will go away in 3.1.
2979 UpgradeExceptionHandling(M);
2981 // Check debug info intrinsics.
2982 CheckDebugInfoIntrinsics(TheModule);
2988 //===----------------------------------------------------------------------===//
2989 // External interface
2990 //===----------------------------------------------------------------------===//
2992 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2994 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2995 LLVMContext& Context,
2996 std::string *ErrMsg) {
2997 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2998 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2999 M->setMaterializer(R);
3000 if (R->ParseBitcodeInto(M)) {
3002 *ErrMsg = R->getErrorString();
3004 delete M; // Also deletes R.
3007 // Have the BitcodeReader dtor delete 'Buffer'.
3008 R->setBufferOwned(true);
3012 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3013 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3014 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3015 std::string *ErrMsg){
3016 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3019 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3020 // there was an error.
3021 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3023 // Read in the entire module, and destroy the BitcodeReader.
3024 if (M->MaterializeAllPermanently(ErrMsg)) {
3032 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3033 LLVMContext& Context,
3034 std::string *ErrMsg) {
3035 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3036 // Don't let the BitcodeReader dtor delete 'Buffer'.
3037 R->setBufferOwned(false);
3039 std::string Triple("");
3040 if (R->ParseTriple(Triple))
3042 *ErrMsg = R->getErrorString();