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);
407 //===----------------------------------------------------------------------===//
408 // Functions for parsing blocks from the bitcode file
409 //===----------------------------------------------------------------------===//
411 bool BitcodeReader::ParseAttributeBlock() {
412 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
413 return Error("Malformed block record");
415 if (!MAttributes.empty())
416 return Error("Multiple PARAMATTR blocks found!");
418 SmallVector<uint64_t, 64> Record;
420 SmallVector<AttributeWithIndex, 8> Attrs;
422 // Read all the records.
424 unsigned Code = Stream.ReadCode();
425 if (Code == bitc::END_BLOCK) {
426 if (Stream.ReadBlockEnd())
427 return Error("Error at end of PARAMATTR block");
431 if (Code == bitc::ENTER_SUBBLOCK) {
432 // No known subblocks, always skip them.
433 Stream.ReadSubBlockID();
434 if (Stream.SkipBlock())
435 return Error("Malformed block record");
439 if (Code == bitc::DEFINE_ABBREV) {
440 Stream.ReadAbbrevRecord();
446 switch (Stream.ReadRecord(Code, Record)) {
447 default: // Default behavior: ignore.
449 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
450 if (Record.size() & 1)
451 return Error("Invalid ENTRY record");
453 // FIXME : Remove this autoupgrade code in LLVM 3.0.
454 // If Function attributes are using index 0 then transfer them
455 // to index ~0. Index 0 is used for return value attributes but used to be
456 // used for function attributes.
457 Attributes RetAttribute = Attribute::None;
458 Attributes FnAttribute = Attribute::None;
459 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
460 // FIXME: remove in LLVM 3.0
461 // The alignment is stored as a 16-bit raw value from bits 31--16.
462 // We shift the bits above 31 down by 11 bits.
464 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
465 if (Alignment && !isPowerOf2_32(Alignment))
466 return Error("Alignment is not a power of two.");
468 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
470 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
471 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
472 Record[i+1] = ReconstitutedAttr;
475 RetAttribute = Record[i+1];
476 else if (Record[i] == ~0U)
477 FnAttribute = Record[i+1];
480 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
481 Attribute::ReadOnly|Attribute::ReadNone);
483 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
484 (RetAttribute & OldRetAttrs) != 0) {
485 if (FnAttribute == Attribute::None) { // add a slot so they get added.
486 Record.push_back(~0U);
490 FnAttribute |= RetAttribute & OldRetAttrs;
491 RetAttribute &= ~OldRetAttrs;
494 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
495 if (Record[i] == 0) {
496 if (RetAttribute != Attribute::None)
497 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
498 } else if (Record[i] == ~0U) {
499 if (FnAttribute != Attribute::None)
500 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
501 } else if (Record[i+1] != Attribute::None)
502 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
505 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
513 bool BitcodeReader::ParseTypeTable() {
514 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
515 return Error("Malformed block record");
517 return ParseTypeTableBody();
520 bool BitcodeReader::ParseTypeTableBody() {
521 if (!TypeList.empty())
522 return Error("Multiple TYPE_BLOCKs found!");
524 SmallVector<uint64_t, 64> Record;
525 unsigned NumRecords = 0;
527 SmallString<64> TypeName;
529 // Read all the records for this type table.
531 unsigned Code = Stream.ReadCode();
532 if (Code == bitc::END_BLOCK) {
533 if (NumRecords != TypeList.size())
534 return Error("Invalid type forward reference in TYPE_BLOCK");
535 if (Stream.ReadBlockEnd())
536 return Error("Error at end of type table block");
540 if (Code == bitc::ENTER_SUBBLOCK) {
541 // No known subblocks, always skip them.
542 Stream.ReadSubBlockID();
543 if (Stream.SkipBlock())
544 return Error("Malformed block record");
548 if (Code == bitc::DEFINE_ABBREV) {
549 Stream.ReadAbbrevRecord();
556 switch (Stream.ReadRecord(Code, Record)) {
557 default: return Error("unknown type in type table");
558 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
559 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
560 // type list. This allows us to reserve space.
561 if (Record.size() < 1)
562 return Error("Invalid TYPE_CODE_NUMENTRY record");
563 TypeList.resize(Record[0]);
565 case bitc::TYPE_CODE_VOID: // VOID
566 ResultTy = Type::getVoidTy(Context);
568 case bitc::TYPE_CODE_FLOAT: // FLOAT
569 ResultTy = Type::getFloatTy(Context);
571 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
572 ResultTy = Type::getDoubleTy(Context);
574 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
575 ResultTy = Type::getX86_FP80Ty(Context);
577 case bitc::TYPE_CODE_FP128: // FP128
578 ResultTy = Type::getFP128Ty(Context);
580 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
581 ResultTy = Type::getPPC_FP128Ty(Context);
583 case bitc::TYPE_CODE_LABEL: // LABEL
584 ResultTy = Type::getLabelTy(Context);
586 case bitc::TYPE_CODE_METADATA: // METADATA
587 ResultTy = Type::getMetadataTy(Context);
589 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
590 ResultTy = Type::getX86_MMXTy(Context);
592 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
593 if (Record.size() < 1)
594 return Error("Invalid Integer type record");
596 ResultTy = IntegerType::get(Context, Record[0]);
598 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
599 // [pointee type, address space]
600 if (Record.size() < 1)
601 return Error("Invalid POINTER type record");
602 unsigned AddressSpace = 0;
603 if (Record.size() == 2)
604 AddressSpace = Record[1];
605 ResultTy = getTypeByID(Record[0]);
606 if (ResultTy == 0) return Error("invalid element type in pointer type");
607 ResultTy = PointerType::get(ResultTy, AddressSpace);
610 case bitc::TYPE_CODE_FUNCTION_OLD: {
611 // FIXME: attrid is dead, remove it in LLVM 3.0
612 // FUNCTION: [vararg, attrid, retty, paramty x N]
613 if (Record.size() < 3)
614 return Error("Invalid FUNCTION type record");
615 std::vector<Type*> ArgTys;
616 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
617 if (Type *T = getTypeByID(Record[i]))
623 ResultTy = getTypeByID(Record[2]);
624 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
625 return Error("invalid type in function type");
627 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
630 case bitc::TYPE_CODE_FUNCTION: {
631 // FUNCTION: [vararg, retty, paramty x N]
632 if (Record.size() < 2)
633 return Error("Invalid FUNCTION type record");
634 std::vector<Type*> ArgTys;
635 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
636 if (Type *T = getTypeByID(Record[i]))
642 ResultTy = getTypeByID(Record[1]);
643 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
644 return Error("invalid type in function type");
646 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
649 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
650 if (Record.size() < 1)
651 return Error("Invalid STRUCT type record");
652 std::vector<Type*> EltTys;
653 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
654 if (Type *T = getTypeByID(Record[i]))
659 if (EltTys.size() != Record.size()-1)
660 return Error("invalid type in struct type");
661 ResultTy = StructType::get(Context, EltTys, Record[0]);
664 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
665 if (ConvertToString(Record, 0, TypeName))
666 return Error("Invalid STRUCT_NAME record");
669 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
670 if (Record.size() < 1)
671 return Error("Invalid STRUCT type record");
673 if (NumRecords >= TypeList.size())
674 return Error("invalid TYPE table");
676 // Check to see if this was forward referenced, if so fill in the temp.
677 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
679 Res->setName(TypeName);
680 TypeList[NumRecords] = 0;
681 } else // Otherwise, create a new struct.
682 Res = StructType::create(Context, TypeName);
685 SmallVector<Type*, 8> EltTys;
686 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
687 if (Type *T = getTypeByID(Record[i]))
692 if (EltTys.size() != Record.size()-1)
693 return Error("invalid STRUCT type record");
694 Res->setBody(EltTys, Record[0]);
698 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
699 if (Record.size() != 1)
700 return Error("Invalid OPAQUE type record");
702 if (NumRecords >= TypeList.size())
703 return Error("invalid TYPE table");
705 // Check to see if this was forward referenced, if so fill in the temp.
706 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
708 Res->setName(TypeName);
709 TypeList[NumRecords] = 0;
710 } else // Otherwise, create a new struct with no body.
711 Res = StructType::create(Context, TypeName);
716 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
717 if (Record.size() < 2)
718 return Error("Invalid ARRAY type record");
719 if ((ResultTy = getTypeByID(Record[1])))
720 ResultTy = ArrayType::get(ResultTy, Record[0]);
722 return Error("Invalid ARRAY type element");
724 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
725 if (Record.size() < 2)
726 return Error("Invalid VECTOR type record");
727 if ((ResultTy = getTypeByID(Record[1])))
728 ResultTy = VectorType::get(ResultTy, Record[0]);
730 return Error("Invalid ARRAY type element");
734 if (NumRecords >= TypeList.size())
735 return Error("invalid TYPE table");
736 assert(ResultTy && "Didn't read a type?");
737 assert(TypeList[NumRecords] == 0 && "Already read type?");
738 TypeList[NumRecords++] = ResultTy;
742 bool BitcodeReader::ParseValueSymbolTable() {
743 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
744 return Error("Malformed block record");
746 SmallVector<uint64_t, 64> Record;
748 // Read all the records for this value table.
749 SmallString<128> ValueName;
751 unsigned Code = Stream.ReadCode();
752 if (Code == bitc::END_BLOCK) {
753 if (Stream.ReadBlockEnd())
754 return Error("Error at end of value symbol table block");
757 if (Code == bitc::ENTER_SUBBLOCK) {
758 // No known subblocks, always skip them.
759 Stream.ReadSubBlockID();
760 if (Stream.SkipBlock())
761 return Error("Malformed block record");
765 if (Code == bitc::DEFINE_ABBREV) {
766 Stream.ReadAbbrevRecord();
772 switch (Stream.ReadRecord(Code, Record)) {
773 default: // Default behavior: unknown type.
775 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
776 if (ConvertToString(Record, 1, ValueName))
777 return Error("Invalid VST_ENTRY record");
778 unsigned ValueID = Record[0];
779 if (ValueID >= ValueList.size())
780 return Error("Invalid Value ID in VST_ENTRY record");
781 Value *V = ValueList[ValueID];
783 V->setName(StringRef(ValueName.data(), ValueName.size()));
787 case bitc::VST_CODE_BBENTRY: {
788 if (ConvertToString(Record, 1, ValueName))
789 return Error("Invalid VST_BBENTRY record");
790 BasicBlock *BB = getBasicBlock(Record[0]);
792 return Error("Invalid BB ID in VST_BBENTRY record");
794 BB->setName(StringRef(ValueName.data(), ValueName.size()));
802 bool BitcodeReader::ParseMetadata() {
803 unsigned NextMDValueNo = MDValueList.size();
805 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
806 return Error("Malformed block record");
808 SmallVector<uint64_t, 64> Record;
810 // Read all the records.
812 unsigned Code = Stream.ReadCode();
813 if (Code == bitc::END_BLOCK) {
814 if (Stream.ReadBlockEnd())
815 return Error("Error at end of PARAMATTR block");
819 if (Code == bitc::ENTER_SUBBLOCK) {
820 // No known subblocks, always skip them.
821 Stream.ReadSubBlockID();
822 if (Stream.SkipBlock())
823 return Error("Malformed block record");
827 if (Code == bitc::DEFINE_ABBREV) {
828 Stream.ReadAbbrevRecord();
832 bool IsFunctionLocal = false;
835 Code = Stream.ReadRecord(Code, Record);
837 default: // Default behavior: ignore.
839 case bitc::METADATA_NAME: {
840 // Read named of the named metadata.
841 unsigned NameLength = Record.size();
843 Name.resize(NameLength);
844 for (unsigned i = 0; i != NameLength; ++i)
847 Code = Stream.ReadCode();
849 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
850 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
851 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
853 // Read named metadata elements.
854 unsigned Size = Record.size();
855 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
856 for (unsigned i = 0; i != Size; ++i) {
857 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
859 return Error("Malformed metadata record");
864 case bitc::METADATA_FN_NODE:
865 IsFunctionLocal = true;
867 case bitc::METADATA_NODE: {
868 if (Record.size() % 2 == 1)
869 return Error("Invalid METADATA_NODE record");
871 unsigned Size = Record.size();
872 SmallVector<Value*, 8> Elts;
873 for (unsigned i = 0; i != Size; i += 2) {
874 Type *Ty = getTypeByID(Record[i]);
875 if (!Ty) return Error("Invalid METADATA_NODE record");
876 if (Ty->isMetadataTy())
877 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
878 else if (!Ty->isVoidTy())
879 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
881 Elts.push_back(NULL);
883 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
884 IsFunctionLocal = false;
885 MDValueList.AssignValue(V, NextMDValueNo++);
888 case bitc::METADATA_STRING: {
889 unsigned MDStringLength = Record.size();
890 SmallString<8> String;
891 String.resize(MDStringLength);
892 for (unsigned i = 0; i != MDStringLength; ++i)
893 String[i] = Record[i];
894 Value *V = MDString::get(Context,
895 StringRef(String.data(), String.size()));
896 MDValueList.AssignValue(V, NextMDValueNo++);
899 case bitc::METADATA_KIND: {
900 unsigned RecordLength = Record.size();
901 if (Record.empty() || RecordLength < 2)
902 return Error("Invalid METADATA_KIND record");
904 Name.resize(RecordLength-1);
905 unsigned Kind = Record[0];
906 for (unsigned i = 1; i != RecordLength; ++i)
907 Name[i-1] = Record[i];
909 unsigned NewKind = TheModule->getMDKindID(Name.str());
910 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
911 return Error("Conflicting METADATA_KIND records");
918 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
919 /// the LSB for dense VBR encoding.
920 static uint64_t DecodeSignRotatedValue(uint64_t V) {
925 // There is no such thing as -0 with integers. "-0" really means MININT.
929 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
930 /// values and aliases that we can.
931 bool BitcodeReader::ResolveGlobalAndAliasInits() {
932 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
933 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
935 GlobalInitWorklist.swap(GlobalInits);
936 AliasInitWorklist.swap(AliasInits);
938 while (!GlobalInitWorklist.empty()) {
939 unsigned ValID = GlobalInitWorklist.back().second;
940 if (ValID >= ValueList.size()) {
941 // Not ready to resolve this yet, it requires something later in the file.
942 GlobalInits.push_back(GlobalInitWorklist.back());
944 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
945 GlobalInitWorklist.back().first->setInitializer(C);
947 return Error("Global variable initializer is not a constant!");
949 GlobalInitWorklist.pop_back();
952 while (!AliasInitWorklist.empty()) {
953 unsigned ValID = AliasInitWorklist.back().second;
954 if (ValID >= ValueList.size()) {
955 AliasInits.push_back(AliasInitWorklist.back());
957 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
958 AliasInitWorklist.back().first->setAliasee(C);
960 return Error("Alias initializer is not a constant!");
962 AliasInitWorklist.pop_back();
967 bool BitcodeReader::ParseConstants() {
968 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
969 return Error("Malformed block record");
971 SmallVector<uint64_t, 64> Record;
973 // Read all the records for this value table.
974 Type *CurTy = Type::getInt32Ty(Context);
975 unsigned NextCstNo = ValueList.size();
977 unsigned Code = Stream.ReadCode();
978 if (Code == bitc::END_BLOCK)
981 if (Code == bitc::ENTER_SUBBLOCK) {
982 // No known subblocks, always skip them.
983 Stream.ReadSubBlockID();
984 if (Stream.SkipBlock())
985 return Error("Malformed block record");
989 if (Code == bitc::DEFINE_ABBREV) {
990 Stream.ReadAbbrevRecord();
997 unsigned BitCode = Stream.ReadRecord(Code, Record);
999 default: // Default behavior: unknown constant
1000 case bitc::CST_CODE_UNDEF: // UNDEF
1001 V = UndefValue::get(CurTy);
1003 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1005 return Error("Malformed CST_SETTYPE record");
1006 if (Record[0] >= TypeList.size())
1007 return Error("Invalid Type ID in CST_SETTYPE record");
1008 CurTy = TypeList[Record[0]];
1009 continue; // Skip the ValueList manipulation.
1010 case bitc::CST_CODE_NULL: // NULL
1011 V = Constant::getNullValue(CurTy);
1013 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1014 if (!CurTy->isIntegerTy() || Record.empty())
1015 return Error("Invalid CST_INTEGER record");
1016 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
1018 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1019 if (!CurTy->isIntegerTy() || Record.empty())
1020 return Error("Invalid WIDE_INTEGER record");
1022 unsigned NumWords = Record.size();
1023 SmallVector<uint64_t, 8> Words;
1024 Words.resize(NumWords);
1025 for (unsigned i = 0; i != NumWords; ++i)
1026 Words[i] = DecodeSignRotatedValue(Record[i]);
1027 V = ConstantInt::get(Context,
1028 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
1032 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1034 return Error("Invalid FLOAT record");
1035 if (CurTy->isFloatTy())
1036 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1037 else if (CurTy->isDoubleTy())
1038 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1039 else if (CurTy->isX86_FP80Ty()) {
1040 // Bits are not stored the same way as a normal i80 APInt, compensate.
1041 uint64_t Rearrange[2];
1042 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1043 Rearrange[1] = Record[0] >> 48;
1044 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1045 } else if (CurTy->isFP128Ty())
1046 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1047 else if (CurTy->isPPC_FP128Ty())
1048 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1050 V = UndefValue::get(CurTy);
1054 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1056 return Error("Invalid CST_AGGREGATE record");
1058 unsigned Size = Record.size();
1059 std::vector<Constant*> Elts;
1061 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1062 for (unsigned i = 0; i != Size; ++i)
1063 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1064 STy->getElementType(i)));
1065 V = ConstantStruct::get(STy, Elts);
1066 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1067 Type *EltTy = ATy->getElementType();
1068 for (unsigned i = 0; i != Size; ++i)
1069 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1070 V = ConstantArray::get(ATy, Elts);
1071 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1072 Type *EltTy = VTy->getElementType();
1073 for (unsigned i = 0; i != Size; ++i)
1074 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1075 V = ConstantVector::get(Elts);
1077 V = UndefValue::get(CurTy);
1081 case bitc::CST_CODE_STRING: { // STRING: [values]
1083 return Error("Invalid CST_AGGREGATE record");
1085 ArrayType *ATy = cast<ArrayType>(CurTy);
1086 Type *EltTy = ATy->getElementType();
1088 unsigned Size = Record.size();
1089 std::vector<Constant*> Elts;
1090 for (unsigned i = 0; i != Size; ++i)
1091 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1092 V = ConstantArray::get(ATy, Elts);
1095 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1097 return Error("Invalid CST_AGGREGATE record");
1099 ArrayType *ATy = cast<ArrayType>(CurTy);
1100 Type *EltTy = ATy->getElementType();
1102 unsigned Size = Record.size();
1103 std::vector<Constant*> Elts;
1104 for (unsigned i = 0; i != Size; ++i)
1105 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1106 Elts.push_back(Constant::getNullValue(EltTy));
1107 V = ConstantArray::get(ATy, Elts);
1110 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1111 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1112 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1114 V = UndefValue::get(CurTy); // Unknown binop.
1116 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1117 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1119 if (Record.size() >= 4) {
1120 if (Opc == Instruction::Add ||
1121 Opc == Instruction::Sub ||
1122 Opc == Instruction::Mul ||
1123 Opc == Instruction::Shl) {
1124 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1125 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1126 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1127 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1128 } else if (Opc == Instruction::SDiv ||
1129 Opc == Instruction::UDiv ||
1130 Opc == Instruction::LShr ||
1131 Opc == Instruction::AShr) {
1132 if (Record[3] & (1 << bitc::PEO_EXACT))
1133 Flags |= SDivOperator::IsExact;
1136 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1140 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1141 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1142 int Opc = GetDecodedCastOpcode(Record[0]);
1144 V = UndefValue::get(CurTy); // Unknown cast.
1146 Type *OpTy = getTypeByID(Record[1]);
1147 if (!OpTy) return Error("Invalid CE_CAST record");
1148 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1149 V = ConstantExpr::getCast(Opc, Op, CurTy);
1153 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1154 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1155 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1156 SmallVector<Constant*, 16> Elts;
1157 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1158 Type *ElTy = getTypeByID(Record[i]);
1159 if (!ElTy) return Error("Invalid CE_GEP record");
1160 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1162 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1163 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1165 bitc::CST_CODE_CE_INBOUNDS_GEP);
1168 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1169 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1170 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1171 Type::getInt1Ty(Context)),
1172 ValueList.getConstantFwdRef(Record[1],CurTy),
1173 ValueList.getConstantFwdRef(Record[2],CurTy));
1175 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1176 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1178 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1179 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1180 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1181 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1182 V = ConstantExpr::getExtractElement(Op0, Op1);
1185 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1186 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1187 if (Record.size() < 3 || OpTy == 0)
1188 return Error("Invalid CE_INSERTELT record");
1189 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1190 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1191 OpTy->getElementType());
1192 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1193 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1196 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1197 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1198 if (Record.size() < 3 || OpTy == 0)
1199 return Error("Invalid CE_SHUFFLEVEC record");
1200 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1201 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1202 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1203 OpTy->getNumElements());
1204 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1205 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1208 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1209 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1211 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1212 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1213 return Error("Invalid CE_SHUFVEC_EX record");
1214 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1215 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1216 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1217 RTy->getNumElements());
1218 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1219 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1222 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1223 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1224 Type *OpTy = getTypeByID(Record[0]);
1225 if (OpTy == 0) return Error("Invalid CE_CMP record");
1226 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1227 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1229 if (OpTy->isFPOrFPVectorTy())
1230 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1232 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1235 case bitc::CST_CODE_INLINEASM: {
1236 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1237 std::string AsmStr, ConstrStr;
1238 bool HasSideEffects = Record[0] & 1;
1239 bool IsAlignStack = Record[0] >> 1;
1240 unsigned AsmStrSize = Record[1];
1241 if (2+AsmStrSize >= Record.size())
1242 return Error("Invalid INLINEASM record");
1243 unsigned ConstStrSize = Record[2+AsmStrSize];
1244 if (3+AsmStrSize+ConstStrSize > Record.size())
1245 return Error("Invalid INLINEASM record");
1247 for (unsigned i = 0; i != AsmStrSize; ++i)
1248 AsmStr += (char)Record[2+i];
1249 for (unsigned i = 0; i != ConstStrSize; ++i)
1250 ConstrStr += (char)Record[3+AsmStrSize+i];
1251 PointerType *PTy = cast<PointerType>(CurTy);
1252 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1253 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1256 case bitc::CST_CODE_BLOCKADDRESS:{
1257 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1258 Type *FnTy = getTypeByID(Record[0]);
1259 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1261 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1262 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1264 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1265 Type::getInt8Ty(Context),
1266 false, GlobalValue::InternalLinkage,
1268 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1274 ValueList.AssignValue(V, NextCstNo);
1278 if (NextCstNo != ValueList.size())
1279 return Error("Invalid constant reference!");
1281 if (Stream.ReadBlockEnd())
1282 return Error("Error at end of constants block");
1284 // Once all the constants have been read, go through and resolve forward
1286 ValueList.ResolveConstantForwardRefs();
1290 bool BitcodeReader::ParseUseLists() {
1291 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1292 return Error("Malformed block record");
1294 SmallVector<uint64_t, 64> Record;
1296 // Read all the records.
1298 unsigned Code = Stream.ReadCode();
1299 if (Code == bitc::END_BLOCK) {
1300 if (Stream.ReadBlockEnd())
1301 return Error("Error at end of use-list table block");
1305 if (Code == bitc::ENTER_SUBBLOCK) {
1306 // No known subblocks, always skip them.
1307 Stream.ReadSubBlockID();
1308 if (Stream.SkipBlock())
1309 return Error("Malformed block record");
1313 if (Code == bitc::DEFINE_ABBREV) {
1314 Stream.ReadAbbrevRecord();
1318 // Read a use list record.
1320 switch (Stream.ReadRecord(Code, Record)) {
1321 default: // Default behavior: unknown type.
1323 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1324 unsigned RecordLength = Record.size();
1325 if (RecordLength < 1)
1326 return Error ("Invalid UseList reader!");
1327 UseListRecords.push_back(Record);
1334 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1335 /// remember where it is and then skip it. This lets us lazily deserialize the
1337 bool BitcodeReader::RememberAndSkipFunctionBody() {
1338 // Get the function we are talking about.
1339 if (FunctionsWithBodies.empty())
1340 return Error("Insufficient function protos");
1342 Function *Fn = FunctionsWithBodies.back();
1343 FunctionsWithBodies.pop_back();
1345 // Save the current stream state.
1346 uint64_t CurBit = Stream.GetCurrentBitNo();
1347 DeferredFunctionInfo[Fn] = CurBit;
1349 // Skip over the function block for now.
1350 if (Stream.SkipBlock())
1351 return Error("Malformed block record");
1355 bool BitcodeReader::ParseModule() {
1356 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1357 return Error("Malformed block record");
1359 SmallVector<uint64_t, 64> Record;
1360 std::vector<std::string> SectionTable;
1361 std::vector<std::string> GCTable;
1363 // Read all the records for this module.
1364 while (!Stream.AtEndOfStream()) {
1365 unsigned Code = Stream.ReadCode();
1366 if (Code == bitc::END_BLOCK) {
1367 if (Stream.ReadBlockEnd())
1368 return Error("Error at end of module block");
1370 // Patch the initializers for globals and aliases up.
1371 ResolveGlobalAndAliasInits();
1372 if (!GlobalInits.empty() || !AliasInits.empty())
1373 return Error("Malformed global initializer set");
1374 if (!FunctionsWithBodies.empty())
1375 return Error("Too few function bodies found");
1377 // Look for intrinsic functions which need to be upgraded at some point
1378 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1381 if (UpgradeIntrinsicFunction(FI, NewFn))
1382 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1385 // Look for global variables which need to be renamed.
1386 for (Module::global_iterator
1387 GI = TheModule->global_begin(), GE = TheModule->global_end();
1389 UpgradeGlobalVariable(GI);
1391 // Force deallocation of memory for these vectors to favor the client that
1392 // want lazy deserialization.
1393 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1394 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1395 std::vector<Function*>().swap(FunctionsWithBodies);
1399 if (Code == bitc::ENTER_SUBBLOCK) {
1400 switch (Stream.ReadSubBlockID()) {
1401 default: // Skip unknown content.
1402 if (Stream.SkipBlock())
1403 return Error("Malformed block record");
1405 case bitc::BLOCKINFO_BLOCK_ID:
1406 if (Stream.ReadBlockInfoBlock())
1407 return Error("Malformed BlockInfoBlock");
1409 case bitc::PARAMATTR_BLOCK_ID:
1410 if (ParseAttributeBlock())
1413 case bitc::TYPE_BLOCK_ID_NEW:
1414 if (ParseTypeTable())
1417 case bitc::VALUE_SYMTAB_BLOCK_ID:
1418 if (ParseValueSymbolTable())
1421 case bitc::CONSTANTS_BLOCK_ID:
1422 if (ParseConstants() || ResolveGlobalAndAliasInits())
1425 case bitc::METADATA_BLOCK_ID:
1426 if (ParseMetadata())
1429 case bitc::FUNCTION_BLOCK_ID:
1430 // If this is the first function body we've seen, reverse the
1431 // FunctionsWithBodies list.
1432 if (!HasReversedFunctionsWithBodies) {
1433 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1434 HasReversedFunctionsWithBodies = true;
1437 if (RememberAndSkipFunctionBody())
1440 case bitc::USELIST_BLOCK_ID:
1441 if (ParseUseLists())
1448 if (Code == bitc::DEFINE_ABBREV) {
1449 Stream.ReadAbbrevRecord();
1454 switch (Stream.ReadRecord(Code, Record)) {
1455 default: break; // Default behavior, ignore unknown content.
1456 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1457 if (Record.size() < 1)
1458 return Error("Malformed MODULE_CODE_VERSION");
1459 // Only version #0 is supported so far.
1461 return Error("Unknown bitstream version!");
1463 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1465 if (ConvertToString(Record, 0, S))
1466 return Error("Invalid MODULE_CODE_TRIPLE record");
1467 TheModule->setTargetTriple(S);
1470 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1472 if (ConvertToString(Record, 0, S))
1473 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1474 TheModule->setDataLayout(S);
1477 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1479 if (ConvertToString(Record, 0, S))
1480 return Error("Invalid MODULE_CODE_ASM record");
1481 TheModule->setModuleInlineAsm(S);
1484 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1486 if (ConvertToString(Record, 0, S))
1487 return Error("Invalid MODULE_CODE_DEPLIB record");
1488 TheModule->addLibrary(S);
1491 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1493 if (ConvertToString(Record, 0, S))
1494 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1495 SectionTable.push_back(S);
1498 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1500 if (ConvertToString(Record, 0, S))
1501 return Error("Invalid MODULE_CODE_GCNAME record");
1502 GCTable.push_back(S);
1505 // GLOBALVAR: [pointer type, isconst, initid,
1506 // linkage, alignment, section, visibility, threadlocal,
1508 case bitc::MODULE_CODE_GLOBALVAR: {
1509 if (Record.size() < 6)
1510 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1511 Type *Ty = getTypeByID(Record[0]);
1512 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1513 if (!Ty->isPointerTy())
1514 return Error("Global not a pointer type!");
1515 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1516 Ty = cast<PointerType>(Ty)->getElementType();
1518 bool isConstant = Record[1];
1519 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1520 unsigned Alignment = (1 << Record[4]) >> 1;
1521 std::string Section;
1523 if (Record[5]-1 >= SectionTable.size())
1524 return Error("Invalid section ID");
1525 Section = SectionTable[Record[5]-1];
1527 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1528 if (Record.size() > 6)
1529 Visibility = GetDecodedVisibility(Record[6]);
1530 bool isThreadLocal = false;
1531 if (Record.size() > 7)
1532 isThreadLocal = Record[7];
1534 bool UnnamedAddr = false;
1535 if (Record.size() > 8)
1536 UnnamedAddr = Record[8];
1538 GlobalVariable *NewGV =
1539 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1540 isThreadLocal, AddressSpace);
1541 NewGV->setAlignment(Alignment);
1542 if (!Section.empty())
1543 NewGV->setSection(Section);
1544 NewGV->setVisibility(Visibility);
1545 NewGV->setThreadLocal(isThreadLocal);
1546 NewGV->setUnnamedAddr(UnnamedAddr);
1548 ValueList.push_back(NewGV);
1550 // Remember which value to use for the global initializer.
1551 if (unsigned InitID = Record[2])
1552 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1555 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1556 // alignment, section, visibility, gc, unnamed_addr]
1557 case bitc::MODULE_CODE_FUNCTION: {
1558 if (Record.size() < 8)
1559 return Error("Invalid MODULE_CODE_FUNCTION record");
1560 Type *Ty = getTypeByID(Record[0]);
1561 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1562 if (!Ty->isPointerTy())
1563 return Error("Function not a pointer type!");
1565 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1567 return Error("Function not a pointer to function type!");
1569 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1572 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1573 bool isProto = Record[2];
1574 Func->setLinkage(GetDecodedLinkage(Record[3]));
1575 Func->setAttributes(getAttributes(Record[4]));
1577 Func->setAlignment((1 << Record[5]) >> 1);
1579 if (Record[6]-1 >= SectionTable.size())
1580 return Error("Invalid section ID");
1581 Func->setSection(SectionTable[Record[6]-1]);
1583 Func->setVisibility(GetDecodedVisibility(Record[7]));
1584 if (Record.size() > 8 && Record[8]) {
1585 if (Record[8]-1 > GCTable.size())
1586 return Error("Invalid GC ID");
1587 Func->setGC(GCTable[Record[8]-1].c_str());
1589 bool UnnamedAddr = false;
1590 if (Record.size() > 9)
1591 UnnamedAddr = Record[9];
1592 Func->setUnnamedAddr(UnnamedAddr);
1593 ValueList.push_back(Func);
1595 // If this is a function with a body, remember the prototype we are
1596 // creating now, so that we can match up the body with them later.
1598 FunctionsWithBodies.push_back(Func);
1601 // ALIAS: [alias type, aliasee val#, linkage]
1602 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1603 case bitc::MODULE_CODE_ALIAS: {
1604 if (Record.size() < 3)
1605 return Error("Invalid MODULE_ALIAS record");
1606 Type *Ty = getTypeByID(Record[0]);
1607 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1608 if (!Ty->isPointerTy())
1609 return Error("Function not a pointer type!");
1611 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1613 // Old bitcode files didn't have visibility field.
1614 if (Record.size() > 3)
1615 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1616 ValueList.push_back(NewGA);
1617 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1620 /// MODULE_CODE_PURGEVALS: [numvals]
1621 case bitc::MODULE_CODE_PURGEVALS:
1622 // Trim down the value list to the specified size.
1623 if (Record.size() < 1 || Record[0] > ValueList.size())
1624 return Error("Invalid MODULE_PURGEVALS record");
1625 ValueList.shrinkTo(Record[0]);
1631 return Error("Premature end of bitstream");
1634 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1637 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1638 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1640 if (Buffer->getBufferSize() & 3) {
1641 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1642 return Error("Invalid bitcode signature");
1644 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1647 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1648 // The magic number is 0x0B17C0DE stored in little endian.
1649 if (isBitcodeWrapper(BufPtr, BufEnd))
1650 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1651 return Error("Invalid bitcode wrapper header");
1653 StreamFile.init(BufPtr, BufEnd);
1654 Stream.init(StreamFile);
1656 // Sniff for the signature.
1657 if (Stream.Read(8) != 'B' ||
1658 Stream.Read(8) != 'C' ||
1659 Stream.Read(4) != 0x0 ||
1660 Stream.Read(4) != 0xC ||
1661 Stream.Read(4) != 0xE ||
1662 Stream.Read(4) != 0xD)
1663 return Error("Invalid bitcode signature");
1665 // We expect a number of well-defined blocks, though we don't necessarily
1666 // need to understand them all.
1667 while (!Stream.AtEndOfStream()) {
1668 unsigned Code = Stream.ReadCode();
1670 if (Code != bitc::ENTER_SUBBLOCK) {
1672 // The ranlib in xcode 4 will align archive members by appending newlines
1673 // to the end of them. If this file size is a multiple of 4 but not 8, we
1674 // have to read and ignore these final 4 bytes :-(
1675 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1676 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1677 Stream.AtEndOfStream())
1680 return Error("Invalid record at top-level");
1683 unsigned BlockID = Stream.ReadSubBlockID();
1685 // We only know the MODULE subblock ID.
1687 case bitc::BLOCKINFO_BLOCK_ID:
1688 if (Stream.ReadBlockInfoBlock())
1689 return Error("Malformed BlockInfoBlock");
1691 case bitc::MODULE_BLOCK_ID:
1692 // Reject multiple MODULE_BLOCK's in a single bitstream.
1694 return Error("Multiple MODULE_BLOCKs in same stream");
1700 if (Stream.SkipBlock())
1701 return Error("Malformed block record");
1709 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1710 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1711 return Error("Malformed block record");
1713 SmallVector<uint64_t, 64> Record;
1715 // Read all the records for this module.
1716 while (!Stream.AtEndOfStream()) {
1717 unsigned Code = Stream.ReadCode();
1718 if (Code == bitc::END_BLOCK) {
1719 if (Stream.ReadBlockEnd())
1720 return Error("Error at end of module block");
1725 if (Code == bitc::ENTER_SUBBLOCK) {
1726 switch (Stream.ReadSubBlockID()) {
1727 default: // Skip unknown content.
1728 if (Stream.SkipBlock())
1729 return Error("Malformed block record");
1735 if (Code == bitc::DEFINE_ABBREV) {
1736 Stream.ReadAbbrevRecord();
1741 switch (Stream.ReadRecord(Code, Record)) {
1742 default: break; // Default behavior, ignore unknown content.
1743 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1744 if (Record.size() < 1)
1745 return Error("Malformed MODULE_CODE_VERSION");
1746 // Only version #0 is supported so far.
1748 return Error("Unknown bitstream version!");
1750 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1752 if (ConvertToString(Record, 0, S))
1753 return Error("Invalid MODULE_CODE_TRIPLE record");
1761 return Error("Premature end of bitstream");
1764 bool BitcodeReader::ParseTriple(std::string &Triple) {
1765 if (Buffer->getBufferSize() & 3)
1766 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1768 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1769 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1771 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1772 // The magic number is 0x0B17C0DE stored in little endian.
1773 if (isBitcodeWrapper(BufPtr, BufEnd))
1774 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1775 return Error("Invalid bitcode wrapper header");
1777 StreamFile.init(BufPtr, BufEnd);
1778 Stream.init(StreamFile);
1780 // Sniff for the signature.
1781 if (Stream.Read(8) != 'B' ||
1782 Stream.Read(8) != 'C' ||
1783 Stream.Read(4) != 0x0 ||
1784 Stream.Read(4) != 0xC ||
1785 Stream.Read(4) != 0xE ||
1786 Stream.Read(4) != 0xD)
1787 return Error("Invalid bitcode signature");
1789 // We expect a number of well-defined blocks, though we don't necessarily
1790 // need to understand them all.
1791 while (!Stream.AtEndOfStream()) {
1792 unsigned Code = Stream.ReadCode();
1794 if (Code != bitc::ENTER_SUBBLOCK)
1795 return Error("Invalid record at top-level");
1797 unsigned BlockID = Stream.ReadSubBlockID();
1799 // We only know the MODULE subblock ID.
1801 case bitc::MODULE_BLOCK_ID:
1802 if (ParseModuleTriple(Triple))
1806 if (Stream.SkipBlock())
1807 return Error("Malformed block record");
1815 /// ParseMetadataAttachment - Parse metadata attachments.
1816 bool BitcodeReader::ParseMetadataAttachment() {
1817 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1818 return Error("Malformed block record");
1820 SmallVector<uint64_t, 64> Record;
1822 unsigned Code = Stream.ReadCode();
1823 if (Code == bitc::END_BLOCK) {
1824 if (Stream.ReadBlockEnd())
1825 return Error("Error at end of PARAMATTR block");
1828 if (Code == bitc::DEFINE_ABBREV) {
1829 Stream.ReadAbbrevRecord();
1832 // Read a metadata attachment record.
1834 switch (Stream.ReadRecord(Code, Record)) {
1835 default: // Default behavior: ignore.
1837 case bitc::METADATA_ATTACHMENT: {
1838 unsigned RecordLength = Record.size();
1839 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1840 return Error ("Invalid METADATA_ATTACHMENT reader!");
1841 Instruction *Inst = InstructionList[Record[0]];
1842 for (unsigned i = 1; i != RecordLength; i = i+2) {
1843 unsigned Kind = Record[i];
1844 DenseMap<unsigned, unsigned>::iterator I =
1845 MDKindMap.find(Kind);
1846 if (I == MDKindMap.end())
1847 return Error("Invalid metadata kind ID");
1848 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1849 Inst->setMetadata(I->second, cast<MDNode>(Node));
1858 /// ParseFunctionBody - Lazily parse the specified function body block.
1859 bool BitcodeReader::ParseFunctionBody(Function *F) {
1860 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1861 return Error("Malformed block record");
1863 InstructionList.clear();
1864 unsigned ModuleValueListSize = ValueList.size();
1865 unsigned ModuleMDValueListSize = MDValueList.size();
1867 // Add all the function arguments to the value table.
1868 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1869 ValueList.push_back(I);
1871 unsigned NextValueNo = ValueList.size();
1872 BasicBlock *CurBB = 0;
1873 unsigned CurBBNo = 0;
1877 // Read all the records.
1878 SmallVector<uint64_t, 64> Record;
1880 unsigned Code = Stream.ReadCode();
1881 if (Code == bitc::END_BLOCK) {
1882 if (Stream.ReadBlockEnd())
1883 return Error("Error at end of function block");
1887 if (Code == bitc::ENTER_SUBBLOCK) {
1888 switch (Stream.ReadSubBlockID()) {
1889 default: // Skip unknown content.
1890 if (Stream.SkipBlock())
1891 return Error("Malformed block record");
1893 case bitc::CONSTANTS_BLOCK_ID:
1894 if (ParseConstants()) return true;
1895 NextValueNo = ValueList.size();
1897 case bitc::VALUE_SYMTAB_BLOCK_ID:
1898 if (ParseValueSymbolTable()) return true;
1900 case bitc::METADATA_ATTACHMENT_ID:
1901 if (ParseMetadataAttachment()) return true;
1903 case bitc::METADATA_BLOCK_ID:
1904 if (ParseMetadata()) return true;
1910 if (Code == bitc::DEFINE_ABBREV) {
1911 Stream.ReadAbbrevRecord();
1918 unsigned BitCode = Stream.ReadRecord(Code, Record);
1920 default: // Default behavior: reject
1921 return Error("Unknown instruction");
1922 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1923 if (Record.size() < 1 || Record[0] == 0)
1924 return Error("Invalid DECLAREBLOCKS record");
1925 // Create all the basic blocks for the function.
1926 FunctionBBs.resize(Record[0]);
1927 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1928 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1929 CurBB = FunctionBBs[0];
1932 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1933 // This record indicates that the last instruction is at the same
1934 // location as the previous instruction with a location.
1937 // Get the last instruction emitted.
1938 if (CurBB && !CurBB->empty())
1940 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1941 !FunctionBBs[CurBBNo-1]->empty())
1942 I = &FunctionBBs[CurBBNo-1]->back();
1944 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1945 I->setDebugLoc(LastLoc);
1949 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
1950 I = 0; // Get the last instruction emitted.
1951 if (CurBB && !CurBB->empty())
1953 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1954 !FunctionBBs[CurBBNo-1]->empty())
1955 I = &FunctionBBs[CurBBNo-1]->back();
1956 if (I == 0 || Record.size() < 4)
1957 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1959 unsigned Line = Record[0], Col = Record[1];
1960 unsigned ScopeID = Record[2], IAID = Record[3];
1962 MDNode *Scope = 0, *IA = 0;
1963 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1964 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1965 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1966 I->setDebugLoc(LastLoc);
1971 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1974 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1975 getValue(Record, OpNum, LHS->getType(), RHS) ||
1976 OpNum+1 > Record.size())
1977 return Error("Invalid BINOP record");
1979 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1980 if (Opc == -1) return Error("Invalid BINOP record");
1981 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1982 InstructionList.push_back(I);
1983 if (OpNum < Record.size()) {
1984 if (Opc == Instruction::Add ||
1985 Opc == Instruction::Sub ||
1986 Opc == Instruction::Mul ||
1987 Opc == Instruction::Shl) {
1988 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1989 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1990 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1991 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1992 } else if (Opc == Instruction::SDiv ||
1993 Opc == Instruction::UDiv ||
1994 Opc == Instruction::LShr ||
1995 Opc == Instruction::AShr) {
1996 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
1997 cast<BinaryOperator>(I)->setIsExact(true);
2002 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2005 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2006 OpNum+2 != Record.size())
2007 return Error("Invalid CAST record");
2009 Type *ResTy = getTypeByID(Record[OpNum]);
2010 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2011 if (Opc == -1 || ResTy == 0)
2012 return Error("Invalid CAST record");
2013 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2014 InstructionList.push_back(I);
2017 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2018 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2021 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2022 return Error("Invalid GEP record");
2024 SmallVector<Value*, 16> GEPIdx;
2025 while (OpNum != Record.size()) {
2027 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2028 return Error("Invalid GEP record");
2029 GEPIdx.push_back(Op);
2032 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2033 InstructionList.push_back(I);
2034 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2035 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2039 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2040 // EXTRACTVAL: [opty, opval, n x indices]
2043 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2044 return Error("Invalid EXTRACTVAL record");
2046 SmallVector<unsigned, 4> EXTRACTVALIdx;
2047 for (unsigned RecSize = Record.size();
2048 OpNum != RecSize; ++OpNum) {
2049 uint64_t Index = Record[OpNum];
2050 if ((unsigned)Index != Index)
2051 return Error("Invalid EXTRACTVAL index");
2052 EXTRACTVALIdx.push_back((unsigned)Index);
2055 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2056 InstructionList.push_back(I);
2060 case bitc::FUNC_CODE_INST_INSERTVAL: {
2061 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2064 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2065 return Error("Invalid INSERTVAL record");
2067 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2068 return Error("Invalid INSERTVAL record");
2070 SmallVector<unsigned, 4> INSERTVALIdx;
2071 for (unsigned RecSize = Record.size();
2072 OpNum != RecSize; ++OpNum) {
2073 uint64_t Index = Record[OpNum];
2074 if ((unsigned)Index != Index)
2075 return Error("Invalid INSERTVAL index");
2076 INSERTVALIdx.push_back((unsigned)Index);
2079 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2080 InstructionList.push_back(I);
2084 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2085 // obsolete form of select
2086 // handles select i1 ... in old bitcode
2088 Value *TrueVal, *FalseVal, *Cond;
2089 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2090 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2091 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2092 return Error("Invalid SELECT record");
2094 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2095 InstructionList.push_back(I);
2099 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2100 // new form of select
2101 // handles select i1 or select [N x i1]
2103 Value *TrueVal, *FalseVal, *Cond;
2104 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2105 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2106 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2107 return Error("Invalid SELECT record");
2109 // select condition can be either i1 or [N x i1]
2110 if (VectorType* vector_type =
2111 dyn_cast<VectorType>(Cond->getType())) {
2113 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2114 return Error("Invalid SELECT condition type");
2117 if (Cond->getType() != Type::getInt1Ty(Context))
2118 return Error("Invalid SELECT condition type");
2121 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2122 InstructionList.push_back(I);
2126 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2129 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2130 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2131 return Error("Invalid EXTRACTELT record");
2132 I = ExtractElementInst::Create(Vec, Idx);
2133 InstructionList.push_back(I);
2137 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2139 Value *Vec, *Elt, *Idx;
2140 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2141 getValue(Record, OpNum,
2142 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2143 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2144 return Error("Invalid INSERTELT record");
2145 I = InsertElementInst::Create(Vec, Elt, Idx);
2146 InstructionList.push_back(I);
2150 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2152 Value *Vec1, *Vec2, *Mask;
2153 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2154 getValue(Record, OpNum, Vec1->getType(), Vec2))
2155 return Error("Invalid SHUFFLEVEC record");
2157 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2158 return Error("Invalid SHUFFLEVEC record");
2159 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2160 InstructionList.push_back(I);
2164 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2165 // Old form of ICmp/FCmp returning bool
2166 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2167 // both legal on vectors but had different behaviour.
2168 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2169 // FCmp/ICmp returning bool or vector of bool
2173 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2174 getValue(Record, OpNum, LHS->getType(), RHS) ||
2175 OpNum+1 != Record.size())
2176 return Error("Invalid CMP record");
2178 if (LHS->getType()->isFPOrFPVectorTy())
2179 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2181 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2182 InstructionList.push_back(I);
2186 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2188 unsigned Size = Record.size();
2190 I = ReturnInst::Create(Context);
2191 InstructionList.push_back(I);
2197 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2198 return Error("Invalid RET record");
2199 if (OpNum != Record.size())
2200 return Error("Invalid RET record");
2202 I = ReturnInst::Create(Context, Op);
2203 InstructionList.push_back(I);
2206 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2207 if (Record.size() != 1 && Record.size() != 3)
2208 return Error("Invalid BR record");
2209 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2211 return Error("Invalid BR record");
2213 if (Record.size() == 1) {
2214 I = BranchInst::Create(TrueDest);
2215 InstructionList.push_back(I);
2218 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2219 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2220 if (FalseDest == 0 || Cond == 0)
2221 return Error("Invalid BR record");
2222 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2223 InstructionList.push_back(I);
2227 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2228 if (Record.size() < 3 || (Record.size() & 1) == 0)
2229 return Error("Invalid SWITCH record");
2230 Type *OpTy = getTypeByID(Record[0]);
2231 Value *Cond = getFnValueByID(Record[1], OpTy);
2232 BasicBlock *Default = getBasicBlock(Record[2]);
2233 if (OpTy == 0 || Cond == 0 || Default == 0)
2234 return Error("Invalid SWITCH record");
2235 unsigned NumCases = (Record.size()-3)/2;
2236 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2237 InstructionList.push_back(SI);
2238 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2239 ConstantInt *CaseVal =
2240 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2241 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2242 if (CaseVal == 0 || DestBB == 0) {
2244 return Error("Invalid SWITCH record!");
2246 SI->addCase(CaseVal, DestBB);
2251 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2252 if (Record.size() < 2)
2253 return Error("Invalid INDIRECTBR record");
2254 Type *OpTy = getTypeByID(Record[0]);
2255 Value *Address = getFnValueByID(Record[1], OpTy);
2256 if (OpTy == 0 || Address == 0)
2257 return Error("Invalid INDIRECTBR record");
2258 unsigned NumDests = Record.size()-2;
2259 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2260 InstructionList.push_back(IBI);
2261 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2262 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2263 IBI->addDestination(DestBB);
2266 return Error("Invalid INDIRECTBR record!");
2273 case bitc::FUNC_CODE_INST_INVOKE: {
2274 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2275 if (Record.size() < 4) return Error("Invalid INVOKE record");
2276 AttrListPtr PAL = getAttributes(Record[0]);
2277 unsigned CCInfo = Record[1];
2278 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2279 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2283 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2284 return Error("Invalid INVOKE record");
2286 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2287 FunctionType *FTy = !CalleeTy ? 0 :
2288 dyn_cast<FunctionType>(CalleeTy->getElementType());
2290 // Check that the right number of fixed parameters are here.
2291 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2292 Record.size() < OpNum+FTy->getNumParams())
2293 return Error("Invalid INVOKE record");
2295 SmallVector<Value*, 16> Ops;
2296 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2297 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2298 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2301 if (!FTy->isVarArg()) {
2302 if (Record.size() != OpNum)
2303 return Error("Invalid INVOKE record");
2305 // Read type/value pairs for varargs params.
2306 while (OpNum != Record.size()) {
2308 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2309 return Error("Invalid INVOKE record");
2314 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2315 InstructionList.push_back(I);
2316 cast<InvokeInst>(I)->setCallingConv(
2317 static_cast<CallingConv::ID>(CCInfo));
2318 cast<InvokeInst>(I)->setAttributes(PAL);
2321 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2324 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2325 return Error("Invalid RESUME record");
2326 I = ResumeInst::Create(Val);
2327 InstructionList.push_back(I);
2330 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2331 I = new UnwindInst(Context);
2332 InstructionList.push_back(I);
2334 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2335 I = new UnreachableInst(Context);
2336 InstructionList.push_back(I);
2338 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2339 if (Record.size() < 1 || ((Record.size()-1)&1))
2340 return Error("Invalid PHI record");
2341 Type *Ty = getTypeByID(Record[0]);
2342 if (!Ty) return Error("Invalid PHI record");
2344 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2345 InstructionList.push_back(PN);
2347 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2348 Value *V = getFnValueByID(Record[1+i], Ty);
2349 BasicBlock *BB = getBasicBlock(Record[2+i]);
2350 if (!V || !BB) return Error("Invalid PHI record");
2351 PN->addIncoming(V, BB);
2357 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2358 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2360 if (Record.size() < 4)
2361 return Error("Invalid LANDINGPAD record");
2362 Type *Ty = getTypeByID(Record[Idx++]);
2363 if (!Ty) return Error("Invalid LANDINGPAD record");
2365 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2366 return Error("Invalid LANDINGPAD record");
2368 bool IsCleanup = !!Record[Idx++];
2369 unsigned NumClauses = Record[Idx++];
2370 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2371 LP->setCleanup(IsCleanup);
2372 for (unsigned J = 0; J != NumClauses; ++J) {
2373 LandingPadInst::ClauseType CT =
2374 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2377 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2379 return Error("Invalid LANDINGPAD record");
2382 assert((CT != LandingPadInst::Catch ||
2383 !isa<ArrayType>(Val->getType())) &&
2384 "Catch clause has a invalid type!");
2385 assert((CT != LandingPadInst::Filter ||
2386 isa<ArrayType>(Val->getType())) &&
2387 "Filter clause has invalid type!");
2392 InstructionList.push_back(I);
2396 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2397 if (Record.size() != 4)
2398 return Error("Invalid ALLOCA record");
2400 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2401 Type *OpTy = getTypeByID(Record[1]);
2402 Value *Size = getFnValueByID(Record[2], OpTy);
2403 unsigned Align = Record[3];
2404 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2405 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2406 InstructionList.push_back(I);
2409 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2412 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2413 OpNum+2 != Record.size())
2414 return Error("Invalid LOAD record");
2416 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2417 InstructionList.push_back(I);
2420 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2421 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2424 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2425 OpNum+4 != Record.size())
2426 return Error("Invalid LOADATOMIC record");
2429 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2430 if (Ordering == NotAtomic || Ordering == Release ||
2431 Ordering == AcquireRelease)
2432 return Error("Invalid LOADATOMIC record");
2433 if (Ordering != NotAtomic && Record[OpNum] == 0)
2434 return Error("Invalid LOADATOMIC record");
2435 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2437 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2438 Ordering, SynchScope);
2439 InstructionList.push_back(I);
2442 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2445 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2446 getValue(Record, OpNum,
2447 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2448 OpNum+2 != Record.size())
2449 return Error("Invalid STORE record");
2451 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2452 InstructionList.push_back(I);
2455 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2456 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2459 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2460 getValue(Record, OpNum,
2461 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2462 OpNum+4 != Record.size())
2463 return Error("Invalid STOREATOMIC record");
2465 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2466 if (Ordering == NotAtomic || Ordering == Acquire ||
2467 Ordering == AcquireRelease)
2468 return Error("Invalid STOREATOMIC record");
2469 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2470 if (Ordering != NotAtomic && Record[OpNum] == 0)
2471 return Error("Invalid STOREATOMIC record");
2473 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2474 Ordering, SynchScope);
2475 InstructionList.push_back(I);
2478 case bitc::FUNC_CODE_INST_CMPXCHG: {
2479 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2481 Value *Ptr, *Cmp, *New;
2482 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2483 getValue(Record, OpNum,
2484 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2485 getValue(Record, OpNum,
2486 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2487 OpNum+3 != Record.size())
2488 return Error("Invalid CMPXCHG record");
2489 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2490 if (Ordering == NotAtomic || Ordering == Unordered)
2491 return Error("Invalid CMPXCHG record");
2492 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2493 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2494 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2495 InstructionList.push_back(I);
2498 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2499 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2502 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2503 getValue(Record, OpNum,
2504 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2505 OpNum+4 != Record.size())
2506 return Error("Invalid ATOMICRMW record");
2507 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2508 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2509 Operation > AtomicRMWInst::LAST_BINOP)
2510 return Error("Invalid ATOMICRMW record");
2511 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2512 if (Ordering == NotAtomic || Ordering == Unordered)
2513 return Error("Invalid ATOMICRMW record");
2514 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2515 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2516 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2517 InstructionList.push_back(I);
2520 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2521 if (2 != Record.size())
2522 return Error("Invalid FENCE record");
2523 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2524 if (Ordering == NotAtomic || Ordering == Unordered ||
2525 Ordering == Monotonic)
2526 return Error("Invalid FENCE record");
2527 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2528 I = new FenceInst(Context, Ordering, SynchScope);
2529 InstructionList.push_back(I);
2532 case bitc::FUNC_CODE_INST_CALL: {
2533 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2534 if (Record.size() < 3)
2535 return Error("Invalid CALL record");
2537 AttrListPtr PAL = getAttributes(Record[0]);
2538 unsigned CCInfo = Record[1];
2542 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2543 return Error("Invalid CALL record");
2545 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2546 FunctionType *FTy = 0;
2547 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2548 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2549 return Error("Invalid CALL record");
2551 SmallVector<Value*, 16> Args;
2552 // Read the fixed params.
2553 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2554 if (FTy->getParamType(i)->isLabelTy())
2555 Args.push_back(getBasicBlock(Record[OpNum]));
2557 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2558 if (Args.back() == 0) return Error("Invalid CALL record");
2561 // Read type/value pairs for varargs params.
2562 if (!FTy->isVarArg()) {
2563 if (OpNum != Record.size())
2564 return Error("Invalid CALL record");
2566 while (OpNum != Record.size()) {
2568 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2569 return Error("Invalid CALL record");
2574 I = CallInst::Create(Callee, Args);
2575 InstructionList.push_back(I);
2576 cast<CallInst>(I)->setCallingConv(
2577 static_cast<CallingConv::ID>(CCInfo>>1));
2578 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2579 cast<CallInst>(I)->setAttributes(PAL);
2582 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2583 if (Record.size() < 3)
2584 return Error("Invalid VAARG record");
2585 Type *OpTy = getTypeByID(Record[0]);
2586 Value *Op = getFnValueByID(Record[1], OpTy);
2587 Type *ResTy = getTypeByID(Record[2]);
2588 if (!OpTy || !Op || !ResTy)
2589 return Error("Invalid VAARG record");
2590 I = new VAArgInst(Op, ResTy);
2591 InstructionList.push_back(I);
2596 // Add instruction to end of current BB. If there is no current BB, reject
2600 return Error("Invalid instruction with no BB");
2602 CurBB->getInstList().push_back(I);
2604 // If this was a terminator instruction, move to the next block.
2605 if (isa<TerminatorInst>(I)) {
2607 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2610 // Non-void values get registered in the value table for future use.
2611 if (I && !I->getType()->isVoidTy())
2612 ValueList.AssignValue(I, NextValueNo++);
2615 // Check the function list for unresolved values.
2616 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2617 if (A->getParent() == 0) {
2618 // We found at least one unresolved value. Nuke them all to avoid leaks.
2619 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2620 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2621 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2625 return Error("Never resolved value found in function!");
2629 // FIXME: Check for unresolved forward-declared metadata references
2630 // and clean up leaks.
2632 // See if anything took the address of blocks in this function. If so,
2633 // resolve them now.
2634 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2635 BlockAddrFwdRefs.find(F);
2636 if (BAFRI != BlockAddrFwdRefs.end()) {
2637 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2638 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2639 unsigned BlockIdx = RefList[i].first;
2640 if (BlockIdx >= FunctionBBs.size())
2641 return Error("Invalid blockaddress block #");
2643 GlobalVariable *FwdRef = RefList[i].second;
2644 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2645 FwdRef->eraseFromParent();
2648 BlockAddrFwdRefs.erase(BAFRI);
2651 // Trim the value list down to the size it was before we parsed this function.
2652 ValueList.shrinkTo(ModuleValueListSize);
2653 MDValueList.shrinkTo(ModuleMDValueListSize);
2654 std::vector<BasicBlock*>().swap(FunctionBBs);
2658 //===----------------------------------------------------------------------===//
2659 // GVMaterializer implementation
2660 //===----------------------------------------------------------------------===//
2663 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2664 if (const Function *F = dyn_cast<Function>(GV)) {
2665 return F->isDeclaration() &&
2666 DeferredFunctionInfo.count(const_cast<Function*>(F));
2671 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2672 Function *F = dyn_cast<Function>(GV);
2673 // If it's not a function or is already material, ignore the request.
2674 if (!F || !F->isMaterializable()) return false;
2676 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2677 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2679 // Move the bit stream to the saved position of the deferred function body.
2680 Stream.JumpToBit(DFII->second);
2682 if (ParseFunctionBody(F)) {
2683 if (ErrInfo) *ErrInfo = ErrorString;
2687 // Upgrade any old intrinsic calls in the function.
2688 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2689 E = UpgradedIntrinsics.end(); I != E; ++I) {
2690 if (I->first != I->second) {
2691 for (Value::use_iterator UI = I->first->use_begin(),
2692 UE = I->first->use_end(); UI != UE; ) {
2693 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2694 UpgradeIntrinsicCall(CI, I->second);
2702 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2703 const Function *F = dyn_cast<Function>(GV);
2704 if (!F || F->isDeclaration())
2706 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2709 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2710 Function *F = dyn_cast<Function>(GV);
2711 // If this function isn't dematerializable, this is a noop.
2712 if (!F || !isDematerializable(F))
2715 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2717 // Just forget the function body, we can remat it later.
2722 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2723 assert(M == TheModule &&
2724 "Can only Materialize the Module this BitcodeReader is attached to.");
2725 // Iterate over the module, deserializing any functions that are still on
2727 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2729 if (F->isMaterializable() &&
2730 Materialize(F, ErrInfo))
2733 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2734 // delete the old functions to clean up. We can't do this unless the entire
2735 // module is materialized because there could always be another function body
2736 // with calls to the old function.
2737 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2738 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2739 if (I->first != I->second) {
2740 for (Value::use_iterator UI = I->first->use_begin(),
2741 UE = I->first->use_end(); UI != UE; ) {
2742 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2743 UpgradeIntrinsicCall(CI, I->second);
2745 if (!I->first->use_empty())
2746 I->first->replaceAllUsesWith(I->second);
2747 I->first->eraseFromParent();
2750 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2756 //===----------------------------------------------------------------------===//
2757 // External interface
2758 //===----------------------------------------------------------------------===//
2760 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2762 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2763 LLVMContext& Context,
2764 std::string *ErrMsg) {
2765 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2766 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2767 M->setMaterializer(R);
2768 if (R->ParseBitcodeInto(M)) {
2770 *ErrMsg = R->getErrorString();
2772 delete M; // Also deletes R.
2775 // Have the BitcodeReader dtor delete 'Buffer'.
2776 R->setBufferOwned(true);
2780 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2781 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2782 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2783 std::string *ErrMsg){
2784 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2787 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2788 // there was an error.
2789 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2791 // Read in the entire module, and destroy the BitcodeReader.
2792 if (M->MaterializeAllPermanently(ErrMsg)) {
2797 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2798 // written. We must defer until the Module has been fully materialized.
2803 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2804 LLVMContext& Context,
2805 std::string *ErrMsg) {
2806 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2807 // Don't let the BitcodeReader dtor delete 'Buffer'.
2808 R->setBufferOwned(false);
2810 std::string Triple("");
2811 if (R->ParseTriple(Triple))
2813 *ErrMsg = R->getErrorString();