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, None);
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 & (0xfffffULL << 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));
497 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
498 for (unsigned i = 0, e = Record.size(); i != e; ++i)
499 Attrs.push_back(MAttributeGroups[Record[i]]);
501 MAttributes.push_back(AttributeSet::get(Context, Attrs));
509 bool BitcodeReader::ParseAttributeGroupBlock() {
510 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
511 return Error("Malformed block record");
513 if (!MAttributeGroups.empty())
514 return Error("Multiple PARAMATTR_GROUP blocks found!");
516 SmallVector<uint64_t, 64> Record;
518 // Read all the records.
520 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
522 switch (Entry.Kind) {
523 case BitstreamEntry::SubBlock: // Handled for us already.
524 case BitstreamEntry::Error:
525 return Error("Error at end of PARAMATTR_GROUP block");
526 case BitstreamEntry::EndBlock:
528 case BitstreamEntry::Record:
529 // The interesting case.
535 switch (Stream.readRecord(Entry.ID, Record)) {
536 default: // Default behavior: ignore.
538 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
539 if (Record.size() < 3)
540 return Error("Invalid ENTRY record");
542 uint64_t GrpID = Record[0];
543 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
546 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
547 if (Record[i] == 0) { // Enum attribute
548 B.addAttribute(Attribute::AttrKind(Record[++i]));
549 } else if (Record[i] == 1) { // Align attribute
550 if (Attribute::AttrKind(Record[++i]) == Attribute::Alignment)
551 B.addAlignmentAttr(Record[++i]);
553 B.addStackAlignmentAttr(Record[++i]);
554 } else { // String attribute
555 assert((Record[i] == 3 || Record[i] == 4) &&
556 "Invalid attribute group entry");
557 bool HasValue = (Record[i++] == 4);
558 SmallString<64> KindStr;
559 SmallString<64> ValStr;
561 while (Record[i] != 0 && i != e)
562 KindStr += Record[i++];
563 assert(Record[i] == 0 && "Kind string not null terminated");
566 // Has a value associated with it.
567 ++i; // Skip the '0' that terminates the "kind" string.
568 while (Record[i] != 0 && i != e)
569 ValStr += Record[i++];
570 assert(Record[i] == 0 && "Value string not null terminated");
573 B.addAttribute(KindStr.str(), ValStr.str());
577 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
584 bool BitcodeReader::ParseTypeTable() {
585 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
586 return Error("Malformed block record");
588 return ParseTypeTableBody();
591 bool BitcodeReader::ParseTypeTableBody() {
592 if (!TypeList.empty())
593 return Error("Multiple TYPE_BLOCKs found!");
595 SmallVector<uint64_t, 64> Record;
596 unsigned NumRecords = 0;
598 SmallString<64> TypeName;
600 // Read all the records for this type table.
602 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
604 switch (Entry.Kind) {
605 case BitstreamEntry::SubBlock: // Handled for us already.
606 case BitstreamEntry::Error:
607 Error("Error in the type table block");
609 case BitstreamEntry::EndBlock:
610 if (NumRecords != TypeList.size())
611 return Error("Invalid type forward reference in TYPE_BLOCK");
613 case BitstreamEntry::Record:
614 // The interesting case.
621 switch (Stream.readRecord(Entry.ID, Record)) {
622 default: return Error("unknown type in type table");
623 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
624 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
625 // type list. This allows us to reserve space.
626 if (Record.size() < 1)
627 return Error("Invalid TYPE_CODE_NUMENTRY record");
628 TypeList.resize(Record[0]);
630 case bitc::TYPE_CODE_VOID: // VOID
631 ResultTy = Type::getVoidTy(Context);
633 case bitc::TYPE_CODE_HALF: // HALF
634 ResultTy = Type::getHalfTy(Context);
636 case bitc::TYPE_CODE_FLOAT: // FLOAT
637 ResultTy = Type::getFloatTy(Context);
639 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
640 ResultTy = Type::getDoubleTy(Context);
642 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
643 ResultTy = Type::getX86_FP80Ty(Context);
645 case bitc::TYPE_CODE_FP128: // FP128
646 ResultTy = Type::getFP128Ty(Context);
648 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
649 ResultTy = Type::getPPC_FP128Ty(Context);
651 case bitc::TYPE_CODE_LABEL: // LABEL
652 ResultTy = Type::getLabelTy(Context);
654 case bitc::TYPE_CODE_METADATA: // METADATA
655 ResultTy = Type::getMetadataTy(Context);
657 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
658 ResultTy = Type::getX86_MMXTy(Context);
660 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
661 if (Record.size() < 1)
662 return Error("Invalid Integer type record");
664 ResultTy = IntegerType::get(Context, Record[0]);
666 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
667 // [pointee type, address space]
668 if (Record.size() < 1)
669 return Error("Invalid POINTER type record");
670 unsigned AddressSpace = 0;
671 if (Record.size() == 2)
672 AddressSpace = Record[1];
673 ResultTy = getTypeByID(Record[0]);
674 if (ResultTy == 0) return Error("invalid element type in pointer type");
675 ResultTy = PointerType::get(ResultTy, AddressSpace);
678 case bitc::TYPE_CODE_FUNCTION_OLD: {
679 // FIXME: attrid is dead, remove it in LLVM 4.0
680 // FUNCTION: [vararg, attrid, retty, paramty x N]
681 if (Record.size() < 3)
682 return Error("Invalid FUNCTION type record");
683 SmallVector<Type*, 8> ArgTys;
684 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
685 if (Type *T = getTypeByID(Record[i]))
691 ResultTy = getTypeByID(Record[2]);
692 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
693 return Error("invalid type in function type");
695 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
698 case bitc::TYPE_CODE_FUNCTION: {
699 // FUNCTION: [vararg, retty, paramty x N]
700 if (Record.size() < 2)
701 return Error("Invalid FUNCTION type record");
702 SmallVector<Type*, 8> ArgTys;
703 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
704 if (Type *T = getTypeByID(Record[i]))
710 ResultTy = getTypeByID(Record[1]);
711 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
712 return Error("invalid type in function type");
714 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
717 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
718 if (Record.size() < 1)
719 return Error("Invalid STRUCT type record");
720 SmallVector<Type*, 8> EltTys;
721 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
722 if (Type *T = getTypeByID(Record[i]))
727 if (EltTys.size() != Record.size()-1)
728 return Error("invalid type in struct type");
729 ResultTy = StructType::get(Context, EltTys, Record[0]);
732 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
733 if (ConvertToString(Record, 0, TypeName))
734 return Error("Invalid STRUCT_NAME record");
737 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
738 if (Record.size() < 1)
739 return Error("Invalid STRUCT type record");
741 if (NumRecords >= TypeList.size())
742 return Error("invalid TYPE table");
744 // Check to see if this was forward referenced, if so fill in the temp.
745 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
747 Res->setName(TypeName);
748 TypeList[NumRecords] = 0;
749 } else // Otherwise, create a new struct.
750 Res = StructType::create(Context, TypeName);
753 SmallVector<Type*, 8> EltTys;
754 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
755 if (Type *T = getTypeByID(Record[i]))
760 if (EltTys.size() != Record.size()-1)
761 return Error("invalid STRUCT type record");
762 Res->setBody(EltTys, Record[0]);
766 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
767 if (Record.size() != 1)
768 return Error("Invalid OPAQUE type record");
770 if (NumRecords >= TypeList.size())
771 return Error("invalid TYPE table");
773 // Check to see if this was forward referenced, if so fill in the temp.
774 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
776 Res->setName(TypeName);
777 TypeList[NumRecords] = 0;
778 } else // Otherwise, create a new struct with no body.
779 Res = StructType::create(Context, TypeName);
784 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
785 if (Record.size() < 2)
786 return Error("Invalid ARRAY type record");
787 if ((ResultTy = getTypeByID(Record[1])))
788 ResultTy = ArrayType::get(ResultTy, Record[0]);
790 return Error("Invalid ARRAY type element");
792 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
793 if (Record.size() < 2)
794 return Error("Invalid VECTOR type record");
795 if ((ResultTy = getTypeByID(Record[1])))
796 ResultTy = VectorType::get(ResultTy, Record[0]);
798 return Error("Invalid ARRAY type element");
802 if (NumRecords >= TypeList.size())
803 return Error("invalid TYPE table");
804 assert(ResultTy && "Didn't read a type?");
805 assert(TypeList[NumRecords] == 0 && "Already read type?");
806 TypeList[NumRecords++] = ResultTy;
810 bool BitcodeReader::ParseValueSymbolTable() {
811 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
812 return Error("Malformed block record");
814 SmallVector<uint64_t, 64> Record;
816 // Read all the records for this value table.
817 SmallString<128> ValueName;
819 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
821 switch (Entry.Kind) {
822 case BitstreamEntry::SubBlock: // Handled for us already.
823 case BitstreamEntry::Error:
824 return Error("malformed value symbol table block");
825 case BitstreamEntry::EndBlock:
827 case BitstreamEntry::Record:
828 // The interesting case.
834 switch (Stream.readRecord(Entry.ID, Record)) {
835 default: // Default behavior: unknown type.
837 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
838 if (ConvertToString(Record, 1, ValueName))
839 return Error("Invalid VST_ENTRY record");
840 unsigned ValueID = Record[0];
841 if (ValueID >= ValueList.size())
842 return Error("Invalid Value ID in VST_ENTRY record");
843 Value *V = ValueList[ValueID];
845 V->setName(StringRef(ValueName.data(), ValueName.size()));
849 case bitc::VST_CODE_BBENTRY: {
850 if (ConvertToString(Record, 1, ValueName))
851 return Error("Invalid VST_BBENTRY record");
852 BasicBlock *BB = getBasicBlock(Record[0]);
854 return Error("Invalid BB ID in VST_BBENTRY record");
856 BB->setName(StringRef(ValueName.data(), ValueName.size()));
864 bool BitcodeReader::ParseMetadata() {
865 unsigned NextMDValueNo = MDValueList.size();
867 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
868 return Error("Malformed block record");
870 SmallVector<uint64_t, 64> Record;
872 // Read all the records.
874 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
876 switch (Entry.Kind) {
877 case BitstreamEntry::SubBlock: // Handled for us already.
878 case BitstreamEntry::Error:
879 Error("malformed metadata block");
881 case BitstreamEntry::EndBlock:
883 case BitstreamEntry::Record:
884 // The interesting case.
888 bool IsFunctionLocal = false;
891 unsigned Code = Stream.readRecord(Entry.ID, Record);
893 default: // Default behavior: ignore.
895 case bitc::METADATA_NAME: {
896 // Read name of the named metadata.
897 SmallString<8> Name(Record.begin(), Record.end());
899 Code = Stream.ReadCode();
901 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
902 unsigned NextBitCode = Stream.readRecord(Code, Record);
903 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
905 // Read named metadata elements.
906 unsigned Size = Record.size();
907 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
908 for (unsigned i = 0; i != Size; ++i) {
909 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
911 return Error("Malformed metadata record");
916 case bitc::METADATA_FN_NODE:
917 IsFunctionLocal = true;
919 case bitc::METADATA_NODE: {
920 if (Record.size() % 2 == 1)
921 return Error("Invalid METADATA_NODE record");
923 unsigned Size = Record.size();
924 SmallVector<Value*, 8> Elts;
925 for (unsigned i = 0; i != Size; i += 2) {
926 Type *Ty = getTypeByID(Record[i]);
927 if (!Ty) return Error("Invalid METADATA_NODE record");
928 if (Ty->isMetadataTy())
929 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
930 else if (!Ty->isVoidTy())
931 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
933 Elts.push_back(NULL);
935 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
936 IsFunctionLocal = false;
937 MDValueList.AssignValue(V, NextMDValueNo++);
940 case bitc::METADATA_STRING: {
941 SmallString<8> String(Record.begin(), Record.end());
942 Value *V = MDString::get(Context, String);
943 MDValueList.AssignValue(V, NextMDValueNo++);
946 case bitc::METADATA_KIND: {
947 if (Record.size() < 2)
948 return Error("Invalid METADATA_KIND record");
950 unsigned Kind = Record[0];
951 SmallString<8> Name(Record.begin()+1, Record.end());
953 unsigned NewKind = TheModule->getMDKindID(Name.str());
954 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
955 return Error("Conflicting METADATA_KIND records");
962 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
963 /// the LSB for dense VBR encoding.
964 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
969 // There is no such thing as -0 with integers. "-0" really means MININT.
973 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
974 /// values and aliases that we can.
975 bool BitcodeReader::ResolveGlobalAndAliasInits() {
976 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
977 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
979 GlobalInitWorklist.swap(GlobalInits);
980 AliasInitWorklist.swap(AliasInits);
982 while (!GlobalInitWorklist.empty()) {
983 unsigned ValID = GlobalInitWorklist.back().second;
984 if (ValID >= ValueList.size()) {
985 // Not ready to resolve this yet, it requires something later in the file.
986 GlobalInits.push_back(GlobalInitWorklist.back());
988 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
989 GlobalInitWorklist.back().first->setInitializer(C);
991 return Error("Global variable initializer is not a constant!");
993 GlobalInitWorklist.pop_back();
996 while (!AliasInitWorklist.empty()) {
997 unsigned ValID = AliasInitWorklist.back().second;
998 if (ValID >= ValueList.size()) {
999 AliasInits.push_back(AliasInitWorklist.back());
1001 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1002 AliasInitWorklist.back().first->setAliasee(C);
1004 return Error("Alias initializer is not a constant!");
1006 AliasInitWorklist.pop_back();
1011 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1012 SmallVector<uint64_t, 8> Words(Vals.size());
1013 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1014 BitcodeReader::decodeSignRotatedValue);
1016 return APInt(TypeBits, Words);
1019 bool BitcodeReader::ParseConstants() {
1020 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1021 return Error("Malformed block record");
1023 SmallVector<uint64_t, 64> Record;
1025 // Read all the records for this value table.
1026 Type *CurTy = Type::getInt32Ty(Context);
1027 unsigned NextCstNo = ValueList.size();
1029 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1031 switch (Entry.Kind) {
1032 case BitstreamEntry::SubBlock: // Handled for us already.
1033 case BitstreamEntry::Error:
1034 return Error("malformed block record in AST file");
1035 case BitstreamEntry::EndBlock:
1036 if (NextCstNo != ValueList.size())
1037 return Error("Invalid constant reference!");
1039 // Once all the constants have been read, go through and resolve forward
1041 ValueList.ResolveConstantForwardRefs();
1043 case BitstreamEntry::Record:
1044 // The interesting case.
1051 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1053 default: // Default behavior: unknown constant
1054 case bitc::CST_CODE_UNDEF: // UNDEF
1055 V = UndefValue::get(CurTy);
1057 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1059 return Error("Malformed CST_SETTYPE record");
1060 if (Record[0] >= TypeList.size())
1061 return Error("Invalid Type ID in CST_SETTYPE record");
1062 CurTy = TypeList[Record[0]];
1063 continue; // Skip the ValueList manipulation.
1064 case bitc::CST_CODE_NULL: // NULL
1065 V = Constant::getNullValue(CurTy);
1067 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1068 if (!CurTy->isIntegerTy() || Record.empty())
1069 return Error("Invalid CST_INTEGER record");
1070 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1072 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1073 if (!CurTy->isIntegerTy() || Record.empty())
1074 return Error("Invalid WIDE_INTEGER record");
1076 APInt VInt = ReadWideAPInt(Record,
1077 cast<IntegerType>(CurTy)->getBitWidth());
1078 V = ConstantInt::get(Context, VInt);
1082 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1084 return Error("Invalid FLOAT record");
1085 if (CurTy->isHalfTy())
1086 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1087 APInt(16, (uint16_t)Record[0])));
1088 else if (CurTy->isFloatTy())
1089 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1090 APInt(32, (uint32_t)Record[0])));
1091 else if (CurTy->isDoubleTy())
1092 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1093 APInt(64, Record[0])));
1094 else if (CurTy->isX86_FP80Ty()) {
1095 // Bits are not stored the same way as a normal i80 APInt, compensate.
1096 uint64_t Rearrange[2];
1097 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1098 Rearrange[1] = Record[0] >> 48;
1099 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1100 APInt(80, Rearrange)));
1101 } else if (CurTy->isFP128Ty())
1102 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1103 APInt(128, Record)));
1104 else if (CurTy->isPPC_FP128Ty())
1105 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1106 APInt(128, Record)));
1108 V = UndefValue::get(CurTy);
1112 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1114 return Error("Invalid CST_AGGREGATE record");
1116 unsigned Size = Record.size();
1117 SmallVector<Constant*, 16> Elts;
1119 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1120 for (unsigned i = 0; i != Size; ++i)
1121 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1122 STy->getElementType(i)));
1123 V = ConstantStruct::get(STy, Elts);
1124 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1125 Type *EltTy = ATy->getElementType();
1126 for (unsigned i = 0; i != Size; ++i)
1127 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1128 V = ConstantArray::get(ATy, Elts);
1129 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1130 Type *EltTy = VTy->getElementType();
1131 for (unsigned i = 0; i != Size; ++i)
1132 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1133 V = ConstantVector::get(Elts);
1135 V = UndefValue::get(CurTy);
1139 case bitc::CST_CODE_STRING: // STRING: [values]
1140 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1142 return Error("Invalid CST_STRING record");
1144 SmallString<16> Elts(Record.begin(), Record.end());
1145 V = ConstantDataArray::getString(Context, Elts,
1146 BitCode == bitc::CST_CODE_CSTRING);
1149 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1151 return Error("Invalid CST_DATA record");
1153 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1154 unsigned Size = Record.size();
1156 if (EltTy->isIntegerTy(8)) {
1157 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1158 if (isa<VectorType>(CurTy))
1159 V = ConstantDataVector::get(Context, Elts);
1161 V = ConstantDataArray::get(Context, Elts);
1162 } else if (EltTy->isIntegerTy(16)) {
1163 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1164 if (isa<VectorType>(CurTy))
1165 V = ConstantDataVector::get(Context, Elts);
1167 V = ConstantDataArray::get(Context, Elts);
1168 } else if (EltTy->isIntegerTy(32)) {
1169 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1170 if (isa<VectorType>(CurTy))
1171 V = ConstantDataVector::get(Context, Elts);
1173 V = ConstantDataArray::get(Context, Elts);
1174 } else if (EltTy->isIntegerTy(64)) {
1175 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1176 if (isa<VectorType>(CurTy))
1177 V = ConstantDataVector::get(Context, Elts);
1179 V = ConstantDataArray::get(Context, Elts);
1180 } else if (EltTy->isFloatTy()) {
1181 SmallVector<float, 16> Elts(Size);
1182 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1183 if (isa<VectorType>(CurTy))
1184 V = ConstantDataVector::get(Context, Elts);
1186 V = ConstantDataArray::get(Context, Elts);
1187 } else if (EltTy->isDoubleTy()) {
1188 SmallVector<double, 16> Elts(Size);
1189 std::transform(Record.begin(), Record.end(), Elts.begin(),
1191 if (isa<VectorType>(CurTy))
1192 V = ConstantDataVector::get(Context, Elts);
1194 V = ConstantDataArray::get(Context, Elts);
1196 return Error("Unknown element type in CE_DATA");
1201 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1202 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1203 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1205 V = UndefValue::get(CurTy); // Unknown binop.
1207 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1208 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1210 if (Record.size() >= 4) {
1211 if (Opc == Instruction::Add ||
1212 Opc == Instruction::Sub ||
1213 Opc == Instruction::Mul ||
1214 Opc == Instruction::Shl) {
1215 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1216 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1217 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1218 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1219 } else if (Opc == Instruction::SDiv ||
1220 Opc == Instruction::UDiv ||
1221 Opc == Instruction::LShr ||
1222 Opc == Instruction::AShr) {
1223 if (Record[3] & (1 << bitc::PEO_EXACT))
1224 Flags |= SDivOperator::IsExact;
1227 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1231 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1232 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1233 int Opc = GetDecodedCastOpcode(Record[0]);
1235 V = UndefValue::get(CurTy); // Unknown cast.
1237 Type *OpTy = getTypeByID(Record[1]);
1238 if (!OpTy) return Error("Invalid CE_CAST record");
1239 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1240 V = ConstantExpr::getCast(Opc, Op, CurTy);
1244 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1245 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1246 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1247 SmallVector<Constant*, 16> Elts;
1248 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1249 Type *ElTy = getTypeByID(Record[i]);
1250 if (!ElTy) return Error("Invalid CE_GEP record");
1251 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1253 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1254 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1256 bitc::CST_CODE_CE_INBOUNDS_GEP);
1259 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1260 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1261 V = ConstantExpr::getSelect(
1262 ValueList.getConstantFwdRef(Record[0],
1263 Type::getInt1Ty(Context)),
1264 ValueList.getConstantFwdRef(Record[1],CurTy),
1265 ValueList.getConstantFwdRef(Record[2],CurTy));
1267 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1268 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1270 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1271 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1272 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1273 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1274 Type::getInt32Ty(Context));
1275 V = ConstantExpr::getExtractElement(Op0, Op1);
1278 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1279 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1280 if (Record.size() < 3 || OpTy == 0)
1281 return Error("Invalid CE_INSERTELT record");
1282 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1283 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1284 OpTy->getElementType());
1285 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1286 Type::getInt32Ty(Context));
1287 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1290 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1291 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1292 if (Record.size() < 3 || OpTy == 0)
1293 return Error("Invalid CE_SHUFFLEVEC record");
1294 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1295 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1296 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1297 OpTy->getNumElements());
1298 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1299 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1302 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1303 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1305 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1306 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1307 return Error("Invalid CE_SHUFVEC_EX record");
1308 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1309 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1310 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1311 RTy->getNumElements());
1312 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1313 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1316 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1317 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1318 Type *OpTy = getTypeByID(Record[0]);
1319 if (OpTy == 0) return Error("Invalid CE_CMP record");
1320 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1321 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1323 if (OpTy->isFPOrFPVectorTy())
1324 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1326 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1329 // This maintains backward compatibility, pre-asm dialect keywords.
1330 // FIXME: Remove with the 4.0 release.
1331 case bitc::CST_CODE_INLINEASM_OLD: {
1332 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1333 std::string AsmStr, ConstrStr;
1334 bool HasSideEffects = Record[0] & 1;
1335 bool IsAlignStack = Record[0] >> 1;
1336 unsigned AsmStrSize = Record[1];
1337 if (2+AsmStrSize >= Record.size())
1338 return Error("Invalid INLINEASM record");
1339 unsigned ConstStrSize = Record[2+AsmStrSize];
1340 if (3+AsmStrSize+ConstStrSize > Record.size())
1341 return Error("Invalid INLINEASM record");
1343 for (unsigned i = 0; i != AsmStrSize; ++i)
1344 AsmStr += (char)Record[2+i];
1345 for (unsigned i = 0; i != ConstStrSize; ++i)
1346 ConstrStr += (char)Record[3+AsmStrSize+i];
1347 PointerType *PTy = cast<PointerType>(CurTy);
1348 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1349 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1352 // This version adds support for the asm dialect keywords (e.g.,
1354 case bitc::CST_CODE_INLINEASM: {
1355 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1356 std::string AsmStr, ConstrStr;
1357 bool HasSideEffects = Record[0] & 1;
1358 bool IsAlignStack = (Record[0] >> 1) & 1;
1359 unsigned AsmDialect = Record[0] >> 2;
1360 unsigned AsmStrSize = Record[1];
1361 if (2+AsmStrSize >= Record.size())
1362 return Error("Invalid INLINEASM record");
1363 unsigned ConstStrSize = Record[2+AsmStrSize];
1364 if (3+AsmStrSize+ConstStrSize > Record.size())
1365 return Error("Invalid INLINEASM record");
1367 for (unsigned i = 0; i != AsmStrSize; ++i)
1368 AsmStr += (char)Record[2+i];
1369 for (unsigned i = 0; i != ConstStrSize; ++i)
1370 ConstrStr += (char)Record[3+AsmStrSize+i];
1371 PointerType *PTy = cast<PointerType>(CurTy);
1372 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1373 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1374 InlineAsm::AsmDialect(AsmDialect));
1377 case bitc::CST_CODE_BLOCKADDRESS:{
1378 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1379 Type *FnTy = getTypeByID(Record[0]);
1380 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1382 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1383 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1385 // If the function is already parsed we can insert the block address right
1388 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1389 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1391 return Error("Invalid blockaddress block #");
1394 V = BlockAddress::get(Fn, BBI);
1396 // Otherwise insert a placeholder and remember it so it can be inserted
1397 // when the function is parsed.
1398 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1399 Type::getInt8Ty(Context),
1400 false, GlobalValue::InternalLinkage,
1402 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1409 ValueList.AssignValue(V, NextCstNo);
1414 bool BitcodeReader::ParseUseLists() {
1415 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1416 return Error("Malformed block record");
1418 SmallVector<uint64_t, 64> Record;
1420 // Read all the records.
1422 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1424 switch (Entry.Kind) {
1425 case BitstreamEntry::SubBlock: // Handled for us already.
1426 case BitstreamEntry::Error:
1427 return Error("malformed use list block");
1428 case BitstreamEntry::EndBlock:
1430 case BitstreamEntry::Record:
1431 // The interesting case.
1435 // Read a use list record.
1437 switch (Stream.readRecord(Entry.ID, Record)) {
1438 default: // Default behavior: unknown type.
1440 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1441 unsigned RecordLength = Record.size();
1442 if (RecordLength < 1)
1443 return Error ("Invalid UseList reader!");
1444 UseListRecords.push_back(Record);
1451 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1452 /// remember where it is and then skip it. This lets us lazily deserialize the
1454 bool BitcodeReader::RememberAndSkipFunctionBody() {
1455 // Get the function we are talking about.
1456 if (FunctionsWithBodies.empty())
1457 return Error("Insufficient function protos");
1459 Function *Fn = FunctionsWithBodies.back();
1460 FunctionsWithBodies.pop_back();
1462 // Save the current stream state.
1463 uint64_t CurBit = Stream.GetCurrentBitNo();
1464 DeferredFunctionInfo[Fn] = CurBit;
1466 // Skip over the function block for now.
1467 if (Stream.SkipBlock())
1468 return Error("Malformed block record");
1472 bool BitcodeReader::GlobalCleanup() {
1473 // Patch the initializers for globals and aliases up.
1474 ResolveGlobalAndAliasInits();
1475 if (!GlobalInits.empty() || !AliasInits.empty())
1476 return Error("Malformed global initializer set");
1478 // Look for intrinsic functions which need to be upgraded at some point
1479 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1482 if (UpgradeIntrinsicFunction(FI, NewFn))
1483 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1486 // Look for global variables which need to be renamed.
1487 for (Module::global_iterator
1488 GI = TheModule->global_begin(), GE = TheModule->global_end();
1490 UpgradeGlobalVariable(GI);
1491 // Force deallocation of memory for these vectors to favor the client that
1492 // want lazy deserialization.
1493 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1494 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1498 bool BitcodeReader::ParseModule(bool Resume) {
1500 Stream.JumpToBit(NextUnreadBit);
1501 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1502 return Error("Malformed block record");
1504 SmallVector<uint64_t, 64> Record;
1505 std::vector<std::string> SectionTable;
1506 std::vector<std::string> GCTable;
1508 // Read all the records for this module.
1510 BitstreamEntry Entry = Stream.advance();
1512 switch (Entry.Kind) {
1513 case BitstreamEntry::Error:
1514 Error("malformed module block");
1516 case BitstreamEntry::EndBlock:
1517 return GlobalCleanup();
1519 case BitstreamEntry::SubBlock:
1521 default: // Skip unknown content.
1522 if (Stream.SkipBlock())
1523 return Error("Malformed block record");
1525 case bitc::BLOCKINFO_BLOCK_ID:
1526 if (Stream.ReadBlockInfoBlock())
1527 return Error("Malformed BlockInfoBlock");
1529 case bitc::PARAMATTR_BLOCK_ID:
1530 if (ParseAttributeBlock())
1533 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1534 if (ParseAttributeGroupBlock())
1537 case bitc::TYPE_BLOCK_ID_NEW:
1538 if (ParseTypeTable())
1541 case bitc::VALUE_SYMTAB_BLOCK_ID:
1542 if (ParseValueSymbolTable())
1544 SeenValueSymbolTable = true;
1546 case bitc::CONSTANTS_BLOCK_ID:
1547 if (ParseConstants() || ResolveGlobalAndAliasInits())
1550 case bitc::METADATA_BLOCK_ID:
1551 if (ParseMetadata())
1554 case bitc::FUNCTION_BLOCK_ID:
1555 // If this is the first function body we've seen, reverse the
1556 // FunctionsWithBodies list.
1557 if (!SeenFirstFunctionBody) {
1558 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1559 if (GlobalCleanup())
1561 SeenFirstFunctionBody = true;
1564 if (RememberAndSkipFunctionBody())
1566 // For streaming bitcode, suspend parsing when we reach the function
1567 // bodies. Subsequent materialization calls will resume it when
1568 // necessary. For streaming, the function bodies must be at the end of
1569 // the bitcode. If the bitcode file is old, the symbol table will be
1570 // at the end instead and will not have been seen yet. In this case,
1571 // just finish the parse now.
1572 if (LazyStreamer && SeenValueSymbolTable) {
1573 NextUnreadBit = Stream.GetCurrentBitNo();
1577 case bitc::USELIST_BLOCK_ID:
1578 if (ParseUseLists())
1584 case BitstreamEntry::Record:
1585 // The interesting case.
1591 switch (Stream.readRecord(Entry.ID, Record)) {
1592 default: break; // Default behavior, ignore unknown content.
1593 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1594 if (Record.size() < 1)
1595 return Error("Malformed MODULE_CODE_VERSION");
1596 // Only version #0 and #1 are supported so far.
1597 unsigned module_version = Record[0];
1598 switch (module_version) {
1599 default: return Error("Unknown bitstream version!");
1601 UseRelativeIDs = false;
1604 UseRelativeIDs = true;
1609 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1611 if (ConvertToString(Record, 0, S))
1612 return Error("Invalid MODULE_CODE_TRIPLE record");
1613 TheModule->setTargetTriple(S);
1616 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1618 if (ConvertToString(Record, 0, S))
1619 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1620 TheModule->setDataLayout(S);
1623 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1625 if (ConvertToString(Record, 0, S))
1626 return Error("Invalid MODULE_CODE_ASM record");
1627 TheModule->setModuleInlineAsm(S);
1630 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1631 // FIXME: Remove in 4.0.
1633 if (ConvertToString(Record, 0, S))
1634 return Error("Invalid MODULE_CODE_DEPLIB record");
1638 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1640 if (ConvertToString(Record, 0, S))
1641 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1642 SectionTable.push_back(S);
1645 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1647 if (ConvertToString(Record, 0, S))
1648 return Error("Invalid MODULE_CODE_GCNAME record");
1649 GCTable.push_back(S);
1652 // GLOBALVAR: [pointer type, isconst, initid,
1653 // linkage, alignment, section, visibility, threadlocal,
1655 case bitc::MODULE_CODE_GLOBALVAR: {
1656 if (Record.size() < 6)
1657 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1658 Type *Ty = getTypeByID(Record[0]);
1659 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1660 if (!Ty->isPointerTy())
1661 return Error("Global not a pointer type!");
1662 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1663 Ty = cast<PointerType>(Ty)->getElementType();
1665 bool isConstant = Record[1];
1666 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1667 unsigned Alignment = (1 << Record[4]) >> 1;
1668 std::string Section;
1670 if (Record[5]-1 >= SectionTable.size())
1671 return Error("Invalid section ID");
1672 Section = SectionTable[Record[5]-1];
1674 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1675 if (Record.size() > 6)
1676 Visibility = GetDecodedVisibility(Record[6]);
1678 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1679 if (Record.size() > 7)
1680 TLM = GetDecodedThreadLocalMode(Record[7]);
1682 bool UnnamedAddr = false;
1683 if (Record.size() > 8)
1684 UnnamedAddr = Record[8];
1686 bool ExternallyInitialized = false;
1687 if (Record.size() > 9)
1688 ExternallyInitialized = Record[9];
1690 GlobalVariable *NewGV =
1691 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1692 TLM, AddressSpace, ExternallyInitialized);
1693 NewGV->setAlignment(Alignment);
1694 if (!Section.empty())
1695 NewGV->setSection(Section);
1696 NewGV->setVisibility(Visibility);
1697 NewGV->setUnnamedAddr(UnnamedAddr);
1699 ValueList.push_back(NewGV);
1701 // Remember which value to use for the global initializer.
1702 if (unsigned InitID = Record[2])
1703 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1706 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1707 // alignment, section, visibility, gc, unnamed_addr]
1708 case bitc::MODULE_CODE_FUNCTION: {
1709 if (Record.size() < 8)
1710 return Error("Invalid MODULE_CODE_FUNCTION record");
1711 Type *Ty = getTypeByID(Record[0]);
1712 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1713 if (!Ty->isPointerTy())
1714 return Error("Function not a pointer type!");
1716 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1718 return Error("Function not a pointer to function type!");
1720 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1723 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1724 bool isProto = Record[2];
1725 Func->setLinkage(GetDecodedLinkage(Record[3]));
1726 Func->setAttributes(getAttributes(Record[4]));
1728 Func->setAlignment((1 << Record[5]) >> 1);
1730 if (Record[6]-1 >= SectionTable.size())
1731 return Error("Invalid section ID");
1732 Func->setSection(SectionTable[Record[6]-1]);
1734 Func->setVisibility(GetDecodedVisibility(Record[7]));
1735 if (Record.size() > 8 && Record[8]) {
1736 if (Record[8]-1 > GCTable.size())
1737 return Error("Invalid GC ID");
1738 Func->setGC(GCTable[Record[8]-1].c_str());
1740 bool UnnamedAddr = false;
1741 if (Record.size() > 9)
1742 UnnamedAddr = Record[9];
1743 Func->setUnnamedAddr(UnnamedAddr);
1744 ValueList.push_back(Func);
1746 // If this is a function with a body, remember the prototype we are
1747 // creating now, so that we can match up the body with them later.
1749 FunctionsWithBodies.push_back(Func);
1750 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1754 // ALIAS: [alias type, aliasee val#, linkage]
1755 // ALIAS: [alias type, aliasee val#, linkage, visibility]
1756 case bitc::MODULE_CODE_ALIAS: {
1757 if (Record.size() < 3)
1758 return Error("Invalid MODULE_ALIAS record");
1759 Type *Ty = getTypeByID(Record[0]);
1760 if (!Ty) return Error("Invalid MODULE_ALIAS record");
1761 if (!Ty->isPointerTy())
1762 return Error("Function not a pointer type!");
1764 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1766 // Old bitcode files didn't have visibility field.
1767 if (Record.size() > 3)
1768 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1769 ValueList.push_back(NewGA);
1770 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1773 /// MODULE_CODE_PURGEVALS: [numvals]
1774 case bitc::MODULE_CODE_PURGEVALS:
1775 // Trim down the value list to the specified size.
1776 if (Record.size() < 1 || Record[0] > ValueList.size())
1777 return Error("Invalid MODULE_PURGEVALS record");
1778 ValueList.shrinkTo(Record[0]);
1785 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1788 if (InitStream()) return true;
1790 // Sniff for the signature.
1791 if (Stream.Read(8) != 'B' ||
1792 Stream.Read(8) != 'C' ||
1793 Stream.Read(4) != 0x0 ||
1794 Stream.Read(4) != 0xC ||
1795 Stream.Read(4) != 0xE ||
1796 Stream.Read(4) != 0xD)
1797 return Error("Invalid bitcode signature");
1799 // We expect a number of well-defined blocks, though we don't necessarily
1800 // need to understand them all.
1802 if (Stream.AtEndOfStream())
1805 BitstreamEntry Entry =
1806 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1808 switch (Entry.Kind) {
1809 case BitstreamEntry::Error:
1810 Error("malformed module file");
1812 case BitstreamEntry::EndBlock:
1815 case BitstreamEntry::SubBlock:
1817 case bitc::BLOCKINFO_BLOCK_ID:
1818 if (Stream.ReadBlockInfoBlock())
1819 return Error("Malformed BlockInfoBlock");
1821 case bitc::MODULE_BLOCK_ID:
1822 // Reject multiple MODULE_BLOCK's in a single bitstream.
1824 return Error("Multiple MODULE_BLOCKs in same stream");
1826 if (ParseModule(false))
1828 if (LazyStreamer) return false;
1831 if (Stream.SkipBlock())
1832 return Error("Malformed block record");
1836 case BitstreamEntry::Record:
1837 // There should be no records in the top-level of blocks.
1839 // The ranlib in Xcode 4 will align archive members by appending newlines
1840 // to the end of them. If this file size is a multiple of 4 but not 8, we
1841 // have to read and ignore these final 4 bytes :-(
1842 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1843 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1844 Stream.AtEndOfStream())
1847 return Error("Invalid record at top-level");
1852 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1853 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1854 return Error("Malformed block record");
1856 SmallVector<uint64_t, 64> Record;
1858 // Read all the records for this module.
1860 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1862 switch (Entry.Kind) {
1863 case BitstreamEntry::SubBlock: // Handled for us already.
1864 case BitstreamEntry::Error:
1865 return Error("malformed module block");
1866 case BitstreamEntry::EndBlock:
1868 case BitstreamEntry::Record:
1869 // The interesting case.
1874 switch (Stream.readRecord(Entry.ID, Record)) {
1875 default: break; // Default behavior, ignore unknown content.
1876 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1878 if (ConvertToString(Record, 0, S))
1879 return Error("Invalid MODULE_CODE_TRIPLE record");
1888 bool BitcodeReader::ParseTriple(std::string &Triple) {
1889 if (InitStream()) return true;
1891 // Sniff for the signature.
1892 if (Stream.Read(8) != 'B' ||
1893 Stream.Read(8) != 'C' ||
1894 Stream.Read(4) != 0x0 ||
1895 Stream.Read(4) != 0xC ||
1896 Stream.Read(4) != 0xE ||
1897 Stream.Read(4) != 0xD)
1898 return Error("Invalid bitcode signature");
1900 // We expect a number of well-defined blocks, though we don't necessarily
1901 // need to understand them all.
1903 BitstreamEntry Entry = Stream.advance();
1905 switch (Entry.Kind) {
1906 case BitstreamEntry::Error:
1907 Error("malformed module file");
1909 case BitstreamEntry::EndBlock:
1912 case BitstreamEntry::SubBlock:
1913 if (Entry.ID == bitc::MODULE_BLOCK_ID)
1914 return ParseModuleTriple(Triple);
1916 // Ignore other sub-blocks.
1917 if (Stream.SkipBlock()) {
1918 Error("malformed block record in AST file");
1923 case BitstreamEntry::Record:
1924 Stream.skipRecord(Entry.ID);
1930 /// ParseMetadataAttachment - Parse metadata attachments.
1931 bool BitcodeReader::ParseMetadataAttachment() {
1932 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1933 return Error("Malformed block record");
1935 SmallVector<uint64_t, 64> Record;
1937 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1939 switch (Entry.Kind) {
1940 case BitstreamEntry::SubBlock: // Handled for us already.
1941 case BitstreamEntry::Error:
1942 return Error("malformed metadata block");
1943 case BitstreamEntry::EndBlock:
1945 case BitstreamEntry::Record:
1946 // The interesting case.
1950 // Read a metadata attachment record.
1952 switch (Stream.readRecord(Entry.ID, Record)) {
1953 default: // Default behavior: ignore.
1955 case bitc::METADATA_ATTACHMENT: {
1956 unsigned RecordLength = Record.size();
1957 if (Record.empty() || (RecordLength - 1) % 2 == 1)
1958 return Error ("Invalid METADATA_ATTACHMENT reader!");
1959 Instruction *Inst = InstructionList[Record[0]];
1960 for (unsigned i = 1; i != RecordLength; i = i+2) {
1961 unsigned Kind = Record[i];
1962 DenseMap<unsigned, unsigned>::iterator I =
1963 MDKindMap.find(Kind);
1964 if (I == MDKindMap.end())
1965 return Error("Invalid metadata kind ID");
1966 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1967 Inst->setMetadata(I->second, cast<MDNode>(Node));
1975 /// ParseFunctionBody - Lazily parse the specified function body block.
1976 bool BitcodeReader::ParseFunctionBody(Function *F) {
1977 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1978 return Error("Malformed block record");
1980 InstructionList.clear();
1981 unsigned ModuleValueListSize = ValueList.size();
1982 unsigned ModuleMDValueListSize = MDValueList.size();
1984 // Add all the function arguments to the value table.
1985 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1986 ValueList.push_back(I);
1988 unsigned NextValueNo = ValueList.size();
1989 BasicBlock *CurBB = 0;
1990 unsigned CurBBNo = 0;
1994 // Read all the records.
1995 SmallVector<uint64_t, 64> Record;
1997 BitstreamEntry Entry = Stream.advance();
1999 switch (Entry.Kind) {
2000 case BitstreamEntry::Error:
2001 return Error("Bitcode error in function block");
2002 case BitstreamEntry::EndBlock:
2003 goto OutOfRecordLoop;
2005 case BitstreamEntry::SubBlock:
2007 default: // Skip unknown content.
2008 if (Stream.SkipBlock())
2009 return Error("Malformed block record");
2011 case bitc::CONSTANTS_BLOCK_ID:
2012 if (ParseConstants()) return true;
2013 NextValueNo = ValueList.size();
2015 case bitc::VALUE_SYMTAB_BLOCK_ID:
2016 if (ParseValueSymbolTable()) return true;
2018 case bitc::METADATA_ATTACHMENT_ID:
2019 if (ParseMetadataAttachment()) return true;
2021 case bitc::METADATA_BLOCK_ID:
2022 if (ParseMetadata()) return true;
2027 case BitstreamEntry::Record:
2028 // The interesting case.
2035 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2037 default: // Default behavior: reject
2038 return Error("Unknown instruction");
2039 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2040 if (Record.size() < 1 || Record[0] == 0)
2041 return Error("Invalid DECLAREBLOCKS record");
2042 // Create all the basic blocks for the function.
2043 FunctionBBs.resize(Record[0]);
2044 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2045 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2046 CurBB = FunctionBBs[0];
2049 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2050 // This record indicates that the last instruction is at the same
2051 // location as the previous instruction with a location.
2054 // Get the last instruction emitted.
2055 if (CurBB && !CurBB->empty())
2057 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2058 !FunctionBBs[CurBBNo-1]->empty())
2059 I = &FunctionBBs[CurBBNo-1]->back();
2061 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2062 I->setDebugLoc(LastLoc);
2066 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2067 I = 0; // Get the last instruction emitted.
2068 if (CurBB && !CurBB->empty())
2070 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2071 !FunctionBBs[CurBBNo-1]->empty())
2072 I = &FunctionBBs[CurBBNo-1]->back();
2073 if (I == 0 || Record.size() < 4)
2074 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2076 unsigned Line = Record[0], Col = Record[1];
2077 unsigned ScopeID = Record[2], IAID = Record[3];
2079 MDNode *Scope = 0, *IA = 0;
2080 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2081 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2082 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2083 I->setDebugLoc(LastLoc);
2088 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2091 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2092 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2093 OpNum+1 > Record.size())
2094 return Error("Invalid BINOP record");
2096 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2097 if (Opc == -1) return Error("Invalid BINOP record");
2098 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2099 InstructionList.push_back(I);
2100 if (OpNum < Record.size()) {
2101 if (Opc == Instruction::Add ||
2102 Opc == Instruction::Sub ||
2103 Opc == Instruction::Mul ||
2104 Opc == Instruction::Shl) {
2105 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2106 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2107 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2108 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2109 } else if (Opc == Instruction::SDiv ||
2110 Opc == Instruction::UDiv ||
2111 Opc == Instruction::LShr ||
2112 Opc == Instruction::AShr) {
2113 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2114 cast<BinaryOperator>(I)->setIsExact(true);
2115 } else if (isa<FPMathOperator>(I)) {
2117 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2118 FMF.setUnsafeAlgebra();
2119 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2121 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2123 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2124 FMF.setNoSignedZeros();
2125 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2126 FMF.setAllowReciprocal();
2128 I->setFastMathFlags(FMF);
2134 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2137 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2138 OpNum+2 != Record.size())
2139 return Error("Invalid CAST record");
2141 Type *ResTy = getTypeByID(Record[OpNum]);
2142 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2143 if (Opc == -1 || ResTy == 0)
2144 return Error("Invalid CAST record");
2145 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2146 InstructionList.push_back(I);
2149 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2150 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2153 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2154 return Error("Invalid GEP record");
2156 SmallVector<Value*, 16> GEPIdx;
2157 while (OpNum != Record.size()) {
2159 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2160 return Error("Invalid GEP record");
2161 GEPIdx.push_back(Op);
2164 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2165 InstructionList.push_back(I);
2166 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2167 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2171 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2172 // EXTRACTVAL: [opty, opval, n x indices]
2175 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2176 return Error("Invalid EXTRACTVAL record");
2178 SmallVector<unsigned, 4> EXTRACTVALIdx;
2179 for (unsigned RecSize = Record.size();
2180 OpNum != RecSize; ++OpNum) {
2181 uint64_t Index = Record[OpNum];
2182 if ((unsigned)Index != Index)
2183 return Error("Invalid EXTRACTVAL index");
2184 EXTRACTVALIdx.push_back((unsigned)Index);
2187 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2188 InstructionList.push_back(I);
2192 case bitc::FUNC_CODE_INST_INSERTVAL: {
2193 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2196 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2197 return Error("Invalid INSERTVAL record");
2199 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2200 return Error("Invalid INSERTVAL record");
2202 SmallVector<unsigned, 4> INSERTVALIdx;
2203 for (unsigned RecSize = Record.size();
2204 OpNum != RecSize; ++OpNum) {
2205 uint64_t Index = Record[OpNum];
2206 if ((unsigned)Index != Index)
2207 return Error("Invalid INSERTVAL index");
2208 INSERTVALIdx.push_back((unsigned)Index);
2211 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2212 InstructionList.push_back(I);
2216 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2217 // obsolete form of select
2218 // handles select i1 ... in old bitcode
2220 Value *TrueVal, *FalseVal, *Cond;
2221 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2222 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2223 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2224 return Error("Invalid SELECT record");
2226 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2227 InstructionList.push_back(I);
2231 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2232 // new form of select
2233 // handles select i1 or select [N x i1]
2235 Value *TrueVal, *FalseVal, *Cond;
2236 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2237 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2238 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2239 return Error("Invalid SELECT record");
2241 // select condition can be either i1 or [N x i1]
2242 if (VectorType* vector_type =
2243 dyn_cast<VectorType>(Cond->getType())) {
2245 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2246 return Error("Invalid SELECT condition type");
2249 if (Cond->getType() != Type::getInt1Ty(Context))
2250 return Error("Invalid SELECT condition type");
2253 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2254 InstructionList.push_back(I);
2258 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2261 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2262 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2263 return Error("Invalid EXTRACTELT record");
2264 I = ExtractElementInst::Create(Vec, Idx);
2265 InstructionList.push_back(I);
2269 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2271 Value *Vec, *Elt, *Idx;
2272 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2273 popValue(Record, OpNum, NextValueNo,
2274 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2275 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2276 return Error("Invalid INSERTELT record");
2277 I = InsertElementInst::Create(Vec, Elt, Idx);
2278 InstructionList.push_back(I);
2282 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2284 Value *Vec1, *Vec2, *Mask;
2285 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2286 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2287 return Error("Invalid SHUFFLEVEC record");
2289 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2290 return Error("Invalid SHUFFLEVEC record");
2291 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2292 InstructionList.push_back(I);
2296 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2297 // Old form of ICmp/FCmp returning bool
2298 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2299 // both legal on vectors but had different behaviour.
2300 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2301 // FCmp/ICmp returning bool or vector of bool
2305 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2306 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2307 OpNum+1 != Record.size())
2308 return Error("Invalid CMP record");
2310 if (LHS->getType()->isFPOrFPVectorTy())
2311 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2313 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2314 InstructionList.push_back(I);
2318 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2320 unsigned Size = Record.size();
2322 I = ReturnInst::Create(Context);
2323 InstructionList.push_back(I);
2329 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2330 return Error("Invalid RET record");
2331 if (OpNum != Record.size())
2332 return Error("Invalid RET record");
2334 I = ReturnInst::Create(Context, Op);
2335 InstructionList.push_back(I);
2338 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2339 if (Record.size() != 1 && Record.size() != 3)
2340 return Error("Invalid BR record");
2341 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2343 return Error("Invalid BR record");
2345 if (Record.size() == 1) {
2346 I = BranchInst::Create(TrueDest);
2347 InstructionList.push_back(I);
2350 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2351 Value *Cond = getValue(Record, 2, NextValueNo,
2352 Type::getInt1Ty(Context));
2353 if (FalseDest == 0 || Cond == 0)
2354 return Error("Invalid BR record");
2355 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2356 InstructionList.push_back(I);
2360 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2362 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2363 // New SwitchInst format with case ranges.
2365 Type *OpTy = getTypeByID(Record[1]);
2366 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2368 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2369 BasicBlock *Default = getBasicBlock(Record[3]);
2370 if (OpTy == 0 || Cond == 0 || Default == 0)
2371 return Error("Invalid SWITCH record");
2373 unsigned NumCases = Record[4];
2375 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2376 InstructionList.push_back(SI);
2378 unsigned CurIdx = 5;
2379 for (unsigned i = 0; i != NumCases; ++i) {
2380 IntegersSubsetToBB CaseBuilder;
2381 unsigned NumItems = Record[CurIdx++];
2382 for (unsigned ci = 0; ci != NumItems; ++ci) {
2383 bool isSingleNumber = Record[CurIdx++];
2386 unsigned ActiveWords = 1;
2387 if (ValueBitWidth > 64)
2388 ActiveWords = Record[CurIdx++];
2389 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2391 CurIdx += ActiveWords;
2393 if (!isSingleNumber) {
2395 if (ValueBitWidth > 64)
2396 ActiveWords = Record[CurIdx++];
2398 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2401 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2402 IntItem::fromType(OpTy, High));
2403 CurIdx += ActiveWords;
2405 CaseBuilder.add(IntItem::fromType(OpTy, Low));
2407 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2408 IntegersSubset Case = CaseBuilder.getCase();
2409 SI->addCase(Case, DestBB);
2411 uint16_t Hash = SI->hash();
2412 if (Hash != (Record[0] & 0xFFFF))
2413 return Error("Invalid SWITCH record");
2418 // Old SwitchInst format without case ranges.
2420 if (Record.size() < 3 || (Record.size() & 1) == 0)
2421 return Error("Invalid SWITCH record");
2422 Type *OpTy = getTypeByID(Record[0]);
2423 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2424 BasicBlock *Default = getBasicBlock(Record[2]);
2425 if (OpTy == 0 || Cond == 0 || Default == 0)
2426 return Error("Invalid SWITCH record");
2427 unsigned NumCases = (Record.size()-3)/2;
2428 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2429 InstructionList.push_back(SI);
2430 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2431 ConstantInt *CaseVal =
2432 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2433 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2434 if (CaseVal == 0 || DestBB == 0) {
2436 return Error("Invalid SWITCH record!");
2438 SI->addCase(CaseVal, DestBB);
2443 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2444 if (Record.size() < 2)
2445 return Error("Invalid INDIRECTBR record");
2446 Type *OpTy = getTypeByID(Record[0]);
2447 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2448 if (OpTy == 0 || Address == 0)
2449 return Error("Invalid INDIRECTBR record");
2450 unsigned NumDests = Record.size()-2;
2451 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2452 InstructionList.push_back(IBI);
2453 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2454 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2455 IBI->addDestination(DestBB);
2458 return Error("Invalid INDIRECTBR record!");
2465 case bitc::FUNC_CODE_INST_INVOKE: {
2466 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2467 if (Record.size() < 4) return Error("Invalid INVOKE record");
2468 AttributeSet PAL = getAttributes(Record[0]);
2469 unsigned CCInfo = Record[1];
2470 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2471 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2475 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2476 return Error("Invalid INVOKE record");
2478 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2479 FunctionType *FTy = !CalleeTy ? 0 :
2480 dyn_cast<FunctionType>(CalleeTy->getElementType());
2482 // Check that the right number of fixed parameters are here.
2483 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2484 Record.size() < OpNum+FTy->getNumParams())
2485 return Error("Invalid INVOKE record");
2487 SmallVector<Value*, 16> Ops;
2488 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2489 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2490 FTy->getParamType(i)));
2491 if (Ops.back() == 0) return Error("Invalid INVOKE record");
2494 if (!FTy->isVarArg()) {
2495 if (Record.size() != OpNum)
2496 return Error("Invalid INVOKE record");
2498 // Read type/value pairs for varargs params.
2499 while (OpNum != Record.size()) {
2501 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2502 return Error("Invalid INVOKE record");
2507 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2508 InstructionList.push_back(I);
2509 cast<InvokeInst>(I)->setCallingConv(
2510 static_cast<CallingConv::ID>(CCInfo));
2511 cast<InvokeInst>(I)->setAttributes(PAL);
2514 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2517 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2518 return Error("Invalid RESUME record");
2519 I = ResumeInst::Create(Val);
2520 InstructionList.push_back(I);
2523 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2524 I = new UnreachableInst(Context);
2525 InstructionList.push_back(I);
2527 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2528 if (Record.size() < 1 || ((Record.size()-1)&1))
2529 return Error("Invalid PHI record");
2530 Type *Ty = getTypeByID(Record[0]);
2531 if (!Ty) return Error("Invalid PHI record");
2533 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2534 InstructionList.push_back(PN);
2536 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2538 // With the new function encoding, it is possible that operands have
2539 // negative IDs (for forward references). Use a signed VBR
2540 // representation to keep the encoding small.
2542 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2544 V = getValue(Record, 1+i, NextValueNo, Ty);
2545 BasicBlock *BB = getBasicBlock(Record[2+i]);
2546 if (!V || !BB) return Error("Invalid PHI record");
2547 PN->addIncoming(V, BB);
2553 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2554 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2556 if (Record.size() < 4)
2557 return Error("Invalid LANDINGPAD record");
2558 Type *Ty = getTypeByID(Record[Idx++]);
2559 if (!Ty) return Error("Invalid LANDINGPAD record");
2561 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2562 return Error("Invalid LANDINGPAD record");
2564 bool IsCleanup = !!Record[Idx++];
2565 unsigned NumClauses = Record[Idx++];
2566 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2567 LP->setCleanup(IsCleanup);
2568 for (unsigned J = 0; J != NumClauses; ++J) {
2569 LandingPadInst::ClauseType CT =
2570 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2573 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2575 return Error("Invalid LANDINGPAD record");
2578 assert((CT != LandingPadInst::Catch ||
2579 !isa<ArrayType>(Val->getType())) &&
2580 "Catch clause has a invalid type!");
2581 assert((CT != LandingPadInst::Filter ||
2582 isa<ArrayType>(Val->getType())) &&
2583 "Filter clause has invalid type!");
2588 InstructionList.push_back(I);
2592 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2593 if (Record.size() != 4)
2594 return Error("Invalid ALLOCA record");
2596 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2597 Type *OpTy = getTypeByID(Record[1]);
2598 Value *Size = getFnValueByID(Record[2], OpTy);
2599 unsigned Align = Record[3];
2600 if (!Ty || !Size) return Error("Invalid ALLOCA record");
2601 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2602 InstructionList.push_back(I);
2605 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2608 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2609 OpNum+2 != Record.size())
2610 return Error("Invalid LOAD record");
2612 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2613 InstructionList.push_back(I);
2616 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2617 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2620 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2621 OpNum+4 != Record.size())
2622 return Error("Invalid LOADATOMIC record");
2625 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2626 if (Ordering == NotAtomic || Ordering == Release ||
2627 Ordering == AcquireRelease)
2628 return Error("Invalid LOADATOMIC record");
2629 if (Ordering != NotAtomic && Record[OpNum] == 0)
2630 return Error("Invalid LOADATOMIC record");
2631 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2633 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2634 Ordering, SynchScope);
2635 InstructionList.push_back(I);
2638 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2641 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2642 popValue(Record, OpNum, NextValueNo,
2643 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2644 OpNum+2 != Record.size())
2645 return Error("Invalid STORE record");
2647 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2648 InstructionList.push_back(I);
2651 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2652 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2655 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2656 popValue(Record, OpNum, NextValueNo,
2657 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2658 OpNum+4 != Record.size())
2659 return Error("Invalid STOREATOMIC record");
2661 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2662 if (Ordering == NotAtomic || Ordering == Acquire ||
2663 Ordering == AcquireRelease)
2664 return Error("Invalid STOREATOMIC record");
2665 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2666 if (Ordering != NotAtomic && Record[OpNum] == 0)
2667 return Error("Invalid STOREATOMIC record");
2669 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2670 Ordering, SynchScope);
2671 InstructionList.push_back(I);
2674 case bitc::FUNC_CODE_INST_CMPXCHG: {
2675 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2677 Value *Ptr, *Cmp, *New;
2678 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2679 popValue(Record, OpNum, NextValueNo,
2680 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2681 popValue(Record, OpNum, NextValueNo,
2682 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2683 OpNum+3 != Record.size())
2684 return Error("Invalid CMPXCHG record");
2685 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2686 if (Ordering == NotAtomic || Ordering == Unordered)
2687 return Error("Invalid CMPXCHG record");
2688 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2689 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2690 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2691 InstructionList.push_back(I);
2694 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2695 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2698 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2699 popValue(Record, OpNum, NextValueNo,
2700 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2701 OpNum+4 != Record.size())
2702 return Error("Invalid ATOMICRMW record");
2703 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2704 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2705 Operation > AtomicRMWInst::LAST_BINOP)
2706 return Error("Invalid ATOMICRMW record");
2707 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2708 if (Ordering == NotAtomic || Ordering == Unordered)
2709 return Error("Invalid ATOMICRMW record");
2710 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2711 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2712 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2713 InstructionList.push_back(I);
2716 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2717 if (2 != Record.size())
2718 return Error("Invalid FENCE record");
2719 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2720 if (Ordering == NotAtomic || Ordering == Unordered ||
2721 Ordering == Monotonic)
2722 return Error("Invalid FENCE record");
2723 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2724 I = new FenceInst(Context, Ordering, SynchScope);
2725 InstructionList.push_back(I);
2728 case bitc::FUNC_CODE_INST_CALL: {
2729 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2730 if (Record.size() < 3)
2731 return Error("Invalid CALL record");
2733 AttributeSet PAL = getAttributes(Record[0]);
2734 unsigned CCInfo = Record[1];
2738 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2739 return Error("Invalid CALL record");
2741 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2742 FunctionType *FTy = 0;
2743 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2744 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2745 return Error("Invalid CALL record");
2747 SmallVector<Value*, 16> Args;
2748 // Read the fixed params.
2749 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2750 if (FTy->getParamType(i)->isLabelTy())
2751 Args.push_back(getBasicBlock(Record[OpNum]));
2753 Args.push_back(getValue(Record, OpNum, NextValueNo,
2754 FTy->getParamType(i)));
2755 if (Args.back() == 0) return Error("Invalid CALL record");
2758 // Read type/value pairs for varargs params.
2759 if (!FTy->isVarArg()) {
2760 if (OpNum != Record.size())
2761 return Error("Invalid CALL record");
2763 while (OpNum != Record.size()) {
2765 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2766 return Error("Invalid CALL record");
2771 I = CallInst::Create(Callee, Args);
2772 InstructionList.push_back(I);
2773 cast<CallInst>(I)->setCallingConv(
2774 static_cast<CallingConv::ID>(CCInfo>>1));
2775 cast<CallInst>(I)->setTailCall(CCInfo & 1);
2776 cast<CallInst>(I)->setAttributes(PAL);
2779 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2780 if (Record.size() < 3)
2781 return Error("Invalid VAARG record");
2782 Type *OpTy = getTypeByID(Record[0]);
2783 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2784 Type *ResTy = getTypeByID(Record[2]);
2785 if (!OpTy || !Op || !ResTy)
2786 return Error("Invalid VAARG record");
2787 I = new VAArgInst(Op, ResTy);
2788 InstructionList.push_back(I);
2793 // Add instruction to end of current BB. If there is no current BB, reject
2797 return Error("Invalid instruction with no BB");
2799 CurBB->getInstList().push_back(I);
2801 // If this was a terminator instruction, move to the next block.
2802 if (isa<TerminatorInst>(I)) {
2804 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2807 // Non-void values get registered in the value table for future use.
2808 if (I && !I->getType()->isVoidTy())
2809 ValueList.AssignValue(I, NextValueNo++);
2814 // Check the function list for unresolved values.
2815 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2816 if (A->getParent() == 0) {
2817 // We found at least one unresolved value. Nuke them all to avoid leaks.
2818 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2819 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2820 A->replaceAllUsesWith(UndefValue::get(A->getType()));
2824 return Error("Never resolved value found in function!");
2828 // FIXME: Check for unresolved forward-declared metadata references
2829 // and clean up leaks.
2831 // See if anything took the address of blocks in this function. If so,
2832 // resolve them now.
2833 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2834 BlockAddrFwdRefs.find(F);
2835 if (BAFRI != BlockAddrFwdRefs.end()) {
2836 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2837 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2838 unsigned BlockIdx = RefList[i].first;
2839 if (BlockIdx >= FunctionBBs.size())
2840 return Error("Invalid blockaddress block #");
2842 GlobalVariable *FwdRef = RefList[i].second;
2843 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2844 FwdRef->eraseFromParent();
2847 BlockAddrFwdRefs.erase(BAFRI);
2850 // Trim the value list down to the size it was before we parsed this function.
2851 ValueList.shrinkTo(ModuleValueListSize);
2852 MDValueList.shrinkTo(ModuleMDValueListSize);
2853 std::vector<BasicBlock*>().swap(FunctionBBs);
2857 /// FindFunctionInStream - Find the function body in the bitcode stream
2858 bool BitcodeReader::FindFunctionInStream(Function *F,
2859 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2860 while (DeferredFunctionInfoIterator->second == 0) {
2861 if (Stream.AtEndOfStream())
2862 return Error("Could not find Function in stream");
2863 // ParseModule will parse the next body in the stream and set its
2864 // position in the DeferredFunctionInfo map.
2865 if (ParseModule(true)) return true;
2870 //===----------------------------------------------------------------------===//
2871 // GVMaterializer implementation
2872 //===----------------------------------------------------------------------===//
2875 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2876 if (const Function *F = dyn_cast<Function>(GV)) {
2877 return F->isDeclaration() &&
2878 DeferredFunctionInfo.count(const_cast<Function*>(F));
2883 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2884 Function *F = dyn_cast<Function>(GV);
2885 // If it's not a function or is already material, ignore the request.
2886 if (!F || !F->isMaterializable()) return false;
2888 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2889 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2890 // If its position is recorded as 0, its body is somewhere in the stream
2891 // but we haven't seen it yet.
2892 if (DFII->second == 0)
2893 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
2895 // Move the bit stream to the saved position of the deferred function body.
2896 Stream.JumpToBit(DFII->second);
2898 if (ParseFunctionBody(F)) {
2899 if (ErrInfo) *ErrInfo = ErrorString;
2903 // Upgrade any old intrinsic calls in the function.
2904 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2905 E = UpgradedIntrinsics.end(); I != E; ++I) {
2906 if (I->first != I->second) {
2907 for (Value::use_iterator UI = I->first->use_begin(),
2908 UE = I->first->use_end(); UI != UE; ) {
2909 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2910 UpgradeIntrinsicCall(CI, I->second);
2918 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2919 const Function *F = dyn_cast<Function>(GV);
2920 if (!F || F->isDeclaration())
2922 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2925 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2926 Function *F = dyn_cast<Function>(GV);
2927 // If this function isn't dematerializable, this is a noop.
2928 if (!F || !isDematerializable(F))
2931 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2933 // Just forget the function body, we can remat it later.
2938 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2939 assert(M == TheModule &&
2940 "Can only Materialize the Module this BitcodeReader is attached to.");
2941 // Iterate over the module, deserializing any functions that are still on
2943 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2945 if (F->isMaterializable() &&
2946 Materialize(F, ErrInfo))
2949 // At this point, if there are any function bodies, the current bit is
2950 // pointing to the END_BLOCK record after them. Now make sure the rest
2951 // of the bits in the module have been read.
2955 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2956 // delete the old functions to clean up. We can't do this unless the entire
2957 // module is materialized because there could always be another function body
2958 // with calls to the old function.
2959 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2960 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2961 if (I->first != I->second) {
2962 for (Value::use_iterator UI = I->first->use_begin(),
2963 UE = I->first->use_end(); UI != UE; ) {
2964 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2965 UpgradeIntrinsicCall(CI, I->second);
2967 if (!I->first->use_empty())
2968 I->first->replaceAllUsesWith(I->second);
2969 I->first->eraseFromParent();
2972 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2977 bool BitcodeReader::InitStream() {
2978 if (LazyStreamer) return InitLazyStream();
2979 return InitStreamFromBuffer();
2982 bool BitcodeReader::InitStreamFromBuffer() {
2983 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
2984 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2986 if (Buffer->getBufferSize() & 3) {
2987 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2988 return Error("Invalid bitcode signature");
2990 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2993 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2994 // The magic number is 0x0B17C0DE stored in little endian.
2995 if (isBitcodeWrapper(BufPtr, BufEnd))
2996 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2997 return Error("Invalid bitcode wrapper header");
2999 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3000 Stream.init(*StreamFile);
3005 bool BitcodeReader::InitLazyStream() {
3006 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3008 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3009 StreamFile.reset(new BitstreamReader(Bytes));
3010 Stream.init(*StreamFile);
3012 unsigned char buf[16];
3013 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
3014 return Error("Bitcode stream must be at least 16 bytes in length");
3016 if (!isBitcode(buf, buf + 16))
3017 return Error("Invalid bitcode signature");
3019 if (isBitcodeWrapper(buf, buf + 4)) {
3020 const unsigned char *bitcodeStart = buf;
3021 const unsigned char *bitcodeEnd = buf + 16;
3022 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3023 Bytes->dropLeadingBytes(bitcodeStart - buf);
3024 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3029 //===----------------------------------------------------------------------===//
3030 // External interface
3031 //===----------------------------------------------------------------------===//
3033 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3035 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3036 LLVMContext& Context,
3037 std::string *ErrMsg) {
3038 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3039 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3040 M->setMaterializer(R);
3041 if (R->ParseBitcodeInto(M)) {
3043 *ErrMsg = R->getErrorString();
3045 delete M; // Also deletes R.
3048 // Have the BitcodeReader dtor delete 'Buffer'.
3049 R->setBufferOwned(true);
3051 R->materializeForwardReferencedFunctions();
3057 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3058 DataStreamer *streamer,
3059 LLVMContext &Context,
3060 std::string *ErrMsg) {
3061 Module *M = new Module(name, Context);
3062 BitcodeReader *R = new BitcodeReader(streamer, Context);
3063 M->setMaterializer(R);
3064 if (R->ParseBitcodeInto(M)) {
3066 *ErrMsg = R->getErrorString();
3067 delete M; // Also deletes R.
3070 R->setBufferOwned(false); // no buffer to delete
3074 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3075 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3076 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3077 std::string *ErrMsg){
3078 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3081 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3082 // there was an error.
3083 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3085 // Read in the entire module, and destroy the BitcodeReader.
3086 if (M->MaterializeAllPermanently(ErrMsg)) {
3091 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3092 // written. We must defer until the Module has been fully materialized.
3097 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3098 LLVMContext& Context,
3099 std::string *ErrMsg) {
3100 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3101 // Don't let the BitcodeReader dtor delete 'Buffer'.
3102 R->setBufferOwned(false);
3104 std::string Triple("");
3105 if (R->ParseTriple(Triple))
3107 *ErrMsg = R->getErrorString();