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/Bitcode/LLVMBitCodes.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
35 if (WillMaterializeAllForwardRefs)
36 return std::error_code();
39 WillMaterializeAllForwardRefs = true;
41 while (!BlockAddrFwdRefs.empty()) {
42 Function *F = BlockAddrFwdRefs.begin()->first;
43 assert(F && "Expected valid function");
44 // Check for a function that isn't materializable to prevent an infinite
45 // loop. When parsing a blockaddress stored in a global variable, there
46 // isn't a trivial way to check if a function will have a body without a
47 // linear search through FunctionsWithBodies, so just check it here.
48 if (!F->isMaterializable())
49 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
51 // Try to materialize F.
52 if (std::error_code EC = Materialize(F))
57 WillMaterializeAllForwardRefs = false;
58 return std::error_code();
61 void BitcodeReader::FreeState() {
63 std::vector<Type*>().swap(TypeList);
66 std::vector<Comdat *>().swap(ComdatList);
68 std::vector<AttributeSet>().swap(MAttributes);
69 std::vector<BasicBlock*>().swap(FunctionBBs);
70 std::vector<Function*>().swap(FunctionsWithBodies);
71 DeferredFunctionInfo.clear();
74 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
77 //===----------------------------------------------------------------------===//
78 // Helper functions to implement forward reference resolution, etc.
79 //===----------------------------------------------------------------------===//
81 /// ConvertToString - Convert a string from a record into an std::string, return
83 template<typename StrTy>
84 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
86 if (Idx > Record.size())
89 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
90 Result += (char)Record[i];
94 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
96 default: // Map unknown/new linkages to external
97 case 0: return GlobalValue::ExternalLinkage;
98 case 1: return GlobalValue::WeakAnyLinkage;
99 case 2: return GlobalValue::AppendingLinkage;
100 case 3: return GlobalValue::InternalLinkage;
101 case 4: return GlobalValue::LinkOnceAnyLinkage;
102 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
103 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
104 case 7: return GlobalValue::ExternalWeakLinkage;
105 case 8: return GlobalValue::CommonLinkage;
106 case 9: return GlobalValue::PrivateLinkage;
107 case 10: return GlobalValue::WeakODRLinkage;
108 case 11: return GlobalValue::LinkOnceODRLinkage;
109 case 12: return GlobalValue::AvailableExternallyLinkage;
111 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
113 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
117 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
119 default: // Map unknown visibilities to default.
120 case 0: return GlobalValue::DefaultVisibility;
121 case 1: return GlobalValue::HiddenVisibility;
122 case 2: return GlobalValue::ProtectedVisibility;
126 static GlobalValue::DLLStorageClassTypes
127 GetDecodedDLLStorageClass(unsigned Val) {
129 default: // Map unknown values to default.
130 case 0: return GlobalValue::DefaultStorageClass;
131 case 1: return GlobalValue::DLLImportStorageClass;
132 case 2: return GlobalValue::DLLExportStorageClass;
136 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
138 case 0: return GlobalVariable::NotThreadLocal;
139 default: // Map unknown non-zero value to general dynamic.
140 case 1: return GlobalVariable::GeneralDynamicTLSModel;
141 case 2: return GlobalVariable::LocalDynamicTLSModel;
142 case 3: return GlobalVariable::InitialExecTLSModel;
143 case 4: return GlobalVariable::LocalExecTLSModel;
147 static int GetDecodedCastOpcode(unsigned Val) {
150 case bitc::CAST_TRUNC : return Instruction::Trunc;
151 case bitc::CAST_ZEXT : return Instruction::ZExt;
152 case bitc::CAST_SEXT : return Instruction::SExt;
153 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
154 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
155 case bitc::CAST_UITOFP : return Instruction::UIToFP;
156 case bitc::CAST_SITOFP : return Instruction::SIToFP;
157 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
158 case bitc::CAST_FPEXT : return Instruction::FPExt;
159 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
160 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
161 case bitc::CAST_BITCAST : return Instruction::BitCast;
162 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
165 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
168 case bitc::BINOP_ADD:
169 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
170 case bitc::BINOP_SUB:
171 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
172 case bitc::BINOP_MUL:
173 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
174 case bitc::BINOP_UDIV: return Instruction::UDiv;
175 case bitc::BINOP_SDIV:
176 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
177 case bitc::BINOP_UREM: return Instruction::URem;
178 case bitc::BINOP_SREM:
179 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
180 case bitc::BINOP_SHL: return Instruction::Shl;
181 case bitc::BINOP_LSHR: return Instruction::LShr;
182 case bitc::BINOP_ASHR: return Instruction::AShr;
183 case bitc::BINOP_AND: return Instruction::And;
184 case bitc::BINOP_OR: return Instruction::Or;
185 case bitc::BINOP_XOR: return Instruction::Xor;
189 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
191 default: return AtomicRMWInst::BAD_BINOP;
192 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
193 case bitc::RMW_ADD: return AtomicRMWInst::Add;
194 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
195 case bitc::RMW_AND: return AtomicRMWInst::And;
196 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
197 case bitc::RMW_OR: return AtomicRMWInst::Or;
198 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
199 case bitc::RMW_MAX: return AtomicRMWInst::Max;
200 case bitc::RMW_MIN: return AtomicRMWInst::Min;
201 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
202 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
206 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
208 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
209 case bitc::ORDERING_UNORDERED: return Unordered;
210 case bitc::ORDERING_MONOTONIC: return Monotonic;
211 case bitc::ORDERING_ACQUIRE: return Acquire;
212 case bitc::ORDERING_RELEASE: return Release;
213 case bitc::ORDERING_ACQREL: return AcquireRelease;
214 default: // Map unknown orderings to sequentially-consistent.
215 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
219 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
221 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
222 default: // Map unknown scopes to cross-thread.
223 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
227 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
229 default: // Map unknown selection kinds to any.
230 case bitc::COMDAT_SELECTION_KIND_ANY:
232 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
233 return Comdat::ExactMatch;
234 case bitc::COMDAT_SELECTION_KIND_LARGEST:
235 return Comdat::Largest;
236 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
237 return Comdat::NoDuplicates;
238 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
239 return Comdat::SameSize;
243 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
245 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
246 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
252 /// @brief A class for maintaining the slot number definition
253 /// as a placeholder for the actual definition for forward constants defs.
254 class ConstantPlaceHolder : public ConstantExpr {
255 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
257 // allocate space for exactly one operand
258 void *operator new(size_t s) {
259 return User::operator new(s, 1);
261 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
262 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
263 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
266 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
267 static bool classof(const Value *V) {
268 return isa<ConstantExpr>(V) &&
269 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
273 /// Provide fast operand accessors
274 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
278 // FIXME: can we inherit this from ConstantExpr?
280 struct OperandTraits<ConstantPlaceHolder> :
281 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
286 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
295 WeakVH &OldV = ValuePtrs[Idx];
301 // Handle constants and non-constants (e.g. instrs) differently for
303 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
304 ResolveConstants.push_back(std::make_pair(PHC, Idx));
307 // If there was a forward reference to this value, replace it.
308 Value *PrevVal = OldV;
309 OldV->replaceAllUsesWith(V);
315 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
320 if (Value *V = ValuePtrs[Idx]) {
321 assert(Ty == V->getType() && "Type mismatch in constant table!");
322 return cast<Constant>(V);
325 // Create and return a placeholder, which will later be RAUW'd.
326 Constant *C = new ConstantPlaceHolder(Ty, Context);
331 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
335 if (Value *V = ValuePtrs[Idx]) {
336 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
340 // No type specified, must be invalid reference.
341 if (!Ty) return nullptr;
343 // Create and return a placeholder, which will later be RAUW'd.
344 Value *V = new Argument(Ty);
349 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
350 /// resolves any forward references. The idea behind this is that we sometimes
351 /// get constants (such as large arrays) which reference *many* forward ref
352 /// constants. Replacing each of these causes a lot of thrashing when
353 /// building/reuniquing the constant. Instead of doing this, we look at all the
354 /// uses and rewrite all the place holders at once for any constant that uses
356 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
357 // Sort the values by-pointer so that they are efficient to look up with a
359 std::sort(ResolveConstants.begin(), ResolveConstants.end());
361 SmallVector<Constant*, 64> NewOps;
363 while (!ResolveConstants.empty()) {
364 Value *RealVal = operator[](ResolveConstants.back().second);
365 Constant *Placeholder = ResolveConstants.back().first;
366 ResolveConstants.pop_back();
368 // Loop over all users of the placeholder, updating them to reference the
369 // new value. If they reference more than one placeholder, update them all
371 while (!Placeholder->use_empty()) {
372 auto UI = Placeholder->user_begin();
375 // If the using object isn't uniqued, just update the operands. This
376 // handles instructions and initializers for global variables.
377 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
378 UI.getUse().set(RealVal);
382 // Otherwise, we have a constant that uses the placeholder. Replace that
383 // constant with a new constant that has *all* placeholder uses updated.
384 Constant *UserC = cast<Constant>(U);
385 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
388 if (!isa<ConstantPlaceHolder>(*I)) {
389 // Not a placeholder reference.
391 } else if (*I == Placeholder) {
392 // Common case is that it just references this one placeholder.
395 // Otherwise, look up the placeholder in ResolveConstants.
396 ResolveConstantsTy::iterator It =
397 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
398 std::pair<Constant*, unsigned>(cast<Constant>(*I),
400 assert(It != ResolveConstants.end() && It->first == *I);
401 NewOp = operator[](It->second);
404 NewOps.push_back(cast<Constant>(NewOp));
407 // Make the new constant.
409 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
410 NewC = ConstantArray::get(UserCA->getType(), NewOps);
411 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
412 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
413 } else if (isa<ConstantVector>(UserC)) {
414 NewC = ConstantVector::get(NewOps);
416 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
417 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
420 UserC->replaceAllUsesWith(NewC);
421 UserC->destroyConstant();
425 // Update all ValueHandles, they should be the only users at this point.
426 Placeholder->replaceAllUsesWith(RealVal);
431 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
440 WeakVH &OldV = MDValuePtrs[Idx];
446 // If there was a forward reference to this value, replace it.
447 MDNode *PrevVal = cast<MDNode>(OldV);
448 OldV->replaceAllUsesWith(V);
449 MDNode::deleteTemporary(PrevVal);
450 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
452 MDValuePtrs[Idx] = V;
455 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
459 if (Value *V = MDValuePtrs[Idx]) {
460 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
464 // Create and return a placeholder, which will later be RAUW'd.
465 Value *V = MDNode::getTemporary(Context, None);
466 MDValuePtrs[Idx] = V;
470 Type *BitcodeReader::getTypeByID(unsigned ID) {
471 // The type table size is always specified correctly.
472 if (ID >= TypeList.size())
475 if (Type *Ty = TypeList[ID])
478 // If we have a forward reference, the only possible case is when it is to a
479 // named struct. Just create a placeholder for now.
480 return TypeList[ID] = StructType::create(Context);
484 //===----------------------------------------------------------------------===//
485 // Functions for parsing blocks from the bitcode file
486 //===----------------------------------------------------------------------===//
489 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
490 /// been decoded from the given integer. This function must stay in sync with
491 /// 'encodeLLVMAttributesForBitcode'.
492 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
493 uint64_t EncodedAttrs) {
494 // FIXME: Remove in 4.0.
496 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
497 // the bits above 31 down by 11 bits.
498 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
499 assert((!Alignment || isPowerOf2_32(Alignment)) &&
500 "Alignment must be a power of two.");
503 B.addAlignmentAttr(Alignment);
504 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
505 (EncodedAttrs & 0xffff));
508 std::error_code BitcodeReader::ParseAttributeBlock() {
509 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
510 return Error(BitcodeError::InvalidRecord);
512 if (!MAttributes.empty())
513 return Error(BitcodeError::InvalidMultipleBlocks);
515 SmallVector<uint64_t, 64> Record;
517 SmallVector<AttributeSet, 8> Attrs;
519 // Read all the records.
521 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
523 switch (Entry.Kind) {
524 case BitstreamEntry::SubBlock: // Handled for us already.
525 case BitstreamEntry::Error:
526 return Error(BitcodeError::MalformedBlock);
527 case BitstreamEntry::EndBlock:
528 return std::error_code();
529 case BitstreamEntry::Record:
530 // The interesting case.
536 switch (Stream.readRecord(Entry.ID, Record)) {
537 default: // Default behavior: ignore.
539 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
540 // FIXME: Remove in 4.0.
541 if (Record.size() & 1)
542 return Error(BitcodeError::InvalidRecord);
544 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
546 decodeLLVMAttributesForBitcode(B, Record[i+1]);
547 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
550 MAttributes.push_back(AttributeSet::get(Context, Attrs));
554 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
555 for (unsigned i = 0, e = Record.size(); i != e; ++i)
556 Attrs.push_back(MAttributeGroups[Record[i]]);
558 MAttributes.push_back(AttributeSet::get(Context, Attrs));
566 // Returns Attribute::None on unrecognized codes.
567 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
570 return Attribute::None;
571 case bitc::ATTR_KIND_ALIGNMENT:
572 return Attribute::Alignment;
573 case bitc::ATTR_KIND_ALWAYS_INLINE:
574 return Attribute::AlwaysInline;
575 case bitc::ATTR_KIND_BUILTIN:
576 return Attribute::Builtin;
577 case bitc::ATTR_KIND_BY_VAL:
578 return Attribute::ByVal;
579 case bitc::ATTR_KIND_IN_ALLOCA:
580 return Attribute::InAlloca;
581 case bitc::ATTR_KIND_COLD:
582 return Attribute::Cold;
583 case bitc::ATTR_KIND_INLINE_HINT:
584 return Attribute::InlineHint;
585 case bitc::ATTR_KIND_IN_REG:
586 return Attribute::InReg;
587 case bitc::ATTR_KIND_JUMP_TABLE:
588 return Attribute::JumpTable;
589 case bitc::ATTR_KIND_MIN_SIZE:
590 return Attribute::MinSize;
591 case bitc::ATTR_KIND_NAKED:
592 return Attribute::Naked;
593 case bitc::ATTR_KIND_NEST:
594 return Attribute::Nest;
595 case bitc::ATTR_KIND_NO_ALIAS:
596 return Attribute::NoAlias;
597 case bitc::ATTR_KIND_NO_BUILTIN:
598 return Attribute::NoBuiltin;
599 case bitc::ATTR_KIND_NO_CAPTURE:
600 return Attribute::NoCapture;
601 case bitc::ATTR_KIND_NO_DUPLICATE:
602 return Attribute::NoDuplicate;
603 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
604 return Attribute::NoImplicitFloat;
605 case bitc::ATTR_KIND_NO_INLINE:
606 return Attribute::NoInline;
607 case bitc::ATTR_KIND_NON_LAZY_BIND:
608 return Attribute::NonLazyBind;
609 case bitc::ATTR_KIND_NON_NULL:
610 return Attribute::NonNull;
611 case bitc::ATTR_KIND_DEREFERENCEABLE:
612 return Attribute::Dereferenceable;
613 case bitc::ATTR_KIND_NO_RED_ZONE:
614 return Attribute::NoRedZone;
615 case bitc::ATTR_KIND_NO_RETURN:
616 return Attribute::NoReturn;
617 case bitc::ATTR_KIND_NO_UNWIND:
618 return Attribute::NoUnwind;
619 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
620 return Attribute::OptimizeForSize;
621 case bitc::ATTR_KIND_OPTIMIZE_NONE:
622 return Attribute::OptimizeNone;
623 case bitc::ATTR_KIND_READ_NONE:
624 return Attribute::ReadNone;
625 case bitc::ATTR_KIND_READ_ONLY:
626 return Attribute::ReadOnly;
627 case bitc::ATTR_KIND_RETURNED:
628 return Attribute::Returned;
629 case bitc::ATTR_KIND_RETURNS_TWICE:
630 return Attribute::ReturnsTwice;
631 case bitc::ATTR_KIND_S_EXT:
632 return Attribute::SExt;
633 case bitc::ATTR_KIND_STACK_ALIGNMENT:
634 return Attribute::StackAlignment;
635 case bitc::ATTR_KIND_STACK_PROTECT:
636 return Attribute::StackProtect;
637 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
638 return Attribute::StackProtectReq;
639 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
640 return Attribute::StackProtectStrong;
641 case bitc::ATTR_KIND_STRUCT_RET:
642 return Attribute::StructRet;
643 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
644 return Attribute::SanitizeAddress;
645 case bitc::ATTR_KIND_SANITIZE_THREAD:
646 return Attribute::SanitizeThread;
647 case bitc::ATTR_KIND_SANITIZE_MEMORY:
648 return Attribute::SanitizeMemory;
649 case bitc::ATTR_KIND_UW_TABLE:
650 return Attribute::UWTable;
651 case bitc::ATTR_KIND_Z_EXT:
652 return Attribute::ZExt;
656 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
657 Attribute::AttrKind *Kind) {
658 *Kind = GetAttrFromCode(Code);
659 if (*Kind == Attribute::None)
660 return Error(BitcodeError::InvalidValue);
661 return std::error_code();
664 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
665 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
666 return Error(BitcodeError::InvalidRecord);
668 if (!MAttributeGroups.empty())
669 return Error(BitcodeError::InvalidMultipleBlocks);
671 SmallVector<uint64_t, 64> Record;
673 // Read all the records.
675 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
677 switch (Entry.Kind) {
678 case BitstreamEntry::SubBlock: // Handled for us already.
679 case BitstreamEntry::Error:
680 return Error(BitcodeError::MalformedBlock);
681 case BitstreamEntry::EndBlock:
682 return std::error_code();
683 case BitstreamEntry::Record:
684 // The interesting case.
690 switch (Stream.readRecord(Entry.ID, Record)) {
691 default: // Default behavior: ignore.
693 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
694 if (Record.size() < 3)
695 return Error(BitcodeError::InvalidRecord);
697 uint64_t GrpID = Record[0];
698 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
701 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
702 if (Record[i] == 0) { // Enum attribute
703 Attribute::AttrKind Kind;
704 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
707 B.addAttribute(Kind);
708 } else if (Record[i] == 1) { // Integer attribute
709 Attribute::AttrKind Kind;
710 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
712 if (Kind == Attribute::Alignment)
713 B.addAlignmentAttr(Record[++i]);
714 else if (Kind == Attribute::StackAlignment)
715 B.addStackAlignmentAttr(Record[++i]);
716 else if (Kind == Attribute::Dereferenceable)
717 B.addDereferenceableAttr(Record[++i]);
718 } else { // String attribute
719 assert((Record[i] == 3 || Record[i] == 4) &&
720 "Invalid attribute group entry");
721 bool HasValue = (Record[i++] == 4);
722 SmallString<64> KindStr;
723 SmallString<64> ValStr;
725 while (Record[i] != 0 && i != e)
726 KindStr += Record[i++];
727 assert(Record[i] == 0 && "Kind string not null terminated");
730 // Has a value associated with it.
731 ++i; // Skip the '0' that terminates the "kind" string.
732 while (Record[i] != 0 && i != e)
733 ValStr += Record[i++];
734 assert(Record[i] == 0 && "Value string not null terminated");
737 B.addAttribute(KindStr.str(), ValStr.str());
741 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
748 std::error_code BitcodeReader::ParseTypeTable() {
749 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
750 return Error(BitcodeError::InvalidRecord);
752 return ParseTypeTableBody();
755 std::error_code BitcodeReader::ParseTypeTableBody() {
756 if (!TypeList.empty())
757 return Error(BitcodeError::InvalidMultipleBlocks);
759 SmallVector<uint64_t, 64> Record;
760 unsigned NumRecords = 0;
762 SmallString<64> TypeName;
764 // Read all the records for this type table.
766 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
768 switch (Entry.Kind) {
769 case BitstreamEntry::SubBlock: // Handled for us already.
770 case BitstreamEntry::Error:
771 return Error(BitcodeError::MalformedBlock);
772 case BitstreamEntry::EndBlock:
773 if (NumRecords != TypeList.size())
774 return Error(BitcodeError::MalformedBlock);
775 return std::error_code();
776 case BitstreamEntry::Record:
777 // The interesting case.
783 Type *ResultTy = nullptr;
784 switch (Stream.readRecord(Entry.ID, Record)) {
786 return Error(BitcodeError::InvalidValue);
787 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
788 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
789 // type list. This allows us to reserve space.
790 if (Record.size() < 1)
791 return Error(BitcodeError::InvalidRecord);
792 TypeList.resize(Record[0]);
794 case bitc::TYPE_CODE_VOID: // VOID
795 ResultTy = Type::getVoidTy(Context);
797 case bitc::TYPE_CODE_HALF: // HALF
798 ResultTy = Type::getHalfTy(Context);
800 case bitc::TYPE_CODE_FLOAT: // FLOAT
801 ResultTy = Type::getFloatTy(Context);
803 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
804 ResultTy = Type::getDoubleTy(Context);
806 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
807 ResultTy = Type::getX86_FP80Ty(Context);
809 case bitc::TYPE_CODE_FP128: // FP128
810 ResultTy = Type::getFP128Ty(Context);
812 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
813 ResultTy = Type::getPPC_FP128Ty(Context);
815 case bitc::TYPE_CODE_LABEL: // LABEL
816 ResultTy = Type::getLabelTy(Context);
818 case bitc::TYPE_CODE_METADATA: // METADATA
819 ResultTy = Type::getMetadataTy(Context);
821 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
822 ResultTy = Type::getX86_MMXTy(Context);
824 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
825 if (Record.size() < 1)
826 return Error(BitcodeError::InvalidRecord);
828 ResultTy = IntegerType::get(Context, Record[0]);
830 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
831 // [pointee type, address space]
832 if (Record.size() < 1)
833 return Error(BitcodeError::InvalidRecord);
834 unsigned AddressSpace = 0;
835 if (Record.size() == 2)
836 AddressSpace = Record[1];
837 ResultTy = getTypeByID(Record[0]);
839 return Error(BitcodeError::InvalidType);
840 ResultTy = PointerType::get(ResultTy, AddressSpace);
843 case bitc::TYPE_CODE_FUNCTION_OLD: {
844 // FIXME: attrid is dead, remove it in LLVM 4.0
845 // FUNCTION: [vararg, attrid, retty, paramty x N]
846 if (Record.size() < 3)
847 return Error(BitcodeError::InvalidRecord);
848 SmallVector<Type*, 8> ArgTys;
849 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
850 if (Type *T = getTypeByID(Record[i]))
856 ResultTy = getTypeByID(Record[2]);
857 if (!ResultTy || ArgTys.size() < Record.size()-3)
858 return Error(BitcodeError::InvalidType);
860 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
863 case bitc::TYPE_CODE_FUNCTION: {
864 // FUNCTION: [vararg, retty, paramty x N]
865 if (Record.size() < 2)
866 return Error(BitcodeError::InvalidRecord);
867 SmallVector<Type*, 8> ArgTys;
868 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
869 if (Type *T = getTypeByID(Record[i]))
875 ResultTy = getTypeByID(Record[1]);
876 if (!ResultTy || ArgTys.size() < Record.size()-2)
877 return Error(BitcodeError::InvalidType);
879 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
882 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
883 if (Record.size() < 1)
884 return Error(BitcodeError::InvalidRecord);
885 SmallVector<Type*, 8> EltTys;
886 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
887 if (Type *T = getTypeByID(Record[i]))
892 if (EltTys.size() != Record.size()-1)
893 return Error(BitcodeError::InvalidType);
894 ResultTy = StructType::get(Context, EltTys, Record[0]);
897 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
898 if (ConvertToString(Record, 0, TypeName))
899 return Error(BitcodeError::InvalidRecord);
902 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
903 if (Record.size() < 1)
904 return Error(BitcodeError::InvalidRecord);
906 if (NumRecords >= TypeList.size())
907 return Error(BitcodeError::InvalidTYPETable);
909 // Check to see if this was forward referenced, if so fill in the temp.
910 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
912 Res->setName(TypeName);
913 TypeList[NumRecords] = nullptr;
914 } else // Otherwise, create a new struct.
915 Res = StructType::create(Context, TypeName);
918 SmallVector<Type*, 8> EltTys;
919 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
920 if (Type *T = getTypeByID(Record[i]))
925 if (EltTys.size() != Record.size()-1)
926 return Error(BitcodeError::InvalidRecord);
927 Res->setBody(EltTys, Record[0]);
931 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
932 if (Record.size() != 1)
933 return Error(BitcodeError::InvalidRecord);
935 if (NumRecords >= TypeList.size())
936 return Error(BitcodeError::InvalidTYPETable);
938 // Check to see if this was forward referenced, if so fill in the temp.
939 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
941 Res->setName(TypeName);
942 TypeList[NumRecords] = nullptr;
943 } else // Otherwise, create a new struct with no body.
944 Res = StructType::create(Context, TypeName);
949 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
950 if (Record.size() < 2)
951 return Error(BitcodeError::InvalidRecord);
952 if ((ResultTy = getTypeByID(Record[1])))
953 ResultTy = ArrayType::get(ResultTy, Record[0]);
955 return Error(BitcodeError::InvalidType);
957 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
958 if (Record.size() < 2)
959 return Error(BitcodeError::InvalidRecord);
960 if ((ResultTy = getTypeByID(Record[1])))
961 ResultTy = VectorType::get(ResultTy, Record[0]);
963 return Error(BitcodeError::InvalidType);
967 if (NumRecords >= TypeList.size())
968 return Error(BitcodeError::InvalidTYPETable);
969 assert(ResultTy && "Didn't read a type?");
970 assert(!TypeList[NumRecords] && "Already read type?");
971 TypeList[NumRecords++] = ResultTy;
975 std::error_code BitcodeReader::ParseValueSymbolTable() {
976 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
977 return Error(BitcodeError::InvalidRecord);
979 SmallVector<uint64_t, 64> Record;
981 // Read all the records for this value table.
982 SmallString<128> ValueName;
984 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
986 switch (Entry.Kind) {
987 case BitstreamEntry::SubBlock: // Handled for us already.
988 case BitstreamEntry::Error:
989 return Error(BitcodeError::MalformedBlock);
990 case BitstreamEntry::EndBlock:
991 return std::error_code();
992 case BitstreamEntry::Record:
993 // The interesting case.
999 switch (Stream.readRecord(Entry.ID, Record)) {
1000 default: // Default behavior: unknown type.
1002 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1003 if (ConvertToString(Record, 1, ValueName))
1004 return Error(BitcodeError::InvalidRecord);
1005 unsigned ValueID = Record[0];
1006 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1007 return Error(BitcodeError::InvalidRecord);
1008 Value *V = ValueList[ValueID];
1010 V->setName(StringRef(ValueName.data(), ValueName.size()));
1014 case bitc::VST_CODE_BBENTRY: {
1015 if (ConvertToString(Record, 1, ValueName))
1016 return Error(BitcodeError::InvalidRecord);
1017 BasicBlock *BB = getBasicBlock(Record[0]);
1019 return Error(BitcodeError::InvalidRecord);
1021 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1029 std::error_code BitcodeReader::ParseMetadata() {
1030 unsigned NextMDValueNo = MDValueList.size();
1032 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1033 return Error(BitcodeError::InvalidRecord);
1035 SmallVector<uint64_t, 64> Record;
1037 // Read all the records.
1039 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1041 switch (Entry.Kind) {
1042 case BitstreamEntry::SubBlock: // Handled for us already.
1043 case BitstreamEntry::Error:
1044 return Error(BitcodeError::MalformedBlock);
1045 case BitstreamEntry::EndBlock:
1046 return std::error_code();
1047 case BitstreamEntry::Record:
1048 // The interesting case.
1052 bool IsFunctionLocal = false;
1055 unsigned Code = Stream.readRecord(Entry.ID, Record);
1057 default: // Default behavior: ignore.
1059 case bitc::METADATA_NAME: {
1060 // Read name of the named metadata.
1061 SmallString<8> Name(Record.begin(), Record.end());
1063 Code = Stream.ReadCode();
1065 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1066 unsigned NextBitCode = Stream.readRecord(Code, Record);
1067 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1069 // Read named metadata elements.
1070 unsigned Size = Record.size();
1071 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1072 for (unsigned i = 0; i != Size; ++i) {
1073 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1075 return Error(BitcodeError::InvalidRecord);
1076 NMD->addOperand(MD);
1080 case bitc::METADATA_FN_NODE:
1081 IsFunctionLocal = true;
1083 case bitc::METADATA_NODE: {
1084 if (Record.size() % 2 == 1)
1085 return Error(BitcodeError::InvalidRecord);
1087 unsigned Size = Record.size();
1088 SmallVector<Value*, 8> Elts;
1089 for (unsigned i = 0; i != Size; i += 2) {
1090 Type *Ty = getTypeByID(Record[i]);
1092 return Error(BitcodeError::InvalidRecord);
1093 if (Ty->isMetadataTy())
1094 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1095 else if (!Ty->isVoidTy())
1096 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1098 Elts.push_back(nullptr);
1100 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1101 IsFunctionLocal = false;
1102 MDValueList.AssignValue(V, NextMDValueNo++);
1105 case bitc::METADATA_STRING: {
1106 std::string String(Record.begin(), Record.end());
1107 llvm::UpgradeMDStringConstant(String);
1108 Value *V = MDString::get(Context, String);
1109 MDValueList.AssignValue(V, NextMDValueNo++);
1112 case bitc::METADATA_KIND: {
1113 if (Record.size() < 2)
1114 return Error(BitcodeError::InvalidRecord);
1116 unsigned Kind = Record[0];
1117 SmallString<8> Name(Record.begin()+1, Record.end());
1119 unsigned NewKind = TheModule->getMDKindID(Name.str());
1120 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1121 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1128 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1129 /// the LSB for dense VBR encoding.
1130 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1135 // There is no such thing as -0 with integers. "-0" really means MININT.
1139 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1140 /// values and aliases that we can.
1141 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1142 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1143 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1144 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1146 GlobalInitWorklist.swap(GlobalInits);
1147 AliasInitWorklist.swap(AliasInits);
1148 FunctionPrefixWorklist.swap(FunctionPrefixes);
1150 while (!GlobalInitWorklist.empty()) {
1151 unsigned ValID = GlobalInitWorklist.back().second;
1152 if (ValID >= ValueList.size()) {
1153 // Not ready to resolve this yet, it requires something later in the file.
1154 GlobalInits.push_back(GlobalInitWorklist.back());
1156 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1157 GlobalInitWorklist.back().first->setInitializer(C);
1159 return Error(BitcodeError::ExpectedConstant);
1161 GlobalInitWorklist.pop_back();
1164 while (!AliasInitWorklist.empty()) {
1165 unsigned ValID = AliasInitWorklist.back().second;
1166 if (ValID >= ValueList.size()) {
1167 AliasInits.push_back(AliasInitWorklist.back());
1169 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1170 AliasInitWorklist.back().first->setAliasee(C);
1172 return Error(BitcodeError::ExpectedConstant);
1174 AliasInitWorklist.pop_back();
1177 while (!FunctionPrefixWorklist.empty()) {
1178 unsigned ValID = FunctionPrefixWorklist.back().second;
1179 if (ValID >= ValueList.size()) {
1180 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1182 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1183 FunctionPrefixWorklist.back().first->setPrefixData(C);
1185 return Error(BitcodeError::ExpectedConstant);
1187 FunctionPrefixWorklist.pop_back();
1190 return std::error_code();
1193 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1194 SmallVector<uint64_t, 8> Words(Vals.size());
1195 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1196 BitcodeReader::decodeSignRotatedValue);
1198 return APInt(TypeBits, Words);
1201 std::error_code BitcodeReader::ParseConstants() {
1202 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1203 return Error(BitcodeError::InvalidRecord);
1205 SmallVector<uint64_t, 64> Record;
1207 // Read all the records for this value table.
1208 Type *CurTy = Type::getInt32Ty(Context);
1209 unsigned NextCstNo = ValueList.size();
1211 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1213 switch (Entry.Kind) {
1214 case BitstreamEntry::SubBlock: // Handled for us already.
1215 case BitstreamEntry::Error:
1216 return Error(BitcodeError::MalformedBlock);
1217 case BitstreamEntry::EndBlock:
1218 if (NextCstNo != ValueList.size())
1219 return Error(BitcodeError::InvalidConstantReference);
1221 // Once all the constants have been read, go through and resolve forward
1223 ValueList.ResolveConstantForwardRefs();
1224 return std::error_code();
1225 case BitstreamEntry::Record:
1226 // The interesting case.
1233 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1235 default: // Default behavior: unknown constant
1236 case bitc::CST_CODE_UNDEF: // UNDEF
1237 V = UndefValue::get(CurTy);
1239 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1241 return Error(BitcodeError::InvalidRecord);
1242 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1243 return Error(BitcodeError::InvalidRecord);
1244 CurTy = TypeList[Record[0]];
1245 continue; // Skip the ValueList manipulation.
1246 case bitc::CST_CODE_NULL: // NULL
1247 V = Constant::getNullValue(CurTy);
1249 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1250 if (!CurTy->isIntegerTy() || Record.empty())
1251 return Error(BitcodeError::InvalidRecord);
1252 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1254 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1255 if (!CurTy->isIntegerTy() || Record.empty())
1256 return Error(BitcodeError::InvalidRecord);
1258 APInt VInt = ReadWideAPInt(Record,
1259 cast<IntegerType>(CurTy)->getBitWidth());
1260 V = ConstantInt::get(Context, VInt);
1264 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1266 return Error(BitcodeError::InvalidRecord);
1267 if (CurTy->isHalfTy())
1268 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1269 APInt(16, (uint16_t)Record[0])));
1270 else if (CurTy->isFloatTy())
1271 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1272 APInt(32, (uint32_t)Record[0])));
1273 else if (CurTy->isDoubleTy())
1274 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1275 APInt(64, Record[0])));
1276 else if (CurTy->isX86_FP80Ty()) {
1277 // Bits are not stored the same way as a normal i80 APInt, compensate.
1278 uint64_t Rearrange[2];
1279 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1280 Rearrange[1] = Record[0] >> 48;
1281 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1282 APInt(80, Rearrange)));
1283 } else if (CurTy->isFP128Ty())
1284 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1285 APInt(128, Record)));
1286 else if (CurTy->isPPC_FP128Ty())
1287 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1288 APInt(128, Record)));
1290 V = UndefValue::get(CurTy);
1294 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1296 return Error(BitcodeError::InvalidRecord);
1298 unsigned Size = Record.size();
1299 SmallVector<Constant*, 16> Elts;
1301 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1302 for (unsigned i = 0; i != Size; ++i)
1303 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1304 STy->getElementType(i)));
1305 V = ConstantStruct::get(STy, Elts);
1306 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1307 Type *EltTy = ATy->getElementType();
1308 for (unsigned i = 0; i != Size; ++i)
1309 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1310 V = ConstantArray::get(ATy, Elts);
1311 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1312 Type *EltTy = VTy->getElementType();
1313 for (unsigned i = 0; i != Size; ++i)
1314 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1315 V = ConstantVector::get(Elts);
1317 V = UndefValue::get(CurTy);
1321 case bitc::CST_CODE_STRING: // STRING: [values]
1322 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1324 return Error(BitcodeError::InvalidRecord);
1326 SmallString<16> Elts(Record.begin(), Record.end());
1327 V = ConstantDataArray::getString(Context, Elts,
1328 BitCode == bitc::CST_CODE_CSTRING);
1331 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1333 return Error(BitcodeError::InvalidRecord);
1335 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1336 unsigned Size = Record.size();
1338 if (EltTy->isIntegerTy(8)) {
1339 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1340 if (isa<VectorType>(CurTy))
1341 V = ConstantDataVector::get(Context, Elts);
1343 V = ConstantDataArray::get(Context, Elts);
1344 } else if (EltTy->isIntegerTy(16)) {
1345 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1346 if (isa<VectorType>(CurTy))
1347 V = ConstantDataVector::get(Context, Elts);
1349 V = ConstantDataArray::get(Context, Elts);
1350 } else if (EltTy->isIntegerTy(32)) {
1351 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1352 if (isa<VectorType>(CurTy))
1353 V = ConstantDataVector::get(Context, Elts);
1355 V = ConstantDataArray::get(Context, Elts);
1356 } else if (EltTy->isIntegerTy(64)) {
1357 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1358 if (isa<VectorType>(CurTy))
1359 V = ConstantDataVector::get(Context, Elts);
1361 V = ConstantDataArray::get(Context, Elts);
1362 } else if (EltTy->isFloatTy()) {
1363 SmallVector<float, 16> Elts(Size);
1364 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1365 if (isa<VectorType>(CurTy))
1366 V = ConstantDataVector::get(Context, Elts);
1368 V = ConstantDataArray::get(Context, Elts);
1369 } else if (EltTy->isDoubleTy()) {
1370 SmallVector<double, 16> Elts(Size);
1371 std::transform(Record.begin(), Record.end(), Elts.begin(),
1373 if (isa<VectorType>(CurTy))
1374 V = ConstantDataVector::get(Context, Elts);
1376 V = ConstantDataArray::get(Context, Elts);
1378 return Error(BitcodeError::InvalidTypeForValue);
1383 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1384 if (Record.size() < 3)
1385 return Error(BitcodeError::InvalidRecord);
1386 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1388 V = UndefValue::get(CurTy); // Unknown binop.
1390 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1391 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1393 if (Record.size() >= 4) {
1394 if (Opc == Instruction::Add ||
1395 Opc == Instruction::Sub ||
1396 Opc == Instruction::Mul ||
1397 Opc == Instruction::Shl) {
1398 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1399 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1400 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1401 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1402 } else if (Opc == Instruction::SDiv ||
1403 Opc == Instruction::UDiv ||
1404 Opc == Instruction::LShr ||
1405 Opc == Instruction::AShr) {
1406 if (Record[3] & (1 << bitc::PEO_EXACT))
1407 Flags |= SDivOperator::IsExact;
1410 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1414 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1415 if (Record.size() < 3)
1416 return Error(BitcodeError::InvalidRecord);
1417 int Opc = GetDecodedCastOpcode(Record[0]);
1419 V = UndefValue::get(CurTy); // Unknown cast.
1421 Type *OpTy = getTypeByID(Record[1]);
1423 return Error(BitcodeError::InvalidRecord);
1424 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1425 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1426 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1430 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1431 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1432 if (Record.size() & 1)
1433 return Error(BitcodeError::InvalidRecord);
1434 SmallVector<Constant*, 16> Elts;
1435 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1436 Type *ElTy = getTypeByID(Record[i]);
1438 return Error(BitcodeError::InvalidRecord);
1439 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1441 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1442 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1444 bitc::CST_CODE_CE_INBOUNDS_GEP);
1447 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1448 if (Record.size() < 3)
1449 return Error(BitcodeError::InvalidRecord);
1451 Type *SelectorTy = Type::getInt1Ty(Context);
1453 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1454 // vector. Otherwise, it must be a single bit.
1455 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1456 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1457 VTy->getNumElements());
1459 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1461 ValueList.getConstantFwdRef(Record[1],CurTy),
1462 ValueList.getConstantFwdRef(Record[2],CurTy));
1465 case bitc::CST_CODE_CE_EXTRACTELT
1466 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1467 if (Record.size() < 3)
1468 return Error(BitcodeError::InvalidRecord);
1470 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1472 return Error(BitcodeError::InvalidRecord);
1473 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1474 Constant *Op1 = nullptr;
1475 if (Record.size() == 4) {
1476 Type *IdxTy = getTypeByID(Record[2]);
1478 return Error(BitcodeError::InvalidRecord);
1479 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1480 } else // TODO: Remove with llvm 4.0
1481 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1483 return Error(BitcodeError::InvalidRecord);
1484 V = ConstantExpr::getExtractElement(Op0, Op1);
1487 case bitc::CST_CODE_CE_INSERTELT
1488 : { // CE_INSERTELT: [opval, opval, opty, opval]
1489 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1490 if (Record.size() < 3 || !OpTy)
1491 return Error(BitcodeError::InvalidRecord);
1492 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1493 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1494 OpTy->getElementType());
1495 Constant *Op2 = nullptr;
1496 if (Record.size() == 4) {
1497 Type *IdxTy = getTypeByID(Record[2]);
1499 return Error(BitcodeError::InvalidRecord);
1500 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1501 } else // TODO: Remove with llvm 4.0
1502 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1504 return Error(BitcodeError::InvalidRecord);
1505 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1508 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1509 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1510 if (Record.size() < 3 || !OpTy)
1511 return Error(BitcodeError::InvalidRecord);
1512 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1513 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1514 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1515 OpTy->getNumElements());
1516 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1517 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1520 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1521 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1523 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1524 if (Record.size() < 4 || !RTy || !OpTy)
1525 return Error(BitcodeError::InvalidRecord);
1526 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1527 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1528 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1529 RTy->getNumElements());
1530 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1531 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1534 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1535 if (Record.size() < 4)
1536 return Error(BitcodeError::InvalidRecord);
1537 Type *OpTy = getTypeByID(Record[0]);
1539 return Error(BitcodeError::InvalidRecord);
1540 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1541 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1543 if (OpTy->isFPOrFPVectorTy())
1544 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1546 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1549 // This maintains backward compatibility, pre-asm dialect keywords.
1550 // FIXME: Remove with the 4.0 release.
1551 case bitc::CST_CODE_INLINEASM_OLD: {
1552 if (Record.size() < 2)
1553 return Error(BitcodeError::InvalidRecord);
1554 std::string AsmStr, ConstrStr;
1555 bool HasSideEffects = Record[0] & 1;
1556 bool IsAlignStack = Record[0] >> 1;
1557 unsigned AsmStrSize = Record[1];
1558 if (2+AsmStrSize >= Record.size())
1559 return Error(BitcodeError::InvalidRecord);
1560 unsigned ConstStrSize = Record[2+AsmStrSize];
1561 if (3+AsmStrSize+ConstStrSize > Record.size())
1562 return Error(BitcodeError::InvalidRecord);
1564 for (unsigned i = 0; i != AsmStrSize; ++i)
1565 AsmStr += (char)Record[2+i];
1566 for (unsigned i = 0; i != ConstStrSize; ++i)
1567 ConstrStr += (char)Record[3+AsmStrSize+i];
1568 PointerType *PTy = cast<PointerType>(CurTy);
1569 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1570 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1573 // This version adds support for the asm dialect keywords (e.g.,
1575 case bitc::CST_CODE_INLINEASM: {
1576 if (Record.size() < 2)
1577 return Error(BitcodeError::InvalidRecord);
1578 std::string AsmStr, ConstrStr;
1579 bool HasSideEffects = Record[0] & 1;
1580 bool IsAlignStack = (Record[0] >> 1) & 1;
1581 unsigned AsmDialect = Record[0] >> 2;
1582 unsigned AsmStrSize = Record[1];
1583 if (2+AsmStrSize >= Record.size())
1584 return Error(BitcodeError::InvalidRecord);
1585 unsigned ConstStrSize = Record[2+AsmStrSize];
1586 if (3+AsmStrSize+ConstStrSize > Record.size())
1587 return Error(BitcodeError::InvalidRecord);
1589 for (unsigned i = 0; i != AsmStrSize; ++i)
1590 AsmStr += (char)Record[2+i];
1591 for (unsigned i = 0; i != ConstStrSize; ++i)
1592 ConstrStr += (char)Record[3+AsmStrSize+i];
1593 PointerType *PTy = cast<PointerType>(CurTy);
1594 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1595 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1596 InlineAsm::AsmDialect(AsmDialect));
1599 case bitc::CST_CODE_BLOCKADDRESS:{
1600 if (Record.size() < 3)
1601 return Error(BitcodeError::InvalidRecord);
1602 Type *FnTy = getTypeByID(Record[0]);
1604 return Error(BitcodeError::InvalidRecord);
1606 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1608 return Error(BitcodeError::InvalidRecord);
1610 // Don't let Fn get dematerialized.
1611 BlockAddressesTaken.insert(Fn);
1613 // If the function is already parsed we can insert the block address right
1616 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1617 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1619 return Error(BitcodeError::InvalidID);
1622 V = BlockAddress::get(Fn, BBI);
1624 // Otherwise insert a placeholder and remember it so it can be inserted
1625 // when the function is parsed.
1626 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1627 Type::getInt8Ty(Context),
1628 false, GlobalValue::InternalLinkage,
1630 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1637 ValueList.AssignValue(V, NextCstNo);
1642 std::error_code BitcodeReader::ParseUseLists() {
1643 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1644 return Error(BitcodeError::InvalidRecord);
1646 // Read all the records.
1647 SmallVector<uint64_t, 64> Record;
1649 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1651 switch (Entry.Kind) {
1652 case BitstreamEntry::SubBlock: // Handled for us already.
1653 case BitstreamEntry::Error:
1654 return Error(BitcodeError::MalformedBlock);
1655 case BitstreamEntry::EndBlock:
1656 return std::error_code();
1657 case BitstreamEntry::Record:
1658 // The interesting case.
1662 // Read a use list record.
1665 switch (Stream.readRecord(Entry.ID, Record)) {
1666 default: // Default behavior: unknown type.
1668 case bitc::USELIST_CODE_BB:
1671 case bitc::USELIST_CODE_DEFAULT: {
1672 unsigned RecordLength = Record.size();
1673 if (RecordLength < 3)
1674 // Records should have at least an ID and two indexes.
1675 return Error(BitcodeError::InvalidRecord);
1676 unsigned ID = Record.back();
1681 assert(ID < FunctionBBs.size() && "Basic block not found");
1682 V = FunctionBBs[ID];
1685 unsigned NumUses = 0;
1686 SmallDenseMap<const Use *, unsigned, 16> Order;
1687 for (const Use &U : V->uses()) {
1688 if (NumUses > Record.size())
1690 Order[&U] = Record[NumUses++];
1692 if (Order.size() != Record.size() || NumUses > Record.size())
1693 // Mismatches can happen if the functions are being materialized lazily
1694 // (out-of-order), or a value has been upgraded.
1697 V->sortUseList([&](const Use &L, const Use &R) {
1698 return Order.lookup(&L) < Order.lookup(&R);
1706 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1707 /// remember where it is and then skip it. This lets us lazily deserialize the
1709 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1710 // Get the function we are talking about.
1711 if (FunctionsWithBodies.empty())
1712 return Error(BitcodeError::InsufficientFunctionProtos);
1714 Function *Fn = FunctionsWithBodies.back();
1715 FunctionsWithBodies.pop_back();
1717 // Save the current stream state.
1718 uint64_t CurBit = Stream.GetCurrentBitNo();
1719 DeferredFunctionInfo[Fn] = CurBit;
1721 // Skip over the function block for now.
1722 if (Stream.SkipBlock())
1723 return Error(BitcodeError::InvalidRecord);
1724 return std::error_code();
1727 std::error_code BitcodeReader::GlobalCleanup() {
1728 // Patch the initializers for globals and aliases up.
1729 ResolveGlobalAndAliasInits();
1730 if (!GlobalInits.empty() || !AliasInits.empty())
1731 return Error(BitcodeError::MalformedGlobalInitializerSet);
1733 // Look for intrinsic functions which need to be upgraded at some point
1734 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1737 if (UpgradeIntrinsicFunction(FI, NewFn))
1738 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1741 // Look for global variables which need to be renamed.
1742 for (Module::global_iterator
1743 GI = TheModule->global_begin(), GE = TheModule->global_end();
1745 GlobalVariable *GV = GI++;
1746 UpgradeGlobalVariable(GV);
1749 // Force deallocation of memory for these vectors to favor the client that
1750 // want lazy deserialization.
1751 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1752 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1753 return std::error_code();
1756 std::error_code BitcodeReader::ParseModule(bool Resume) {
1758 Stream.JumpToBit(NextUnreadBit);
1759 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1760 return Error(BitcodeError::InvalidRecord);
1762 SmallVector<uint64_t, 64> Record;
1763 std::vector<std::string> SectionTable;
1764 std::vector<std::string> GCTable;
1766 // Read all the records for this module.
1768 BitstreamEntry Entry = Stream.advance();
1770 switch (Entry.Kind) {
1771 case BitstreamEntry::Error:
1772 return Error(BitcodeError::MalformedBlock);
1773 case BitstreamEntry::EndBlock:
1774 return GlobalCleanup();
1776 case BitstreamEntry::SubBlock:
1778 default: // Skip unknown content.
1779 if (Stream.SkipBlock())
1780 return Error(BitcodeError::InvalidRecord);
1782 case bitc::BLOCKINFO_BLOCK_ID:
1783 if (Stream.ReadBlockInfoBlock())
1784 return Error(BitcodeError::MalformedBlock);
1786 case bitc::PARAMATTR_BLOCK_ID:
1787 if (std::error_code EC = ParseAttributeBlock())
1790 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1791 if (std::error_code EC = ParseAttributeGroupBlock())
1794 case bitc::TYPE_BLOCK_ID_NEW:
1795 if (std::error_code EC = ParseTypeTable())
1798 case bitc::VALUE_SYMTAB_BLOCK_ID:
1799 if (std::error_code EC = ParseValueSymbolTable())
1801 SeenValueSymbolTable = true;
1803 case bitc::CONSTANTS_BLOCK_ID:
1804 if (std::error_code EC = ParseConstants())
1806 if (std::error_code EC = ResolveGlobalAndAliasInits())
1809 case bitc::METADATA_BLOCK_ID:
1810 if (std::error_code EC = ParseMetadata())
1813 case bitc::FUNCTION_BLOCK_ID:
1814 // If this is the first function body we've seen, reverse the
1815 // FunctionsWithBodies list.
1816 if (!SeenFirstFunctionBody) {
1817 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1818 if (std::error_code EC = GlobalCleanup())
1820 SeenFirstFunctionBody = true;
1823 if (std::error_code EC = RememberAndSkipFunctionBody())
1825 // For streaming bitcode, suspend parsing when we reach the function
1826 // bodies. Subsequent materialization calls will resume it when
1827 // necessary. For streaming, the function bodies must be at the end of
1828 // the bitcode. If the bitcode file is old, the symbol table will be
1829 // at the end instead and will not have been seen yet. In this case,
1830 // just finish the parse now.
1831 if (LazyStreamer && SeenValueSymbolTable) {
1832 NextUnreadBit = Stream.GetCurrentBitNo();
1833 return std::error_code();
1836 case bitc::USELIST_BLOCK_ID:
1837 if (std::error_code EC = ParseUseLists())
1843 case BitstreamEntry::Record:
1844 // The interesting case.
1850 switch (Stream.readRecord(Entry.ID, Record)) {
1851 default: break; // Default behavior, ignore unknown content.
1852 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1853 if (Record.size() < 1)
1854 return Error(BitcodeError::InvalidRecord);
1855 // Only version #0 and #1 are supported so far.
1856 unsigned module_version = Record[0];
1857 switch (module_version) {
1859 return Error(BitcodeError::InvalidValue);
1861 UseRelativeIDs = false;
1864 UseRelativeIDs = true;
1869 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1871 if (ConvertToString(Record, 0, S))
1872 return Error(BitcodeError::InvalidRecord);
1873 TheModule->setTargetTriple(S);
1876 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1878 if (ConvertToString(Record, 0, S))
1879 return Error(BitcodeError::InvalidRecord);
1880 TheModule->setDataLayout(S);
1883 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1885 if (ConvertToString(Record, 0, S))
1886 return Error(BitcodeError::InvalidRecord);
1887 TheModule->setModuleInlineAsm(S);
1890 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1891 // FIXME: Remove in 4.0.
1893 if (ConvertToString(Record, 0, S))
1894 return Error(BitcodeError::InvalidRecord);
1898 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1900 if (ConvertToString(Record, 0, S))
1901 return Error(BitcodeError::InvalidRecord);
1902 SectionTable.push_back(S);
1905 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1907 if (ConvertToString(Record, 0, S))
1908 return Error(BitcodeError::InvalidRecord);
1909 GCTable.push_back(S);
1912 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1913 if (Record.size() < 2)
1914 return Error(BitcodeError::InvalidRecord);
1915 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1916 unsigned ComdatNameSize = Record[1];
1917 std::string ComdatName;
1918 ComdatName.reserve(ComdatNameSize);
1919 for (unsigned i = 0; i != ComdatNameSize; ++i)
1920 ComdatName += (char)Record[2 + i];
1921 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1922 C->setSelectionKind(SK);
1923 ComdatList.push_back(C);
1926 // GLOBALVAR: [pointer type, isconst, initid,
1927 // linkage, alignment, section, visibility, threadlocal,
1928 // unnamed_addr, dllstorageclass]
1929 case bitc::MODULE_CODE_GLOBALVAR: {
1930 if (Record.size() < 6)
1931 return Error(BitcodeError::InvalidRecord);
1932 Type *Ty = getTypeByID(Record[0]);
1934 return Error(BitcodeError::InvalidRecord);
1935 if (!Ty->isPointerTy())
1936 return Error(BitcodeError::InvalidTypeForValue);
1937 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1938 Ty = cast<PointerType>(Ty)->getElementType();
1940 bool isConstant = Record[1];
1941 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1942 unsigned Alignment = (1 << Record[4]) >> 1;
1943 std::string Section;
1945 if (Record[5]-1 >= SectionTable.size())
1946 return Error(BitcodeError::InvalidID);
1947 Section = SectionTable[Record[5]-1];
1949 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1950 // Local linkage must have default visibility.
1951 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1952 // FIXME: Change to an error if non-default in 4.0.
1953 Visibility = GetDecodedVisibility(Record[6]);
1955 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1956 if (Record.size() > 7)
1957 TLM = GetDecodedThreadLocalMode(Record[7]);
1959 bool UnnamedAddr = false;
1960 if (Record.size() > 8)
1961 UnnamedAddr = Record[8];
1963 bool ExternallyInitialized = false;
1964 if (Record.size() > 9)
1965 ExternallyInitialized = Record[9];
1967 GlobalVariable *NewGV =
1968 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1969 TLM, AddressSpace, ExternallyInitialized);
1970 NewGV->setAlignment(Alignment);
1971 if (!Section.empty())
1972 NewGV->setSection(Section);
1973 NewGV->setVisibility(Visibility);
1974 NewGV->setUnnamedAddr(UnnamedAddr);
1976 if (Record.size() > 10)
1977 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1979 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1981 ValueList.push_back(NewGV);
1983 // Remember which value to use for the global initializer.
1984 if (unsigned InitID = Record[2])
1985 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1987 if (Record.size() > 11)
1988 if (unsigned ComdatID = Record[11]) {
1989 assert(ComdatID <= ComdatList.size());
1990 NewGV->setComdat(ComdatList[ComdatID - 1]);
1994 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1995 // alignment, section, visibility, gc, unnamed_addr,
1997 case bitc::MODULE_CODE_FUNCTION: {
1998 if (Record.size() < 8)
1999 return Error(BitcodeError::InvalidRecord);
2000 Type *Ty = getTypeByID(Record[0]);
2002 return Error(BitcodeError::InvalidRecord);
2003 if (!Ty->isPointerTy())
2004 return Error(BitcodeError::InvalidTypeForValue);
2006 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2008 return Error(BitcodeError::InvalidTypeForValue);
2010 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2013 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2014 bool isProto = Record[2];
2015 Func->setLinkage(GetDecodedLinkage(Record[3]));
2016 Func->setAttributes(getAttributes(Record[4]));
2018 Func->setAlignment((1 << Record[5]) >> 1);
2020 if (Record[6]-1 >= SectionTable.size())
2021 return Error(BitcodeError::InvalidID);
2022 Func->setSection(SectionTable[Record[6]-1]);
2024 // Local linkage must have default visibility.
2025 if (!Func->hasLocalLinkage())
2026 // FIXME: Change to an error if non-default in 4.0.
2027 Func->setVisibility(GetDecodedVisibility(Record[7]));
2028 if (Record.size() > 8 && Record[8]) {
2029 if (Record[8]-1 > GCTable.size())
2030 return Error(BitcodeError::InvalidID);
2031 Func->setGC(GCTable[Record[8]-1].c_str());
2033 bool UnnamedAddr = false;
2034 if (Record.size() > 9)
2035 UnnamedAddr = Record[9];
2036 Func->setUnnamedAddr(UnnamedAddr);
2037 if (Record.size() > 10 && Record[10] != 0)
2038 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
2040 if (Record.size() > 11)
2041 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2043 UpgradeDLLImportExportLinkage(Func, Record[3]);
2045 if (Record.size() > 12)
2046 if (unsigned ComdatID = Record[12]) {
2047 assert(ComdatID <= ComdatList.size());
2048 Func->setComdat(ComdatList[ComdatID - 1]);
2051 ValueList.push_back(Func);
2053 // If this is a function with a body, remember the prototype we are
2054 // creating now, so that we can match up the body with them later.
2056 FunctionsWithBodies.push_back(Func);
2057 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
2061 // ALIAS: [alias type, aliasee val#, linkage]
2062 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2063 case bitc::MODULE_CODE_ALIAS: {
2064 if (Record.size() < 3)
2065 return Error(BitcodeError::InvalidRecord);
2066 Type *Ty = getTypeByID(Record[0]);
2068 return Error(BitcodeError::InvalidRecord);
2069 auto *PTy = dyn_cast<PointerType>(Ty);
2071 return Error(BitcodeError::InvalidTypeForValue);
2074 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2075 GetDecodedLinkage(Record[2]), "", TheModule);
2076 // Old bitcode files didn't have visibility field.
2077 // Local linkage must have default visibility.
2078 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2079 // FIXME: Change to an error if non-default in 4.0.
2080 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2081 if (Record.size() > 4)
2082 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2084 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2085 if (Record.size() > 5)
2086 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2087 if (Record.size() > 6)
2088 NewGA->setUnnamedAddr(Record[6]);
2089 ValueList.push_back(NewGA);
2090 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2093 /// MODULE_CODE_PURGEVALS: [numvals]
2094 case bitc::MODULE_CODE_PURGEVALS:
2095 // Trim down the value list to the specified size.
2096 if (Record.size() < 1 || Record[0] > ValueList.size())
2097 return Error(BitcodeError::InvalidRecord);
2098 ValueList.shrinkTo(Record[0]);
2105 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2106 TheModule = nullptr;
2108 if (std::error_code EC = InitStream())
2111 // Sniff for the signature.
2112 if (Stream.Read(8) != 'B' ||
2113 Stream.Read(8) != 'C' ||
2114 Stream.Read(4) != 0x0 ||
2115 Stream.Read(4) != 0xC ||
2116 Stream.Read(4) != 0xE ||
2117 Stream.Read(4) != 0xD)
2118 return Error(BitcodeError::InvalidBitcodeSignature);
2120 // We expect a number of well-defined blocks, though we don't necessarily
2121 // need to understand them all.
2123 if (Stream.AtEndOfStream())
2124 return std::error_code();
2126 BitstreamEntry Entry =
2127 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2129 switch (Entry.Kind) {
2130 case BitstreamEntry::Error:
2131 return Error(BitcodeError::MalformedBlock);
2132 case BitstreamEntry::EndBlock:
2133 return std::error_code();
2135 case BitstreamEntry::SubBlock:
2137 case bitc::BLOCKINFO_BLOCK_ID:
2138 if (Stream.ReadBlockInfoBlock())
2139 return Error(BitcodeError::MalformedBlock);
2141 case bitc::MODULE_BLOCK_ID:
2142 // Reject multiple MODULE_BLOCK's in a single bitstream.
2144 return Error(BitcodeError::InvalidMultipleBlocks);
2146 if (std::error_code EC = ParseModule(false))
2149 return std::error_code();
2152 if (Stream.SkipBlock())
2153 return Error(BitcodeError::InvalidRecord);
2157 case BitstreamEntry::Record:
2158 // There should be no records in the top-level of blocks.
2160 // The ranlib in Xcode 4 will align archive members by appending newlines
2161 // to the end of them. If this file size is a multiple of 4 but not 8, we
2162 // have to read and ignore these final 4 bytes :-(
2163 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2164 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2165 Stream.AtEndOfStream())
2166 return std::error_code();
2168 return Error(BitcodeError::InvalidRecord);
2173 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2174 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2175 return Error(BitcodeError::InvalidRecord);
2177 SmallVector<uint64_t, 64> Record;
2180 // Read all the records for this module.
2182 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2184 switch (Entry.Kind) {
2185 case BitstreamEntry::SubBlock: // Handled for us already.
2186 case BitstreamEntry::Error:
2187 return Error(BitcodeError::MalformedBlock);
2188 case BitstreamEntry::EndBlock:
2190 case BitstreamEntry::Record:
2191 // The interesting case.
2196 switch (Stream.readRecord(Entry.ID, Record)) {
2197 default: break; // Default behavior, ignore unknown content.
2198 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2200 if (ConvertToString(Record, 0, S))
2201 return Error(BitcodeError::InvalidRecord);
2208 llvm_unreachable("Exit infinite loop");
2211 ErrorOr<std::string> BitcodeReader::parseTriple() {
2212 if (std::error_code EC = InitStream())
2215 // Sniff for the signature.
2216 if (Stream.Read(8) != 'B' ||
2217 Stream.Read(8) != 'C' ||
2218 Stream.Read(4) != 0x0 ||
2219 Stream.Read(4) != 0xC ||
2220 Stream.Read(4) != 0xE ||
2221 Stream.Read(4) != 0xD)
2222 return Error(BitcodeError::InvalidBitcodeSignature);
2224 // We expect a number of well-defined blocks, though we don't necessarily
2225 // need to understand them all.
2227 BitstreamEntry Entry = Stream.advance();
2229 switch (Entry.Kind) {
2230 case BitstreamEntry::Error:
2231 return Error(BitcodeError::MalformedBlock);
2232 case BitstreamEntry::EndBlock:
2233 return std::error_code();
2235 case BitstreamEntry::SubBlock:
2236 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2237 return parseModuleTriple();
2239 // Ignore other sub-blocks.
2240 if (Stream.SkipBlock())
2241 return Error(BitcodeError::MalformedBlock);
2244 case BitstreamEntry::Record:
2245 Stream.skipRecord(Entry.ID);
2251 /// ParseMetadataAttachment - Parse metadata attachments.
2252 std::error_code BitcodeReader::ParseMetadataAttachment() {
2253 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2254 return Error(BitcodeError::InvalidRecord);
2256 SmallVector<uint64_t, 64> Record;
2258 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2260 switch (Entry.Kind) {
2261 case BitstreamEntry::SubBlock: // Handled for us already.
2262 case BitstreamEntry::Error:
2263 return Error(BitcodeError::MalformedBlock);
2264 case BitstreamEntry::EndBlock:
2265 return std::error_code();
2266 case BitstreamEntry::Record:
2267 // The interesting case.
2271 // Read a metadata attachment record.
2273 switch (Stream.readRecord(Entry.ID, Record)) {
2274 default: // Default behavior: ignore.
2276 case bitc::METADATA_ATTACHMENT: {
2277 unsigned RecordLength = Record.size();
2278 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2279 return Error(BitcodeError::InvalidRecord);
2280 Instruction *Inst = InstructionList[Record[0]];
2281 for (unsigned i = 1; i != RecordLength; i = i+2) {
2282 unsigned Kind = Record[i];
2283 DenseMap<unsigned, unsigned>::iterator I =
2284 MDKindMap.find(Kind);
2285 if (I == MDKindMap.end())
2286 return Error(BitcodeError::InvalidID);
2287 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2288 Inst->setMetadata(I->second, cast<MDNode>(Node));
2289 if (I->second == LLVMContext::MD_tbaa)
2290 InstsWithTBAATag.push_back(Inst);
2298 /// ParseFunctionBody - Lazily parse the specified function body block.
2299 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2300 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2301 return Error(BitcodeError::InvalidRecord);
2303 InstructionList.clear();
2304 unsigned ModuleValueListSize = ValueList.size();
2305 unsigned ModuleMDValueListSize = MDValueList.size();
2307 // Add all the function arguments to the value table.
2308 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2309 ValueList.push_back(I);
2311 unsigned NextValueNo = ValueList.size();
2312 BasicBlock *CurBB = nullptr;
2313 unsigned CurBBNo = 0;
2317 // Read all the records.
2318 SmallVector<uint64_t, 64> Record;
2320 BitstreamEntry Entry = Stream.advance();
2322 switch (Entry.Kind) {
2323 case BitstreamEntry::Error:
2324 return Error(BitcodeError::MalformedBlock);
2325 case BitstreamEntry::EndBlock:
2326 goto OutOfRecordLoop;
2328 case BitstreamEntry::SubBlock:
2330 default: // Skip unknown content.
2331 if (Stream.SkipBlock())
2332 return Error(BitcodeError::InvalidRecord);
2334 case bitc::CONSTANTS_BLOCK_ID:
2335 if (std::error_code EC = ParseConstants())
2337 NextValueNo = ValueList.size();
2339 case bitc::VALUE_SYMTAB_BLOCK_ID:
2340 if (std::error_code EC = ParseValueSymbolTable())
2343 case bitc::METADATA_ATTACHMENT_ID:
2344 if (std::error_code EC = ParseMetadataAttachment())
2347 case bitc::METADATA_BLOCK_ID:
2348 if (std::error_code EC = ParseMetadata())
2351 case bitc::USELIST_BLOCK_ID:
2352 if (std::error_code EC = ParseUseLists())
2358 case BitstreamEntry::Record:
2359 // The interesting case.
2365 Instruction *I = nullptr;
2366 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2368 default: // Default behavior: reject
2369 return Error(BitcodeError::InvalidValue);
2370 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
2371 if (Record.size() < 1 || Record[0] == 0)
2372 return Error(BitcodeError::InvalidRecord);
2373 // Create all the basic blocks for the function.
2374 FunctionBBs.resize(Record[0]);
2375 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2376 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2377 CurBB = FunctionBBs[0];
2380 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2381 // This record indicates that the last instruction is at the same
2382 // location as the previous instruction with a location.
2385 // Get the last instruction emitted.
2386 if (CurBB && !CurBB->empty())
2388 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2389 !FunctionBBs[CurBBNo-1]->empty())
2390 I = &FunctionBBs[CurBBNo-1]->back();
2393 return Error(BitcodeError::InvalidRecord);
2394 I->setDebugLoc(LastLoc);
2398 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2399 I = nullptr; // Get the last instruction emitted.
2400 if (CurBB && !CurBB->empty())
2402 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2403 !FunctionBBs[CurBBNo-1]->empty())
2404 I = &FunctionBBs[CurBBNo-1]->back();
2405 if (!I || Record.size() < 4)
2406 return Error(BitcodeError::InvalidRecord);
2408 unsigned Line = Record[0], Col = Record[1];
2409 unsigned ScopeID = Record[2], IAID = Record[3];
2411 MDNode *Scope = nullptr, *IA = nullptr;
2412 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2413 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2414 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2415 I->setDebugLoc(LastLoc);
2420 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2423 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2424 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2425 OpNum+1 > Record.size())
2426 return Error(BitcodeError::InvalidRecord);
2428 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2430 return Error(BitcodeError::InvalidRecord);
2431 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2432 InstructionList.push_back(I);
2433 if (OpNum < Record.size()) {
2434 if (Opc == Instruction::Add ||
2435 Opc == Instruction::Sub ||
2436 Opc == Instruction::Mul ||
2437 Opc == Instruction::Shl) {
2438 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2439 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2440 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2441 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2442 } else if (Opc == Instruction::SDiv ||
2443 Opc == Instruction::UDiv ||
2444 Opc == Instruction::LShr ||
2445 Opc == Instruction::AShr) {
2446 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2447 cast<BinaryOperator>(I)->setIsExact(true);
2448 } else if (isa<FPMathOperator>(I)) {
2450 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2451 FMF.setUnsafeAlgebra();
2452 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2454 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2456 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2457 FMF.setNoSignedZeros();
2458 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2459 FMF.setAllowReciprocal();
2461 I->setFastMathFlags(FMF);
2467 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2470 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2471 OpNum+2 != Record.size())
2472 return Error(BitcodeError::InvalidRecord);
2474 Type *ResTy = getTypeByID(Record[OpNum]);
2475 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2476 if (Opc == -1 || !ResTy)
2477 return Error(BitcodeError::InvalidRecord);
2478 Instruction *Temp = nullptr;
2479 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2481 InstructionList.push_back(Temp);
2482 CurBB->getInstList().push_back(Temp);
2485 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2487 InstructionList.push_back(I);
2490 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2491 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2494 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2495 return Error(BitcodeError::InvalidRecord);
2497 SmallVector<Value*, 16> GEPIdx;
2498 while (OpNum != Record.size()) {
2500 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2501 return Error(BitcodeError::InvalidRecord);
2502 GEPIdx.push_back(Op);
2505 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2506 InstructionList.push_back(I);
2507 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2508 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2512 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2513 // EXTRACTVAL: [opty, opval, n x indices]
2516 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2517 return Error(BitcodeError::InvalidRecord);
2519 SmallVector<unsigned, 4> EXTRACTVALIdx;
2520 for (unsigned RecSize = Record.size();
2521 OpNum != RecSize; ++OpNum) {
2522 uint64_t Index = Record[OpNum];
2523 if ((unsigned)Index != Index)
2524 return Error(BitcodeError::InvalidValue);
2525 EXTRACTVALIdx.push_back((unsigned)Index);
2528 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2529 InstructionList.push_back(I);
2533 case bitc::FUNC_CODE_INST_INSERTVAL: {
2534 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2537 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2538 return Error(BitcodeError::InvalidRecord);
2540 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2541 return Error(BitcodeError::InvalidRecord);
2543 SmallVector<unsigned, 4> INSERTVALIdx;
2544 for (unsigned RecSize = Record.size();
2545 OpNum != RecSize; ++OpNum) {
2546 uint64_t Index = Record[OpNum];
2547 if ((unsigned)Index != Index)
2548 return Error(BitcodeError::InvalidValue);
2549 INSERTVALIdx.push_back((unsigned)Index);
2552 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2553 InstructionList.push_back(I);
2557 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2558 // obsolete form of select
2559 // handles select i1 ... in old bitcode
2561 Value *TrueVal, *FalseVal, *Cond;
2562 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2563 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2564 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2565 return Error(BitcodeError::InvalidRecord);
2567 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2568 InstructionList.push_back(I);
2572 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2573 // new form of select
2574 // handles select i1 or select [N x i1]
2576 Value *TrueVal, *FalseVal, *Cond;
2577 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2578 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2579 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2580 return Error(BitcodeError::InvalidRecord);
2582 // select condition can be either i1 or [N x i1]
2583 if (VectorType* vector_type =
2584 dyn_cast<VectorType>(Cond->getType())) {
2586 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2587 return Error(BitcodeError::InvalidTypeForValue);
2590 if (Cond->getType() != Type::getInt1Ty(Context))
2591 return Error(BitcodeError::InvalidTypeForValue);
2594 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2595 InstructionList.push_back(I);
2599 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2602 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2603 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2604 return Error(BitcodeError::InvalidRecord);
2605 I = ExtractElementInst::Create(Vec, Idx);
2606 InstructionList.push_back(I);
2610 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2612 Value *Vec, *Elt, *Idx;
2613 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2614 popValue(Record, OpNum, NextValueNo,
2615 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2616 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2617 return Error(BitcodeError::InvalidRecord);
2618 I = InsertElementInst::Create(Vec, Elt, Idx);
2619 InstructionList.push_back(I);
2623 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2625 Value *Vec1, *Vec2, *Mask;
2626 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2627 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2628 return Error(BitcodeError::InvalidRecord);
2630 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2631 return Error(BitcodeError::InvalidRecord);
2632 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2633 InstructionList.push_back(I);
2637 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2638 // Old form of ICmp/FCmp returning bool
2639 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2640 // both legal on vectors but had different behaviour.
2641 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2642 // FCmp/ICmp returning bool or vector of bool
2646 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2647 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2648 OpNum+1 != Record.size())
2649 return Error(BitcodeError::InvalidRecord);
2651 if (LHS->getType()->isFPOrFPVectorTy())
2652 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2654 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2655 InstructionList.push_back(I);
2659 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2661 unsigned Size = Record.size();
2663 I = ReturnInst::Create(Context);
2664 InstructionList.push_back(I);
2669 Value *Op = nullptr;
2670 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2671 return Error(BitcodeError::InvalidRecord);
2672 if (OpNum != Record.size())
2673 return Error(BitcodeError::InvalidRecord);
2675 I = ReturnInst::Create(Context, Op);
2676 InstructionList.push_back(I);
2679 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2680 if (Record.size() != 1 && Record.size() != 3)
2681 return Error(BitcodeError::InvalidRecord);
2682 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2684 return Error(BitcodeError::InvalidRecord);
2686 if (Record.size() == 1) {
2687 I = BranchInst::Create(TrueDest);
2688 InstructionList.push_back(I);
2691 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2692 Value *Cond = getValue(Record, 2, NextValueNo,
2693 Type::getInt1Ty(Context));
2694 if (!FalseDest || !Cond)
2695 return Error(BitcodeError::InvalidRecord);
2696 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2697 InstructionList.push_back(I);
2701 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2703 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2704 // "New" SwitchInst format with case ranges. The changes to write this
2705 // format were reverted but we still recognize bitcode that uses it.
2706 // Hopefully someday we will have support for case ranges and can use
2707 // this format again.
2709 Type *OpTy = getTypeByID(Record[1]);
2710 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2712 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2713 BasicBlock *Default = getBasicBlock(Record[3]);
2714 if (!OpTy || !Cond || !Default)
2715 return Error(BitcodeError::InvalidRecord);
2717 unsigned NumCases = Record[4];
2719 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2720 InstructionList.push_back(SI);
2722 unsigned CurIdx = 5;
2723 for (unsigned i = 0; i != NumCases; ++i) {
2724 SmallVector<ConstantInt*, 1> CaseVals;
2725 unsigned NumItems = Record[CurIdx++];
2726 for (unsigned ci = 0; ci != NumItems; ++ci) {
2727 bool isSingleNumber = Record[CurIdx++];
2730 unsigned ActiveWords = 1;
2731 if (ValueBitWidth > 64)
2732 ActiveWords = Record[CurIdx++];
2733 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2735 CurIdx += ActiveWords;
2737 if (!isSingleNumber) {
2739 if (ValueBitWidth > 64)
2740 ActiveWords = Record[CurIdx++];
2742 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2744 CurIdx += ActiveWords;
2746 // FIXME: It is not clear whether values in the range should be
2747 // compared as signed or unsigned values. The partially
2748 // implemented changes that used this format in the past used
2749 // unsigned comparisons.
2750 for ( ; Low.ule(High); ++Low)
2751 CaseVals.push_back(ConstantInt::get(Context, Low));
2753 CaseVals.push_back(ConstantInt::get(Context, Low));
2755 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2756 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2757 cve = CaseVals.end(); cvi != cve; ++cvi)
2758 SI->addCase(*cvi, DestBB);
2764 // Old SwitchInst format without case ranges.
2766 if (Record.size() < 3 || (Record.size() & 1) == 0)
2767 return Error(BitcodeError::InvalidRecord);
2768 Type *OpTy = getTypeByID(Record[0]);
2769 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2770 BasicBlock *Default = getBasicBlock(Record[2]);
2771 if (!OpTy || !Cond || !Default)
2772 return Error(BitcodeError::InvalidRecord);
2773 unsigned NumCases = (Record.size()-3)/2;
2774 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2775 InstructionList.push_back(SI);
2776 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2777 ConstantInt *CaseVal =
2778 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2779 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2780 if (!CaseVal || !DestBB) {
2782 return Error(BitcodeError::InvalidRecord);
2784 SI->addCase(CaseVal, DestBB);
2789 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2790 if (Record.size() < 2)
2791 return Error(BitcodeError::InvalidRecord);
2792 Type *OpTy = getTypeByID(Record[0]);
2793 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2794 if (!OpTy || !Address)
2795 return Error(BitcodeError::InvalidRecord);
2796 unsigned NumDests = Record.size()-2;
2797 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2798 InstructionList.push_back(IBI);
2799 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2800 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2801 IBI->addDestination(DestBB);
2804 return Error(BitcodeError::InvalidRecord);
2811 case bitc::FUNC_CODE_INST_INVOKE: {
2812 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2813 if (Record.size() < 4)
2814 return Error(BitcodeError::InvalidRecord);
2815 AttributeSet PAL = getAttributes(Record[0]);
2816 unsigned CCInfo = Record[1];
2817 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2818 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2822 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2823 return Error(BitcodeError::InvalidRecord);
2825 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2826 FunctionType *FTy = !CalleeTy ? nullptr :
2827 dyn_cast<FunctionType>(CalleeTy->getElementType());
2829 // Check that the right number of fixed parameters are here.
2830 if (!FTy || !NormalBB || !UnwindBB ||
2831 Record.size() < OpNum+FTy->getNumParams())
2832 return Error(BitcodeError::InvalidRecord);
2834 SmallVector<Value*, 16> Ops;
2835 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2836 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2837 FTy->getParamType(i)));
2839 return Error(BitcodeError::InvalidRecord);
2842 if (!FTy->isVarArg()) {
2843 if (Record.size() != OpNum)
2844 return Error(BitcodeError::InvalidRecord);
2846 // Read type/value pairs for varargs params.
2847 while (OpNum != Record.size()) {
2849 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2850 return Error(BitcodeError::InvalidRecord);
2855 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2856 InstructionList.push_back(I);
2857 cast<InvokeInst>(I)->setCallingConv(
2858 static_cast<CallingConv::ID>(CCInfo));
2859 cast<InvokeInst>(I)->setAttributes(PAL);
2862 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2864 Value *Val = nullptr;
2865 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2866 return Error(BitcodeError::InvalidRecord);
2867 I = ResumeInst::Create(Val);
2868 InstructionList.push_back(I);
2871 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2872 I = new UnreachableInst(Context);
2873 InstructionList.push_back(I);
2875 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2876 if (Record.size() < 1 || ((Record.size()-1)&1))
2877 return Error(BitcodeError::InvalidRecord);
2878 Type *Ty = getTypeByID(Record[0]);
2880 return Error(BitcodeError::InvalidRecord);
2882 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2883 InstructionList.push_back(PN);
2885 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2887 // With the new function encoding, it is possible that operands have
2888 // negative IDs (for forward references). Use a signed VBR
2889 // representation to keep the encoding small.
2891 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2893 V = getValue(Record, 1+i, NextValueNo, Ty);
2894 BasicBlock *BB = getBasicBlock(Record[2+i]);
2896 return Error(BitcodeError::InvalidRecord);
2897 PN->addIncoming(V, BB);
2903 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2904 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2906 if (Record.size() < 4)
2907 return Error(BitcodeError::InvalidRecord);
2908 Type *Ty = getTypeByID(Record[Idx++]);
2910 return Error(BitcodeError::InvalidRecord);
2911 Value *PersFn = nullptr;
2912 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2913 return Error(BitcodeError::InvalidRecord);
2915 bool IsCleanup = !!Record[Idx++];
2916 unsigned NumClauses = Record[Idx++];
2917 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2918 LP->setCleanup(IsCleanup);
2919 for (unsigned J = 0; J != NumClauses; ++J) {
2920 LandingPadInst::ClauseType CT =
2921 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2924 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2926 return Error(BitcodeError::InvalidRecord);
2929 assert((CT != LandingPadInst::Catch ||
2930 !isa<ArrayType>(Val->getType())) &&
2931 "Catch clause has a invalid type!");
2932 assert((CT != LandingPadInst::Filter ||
2933 isa<ArrayType>(Val->getType())) &&
2934 "Filter clause has invalid type!");
2935 LP->addClause(cast<Constant>(Val));
2939 InstructionList.push_back(I);
2943 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2944 if (Record.size() != 4)
2945 return Error(BitcodeError::InvalidRecord);
2947 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2948 Type *OpTy = getTypeByID(Record[1]);
2949 Value *Size = getFnValueByID(Record[2], OpTy);
2950 unsigned AlignRecord = Record[3];
2951 bool InAlloca = AlignRecord & (1 << 5);
2952 unsigned Align = AlignRecord & ((1 << 5) - 1);
2954 return Error(BitcodeError::InvalidRecord);
2955 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2956 AI->setUsedWithInAlloca(InAlloca);
2958 InstructionList.push_back(I);
2961 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2964 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2965 OpNum+2 != Record.size())
2966 return Error(BitcodeError::InvalidRecord);
2968 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2969 InstructionList.push_back(I);
2972 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2973 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2976 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2977 OpNum+4 != Record.size())
2978 return Error(BitcodeError::InvalidRecord);
2980 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2981 if (Ordering == NotAtomic || Ordering == Release ||
2982 Ordering == AcquireRelease)
2983 return Error(BitcodeError::InvalidRecord);
2984 if (Ordering != NotAtomic && Record[OpNum] == 0)
2985 return Error(BitcodeError::InvalidRecord);
2986 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2988 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2989 Ordering, SynchScope);
2990 InstructionList.push_back(I);
2993 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2996 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2997 popValue(Record, OpNum, NextValueNo,
2998 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2999 OpNum+2 != Record.size())
3000 return Error(BitcodeError::InvalidRecord);
3002 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3003 InstructionList.push_back(I);
3006 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3007 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3010 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3011 popValue(Record, OpNum, NextValueNo,
3012 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3013 OpNum+4 != Record.size())
3014 return Error(BitcodeError::InvalidRecord);
3016 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3017 if (Ordering == NotAtomic || Ordering == Acquire ||
3018 Ordering == AcquireRelease)
3019 return Error(BitcodeError::InvalidRecord);
3020 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3021 if (Ordering != NotAtomic && Record[OpNum] == 0)
3022 return Error(BitcodeError::InvalidRecord);
3024 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3025 Ordering, SynchScope);
3026 InstructionList.push_back(I);
3029 case bitc::FUNC_CODE_INST_CMPXCHG: {
3030 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3031 // failureordering?, isweak?]
3033 Value *Ptr, *Cmp, *New;
3034 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3035 popValue(Record, OpNum, NextValueNo,
3036 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3037 popValue(Record, OpNum, NextValueNo,
3038 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3039 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3040 return Error(BitcodeError::InvalidRecord);
3041 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3042 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3043 return Error(BitcodeError::InvalidRecord);
3044 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3046 AtomicOrdering FailureOrdering;
3047 if (Record.size() < 7)
3049 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3051 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3053 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3055 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3057 if (Record.size() < 8) {
3058 // Before weak cmpxchgs existed, the instruction simply returned the
3059 // value loaded from memory, so bitcode files from that era will be
3060 // expecting the first component of a modern cmpxchg.
3061 CurBB->getInstList().push_back(I);
3062 I = ExtractValueInst::Create(I, 0);
3064 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3067 InstructionList.push_back(I);
3070 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3071 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3074 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3075 popValue(Record, OpNum, NextValueNo,
3076 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3077 OpNum+4 != Record.size())
3078 return Error(BitcodeError::InvalidRecord);
3079 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3080 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3081 Operation > AtomicRMWInst::LAST_BINOP)
3082 return Error(BitcodeError::InvalidRecord);
3083 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3084 if (Ordering == NotAtomic || Ordering == Unordered)
3085 return Error(BitcodeError::InvalidRecord);
3086 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3087 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3088 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3089 InstructionList.push_back(I);
3092 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3093 if (2 != Record.size())
3094 return Error(BitcodeError::InvalidRecord);
3095 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3096 if (Ordering == NotAtomic || Ordering == Unordered ||
3097 Ordering == Monotonic)
3098 return Error(BitcodeError::InvalidRecord);
3099 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3100 I = new FenceInst(Context, Ordering, SynchScope);
3101 InstructionList.push_back(I);
3104 case bitc::FUNC_CODE_INST_CALL: {
3105 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3106 if (Record.size() < 3)
3107 return Error(BitcodeError::InvalidRecord);
3109 AttributeSet PAL = getAttributes(Record[0]);
3110 unsigned CCInfo = Record[1];
3114 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3115 return Error(BitcodeError::InvalidRecord);
3117 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3118 FunctionType *FTy = nullptr;
3119 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3120 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3121 return Error(BitcodeError::InvalidRecord);
3123 SmallVector<Value*, 16> Args;
3124 // Read the fixed params.
3125 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3126 if (FTy->getParamType(i)->isLabelTy())
3127 Args.push_back(getBasicBlock(Record[OpNum]));
3129 Args.push_back(getValue(Record, OpNum, NextValueNo,
3130 FTy->getParamType(i)));
3132 return Error(BitcodeError::InvalidRecord);
3135 // Read type/value pairs for varargs params.
3136 if (!FTy->isVarArg()) {
3137 if (OpNum != Record.size())
3138 return Error(BitcodeError::InvalidRecord);
3140 while (OpNum != Record.size()) {
3142 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3143 return Error(BitcodeError::InvalidRecord);
3148 I = CallInst::Create(Callee, Args);
3149 InstructionList.push_back(I);
3150 cast<CallInst>(I)->setCallingConv(
3151 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3152 CallInst::TailCallKind TCK = CallInst::TCK_None;
3154 TCK = CallInst::TCK_Tail;
3155 if (CCInfo & (1 << 14))
3156 TCK = CallInst::TCK_MustTail;
3157 cast<CallInst>(I)->setTailCallKind(TCK);
3158 cast<CallInst>(I)->setAttributes(PAL);
3161 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3162 if (Record.size() < 3)
3163 return Error(BitcodeError::InvalidRecord);
3164 Type *OpTy = getTypeByID(Record[0]);
3165 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3166 Type *ResTy = getTypeByID(Record[2]);
3167 if (!OpTy || !Op || !ResTy)
3168 return Error(BitcodeError::InvalidRecord);
3169 I = new VAArgInst(Op, ResTy);
3170 InstructionList.push_back(I);
3175 // Add instruction to end of current BB. If there is no current BB, reject
3179 return Error(BitcodeError::InvalidInstructionWithNoBB);
3181 CurBB->getInstList().push_back(I);
3183 // If this was a terminator instruction, move to the next block.
3184 if (isa<TerminatorInst>(I)) {
3186 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3189 // Non-void values get registered in the value table for future use.
3190 if (I && !I->getType()->isVoidTy())
3191 ValueList.AssignValue(I, NextValueNo++);
3196 // Check the function list for unresolved values.
3197 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3198 if (!A->getParent()) {
3199 // We found at least one unresolved value. Nuke them all to avoid leaks.
3200 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3201 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3202 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3206 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3210 // FIXME: Check for unresolved forward-declared metadata references
3211 // and clean up leaks.
3213 // See if anything took the address of blocks in this function. If so,
3214 // resolve them now.
3215 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3216 BlockAddrFwdRefs.find(F);
3217 if (BAFRI != BlockAddrFwdRefs.end()) {
3218 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3219 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3220 unsigned BlockIdx = RefList[i].first;
3221 if (BlockIdx >= FunctionBBs.size())
3222 return Error(BitcodeError::InvalidID);
3224 GlobalVariable *FwdRef = RefList[i].second;
3225 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3226 FwdRef->eraseFromParent();
3229 BlockAddrFwdRefs.erase(BAFRI);
3232 // Trim the value list down to the size it was before we parsed this function.
3233 ValueList.shrinkTo(ModuleValueListSize);
3234 MDValueList.shrinkTo(ModuleMDValueListSize);
3235 std::vector<BasicBlock*>().swap(FunctionBBs);
3236 return std::error_code();
3239 /// Find the function body in the bitcode stream
3240 std::error_code BitcodeReader::FindFunctionInStream(
3242 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3243 while (DeferredFunctionInfoIterator->second == 0) {
3244 if (Stream.AtEndOfStream())
3245 return Error(BitcodeError::CouldNotFindFunctionInStream);
3246 // ParseModule will parse the next body in the stream and set its
3247 // position in the DeferredFunctionInfo map.
3248 if (std::error_code EC = ParseModule(true))
3251 return std::error_code();
3254 //===----------------------------------------------------------------------===//
3255 // GVMaterializer implementation
3256 //===----------------------------------------------------------------------===//
3258 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3260 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3261 if (const Function *F = dyn_cast<Function>(GV)) {
3262 return F->isDeclaration() &&
3263 DeferredFunctionInfo.count(const_cast<Function*>(F));
3268 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
3269 Function *F = dyn_cast<Function>(GV);
3270 // If it's not a function or is already material, ignore the request.
3271 if (!F || !F->isMaterializable())
3272 return std::error_code();
3274 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3275 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3276 // If its position is recorded as 0, its body is somewhere in the stream
3277 // but we haven't seen it yet.
3278 if (DFII->second == 0 && LazyStreamer)
3279 if (std::error_code EC = FindFunctionInStream(F, DFII))
3282 // Move the bit stream to the saved position of the deferred function body.
3283 Stream.JumpToBit(DFII->second);
3285 if (std::error_code EC = ParseFunctionBody(F))
3288 // Upgrade any old intrinsic calls in the function.
3289 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3290 E = UpgradedIntrinsics.end(); I != E; ++I) {
3291 if (I->first != I->second) {
3292 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3294 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3295 UpgradeIntrinsicCall(CI, I->second);
3300 // Bring in any functions that this function forward-referenced via
3302 return materializeForwardReferencedFunctions();
3305 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3306 const Function *F = dyn_cast<Function>(GV);
3307 if (!F || F->isDeclaration())
3310 // Dematerializing F would leave dangling references that wouldn't be
3311 // reconnected on re-materialization.
3312 if (BlockAddressesTaken.count(F))
3315 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3318 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3319 Function *F = dyn_cast<Function>(GV);
3320 // If this function isn't dematerializable, this is a noop.
3321 if (!F || !isDematerializable(F))
3324 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3326 // Just forget the function body, we can remat it later.
3330 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3331 assert(M == TheModule &&
3332 "Can only Materialize the Module this BitcodeReader is attached to.");
3334 // Promise to materialize all forward references.
3335 WillMaterializeAllForwardRefs = true;
3337 // Iterate over the module, deserializing any functions that are still on
3339 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3341 if (F->isMaterializable()) {
3342 if (std::error_code EC = Materialize(F))
3346 // At this point, if there are any function bodies, the current bit is
3347 // pointing to the END_BLOCK record after them. Now make sure the rest
3348 // of the bits in the module have been read.
3352 // Check that all block address forward references got resolved (as we
3354 if (!BlockAddrFwdRefs.empty())
3355 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3357 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3358 // delete the old functions to clean up. We can't do this unless the entire
3359 // module is materialized because there could always be another function body
3360 // with calls to the old function.
3361 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3362 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3363 if (I->first != I->second) {
3364 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3366 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3367 UpgradeIntrinsicCall(CI, I->second);
3369 if (!I->first->use_empty())
3370 I->first->replaceAllUsesWith(I->second);
3371 I->first->eraseFromParent();
3374 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3376 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3377 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3379 UpgradeDebugInfo(*M);
3380 return std::error_code();
3383 std::error_code BitcodeReader::InitStream() {
3385 return InitLazyStream();
3386 return InitStreamFromBuffer();
3389 std::error_code BitcodeReader::InitStreamFromBuffer() {
3390 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3391 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3393 if (Buffer->getBufferSize() & 3)
3394 return Error(BitcodeError::InvalidBitcodeSignature);
3396 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3397 // The magic number is 0x0B17C0DE stored in little endian.
3398 if (isBitcodeWrapper(BufPtr, BufEnd))
3399 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3400 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3402 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3403 Stream.init(*StreamFile);
3405 return std::error_code();
3408 std::error_code BitcodeReader::InitLazyStream() {
3409 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3411 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3412 StreamFile.reset(new BitstreamReader(Bytes));
3413 Stream.init(*StreamFile);
3415 unsigned char buf[16];
3416 if (Bytes->readBytes(0, 16, buf) == -1)
3417 return Error(BitcodeError::InvalidBitcodeSignature);
3419 if (!isBitcode(buf, buf + 16))
3420 return Error(BitcodeError::InvalidBitcodeSignature);
3422 if (isBitcodeWrapper(buf, buf + 4)) {
3423 const unsigned char *bitcodeStart = buf;
3424 const unsigned char *bitcodeEnd = buf + 16;
3425 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3426 Bytes->dropLeadingBytes(bitcodeStart - buf);
3427 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3429 return std::error_code();
3433 class BitcodeErrorCategoryType : public std::error_category {
3434 const char *name() const LLVM_NOEXCEPT override {
3435 return "llvm.bitcode";
3437 std::string message(int IE) const override {
3438 BitcodeError E = static_cast<BitcodeError>(IE);
3440 case BitcodeError::ConflictingMETADATA_KINDRecords:
3441 return "Conflicting METADATA_KIND records";
3442 case BitcodeError::CouldNotFindFunctionInStream:
3443 return "Could not find function in stream";
3444 case BitcodeError::ExpectedConstant:
3445 return "Expected a constant";
3446 case BitcodeError::InsufficientFunctionProtos:
3447 return "Insufficient function protos";
3448 case BitcodeError::InvalidBitcodeSignature:
3449 return "Invalid bitcode signature";
3450 case BitcodeError::InvalidBitcodeWrapperHeader:
3451 return "Invalid bitcode wrapper header";
3452 case BitcodeError::InvalidConstantReference:
3453 return "Invalid ronstant reference";
3454 case BitcodeError::InvalidID:
3455 return "Invalid ID";
3456 case BitcodeError::InvalidInstructionWithNoBB:
3457 return "Invalid instruction with no BB";
3458 case BitcodeError::InvalidRecord:
3459 return "Invalid record";
3460 case BitcodeError::InvalidTypeForValue:
3461 return "Invalid type for value";
3462 case BitcodeError::InvalidTYPETable:
3463 return "Invalid TYPE table";
3464 case BitcodeError::InvalidType:
3465 return "Invalid type";
3466 case BitcodeError::MalformedBlock:
3467 return "Malformed block";
3468 case BitcodeError::MalformedGlobalInitializerSet:
3469 return "Malformed global initializer set";
3470 case BitcodeError::InvalidMultipleBlocks:
3471 return "Invalid multiple blocks";
3472 case BitcodeError::NeverResolvedValueFoundInFunction:
3473 return "Never resolved value found in function";
3474 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3475 return "Never resolved function from blockaddress";
3476 case BitcodeError::InvalidValue:
3477 return "Invalid value";
3479 llvm_unreachable("Unknown error type!");
3484 const std::error_category &llvm::BitcodeErrorCategory() {
3485 static BitcodeErrorCategoryType O;
3489 //===----------------------------------------------------------------------===//
3490 // External interface
3491 //===----------------------------------------------------------------------===//
3493 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3495 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3496 LLVMContext &Context) {
3497 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3498 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3499 M->setMaterializer(R);
3501 auto cleanupOnError = [&](std::error_code EC) {
3502 R->releaseBuffer(); // Never take ownership on error.
3503 delete M; // Also deletes R.
3507 if (std::error_code EC = R->ParseBitcodeInto(M))
3508 return cleanupOnError(EC);
3510 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3511 return cleanupOnError(EC);
3517 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3518 DataStreamer *streamer,
3519 LLVMContext &Context,
3520 std::string *ErrMsg) {
3521 Module *M = new Module(name, Context);
3522 BitcodeReader *R = new BitcodeReader(streamer, Context);
3523 M->setMaterializer(R);
3524 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3526 *ErrMsg = EC.message();
3527 delete M; // Also deletes R.
3533 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer,
3534 LLVMContext &Context) {
3535 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context);
3538 Module *M = ModuleOrErr.get();
3539 // Read in the entire module, and destroy the BitcodeReader.
3540 if (std::error_code EC = M->materializeAllPermanently(true)) {
3545 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3546 // written. We must defer until the Module has been fully materialized.
3551 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3552 LLVMContext &Context) {
3553 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3554 ErrorOr<std::string> Triple = R->parseTriple();
3557 if (Triple.getError())
3559 return Triple.get();