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 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/DerivedTypes.h"
17 #include "llvm/IR/InlineAsm.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/OperandTraits.h"
21 #include "llvm/IR/Operator.h"
22 #include "llvm/Support/DataStream.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/MemoryBuffer.h"
28 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
31 void BitcodeReader::materializeForwardReferencedFunctions() {
32 while (!BlockAddrFwdRefs.empty()) {
33 Function *F = BlockAddrFwdRefs.begin()->first;
38 void BitcodeReader::FreeState() {
42 std::vector<Type*>().swap(TypeList);
46 std::vector<AttributeSet>().swap(MAttributes);
47 std::vector<BasicBlock*>().swap(FunctionBBs);
48 std::vector<Function*>().swap(FunctionsWithBodies);
49 DeferredFunctionInfo.clear();
52 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
55 //===----------------------------------------------------------------------===//
56 // Helper functions to implement forward reference resolution, etc.
57 //===----------------------------------------------------------------------===//
59 /// ConvertToString - Convert a string from a record into an std::string, return
61 template<typename StrTy>
62 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
64 if (Idx > Record.size())
67 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
68 Result += (char)Record[i];
72 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
74 default: // Map unknown/new linkages to external
75 case 0: return GlobalValue::ExternalLinkage;
76 case 1: return GlobalValue::WeakAnyLinkage;
77 case 2: return GlobalValue::AppendingLinkage;
78 case 3: return GlobalValue::InternalLinkage;
79 case 4: return GlobalValue::LinkOnceAnyLinkage;
80 case 5: return GlobalValue::DLLImportLinkage;
81 case 6: return GlobalValue::DLLExportLinkage;
82 case 7: return GlobalValue::ExternalWeakLinkage;
83 case 8: return GlobalValue::CommonLinkage;
84 case 9: return GlobalValue::PrivateLinkage;
85 case 10: return GlobalValue::WeakODRLinkage;
86 case 11: return GlobalValue::LinkOnceODRLinkage;
87 case 12: return GlobalValue::AvailableExternallyLinkage;
88 case 13: return GlobalValue::LinkerPrivateLinkage;
89 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
90 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
94 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
96 default: // Map unknown visibilities to default.
97 case 0: return GlobalValue::DefaultVisibility;
98 case 1: return GlobalValue::HiddenVisibility;
99 case 2: return GlobalValue::ProtectedVisibility;
103 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
105 case 0: return GlobalVariable::NotThreadLocal;
106 default: // Map unknown non-zero value to general dynamic.
107 case 1: return GlobalVariable::GeneralDynamicTLSModel;
108 case 2: return GlobalVariable::LocalDynamicTLSModel;
109 case 3: return GlobalVariable::InitialExecTLSModel;
110 case 4: return GlobalVariable::LocalExecTLSModel;
114 static int GetDecodedCastOpcode(unsigned Val) {
117 case bitc::CAST_TRUNC : return Instruction::Trunc;
118 case bitc::CAST_ZEXT : return Instruction::ZExt;
119 case bitc::CAST_SEXT : return Instruction::SExt;
120 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
121 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
122 case bitc::CAST_UITOFP : return Instruction::UIToFP;
123 case bitc::CAST_SITOFP : return Instruction::SIToFP;
124 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
125 case bitc::CAST_FPEXT : return Instruction::FPExt;
126 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
127 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
128 case bitc::CAST_BITCAST : return Instruction::BitCast;
131 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
134 case bitc::BINOP_ADD:
135 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
136 case bitc::BINOP_SUB:
137 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
138 case bitc::BINOP_MUL:
139 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
140 case bitc::BINOP_UDIV: return Instruction::UDiv;
141 case bitc::BINOP_SDIV:
142 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
143 case bitc::BINOP_UREM: return Instruction::URem;
144 case bitc::BINOP_SREM:
145 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
146 case bitc::BINOP_SHL: return Instruction::Shl;
147 case bitc::BINOP_LSHR: return Instruction::LShr;
148 case bitc::BINOP_ASHR: return Instruction::AShr;
149 case bitc::BINOP_AND: return Instruction::And;
150 case bitc::BINOP_OR: return Instruction::Or;
151 case bitc::BINOP_XOR: return Instruction::Xor;
155 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
157 default: return AtomicRMWInst::BAD_BINOP;
158 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
159 case bitc::RMW_ADD: return AtomicRMWInst::Add;
160 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
161 case bitc::RMW_AND: return AtomicRMWInst::And;
162 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
163 case bitc::RMW_OR: return AtomicRMWInst::Or;
164 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
165 case bitc::RMW_MAX: return AtomicRMWInst::Max;
166 case bitc::RMW_MIN: return AtomicRMWInst::Min;
167 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
168 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
172 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
174 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
175 case bitc::ORDERING_UNORDERED: return Unordered;
176 case bitc::ORDERING_MONOTONIC: return Monotonic;
177 case bitc::ORDERING_ACQUIRE: return Acquire;
178 case bitc::ORDERING_RELEASE: return Release;
179 case bitc::ORDERING_ACQREL: return AcquireRelease;
180 default: // Map unknown orderings to sequentially-consistent.
181 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
185 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
187 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
188 default: // Map unknown scopes to cross-thread.
189 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
195 /// @brief A class for maintaining the slot number definition
196 /// as a placeholder for the actual definition for forward constants defs.
197 class ConstantPlaceHolder : public ConstantExpr {
198 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
200 // allocate space for exactly one operand
201 void *operator new(size_t s) {
202 return User::operator new(s, 1);
204 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
205 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
206 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
209 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
210 static bool classof(const Value *V) {
211 return isa<ConstantExpr>(V) &&
212 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
216 /// Provide fast operand accessors
217 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
221 // FIXME: can we inherit this from ConstantExpr?
223 struct OperandTraits<ConstantPlaceHolder> :
224 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
229 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
238 WeakVH &OldV = ValuePtrs[Idx];
244 // Handle constants and non-constants (e.g. instrs) differently for
246 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
247 ResolveConstants.push_back(std::make_pair(PHC, Idx));
250 // If there was a forward reference to this value, replace it.
251 Value *PrevVal = OldV;
252 OldV->replaceAllUsesWith(V);
258 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
263 if (Value *V = ValuePtrs[Idx]) {
264 assert(Ty == V->getType() && "Type mismatch in constant table!");
265 return cast<Constant>(V);
268 // Create and return a placeholder, which will later be RAUW'd.
269 Constant *C = new ConstantPlaceHolder(Ty, Context);
274 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
278 if (Value *V = ValuePtrs[Idx]) {
279 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
283 // No type specified, must be invalid reference.
284 if (Ty == 0) return 0;
286 // Create and return a placeholder, which will later be RAUW'd.
287 Value *V = new Argument(Ty);
292 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
293 /// resolves any forward references. The idea behind this is that we sometimes
294 /// get constants (such as large arrays) which reference *many* forward ref
295 /// constants. Replacing each of these causes a lot of thrashing when
296 /// building/reuniquing the constant. Instead of doing this, we look at all the
297 /// uses and rewrite all the place holders at once for any constant that uses
299 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
300 // Sort the values by-pointer so that they are efficient to look up with a
302 std::sort(ResolveConstants.begin(), ResolveConstants.end());
304 SmallVector<Constant*, 64> NewOps;
306 while (!ResolveConstants.empty()) {
307 Value *RealVal = operator[](ResolveConstants.back().second);
308 Constant *Placeholder = ResolveConstants.back().first;
309 ResolveConstants.pop_back();
311 // Loop over all users of the placeholder, updating them to reference the
312 // new value. If they reference more than one placeholder, update them all
314 while (!Placeholder->use_empty()) {
315 Value::use_iterator UI = Placeholder->use_begin();
318 // If the using object isn't uniqued, just update the operands. This
319 // handles instructions and initializers for global variables.
320 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
321 UI.getUse().set(RealVal);
325 // Otherwise, we have a constant that uses the placeholder. Replace that
326 // constant with a new constant that has *all* placeholder uses updated.
327 Constant *UserC = cast<Constant>(U);
328 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
331 if (!isa<ConstantPlaceHolder>(*I)) {
332 // Not a placeholder reference.
334 } else if (*I == Placeholder) {
335 // Common case is that it just references this one placeholder.
338 // Otherwise, look up the placeholder in ResolveConstants.
339 ResolveConstantsTy::iterator It =
340 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
341 std::pair<Constant*, unsigned>(cast<Constant>(*I),
343 assert(It != ResolveConstants.end() && It->first == *I);
344 NewOp = operator[](It->second);
347 NewOps.push_back(cast<Constant>(NewOp));
350 // Make the new constant.
352 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
353 NewC = ConstantArray::get(UserCA->getType(), NewOps);
354 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
355 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
356 } else if (isa<ConstantVector>(UserC)) {
357 NewC = ConstantVector::get(NewOps);
359 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
360 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
363 UserC->replaceAllUsesWith(NewC);
364 UserC->destroyConstant();
368 // Update all ValueHandles, they should be the only users at this point.
369 Placeholder->replaceAllUsesWith(RealVal);
374 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
383 WeakVH &OldV = MDValuePtrs[Idx];
389 // If there was a forward reference to this value, replace it.
390 MDNode *PrevVal = cast<MDNode>(OldV);
391 OldV->replaceAllUsesWith(V);
392 MDNode::deleteTemporary(PrevVal);
393 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
395 MDValuePtrs[Idx] = V;
398 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
402 if (Value *V = MDValuePtrs[Idx]) {
403 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
407 // Create and return a placeholder, which will later be RAUW'd.
408 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
409 MDValuePtrs[Idx] = V;
413 Type *BitcodeReader::getTypeByID(unsigned ID) {
414 // The type table size is always specified correctly.
415 if (ID >= TypeList.size())
418 if (Type *Ty = TypeList[ID])
421 // If we have a forward reference, the only possible case is when it is to a
422 // named struct. Just create a placeholder for now.
423 return TypeList[ID] = StructType::create(Context);
427 //===----------------------------------------------------------------------===//
428 // Functions for parsing blocks from the bitcode file
429 //===----------------------------------------------------------------------===//
432 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
433 /// been decoded from the given integer. This function must stay in sync with
434 /// 'encodeLLVMAttributesForBitcode'.
435 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
436 uint64_t EncodedAttrs) {
437 // FIXME: Remove in 4.0.
439 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
440 // the bits above 31 down by 11 bits.
441 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
442 assert((!Alignment || isPowerOf2_32(Alignment)) &&
443 "Alignment must be a power of two.");
446 B.addAlignmentAttr(Alignment);
447 B.addRawValue(((EncodedAttrs & (0xffffULL << 32)) >> 11) |
448 (EncodedAttrs & 0xffff));
451 bool BitcodeReader::ParseAttributeBlock() {
452 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
453 return Error("Malformed block record");
455 if (!MAttributes.empty())
456 return Error("Multiple PARAMATTR blocks found!");
458 SmallVector<uint64_t, 64> Record;
460 SmallVector<AttributeSet, 8> Attrs;
462 // Read all the records.
464 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
466 switch (Entry.Kind) {
467 case BitstreamEntry::SubBlock: // Handled for us already.
468 case BitstreamEntry::Error:
469 return Error("Error at end of PARAMATTR block");
470 case BitstreamEntry::EndBlock:
472 case BitstreamEntry::Record:
473 // The interesting case.
479 switch (Stream.readRecord(Entry.ID, Record)) {
480 default: // Default behavior: ignore.
482 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
483 // FIXME: Remove in 4.0.
484 if (Record.size() & 1)
485 return Error("Invalid ENTRY record");
487 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
489 decodeLLVMAttributesForBitcode(B, Record[i+1]);
490 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
493 MAttributes.push_back(AttributeSet::get(Context, Attrs));
501 bool BitcodeReader::ParseAttributeGroupBlock() {
502 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
503 return Error("Malformed block record");
505 if (!MAttributeGroups.empty())
506 return Error("Multiple PARAMATTR_GROUP blocks found!");
508 SmallVector<uint64_t, 64> Record;
510 // Read all the records.
512 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
514 switch (Entry.Kind) {
515 case BitstreamEntry::SubBlock: // Handled for us already.
516 case BitstreamEntry::Error:
517 return Error("Error at end of PARAMATTR_GROUP block");
518 case BitstreamEntry::EndBlock:
520 case BitstreamEntry::Record:
521 // The interesting case.
527 switch (Stream.readRecord(Entry.ID, Record)) {
528 default: // Default behavior: ignore.
530 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
531 if (Record.size() < 3)
532 return Error("Invalid ENTRY record");
534 // FIXME: Record[0] is the 'group ID'. What should we do with it here?
536 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
539 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
540 if (Record[i] == 0) { // Enum attribute
541 B.addAttribute(Attribute::AttrKind(Record[++i]));
542 } else if (Record[i] == 1) { // Align attribute
543 if (Attribute::AttrKind(Record[++i]) == Attribute::Alignment)
544 B.addAlignmentAttr(Record[++i]);
546 B.addStackAlignmentAttr(Record[++i]);
547 } else { // String attribute
548 bool HasValue = (Record[i++] == 4);
549 SmallString<64> KindStr;
550 SmallString<64> ValStr;
552 while (Record[i] != 0 && i != e)
553 KindStr += Record[i++];
554 assert(Record[i] == 0 && "Kind string not terminated with 0");
557 // Has a value associated with it.
558 ++i; // Skip the '0' that terminates the kind string.
559 while (Record[i] != 0 && i != e)
560 ValStr += Record[i++];
561 assert(Record[i] == 0 && "Value string not terminated with 0");
564 B.addAttribute(KindStr.str(), ValStr.str());
568 MAttributeGroups.push_back(AttributeSet::get(Context, Idx, B));
575 bool BitcodeReader::ParseTypeTable() {
576 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
577 return Error("Malformed block record");
579 return ParseTypeTableBody();
582 bool BitcodeReader::ParseTypeTableBody() {
583 if (!TypeList.empty())
584 return Error("Multiple TYPE_BLOCKs found!");
586 SmallVector<uint64_t, 64> Record;
587 unsigned NumRecords = 0;
589 SmallString<64> TypeName;
591 // Read all the records for this type table.
593 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
595 switch (Entry.Kind) {
596 case BitstreamEntry::SubBlock: // Handled for us already.
597 case BitstreamEntry::Error:
598 Error("Error in the type table block");
600 case BitstreamEntry::EndBlock:
601 if (NumRecords != TypeList.size())
602 return Error("Invalid type forward reference in TYPE_BLOCK");
604 case BitstreamEntry::Record:
605 // The interesting case.
612 switch (Stream.readRecord(Entry.ID, Record)) {
613 default: return Error("unknown type in type table");
614 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
615 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
616 // type list. This allows us to reserve space.
617 if (Record.size() < 1)
618 return Error("Invalid TYPE_CODE_NUMENTRY record");
619 TypeList.resize(Record[0]);
621 case bitc::TYPE_CODE_VOID: // VOID
622 ResultTy = Type::getVoidTy(Context);
624 case bitc::TYPE_CODE_HALF: // HALF
625 ResultTy = Type::getHalfTy(Context);
627 case bitc::TYPE_CODE_FLOAT: // FLOAT
628 ResultTy = Type::getFloatTy(Context);
630 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
631 ResultTy = Type::getDoubleTy(Context);
633 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
634 ResultTy = Type::getX86_FP80Ty(Context);
636 case bitc::TYPE_CODE_FP128: // FP128
637 ResultTy = Type::getFP128Ty(Context);
639 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
640 ResultTy = Type::getPPC_FP128Ty(Context);
642 case bitc::TYPE_CODE_LABEL: // LABEL
643 ResultTy = Type::getLabelTy(Context);
645 case bitc::TYPE_CODE_METADATA: // METADATA
646 ResultTy = Type::getMetadataTy(Context);
648 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
649 ResultTy = Type::getX86_MMXTy(Context);
651 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
652 if (Record.size() < 1)
653 return Error("Invalid Integer type record");
655 ResultTy = IntegerType::get(Context, Record[0]);
657 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
658 // [pointee type, address space]
659 if (Record.size() < 1)
660 return Error("Invalid POINTER type record");
661 unsigned AddressSpace = 0;
662 if (Record.size() == 2)
663 AddressSpace = Record[1];
664 ResultTy = getTypeByID(Record[0]);
665 if (ResultTy == 0) return Error("invalid element type in pointer type");
666 ResultTy = PointerType::get(ResultTy, AddressSpace);
669 case bitc::TYPE_CODE_FUNCTION_OLD: {
670 // FIXME: attrid is dead, remove it in LLVM 4.0
671 // FUNCTION: [vararg, attrid, retty, paramty x N]
672 if (Record.size() < 3)
673 return Error("Invalid FUNCTION type record");
674 SmallVector<Type*, 8> ArgTys;
675 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
676 if (Type *T = getTypeByID(Record[i]))
682 ResultTy = getTypeByID(Record[2]);
683 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
684 return Error("invalid type in function type");
686 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
689 case bitc::TYPE_CODE_FUNCTION: {
690 // FUNCTION: [vararg, retty, paramty x N]
691 if (Record.size() < 2)
692 return Error("Invalid FUNCTION type record");
693 SmallVector<Type*, 8> ArgTys;
694 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
695 if (Type *T = getTypeByID(Record[i]))
701 ResultTy = getTypeByID(Record[1]);
702 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
703 return Error("invalid type in function type");
705 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
708 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
709 if (Record.size() < 1)
710 return Error("Invalid STRUCT type record");
711 SmallVector<Type*, 8> EltTys;
712 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
713 if (Type *T = getTypeByID(Record[i]))
718 if (EltTys.size() != Record.size()-1)
719 return Error("invalid type in struct type");
720 ResultTy = StructType::get(Context, EltTys, Record[0]);
723 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
724 if (ConvertToString(Record, 0, TypeName))
725 return Error("Invalid STRUCT_NAME record");
728 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
729 if (Record.size() < 1)
730 return Error("Invalid STRUCT type record");
732 if (NumRecords >= TypeList.size())
733 return Error("invalid TYPE table");
735 // Check to see if this was forward referenced, if so fill in the temp.
736 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
738 Res->setName(TypeName);
739 TypeList[NumRecords] = 0;
740 } else // Otherwise, create a new struct.
741 Res = StructType::create(Context, TypeName);
744 SmallVector<Type*, 8> EltTys;
745 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
746 if (Type *T = getTypeByID(Record[i]))
751 if (EltTys.size() != Record.size()-1)
752 return Error("invalid STRUCT type record");
753 Res->setBody(EltTys, Record[0]);
757 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
758 if (Record.size() != 1)
759 return Error("Invalid OPAQUE type record");
761 if (NumRecords >= TypeList.size())
762 return Error("invalid TYPE table");
764 // Check to see if this was forward referenced, if so fill in the temp.
765 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
767 Res->setName(TypeName);
768 TypeList[NumRecords] = 0;
769 } else // Otherwise, create a new struct with no body.
770 Res = StructType::create(Context, TypeName);
775 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
776 if (Record.size() < 2)
777 return Error("Invalid ARRAY type record");
778 if ((ResultTy = getTypeByID(Record[1])))
779 ResultTy = ArrayType::get(ResultTy, Record[0]);
781 return Error("Invalid ARRAY type element");
783 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
784 if (Record.size() < 2)
785 return Error("Invalid VECTOR type record");
786 if ((ResultTy = getTypeByID(Record[1])))
787 ResultTy = VectorType::get(ResultTy, Record[0]);
789 return Error("Invalid ARRAY type element");
793 if (NumRecords >= TypeList.size())
794 return Error("invalid TYPE table");
795 assert(ResultTy && "Didn't read a type?");
796 assert(TypeList[NumRecords] == 0 && "Already read type?");
797 TypeList[NumRecords++] = ResultTy;
801 bool BitcodeReader::ParseValueSymbolTable() {
802 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
803 return Error("Malformed block record");
805 SmallVector<uint64_t, 64> Record;
807 // Read all the records for this value table.
808 SmallString<128> ValueName;
810 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
812 switch (Entry.Kind) {
813 case BitstreamEntry::SubBlock: // Handled for us already.
814 case BitstreamEntry::Error:
815 return Error("malformed value symbol table block");
816 case BitstreamEntry::EndBlock:
818 case BitstreamEntry::Record:
819 // The interesting case.
825 switch (Stream.readRecord(Entry.ID, Record)) {
826 default: // Default behavior: unknown type.
828 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
829 if (ConvertToString(Record, 1, ValueName))
830 return Error("Invalid VST_ENTRY record");
831 unsigned ValueID = Record[0];
832 if (ValueID >= ValueList.size())
833 return Error("Invalid Value ID in VST_ENTRY record");
834 Value *V = ValueList[ValueID];
836 V->setName(StringRef(ValueName.data(), ValueName.size()));
840 case bitc::VST_CODE_BBENTRY: {
841 if (ConvertToString(Record, 1, ValueName))
842 return Error("Invalid VST_BBENTRY record");
843 BasicBlock *BB = getBasicBlock(Record[0]);
845 return Error("Invalid BB ID in VST_BBENTRY record");
847 BB->setName(StringRef(ValueName.data(), ValueName.size()));
855 bool BitcodeReader::ParseMetadata() {
856 unsigned NextMDValueNo = MDValueList.size();
858 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
859 return Error("Malformed block record");
861 SmallVector<uint64_t, 64> Record;
863 // Read all the records.
865 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
867 switch (Entry.Kind) {
868 case BitstreamEntry::SubBlock: // Handled for us already.
869 case BitstreamEntry::Error:
870 Error("malformed metadata block");
872 case BitstreamEntry::EndBlock:
874 case BitstreamEntry::Record:
875 // The interesting case.
879 bool IsFunctionLocal = false;
882 unsigned Code = Stream.readRecord(Entry.ID, Record);
884 default: // Default behavior: ignore.
886 case bitc::METADATA_NAME: {
887 // Read name of the named metadata.
888 SmallString<8> Name(Record.begin(), Record.end());
890 Code = Stream.ReadCode();
892 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
893 unsigned NextBitCode = Stream.readRecord(Code, Record);
894 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
896 // Read named metadata elements.
897 unsigned Size = Record.size();
898 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
899 for (unsigned i = 0; i != Size; ++i) {
900 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
902 return Error("Malformed metadata record");
907 case bitc::METADATA_FN_NODE:
908 IsFunctionLocal = true;
910 case bitc::METADATA_NODE: {
911 if (Record.size() % 2 == 1)
912 return Error("Invalid METADATA_NODE record");
914 unsigned Size = Record.size();
915 SmallVector<Value*, 8> Elts;
916 for (unsigned i = 0; i != Size; i += 2) {
917 Type *Ty = getTypeByID(Record[i]);
918 if (!Ty) return Error("Invalid METADATA_NODE record");
919 if (Ty->isMetadataTy())
920 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
921 else if (!Ty->isVoidTy())
922 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
924 Elts.push_back(NULL);
926 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
927 IsFunctionLocal = false;
928 MDValueList.AssignValue(V, NextMDValueNo++);
931 case bitc::METADATA_STRING: {
932 SmallString<8> String(Record.begin(), Record.end());
933 Value *V = MDString::get(Context, String);
934 MDValueList.AssignValue(V, NextMDValueNo++);
937 case bitc::METADATA_KIND: {
938 if (Record.size() < 2)
939 return Error("Invalid METADATA_KIND record");
941 unsigned Kind = Record[0];
942 SmallString<8> Name(Record.begin()+1, Record.end());
944 unsigned NewKind = TheModule->getMDKindID(Name.str());
945 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
946 return Error("Conflicting METADATA_KIND records");
953 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
954 /// the LSB for dense VBR encoding.
955 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
960 // There is no such thing as -0 with integers. "-0" really means MININT.
964 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
965 /// values and aliases that we can.
966 bool BitcodeReader::ResolveGlobalAndAliasInits() {
967 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
968 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
970 GlobalInitWorklist.swap(GlobalInits);
971 AliasInitWorklist.swap(AliasInits);
973 while (!GlobalInitWorklist.empty()) {
974 unsigned ValID = GlobalInitWorklist.back().second;
975 if (ValID >= ValueList.size()) {
976 // Not ready to resolve this yet, it requires something later in the file.
977 GlobalInits.push_back(GlobalInitWorklist.back());
979 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
980 GlobalInitWorklist.back().first->setInitializer(C);
982 return Error("Global variable initializer is not a constant!");
984 GlobalInitWorklist.pop_back();
987 while (!AliasInitWorklist.empty()) {
988 unsigned ValID = AliasInitWorklist.back().second;
989 if (ValID >= ValueList.size()) {
990 AliasInits.push_back(AliasInitWorklist.back());
992 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
993 AliasInitWorklist.back().first->setAliasee(C);
995 return Error("Alias initializer is not a constant!");
997 AliasInitWorklist.pop_back();
1002 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1003 SmallVector<uint64_t, 8> Words(Vals.size());
1004 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1005 BitcodeReader::decodeSignRotatedValue);
1007 return APInt(TypeBits, Words);
1010 bool BitcodeReader::ParseConstants() {
1011 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1012 return Error("Malformed block record");
1014 SmallVector<uint64_t, 64> Record;
1016 // Read all the records for this value table.
1017 Type *CurTy = Type::getInt32Ty(Context);
1018 unsigned NextCstNo = ValueList.size();
1020 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1022 switch (Entry.Kind) {
1023 case BitstreamEntry::SubBlock: // Handled for us already.
1024 case BitstreamEntry::Error:
1025 return Error("malformed block record in AST file");
1026 case BitstreamEntry::EndBlock:
1027 if (NextCstNo != ValueList.size())
1028 return Error("Invalid constant reference!");
1030 // Once all the constants have been read, go through and resolve forward
1032 ValueList.ResolveConstantForwardRefs();
1034 case BitstreamEntry::Record:
1035 // The interesting case.
1042 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1044 default: // Default behavior: unknown constant
1045 case bitc::CST_CODE_UNDEF: // UNDEF
1046 V = UndefValue::get(CurTy);
1048 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1050 return Error("Malformed CST_SETTYPE record");
1051 if (Record[0] >= TypeList.size())
1052 return Error("Invalid Type ID in CST_SETTYPE record");
1053 CurTy = TypeList[Record[0]];
1054 continue; // Skip the ValueList manipulation.
1055 case bitc::CST_CODE_NULL: // NULL
1056 V = Constant::getNullValue(CurTy);
1058 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1059 if (!CurTy->isIntegerTy() || Record.empty())
1060 return Error("Invalid CST_INTEGER record");
1061 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1063 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1064 if (!CurTy->isIntegerTy() || Record.empty())
1065 return Error("Invalid WIDE_INTEGER record");
1067 APInt VInt = ReadWideAPInt(Record,
1068 cast<IntegerType>(CurTy)->getBitWidth());
1069 V = ConstantInt::get(Context, VInt);
1073 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1075 return Error("Invalid FLOAT record");
1076 if (CurTy->isHalfTy())
1077 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1078 APInt(16, (uint16_t)Record[0])));
1079 else if (CurTy->isFloatTy())
1080 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1081 APInt(32, (uint32_t)Record[0])));
1082 else if (CurTy->isDoubleTy())
1083 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1084 APInt(64, Record[0])));
1085 else if (CurTy->isX86_FP80Ty()) {
1086 // Bits are not stored the same way as a normal i80 APInt, compensate.
1087 uint64_t Rearrange[2];
1088 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1089 Rearrange[1] = Record[0] >> 48;
1090 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1091 APInt(80, Rearrange)));
1092 } else if (CurTy->isFP128Ty())
1093 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1094 APInt(128, Record)));
1095 else if (CurTy->isPPC_FP128Ty())
1096 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1097 APInt(128, Record)));
1099 V = UndefValue::get(CurTy);
1103 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1105 return Error("Invalid CST_AGGREGATE record");
1107 unsigned Size = Record.size();
1108 SmallVector<Constant*, 16> Elts;
1110 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1111 for (unsigned i = 0; i != Size; ++i)
1112 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1113 STy->getElementType(i)));
1114 V = ConstantStruct::get(STy, Elts);
1115 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1116 Type *EltTy = ATy->getElementType();
1117 for (unsigned i = 0; i != Size; ++i)
1118 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1119 V = ConstantArray::get(ATy, Elts);
1120 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1121 Type *EltTy = VTy->getElementType();
1122 for (unsigned i = 0; i != Size; ++i)
1123 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1124 V = ConstantVector::get(Elts);
1126 V = UndefValue::get(CurTy);
1130 case bitc::CST_CODE_STRING: // STRING: [values]
1131 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1133 return Error("Invalid CST_STRING record");
1135 SmallString<16> Elts(Record.begin(), Record.end());
1136 V = ConstantDataArray::getString(Context, Elts,
1137 BitCode == bitc::CST_CODE_CSTRING);
1140 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1142 return Error("Invalid CST_DATA record");
1144 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1145 unsigned Size = Record.size();
1147 if (EltTy->isIntegerTy(8)) {
1148 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1149 if (isa<VectorType>(CurTy))
1150 V = ConstantDataVector::get(Context, Elts);
1152 V = ConstantDataArray::get(Context, Elts);
1153 } else if (EltTy->isIntegerTy(16)) {
1154 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1155 if (isa<VectorType>(CurTy))
1156 V = ConstantDataVector::get(Context, Elts);
1158 V = ConstantDataArray::get(Context, Elts);
1159 } else if (EltTy->isIntegerTy(32)) {
1160 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1161 if (isa<VectorType>(CurTy))
1162 V = ConstantDataVector::get(Context, Elts);
1164 V = ConstantDataArray::get(Context, Elts);
1165 } else if (EltTy->isIntegerTy(64)) {
1166 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1167 if (isa<VectorType>(CurTy))
1168 V = ConstantDataVector::get(Context, Elts);
1170 V = ConstantDataArray::get(Context, Elts);
1171 } else if (EltTy->isFloatTy()) {
1172 SmallVector<float, 16> Elts(Size);
1173 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1174 if (isa<VectorType>(CurTy))
1175 V = ConstantDataVector::get(Context, Elts);
1177 V = ConstantDataArray::get(Context, Elts);
1178 } else if (EltTy->isDoubleTy()) {
1179 SmallVector<double, 16> Elts(Size);
1180 std::transform(Record.begin(), Record.end(), Elts.begin(),
1182 if (isa<VectorType>(CurTy))
1183 V = ConstantDataVector::get(Context, Elts);
1185 V = ConstantDataArray::get(Context, Elts);
1187 return Error("Unknown element type in CE_DATA");
1192 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1193 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1194 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1196 V = UndefValue::get(CurTy); // Unknown binop.
1198 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1199 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1201 if (Record.size() >= 4) {
1202 if (Opc == Instruction::Add ||
1203 Opc == Instruction::Sub ||
1204 Opc == Instruction::Mul ||
1205 Opc == Instruction::Shl) {
1206 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1207 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1208 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1209 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1210 } else if (Opc == Instruction::SDiv ||
1211 Opc == Instruction::UDiv ||
1212 Opc == Instruction::LShr ||
1213 Opc == Instruction::AShr) {
1214 if (Record[3] & (1 << bitc::PEO_EXACT))
1215 Flags |= SDivOperator::IsExact;
1218 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1222 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1223 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1224 int Opc = GetDecodedCastOpcode(Record[0]);
1226 V = UndefValue::get(CurTy); // Unknown cast.
1228 Type *OpTy = getTypeByID(Record[1]);
1229 if (!OpTy) return Error("Invalid CE_CAST record");
1230 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1231 V = ConstantExpr::getCast(Opc, Op, CurTy);
1235 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1236 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1237 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1238 SmallVector<Constant*, 16> Elts;
1239 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1240 Type *ElTy = getTypeByID(Record[i]);
1241 if (!ElTy) return Error("Invalid CE_GEP record");
1242 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1244 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1245 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1247 bitc::CST_CODE_CE_INBOUNDS_GEP);
1250 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1251 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1252 V = ConstantExpr::getSelect(
1253 ValueList.getConstantFwdRef(Record[0],
1254 Type::getInt1Ty(Context)),
1255 ValueList.getConstantFwdRef(Record[1],CurTy),
1256 ValueList.getConstantFwdRef(Record[2],CurTy));
1258 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1259 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1261 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1262 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1263 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1264 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1265 Type::getInt32Ty(Context));
1266 V = ConstantExpr::getExtractElement(Op0, Op1);
1269 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1270 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1271 if (Record.size() < 3 || OpTy == 0)
1272 return Error("Invalid CE_INSERTELT record");
1273 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1274 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1275 OpTy->getElementType());
1276 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1277 Type::getInt32Ty(Context));
1278 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1281 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1282 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1283 if (Record.size() < 3 || OpTy == 0)
1284 return Error("Invalid CE_SHUFFLEVEC record");
1285 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1286 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1287 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1288 OpTy->getNumElements());
1289 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1290 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1293 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1294 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1296 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1297 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1298 return Error("Invalid CE_SHUFVEC_EX record");
1299 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1300 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1301 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1302 RTy->getNumElements());
1303 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1304 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1307 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1308 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1309 Type *OpTy = getTypeByID(Record[0]);
1310 if (OpTy == 0) return Error("Invalid CE_CMP record");
1311 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1312 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1314 if (OpTy->isFPOrFPVectorTy())
1315 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1317 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1320 // This maintains backward compatibility, pre-asm dialect keywords.
1321 // FIXME: Remove with the 4.0 release.
1322 case bitc::CST_CODE_INLINEASM_OLD: {
1323 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1324 std::string AsmStr, ConstrStr;
1325 bool HasSideEffects = Record[0] & 1;
1326 bool IsAlignStack = Record[0] >> 1;
1327 unsigned AsmStrSize = Record[1];
1328 if (2+AsmStrSize >= Record.size())
1329 return Error("Invalid INLINEASM record");
1330 unsigned ConstStrSize = Record[2+AsmStrSize];
1331 if (3+AsmStrSize+ConstStrSize > Record.size())
1332 return Error("Invalid INLINEASM record");
1334 for (unsigned i = 0; i != AsmStrSize; ++i)
1335 AsmStr += (char)Record[2+i];
1336 for (unsigned i = 0; i != ConstStrSize; ++i)
1337 ConstrStr += (char)Record[3+AsmStrSize+i];
1338 PointerType *PTy = cast<PointerType>(CurTy);
1339 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1340 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1343 // This version adds support for the asm dialect keywords (e.g.,
1345 case bitc::CST_CODE_INLINEASM: {
1346 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1347 std::string AsmStr, ConstrStr;
1348 bool HasSideEffects = Record[0] & 1;
1349 bool IsAlignStack = (Record[0] >> 1) & 1;
1350 unsigned AsmDialect = Record[0] >> 2;
1351 unsigned AsmStrSize = Record[1];
1352 if (2+AsmStrSize >= Record.size())
1353 return Error("Invalid INLINEASM record");
1354 unsigned ConstStrSize = Record[2+AsmStrSize];
1355 if (3+AsmStrSize+ConstStrSize > Record.size())
1356 return Error("Invalid INLINEASM record");
1358 for (unsigned i = 0; i != AsmStrSize; ++i)
1359 AsmStr += (char)Record[2+i];
1360 for (unsigned i = 0; i != ConstStrSize; ++i)
1361 ConstrStr += (char)Record[3+AsmStrSize+i];
1362 PointerType *PTy = cast<PointerType>(CurTy);
1363 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1364 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1365 InlineAsm::AsmDialect(AsmDialect));
1368 case bitc::CST_CODE_BLOCKADDRESS:{
1369 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1370 Type *FnTy = getTypeByID(Record[0]);
1371 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1373 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1374 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1376 // If the function is already parsed we can insert the block address right
1379 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1380 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1382 return Error("Invalid blockaddress block #");
1385 V = BlockAddress::get(Fn, BBI);
1387 // Otherwise insert a placeholder and remember it so it can be inserted
1388 // when the function is parsed.
1389 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1390 Type::getInt8Ty(Context),
1391 false, GlobalValue::InternalLinkage,
1393 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1400 ValueList.AssignValue(V, NextCstNo);
1405 bool BitcodeReader::ParseUseLists() {
1406 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1407 return Error("Malformed block record");
1409 SmallVector<uint64_t, 64> Record;
1411 // Read all the records.
1413 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1415 switch (Entry.Kind) {
1416 case BitstreamEntry::SubBlock: // Handled for us already.
1417 case BitstreamEntry::Error:
1418 return Error("malformed use list block");
1419 case BitstreamEntry::EndBlock:
1421 case BitstreamEntry::Record:
1422 // The interesting case.
1426 // Read a use list record.
1428 switch (Stream.readRecord(Entry.ID, Record)) {
1429 default: // Default behavior: unknown type.
1431 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1432 unsigned RecordLength = Record.size();
1433 if (RecordLength < 1)
1434 return Error ("Invalid UseList reader!");
1435 UseListRecords.push_back(Record);
1442 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1443 /// remember where it is and then skip it. This lets us lazily deserialize the
1445 bool BitcodeReader::RememberAndSkipFunctionBody() {
1446 // Get the function we are talking about.
1447 if (FunctionsWithBodies.empty())
1448 return Error("Insufficient function protos");
1450 Function *Fn = FunctionsWithBodies.back();
1451 FunctionsWithBodies.pop_back();
1453 // Save the current stream state.
1454 uint64_t CurBit = Stream.GetCurrentBitNo();
1455 DeferredFunctionInfo[Fn] = CurBit;
1457 // Skip over the function block for now.
1458 if (Stream.SkipBlock())
1459 return Error("Malformed block record");
1463 bool BitcodeReader::GlobalCleanup() {
1464 // Patch the initializers for globals and aliases up.
1465 ResolveGlobalAndAliasInits();
1466 if (!GlobalInits.empty() || !AliasInits.empty())
1467 return Error("Malformed global initializer set");
1469 // Look for intrinsic functions which need to be upgraded at some point
1470 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1473 if (UpgradeIntrinsicFunction(FI, NewFn))
1474 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1477 // Look for global variables which need to be renamed.
1478 for (Module::global_iterator
1479 GI = TheModule->global_begin(), GE = TheModule->global_end();
1481 UpgradeGlobalVariable(GI);
1482 // Force deallocation of memory for these vectors to favor the client that
1483 // want lazy deserialization.
1484 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1485 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1489 bool BitcodeReader::ParseModule(bool Resume) {
1491 Stream.JumpToBit(NextUnreadBit);
1492 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1493 return Error("Malformed block record");
1495 SmallVector<uint64_t, 64> Record;
1496 std::vector<std::string> SectionTable;
1497 std::vector<std::string> GCTable;
1499 // Read all the records for this module.
1501 BitstreamEntry Entry = Stream.advance();
1503 switch (Entry.Kind) {
1504 case BitstreamEntry::Error:
1505 Error("malformed module block");
1507 case BitstreamEntry::EndBlock:
1508 return GlobalCleanup();
1510 case BitstreamEntry::SubBlock:
1512 default: // Skip unknown content.
1513 if (Stream.SkipBlock())
1514 return Error("Malformed block record");
1516 case bitc::BLOCKINFO_BLOCK_ID:
1517 if (Stream.ReadBlockInfoBlock())
1518 return Error("Malformed BlockInfoBlock");
1520 case bitc::PARAMATTR_BLOCK_ID:
1521 if (ParseAttributeBlock())
1524 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1525 if (ParseAttributeGroupBlock())
1528 case bitc::TYPE_BLOCK_ID_NEW:
1529 if (ParseTypeTable())
1532 case bitc::VALUE_SYMTAB_BLOCK_ID:
1533 if (ParseValueSymbolTable())
1535 SeenValueSymbolTable = true;
1537 case bitc::CONSTANTS_BLOCK_ID:
1538 if (ParseConstants() || ResolveGlobalAndAliasInits())
1541 case bitc::METADATA_BLOCK_ID:
1542 if (ParseMetadata())
1545 case bitc::FUNCTION_BLOCK_ID:
1546 // If this is the first function body we've seen, reverse the
1547 // FunctionsWithBodies list.
1548 if (!SeenFirstFunctionBody) {
1549 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1550 if (GlobalCleanup())
1552 SeenFirstFunctionBody = true;
1555 if (RememberAndSkipFunctionBody())
1557 // For streaming bitcode, suspend parsing when we reach the function
1558 // bodies. Subsequent materialization calls will resume it when
1559 // necessary. For streaming, the function bodies must be at the end of
1560 // the bitcode. If the bitcode file is old, the symbol table will be
1561 // at the end instead and will not have been seen yet. In this case,
1562 // just finish the parse now.
1563 if (LazyStreamer && SeenValueSymbolTable) {
1564 NextUnreadBit = Stream.GetCurrentBitNo();
1568 case bitc::USELIST_BLOCK_ID:
1569 if (ParseUseLists())
1575 case BitstreamEntry::Record:
1576 // The interesting case.
1582 switch (Stream.readRecord(Entry.ID, Record)) {
1583 default: break; // Default behavior, ignore unknown content.
1584 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1585 if (Record.size() < 1)
1586 return Error("Malformed MODULE_CODE_VERSION");
1587 // Only version #0 and #1 are supported so far.
1588 unsigned module_version = Record[0];
1589 switch (module_version) {
1590 default: return Error("Unknown bitstream version!");
1592 UseRelativeIDs = false;
1595 UseRelativeIDs = true;
1600 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1602 if (ConvertToString(Record, 0, S))
1603 return Error("Invalid MODULE_CODE_TRIPLE record");
1604 TheModule->setTargetTriple(S);
1607 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1609 if (ConvertToString(Record, 0, S))
1610 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1611 TheModule->setDataLayout(S);
1614 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1616 if (ConvertToString(Record, 0, S))
1617 return Error("Invalid MODULE_CODE_ASM record");
1618 TheModule->setModuleInlineAsm(S);
1621 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1622 // FIXME: Remove in 4.0.
1624 if (ConvertToString(Record, 0, S))
1625 return Error("Invalid MODULE_CODE_DEPLIB record");
1629 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1631 if (ConvertToString(Record, 0, S))
1632 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1633 SectionTable.push_back(S);
1636 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1638 if (ConvertToString(Record, 0, S))
1639 return Error("Invalid MODULE_CODE_GCNAME record");
1640 GCTable.push_back(S);
1643 // GLOBALVAR: [pointer type, isconst, initid,
1644 // linkage, alignment, section, visibility, threadlocal,
1646 case bitc::MODULE_CODE_GLOBALVAR: {
1647 if (Record.size() < 6)
1648 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1649 Type *Ty = getTypeByID(Record[0]);
1650 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1651 if (!Ty->isPointerTy())
1652 return Error("Global not a pointer type!");
1653 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1654 Ty = cast<PointerType>(Ty)->getElementType();
1656 bool isConstant = Record[1];
1657 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1658 unsigned Alignment = (1 << Record[4]) >> 1;
1659 std::string Section;
1661 if (Record[5]-1 >= SectionTable.size())
1662 return Error("Invalid section ID");
1663 Section = SectionTable[Record[5]-1];
1665 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1666 if (Record.size() > 6)
1667 Visibility = GetDecodedVisibility(Record[6]);
1669 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1670 if (Record.size() > 7)
1671 TLM = GetDecodedThreadLocalMode(Record[7]);
1673 bool UnnamedAddr = false;
1674 if (Record.size() > 8)
1675 UnnamedAddr = Record[8];
1677 bool ExternallyInitialized = false;
1678 if (Record.size() > 9)
1679 ExternallyInitialized = Record[9];
1681 GlobalVariable *NewGV =
1682 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1683 TLM, AddressSpace, ExternallyInitialized);
1684 NewGV->setAlignment(Alignment);
1685 if (!Section.empty())
1686 NewGV->setSection(Section);
1687 NewGV->setVisibility(Visibility);
1688 NewGV->setUnnamedAddr(UnnamedAddr);
1690 ValueList.push_back(NewGV);
1692 // Remember which value to use for the global initializer.
1693 if (unsigned InitID = Record[2])
1694 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1697 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1698 // alignment, section, visibility, gc, unnamed_addr]
1699 case bitc::MODULE_CODE_FUNCTION: {
1700 if (Record.size() < 8)
1701 return Error("Invalid MODULE_CODE_FUNCTION record");
1702 Type *Ty = getTypeByID(Record[0]);
1703 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1704 if (!Ty->isPointerTy())
1705 return Error("Function not a pointer type!");
1707 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1709 return Error("Function not a pointer to function type!");
1711 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1714 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1715 bool isProto = Record[2];
1716 Func->setLinkage(GetDecodedLinkage(Record[3]));
1717 Func->setAttributes(getAttributes(Record[4]));
1719 Func->setAlignment((1 << Record[5]) >> 1);
1721 if (Record[6]-1 >= SectionTable.size())
1722 return Error("Invalid section ID");
1723 Func->setSection(SectionTable[Record[6]-1]);
1725 Func->setVisibility(GetDecodedVisibility(Record[7]));
1726 if (Record.size() > 8 && Record[8]) {
1727 if (Record[8]-1 > GCTable.size())
1728 return Error("Invalid GC ID");
1729 Func->setGC(GCTable[Record[8]-1].c_str());
1731 bool UnnamedAddr = false;
1732 if (Record.size() > 9)
1733 UnnamedAddr = Record[9];
1734 Func->setUnnamedAddr(UnnamedAddr);
1735 ValueList.push_back(Func);
1737 // If this is a function with a body, remember the prototype we are
1738 // creating now, so that we can match up the body with them later.
1740 FunctionsWithBodies.push_back(Func);
1741 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1745 // ALIAS: [alias type, aliasee val#, linkage]
1746 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1747 case bitc::MODULE_CODE_ALIAS: {
1748 if (Record.size() < 3)
1749 return Error("Invalid MODULE_ALIAS record");
1750 Type *Ty = getTypeByID(Record[0]);
1751 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1752 if (!Ty->isPointerTy())
1753 return Error("Function not a pointer type!");
1755 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1757 // Old bitcode files didn't have visibility field.
1758 if (Record.size() > 3)
1759 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1760 ValueList.push_back(NewGA);
1761 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1764 /// MODULE_CODE_PURGEVALS: [numvals]
1765 case bitc::MODULE_CODE_PURGEVALS:
1766 // Trim down the value list to the specified size.
1767 if (Record.size() < 1 || Record[0] > ValueList.size())
1768 return Error("Invalid MODULE_PURGEVALS record");
1769 ValueList.shrinkTo(Record[0]);
1776 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1779 if (InitStream()) return true;
1781 // Sniff for the signature.
1782 if (Stream.Read(8) != 'B' ||
1783 Stream.Read(8) != 'C' ||
1784 Stream.Read(4) != 0x0 ||
1785 Stream.Read(4) != 0xC ||
1786 Stream.Read(4) != 0xE ||
1787 Stream.Read(4) != 0xD)
1788 return Error("Invalid bitcode signature");
1790 // We expect a number of well-defined blocks, though we don't necessarily
1791 // need to understand them all.
1793 if (Stream.AtEndOfStream())
1796 BitstreamEntry Entry =
1797 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1799 switch (Entry.Kind) {
1800 case BitstreamEntry::Error:
1801 Error("malformed module file");
1803 case BitstreamEntry::EndBlock:
1806 case BitstreamEntry::SubBlock:
1808 case bitc::BLOCKINFO_BLOCK_ID:
1809 if (Stream.ReadBlockInfoBlock())
1810 return Error("Malformed BlockInfoBlock");
1812 case bitc::MODULE_BLOCK_ID:
1813 // Reject multiple MODULE_BLOCK's in a single bitstream.
1815 return Error("Multiple MODULE_BLOCKs in same stream");
1817 if (ParseModule(false))
1819 if (LazyStreamer) return false;
1822 if (Stream.SkipBlock())
1823 return Error("Malformed block record");
1827 case BitstreamEntry::Record:
1828 // There should be no records in the top-level of blocks.
1830 // The ranlib in Xcode 4 will align archive members by appending newlines
1831 // to the end of them. If this file size is a multiple of 4 but not 8, we
1832 // have to read and ignore these final 4 bytes :-(
1833 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1834 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1835 Stream.AtEndOfStream())
1838 return Error("Invalid record at top-level");
1843 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1844 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1845 return Error("Malformed block record");
1847 SmallVector<uint64_t, 64> Record;
1849 // Read all the records for this module.
1851 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1853 switch (Entry.Kind) {
1854 case BitstreamEntry::SubBlock: // Handled for us already.
1855 case BitstreamEntry::Error:
1856 return Error("malformed module block");
1857 case BitstreamEntry::EndBlock:
1859 case BitstreamEntry::Record:
1860 // The interesting case.
1865 switch (Stream.readRecord(Entry.ID, Record)) {
1866 default: break; // Default behavior, ignore unknown content.
1867 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1869 if (ConvertToString(Record, 0, S))
1870 return Error("Invalid MODULE_CODE_TRIPLE record");
1879 bool BitcodeReader::ParseTriple(std::string &Triple) {
1880 if (InitStream()) return true;
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.
1894 BitstreamEntry Entry = Stream.advance();
1896 switch (Entry.Kind) {
1897 case BitstreamEntry::Error:
1898 Error("malformed module file");
1900 case BitstreamEntry::EndBlock:
1903 case BitstreamEntry::SubBlock:
1904 if (Entry.ID == bitc::MODULE_BLOCK_ID)
1905 return ParseModuleTriple(Triple);
1907 // Ignore other sub-blocks.
1908 if (Stream.SkipBlock()) {
1909 Error("malformed block record in AST file");
1914 case BitstreamEntry::Record:
1915 Stream.skipRecord(Entry.ID);
1921 /// ParseMetadataAttachment - Parse metadata attachments.
1922 bool BitcodeReader::ParseMetadataAttachment() {
1923 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1924 return Error("Malformed block record");
1926 SmallVector<uint64_t, 64> Record;
1928 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1930 switch (Entry.Kind) {
1931 case BitstreamEntry::SubBlock: // Handled for us already.
1932 case BitstreamEntry::Error:
1933 return Error("malformed metadata block");
1934 case BitstreamEntry::EndBlock:
1936 case BitstreamEntry::Record:
1937 // The interesting case.
1941 // Read a metadata attachment record.
1943 switch (Stream.readRecord(Entry.ID, Record)) {
1944 default: // Default behavior: ignore.
1946 case bitc::METADATA_ATTACHMENT: {
1947 unsigned RecordLength = Record.size();
1948 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1949 return Error ("Invalid METADATA_ATTACHMENT reader!");
1950 Instruction *Inst = InstructionList[Record[0]];
1951 for (unsigned i = 1; i != RecordLength; i = i+2) {
1952 unsigned Kind = Record[i];
1953 DenseMap<unsigned, unsigned>::iterator I =
1954 MDKindMap.find(Kind);
1955 if (I == MDKindMap.end())
1956 return Error("Invalid metadata kind ID");
1957 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1958 Inst->setMetadata(I->second, cast<MDNode>(Node));
1966 /// ParseFunctionBody - Lazily parse the specified function body block.
1967 bool BitcodeReader::ParseFunctionBody(Function *F) {
1968 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1969 return Error("Malformed block record");
1971 InstructionList.clear();
1972 unsigned ModuleValueListSize = ValueList.size();
1973 unsigned ModuleMDValueListSize = MDValueList.size();
1975 // Add all the function arguments to the value table.
1976 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1977 ValueList.push_back(I);
1979 unsigned NextValueNo = ValueList.size();
1980 BasicBlock *CurBB = 0;
1981 unsigned CurBBNo = 0;
1985 // Read all the records.
1986 SmallVector<uint64_t, 64> Record;
1988 BitstreamEntry Entry = Stream.advance();
1990 switch (Entry.Kind) {
1991 case BitstreamEntry::Error:
1992 return Error("Bitcode error in function block");
1993 case BitstreamEntry::EndBlock:
1994 goto OutOfRecordLoop;
1996 case BitstreamEntry::SubBlock:
1998 default: // Skip unknown content.
1999 if (Stream.SkipBlock())
2000 return Error("Malformed block record");
2002 case bitc::CONSTANTS_BLOCK_ID:
2003 if (ParseConstants()) return true;
2004 NextValueNo = ValueList.size();
2006 case bitc::VALUE_SYMTAB_BLOCK_ID:
2007 if (ParseValueSymbolTable()) return true;
2009 case bitc::METADATA_ATTACHMENT_ID:
2010 if (ParseMetadataAttachment()) return true;
2012 case bitc::METADATA_BLOCK_ID:
2013 if (ParseMetadata()) return true;
2018 case BitstreamEntry::Record:
2019 // The interesting case.
2026 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2028 default: // Default behavior: reject
2029 return Error("Unknown instruction");
2030 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2031 if (Record.size() < 1 || Record[0] == 0)
2032 return Error("Invalid DECLAREBLOCKS record");
2033 // Create all the basic blocks for the function.
2034 FunctionBBs.resize(Record[0]);
2035 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2036 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2037 CurBB = FunctionBBs[0];
2040 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2041 // This record indicates that the last instruction is at the same
2042 // location as the previous instruction with a location.
2045 // Get the last instruction emitted.
2046 if (CurBB && !CurBB->empty())
2048 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2049 !FunctionBBs[CurBBNo-1]->empty())
2050 I = &FunctionBBs[CurBBNo-1]->back();
2052 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2053 I->setDebugLoc(LastLoc);
2057 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2058 I = 0; // Get the last instruction emitted.
2059 if (CurBB && !CurBB->empty())
2061 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2062 !FunctionBBs[CurBBNo-1]->empty())
2063 I = &FunctionBBs[CurBBNo-1]->back();
2064 if (I == 0 || Record.size() < 4)
2065 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2067 unsigned Line = Record[0], Col = Record[1];
2068 unsigned ScopeID = Record[2], IAID = Record[3];
2070 MDNode *Scope = 0, *IA = 0;
2071 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2072 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2073 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2074 I->setDebugLoc(LastLoc);
2079 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2082 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2083 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2084 OpNum+1 > Record.size())
2085 return Error("Invalid BINOP record");
2087 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2088 if (Opc == -1) return Error("Invalid BINOP record");
2089 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2090 InstructionList.push_back(I);
2091 if (OpNum < Record.size()) {
2092 if (Opc == Instruction::Add ||
2093 Opc == Instruction::Sub ||
2094 Opc == Instruction::Mul ||
2095 Opc == Instruction::Shl) {
2096 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2097 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2098 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2099 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2100 } else if (Opc == Instruction::SDiv ||
2101 Opc == Instruction::UDiv ||
2102 Opc == Instruction::LShr ||
2103 Opc == Instruction::AShr) {
2104 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2105 cast<BinaryOperator>(I)->setIsExact(true);
2106 } else if (isa<FPMathOperator>(I)) {
2108 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2109 FMF.setUnsafeAlgebra();
2110 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2112 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2114 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2115 FMF.setNoSignedZeros();
2116 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2117 FMF.setAllowReciprocal();
2119 I->setFastMathFlags(FMF);
2125 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2128 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2129 OpNum+2 != Record.size())
2130 return Error("Invalid CAST record");
2132 Type *ResTy = getTypeByID(Record[OpNum]);
2133 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2134 if (Opc == -1 || ResTy == 0)
2135 return Error("Invalid CAST record");
2136 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2137 InstructionList.push_back(I);
2140 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2141 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2144 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2145 return Error("Invalid GEP record");
2147 SmallVector<Value*, 16> GEPIdx;
2148 while (OpNum != Record.size()) {
2150 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2151 return Error("Invalid GEP record");
2152 GEPIdx.push_back(Op);
2155 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2156 InstructionList.push_back(I);
2157 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2158 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2162 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2163 // EXTRACTVAL: [opty, opval, n x indices]
2166 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2167 return Error("Invalid EXTRACTVAL record");
2169 SmallVector<unsigned, 4> EXTRACTVALIdx;
2170 for (unsigned RecSize = Record.size();
2171 OpNum != RecSize; ++OpNum) {
2172 uint64_t Index = Record[OpNum];
2173 if ((unsigned)Index != Index)
2174 return Error("Invalid EXTRACTVAL index");
2175 EXTRACTVALIdx.push_back((unsigned)Index);
2178 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2179 InstructionList.push_back(I);
2183 case bitc::FUNC_CODE_INST_INSERTVAL: {
2184 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2187 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2188 return Error("Invalid INSERTVAL record");
2190 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2191 return Error("Invalid INSERTVAL record");
2193 SmallVector<unsigned, 4> INSERTVALIdx;
2194 for (unsigned RecSize = Record.size();
2195 OpNum != RecSize; ++OpNum) {
2196 uint64_t Index = Record[OpNum];
2197 if ((unsigned)Index != Index)
2198 return Error("Invalid INSERTVAL index");
2199 INSERTVALIdx.push_back((unsigned)Index);
2202 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2203 InstructionList.push_back(I);
2207 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2208 // obsolete form of select
2209 // handles select i1 ... in old bitcode
2211 Value *TrueVal, *FalseVal, *Cond;
2212 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2213 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2214 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2215 return Error("Invalid SELECT record");
2217 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2218 InstructionList.push_back(I);
2222 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2223 // new form of select
2224 // handles select i1 or select [N x i1]
2226 Value *TrueVal, *FalseVal, *Cond;
2227 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2228 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2229 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2230 return Error("Invalid SELECT record");
2232 // select condition can be either i1 or [N x i1]
2233 if (VectorType* vector_type =
2234 dyn_cast<VectorType>(Cond->getType())) {
2236 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2237 return Error("Invalid SELECT condition type");
2240 if (Cond->getType() != Type::getInt1Ty(Context))
2241 return Error("Invalid SELECT condition type");
2244 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2245 InstructionList.push_back(I);
2249 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2252 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2253 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2254 return Error("Invalid EXTRACTELT record");
2255 I = ExtractElementInst::Create(Vec, Idx);
2256 InstructionList.push_back(I);
2260 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2262 Value *Vec, *Elt, *Idx;
2263 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2264 popValue(Record, OpNum, NextValueNo,
2265 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2266 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2267 return Error("Invalid INSERTELT record");
2268 I = InsertElementInst::Create(Vec, Elt, Idx);
2269 InstructionList.push_back(I);
2273 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2275 Value *Vec1, *Vec2, *Mask;
2276 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2277 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2278 return Error("Invalid SHUFFLEVEC record");
2280 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2281 return Error("Invalid SHUFFLEVEC record");
2282 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2283 InstructionList.push_back(I);
2287 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2288 // Old form of ICmp/FCmp returning bool
2289 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2290 // both legal on vectors but had different behaviour.
2291 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2292 // FCmp/ICmp returning bool or vector of bool
2296 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2297 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2298 OpNum+1 != Record.size())
2299 return Error("Invalid CMP record");
2301 if (LHS->getType()->isFPOrFPVectorTy())
2302 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2304 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2305 InstructionList.push_back(I);
2309 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2311 unsigned Size = Record.size();
2313 I = ReturnInst::Create(Context);
2314 InstructionList.push_back(I);
2320 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2321 return Error("Invalid RET record");
2322 if (OpNum != Record.size())
2323 return Error("Invalid RET record");
2325 I = ReturnInst::Create(Context, Op);
2326 InstructionList.push_back(I);
2329 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2330 if (Record.size() != 1 && Record.size() != 3)
2331 return Error("Invalid BR record");
2332 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2334 return Error("Invalid BR record");
2336 if (Record.size() == 1) {
2337 I = BranchInst::Create(TrueDest);
2338 InstructionList.push_back(I);
2341 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2342 Value *Cond = getValue(Record, 2, NextValueNo,
2343 Type::getInt1Ty(Context));
2344 if (FalseDest == 0 || Cond == 0)
2345 return Error("Invalid BR record");
2346 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2347 InstructionList.push_back(I);
2351 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2353 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2354 // New SwitchInst format with case ranges.
2356 Type *OpTy = getTypeByID(Record[1]);
2357 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2359 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2360 BasicBlock *Default = getBasicBlock(Record[3]);
2361 if (OpTy == 0 || Cond == 0 || Default == 0)
2362 return Error("Invalid SWITCH record");
2364 unsigned NumCases = Record[4];
2366 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2367 InstructionList.push_back(SI);
2369 unsigned CurIdx = 5;
2370 for (unsigned i = 0; i != NumCases; ++i) {
2371 IntegersSubsetToBB CaseBuilder;
2372 unsigned NumItems = Record[CurIdx++];
2373 for (unsigned ci = 0; ci != NumItems; ++ci) {
2374 bool isSingleNumber = Record[CurIdx++];
2377 unsigned ActiveWords = 1;
2378 if (ValueBitWidth > 64)
2379 ActiveWords = Record[CurIdx++];
2380 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2382 CurIdx += ActiveWords;
2384 if (!isSingleNumber) {
2386 if (ValueBitWidth > 64)
2387 ActiveWords = Record[CurIdx++];
2389 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2392 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2393 IntItem::fromType(OpTy, High));
2394 CurIdx += ActiveWords;
2396 CaseBuilder.add(IntItem::fromType(OpTy, Low));
2398 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2399 IntegersSubset Case = CaseBuilder.getCase();
2400 SI->addCase(Case, DestBB);
2402 uint16_t Hash = SI->hash();
2403 if (Hash != (Record[0] & 0xFFFF))
2404 return Error("Invalid SWITCH record");
2409 // Old SwitchInst format without case ranges.
2411 if (Record.size() < 3 || (Record.size() & 1) == 0)
2412 return Error("Invalid SWITCH record");
2413 Type *OpTy = getTypeByID(Record[0]);
2414 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2415 BasicBlock *Default = getBasicBlock(Record[2]);
2416 if (OpTy == 0 || Cond == 0 || Default == 0)
2417 return Error("Invalid SWITCH record");
2418 unsigned NumCases = (Record.size()-3)/2;
2419 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2420 InstructionList.push_back(SI);
2421 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2422 ConstantInt *CaseVal =
2423 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2424 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2425 if (CaseVal == 0 || DestBB == 0) {
2427 return Error("Invalid SWITCH record!");
2429 SI->addCase(CaseVal, DestBB);
2434 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2435 if (Record.size() < 2)
2436 return Error("Invalid INDIRECTBR record");
2437 Type *OpTy = getTypeByID(Record[0]);
2438 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2439 if (OpTy == 0 || Address == 0)
2440 return Error("Invalid INDIRECTBR record");
2441 unsigned NumDests = Record.size()-2;
2442 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2443 InstructionList.push_back(IBI);
2444 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2445 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2446 IBI->addDestination(DestBB);
2449 return Error("Invalid INDIRECTBR record!");
2456 case bitc::FUNC_CODE_INST_INVOKE: {
2457 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2458 if (Record.size() < 4) return Error("Invalid INVOKE record");
2459 AttributeSet PAL = getAttributes(Record[0]);
2460 unsigned CCInfo = Record[1];
2461 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2462 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2466 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2467 return Error("Invalid INVOKE record");
2469 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2470 FunctionType *FTy = !CalleeTy ? 0 :
2471 dyn_cast<FunctionType>(CalleeTy->getElementType());
2473 // Check that the right number of fixed parameters are here.
2474 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2475 Record.size() < OpNum+FTy->getNumParams())
2476 return Error("Invalid INVOKE record");
2478 SmallVector<Value*, 16> Ops;
2479 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2480 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2481 FTy->getParamType(i)));
2482 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2485 if (!FTy->isVarArg()) {
2486 if (Record.size() != OpNum)
2487 return Error("Invalid INVOKE record");
2489 // Read type/value pairs for varargs params.
2490 while (OpNum != Record.size()) {
2492 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2493 return Error("Invalid INVOKE record");
2498 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2499 InstructionList.push_back(I);
2500 cast<InvokeInst>(I)->setCallingConv(
2501 static_cast<CallingConv::ID>(CCInfo));
2502 cast<InvokeInst>(I)->setAttributes(PAL);
2505 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2508 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2509 return Error("Invalid RESUME record");
2510 I = ResumeInst::Create(Val);
2511 InstructionList.push_back(I);
2514 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2515 I = new UnreachableInst(Context);
2516 InstructionList.push_back(I);
2518 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2519 if (Record.size() < 1 || ((Record.size()-1)&1))
2520 return Error("Invalid PHI record");
2521 Type *Ty = getTypeByID(Record[0]);
2522 if (!Ty) return Error("Invalid PHI record");
2524 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2525 InstructionList.push_back(PN);
2527 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2529 // With the new function encoding, it is possible that operands have
2530 // negative IDs (for forward references). Use a signed VBR
2531 // representation to keep the encoding small.
2533 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2535 V = getValue(Record, 1+i, NextValueNo, Ty);
2536 BasicBlock *BB = getBasicBlock(Record[2+i]);
2537 if (!V || !BB) return Error("Invalid PHI record");
2538 PN->addIncoming(V, BB);
2544 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2545 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2547 if (Record.size() < 4)
2548 return Error("Invalid LANDINGPAD record");
2549 Type *Ty = getTypeByID(Record[Idx++]);
2550 if (!Ty) return Error("Invalid LANDINGPAD record");
2552 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2553 return Error("Invalid LANDINGPAD record");
2555 bool IsCleanup = !!Record[Idx++];
2556 unsigned NumClauses = Record[Idx++];
2557 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2558 LP->setCleanup(IsCleanup);
2559 for (unsigned J = 0; J != NumClauses; ++J) {
2560 LandingPadInst::ClauseType CT =
2561 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2564 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2566 return Error("Invalid LANDINGPAD record");
2569 assert((CT != LandingPadInst::Catch ||
2570 !isa<ArrayType>(Val->getType())) &&
2571 "Catch clause has a invalid type!");
2572 assert((CT != LandingPadInst::Filter ||
2573 isa<ArrayType>(Val->getType())) &&
2574 "Filter clause has invalid type!");
2579 InstructionList.push_back(I);
2583 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2584 if (Record.size() != 4)
2585 return Error("Invalid ALLOCA record");
2587 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2588 Type *OpTy = getTypeByID(Record[1]);
2589 Value *Size = getFnValueByID(Record[2], OpTy);
2590 unsigned Align = Record[3];
2591 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2592 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2593 InstructionList.push_back(I);
2596 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2599 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2600 OpNum+2 != Record.size())
2601 return Error("Invalid LOAD record");
2603 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2604 InstructionList.push_back(I);
2607 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2608 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2611 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2612 OpNum+4 != Record.size())
2613 return Error("Invalid LOADATOMIC record");
2616 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2617 if (Ordering == NotAtomic || Ordering == Release ||
2618 Ordering == AcquireRelease)
2619 return Error("Invalid LOADATOMIC record");
2620 if (Ordering != NotAtomic && Record[OpNum] == 0)
2621 return Error("Invalid LOADATOMIC record");
2622 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2624 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2625 Ordering, SynchScope);
2626 InstructionList.push_back(I);
2629 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2632 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2633 popValue(Record, OpNum, NextValueNo,
2634 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2635 OpNum+2 != Record.size())
2636 return Error("Invalid STORE record");
2638 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2639 InstructionList.push_back(I);
2642 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2643 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2646 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2647 popValue(Record, OpNum, NextValueNo,
2648 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2649 OpNum+4 != Record.size())
2650 return Error("Invalid STOREATOMIC record");
2652 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2653 if (Ordering == NotAtomic || Ordering == Acquire ||
2654 Ordering == AcquireRelease)
2655 return Error("Invalid STOREATOMIC record");
2656 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2657 if (Ordering != NotAtomic && Record[OpNum] == 0)
2658 return Error("Invalid STOREATOMIC record");
2660 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2661 Ordering, SynchScope);
2662 InstructionList.push_back(I);
2665 case bitc::FUNC_CODE_INST_CMPXCHG: {
2666 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2668 Value *Ptr, *Cmp, *New;
2669 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2670 popValue(Record, OpNum, NextValueNo,
2671 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2672 popValue(Record, OpNum, NextValueNo,
2673 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2674 OpNum+3 != Record.size())
2675 return Error("Invalid CMPXCHG record");
2676 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2677 if (Ordering == NotAtomic || Ordering == Unordered)
2678 return Error("Invalid CMPXCHG record");
2679 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2680 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2681 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2682 InstructionList.push_back(I);
2685 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2686 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2689 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2690 popValue(Record, OpNum, NextValueNo,
2691 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2692 OpNum+4 != Record.size())
2693 return Error("Invalid ATOMICRMW record");
2694 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2695 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2696 Operation > AtomicRMWInst::LAST_BINOP)
2697 return Error("Invalid ATOMICRMW record");
2698 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2699 if (Ordering == NotAtomic || Ordering == Unordered)
2700 return Error("Invalid ATOMICRMW record");
2701 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2702 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2703 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2704 InstructionList.push_back(I);
2707 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2708 if (2 != Record.size())
2709 return Error("Invalid FENCE record");
2710 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2711 if (Ordering == NotAtomic || Ordering == Unordered ||
2712 Ordering == Monotonic)
2713 return Error("Invalid FENCE record");
2714 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2715 I = new FenceInst(Context, Ordering, SynchScope);
2716 InstructionList.push_back(I);
2719 case bitc::FUNC_CODE_INST_CALL: {
2720 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2721 if (Record.size() < 3)
2722 return Error("Invalid CALL record");
2724 AttributeSet PAL = getAttributes(Record[0]);
2725 unsigned CCInfo = Record[1];
2729 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2730 return Error("Invalid CALL record");
2732 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2733 FunctionType *FTy = 0;
2734 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2735 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2736 return Error("Invalid CALL record");
2738 SmallVector<Value*, 16> Args;
2739 // Read the fixed params.
2740 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2741 if (FTy->getParamType(i)->isLabelTy())
2742 Args.push_back(getBasicBlock(Record[OpNum]));
2744 Args.push_back(getValue(Record, OpNum, NextValueNo,
2745 FTy->getParamType(i)));
2746 if (Args.back() == 0) return Error("Invalid CALL record");
2749 // Read type/value pairs for varargs params.
2750 if (!FTy->isVarArg()) {
2751 if (OpNum != Record.size())
2752 return Error("Invalid CALL record");
2754 while (OpNum != Record.size()) {
2756 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2757 return Error("Invalid CALL record");
2762 I = CallInst::Create(Callee, Args);
2763 InstructionList.push_back(I);
2764 cast<CallInst>(I)->setCallingConv(
2765 static_cast<CallingConv::ID>(CCInfo>>1));
2766 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2767 cast<CallInst>(I)->setAttributes(PAL);
2770 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2771 if (Record.size() < 3)
2772 return Error("Invalid VAARG record");
2773 Type *OpTy = getTypeByID(Record[0]);
2774 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2775 Type *ResTy = getTypeByID(Record[2]);
2776 if (!OpTy || !Op || !ResTy)
2777 return Error("Invalid VAARG record");
2778 I = new VAArgInst(Op, ResTy);
2779 InstructionList.push_back(I);
2784 // Add instruction to end of current BB. If there is no current BB, reject
2788 return Error("Invalid instruction with no BB");
2790 CurBB->getInstList().push_back(I);
2792 // If this was a terminator instruction, move to the next block.
2793 if (isa<TerminatorInst>(I)) {
2795 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2798 // Non-void values get registered in the value table for future use.
2799 if (I && !I->getType()->isVoidTy())
2800 ValueList.AssignValue(I, NextValueNo++);
2805 // Check the function list for unresolved values.
2806 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2807 if (A->getParent() == 0) {
2808 // We found at least one unresolved value. Nuke them all to avoid leaks.
2809 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2810 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2811 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2815 return Error("Never resolved value found in function!");
2819 // FIXME: Check for unresolved forward-declared metadata references
2820 // and clean up leaks.
2822 // See if anything took the address of blocks in this function. If so,
2823 // resolve them now.
2824 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2825 BlockAddrFwdRefs.find(F);
2826 if (BAFRI != BlockAddrFwdRefs.end()) {
2827 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2828 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2829 unsigned BlockIdx = RefList[i].first;
2830 if (BlockIdx >= FunctionBBs.size())
2831 return Error("Invalid blockaddress block #");
2833 GlobalVariable *FwdRef = RefList[i].second;
2834 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2835 FwdRef->eraseFromParent();
2838 BlockAddrFwdRefs.erase(BAFRI);
2841 // Trim the value list down to the size it was before we parsed this function.
2842 ValueList.shrinkTo(ModuleValueListSize);
2843 MDValueList.shrinkTo(ModuleMDValueListSize);
2844 std::vector<BasicBlock*>().swap(FunctionBBs);
2848 /// FindFunctionInStream - Find the function body in the bitcode stream
2849 bool BitcodeReader::FindFunctionInStream(Function *F,
2850 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2851 while (DeferredFunctionInfoIterator->second == 0) {
2852 if (Stream.AtEndOfStream())
2853 return Error("Could not find Function in stream");
2854 // ParseModule will parse the next body in the stream and set its
2855 // position in the DeferredFunctionInfo map.
2856 if (ParseModule(true)) return true;
2861 //===----------------------------------------------------------------------===//
2862 // GVMaterializer implementation
2863 //===----------------------------------------------------------------------===//
2866 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2867 if (const Function *F = dyn_cast<Function>(GV)) {
2868 return F->isDeclaration() &&
2869 DeferredFunctionInfo.count(const_cast<Function*>(F));
2874 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2875 Function *F = dyn_cast<Function>(GV);
2876 // If it's not a function or is already material, ignore the request.
2877 if (!F || !F->isMaterializable()) return false;
2879 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2880 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2881 // If its position is recorded as 0, its body is somewhere in the stream
2882 // but we haven't seen it yet.
2883 if (DFII->second == 0)
2884 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
2886 // Move the bit stream to the saved position of the deferred function body.
2887 Stream.JumpToBit(DFII->second);
2889 if (ParseFunctionBody(F)) {
2890 if (ErrInfo) *ErrInfo = ErrorString;
2894 // Upgrade any old intrinsic calls in the function.
2895 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2896 E = UpgradedIntrinsics.end(); I != E; ++I) {
2897 if (I->first != I->second) {
2898 for (Value::use_iterator UI = I->first->use_begin(),
2899 UE = I->first->use_end(); UI != UE; ) {
2900 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2901 UpgradeIntrinsicCall(CI, I->second);
2909 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2910 const Function *F = dyn_cast<Function>(GV);
2911 if (!F || F->isDeclaration())
2913 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2916 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2917 Function *F = dyn_cast<Function>(GV);
2918 // If this function isn't dematerializable, this is a noop.
2919 if (!F || !isDematerializable(F))
2922 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2924 // Just forget the function body, we can remat it later.
2929 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2930 assert(M == TheModule &&
2931 "Can only Materialize the Module this BitcodeReader is attached to.");
2932 // Iterate over the module, deserializing any functions that are still on
2934 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2936 if (F->isMaterializable() &&
2937 Materialize(F, ErrInfo))
2940 // At this point, if there are any function bodies, the current bit is
2941 // pointing to the END_BLOCK record after them. Now make sure the rest
2942 // of the bits in the module have been read.
2946 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2947 // delete the old functions to clean up. We can't do this unless the entire
2948 // module is materialized because there could always be another function body
2949 // with calls to the old function.
2950 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2951 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2952 if (I->first != I->second) {
2953 for (Value::use_iterator UI = I->first->use_begin(),
2954 UE = I->first->use_end(); UI != UE; ) {
2955 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2956 UpgradeIntrinsicCall(CI, I->second);
2958 if (!I->first->use_empty())
2959 I->first->replaceAllUsesWith(I->second);
2960 I->first->eraseFromParent();
2963 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2968 bool BitcodeReader::InitStream() {
2969 if (LazyStreamer) return InitLazyStream();
2970 return InitStreamFromBuffer();
2973 bool BitcodeReader::InitStreamFromBuffer() {
2974 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
2975 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2977 if (Buffer->getBufferSize() & 3) {
2978 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2979 return Error("Invalid bitcode signature");
2981 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2984 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2985 // The magic number is 0x0B17C0DE stored in little endian.
2986 if (isBitcodeWrapper(BufPtr, BufEnd))
2987 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2988 return Error("Invalid bitcode wrapper header");
2990 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2991 Stream.init(*StreamFile);
2996 bool BitcodeReader::InitLazyStream() {
2997 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2999 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3000 StreamFile.reset(new BitstreamReader(Bytes));
3001 Stream.init(*StreamFile);
3003 unsigned char buf[16];
3004 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
3005 return Error("Bitcode stream must be at least 16 bytes in length");
3007 if (!isBitcode(buf, buf + 16))
3008 return Error("Invalid bitcode signature");
3010 if (isBitcodeWrapper(buf, buf + 4)) {
3011 const unsigned char *bitcodeStart = buf;
3012 const unsigned char *bitcodeEnd = buf + 16;
3013 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3014 Bytes->dropLeadingBytes(bitcodeStart - buf);
3015 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3020 //===----------------------------------------------------------------------===//
3021 // External interface
3022 //===----------------------------------------------------------------------===//
3024 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3026 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3027 LLVMContext& Context,
3028 std::string *ErrMsg) {
3029 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3030 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3031 M->setMaterializer(R);
3032 if (R->ParseBitcodeInto(M)) {
3034 *ErrMsg = R->getErrorString();
3036 delete M; // Also deletes R.
3039 // Have the BitcodeReader dtor delete 'Buffer'.
3040 R->setBufferOwned(true);
3042 R->materializeForwardReferencedFunctions();
3048 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3049 DataStreamer *streamer,
3050 LLVMContext &Context,
3051 std::string *ErrMsg) {
3052 Module *M = new Module(name, Context);
3053 BitcodeReader *R = new BitcodeReader(streamer, Context);
3054 M->setMaterializer(R);
3055 if (R->ParseBitcodeInto(M)) {
3057 *ErrMsg = R->getErrorString();
3058 delete M; // Also deletes R.
3061 R->setBufferOwned(false); // no buffer to delete
3065 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3066 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3067 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3068 std::string *ErrMsg){
3069 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3072 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3073 // there was an error.
3074 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3076 // Read in the entire module, and destroy the BitcodeReader.
3077 if (M->MaterializeAllPermanently(ErrMsg)) {
3082 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3083 // written. We must defer until the Module has been fully materialized.
3088 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3089 LLVMContext& Context,
3090 std::string *ErrMsg) {
3091 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3092 // Don't let the BitcodeReader dtor delete 'Buffer'.
3093 R->setBufferOwned(false);
3095 std::string Triple("");
3096 if (R->ParseTriple(Triple))
3098 *ErrMsg = R->getErrorString();