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"
28 #include "llvm/Support/ManagedStatic.h"
33 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
36 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
37 if (WillMaterializeAllForwardRefs)
38 return std::error_code();
41 WillMaterializeAllForwardRefs = true;
43 while (!BasicBlockFwdRefQueue.empty()) {
44 Function *F = BasicBlockFwdRefQueue.front();
45 BasicBlockFwdRefQueue.pop_front();
46 assert(F && "Expected valid function");
47 if (!BasicBlockFwdRefs.count(F))
48 // Already materialized.
51 // Check for a function that isn't materializable to prevent an infinite
52 // loop. When parsing a blockaddress stored in a global variable, there
53 // isn't a trivial way to check if a function will have a body without a
54 // linear search through FunctionsWithBodies, so just check it here.
55 if (!F->isMaterializable())
56 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
58 // Try to materialize F.
59 if (std::error_code EC = materialize(F))
62 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
65 WillMaterializeAllForwardRefs = false;
66 return std::error_code();
69 void BitcodeReader::FreeState() {
71 std::vector<Type*>().swap(TypeList);
74 std::vector<Comdat *>().swap(ComdatList);
76 std::vector<AttributeSet>().swap(MAttributes);
77 std::vector<BasicBlock*>().swap(FunctionBBs);
78 std::vector<Function*>().swap(FunctionsWithBodies);
79 DeferredFunctionInfo.clear();
82 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
83 BasicBlockFwdRefQueue.clear();
86 //===----------------------------------------------------------------------===//
87 // Helper functions to implement forward reference resolution, etc.
88 //===----------------------------------------------------------------------===//
90 /// ConvertToString - Convert a string from a record into an std::string, return
92 template<typename StrTy>
93 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
95 if (Idx > Record.size())
98 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
99 Result += (char)Record[i];
103 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
105 default: // Map unknown/new linkages to external
107 return GlobalValue::ExternalLinkage;
109 return GlobalValue::WeakAnyLinkage;
111 return GlobalValue::AppendingLinkage;
113 return GlobalValue::InternalLinkage;
115 return GlobalValue::LinkOnceAnyLinkage;
117 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
119 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
121 return GlobalValue::ExternalWeakLinkage;
123 return GlobalValue::CommonLinkage;
125 return GlobalValue::PrivateLinkage;
127 return GlobalValue::WeakODRLinkage;
129 return GlobalValue::LinkOnceODRLinkage;
131 return GlobalValue::AvailableExternallyLinkage;
133 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
135 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
139 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
141 default: // Map unknown visibilities to default.
142 case 0: return GlobalValue::DefaultVisibility;
143 case 1: return GlobalValue::HiddenVisibility;
144 case 2: return GlobalValue::ProtectedVisibility;
148 static GlobalValue::DLLStorageClassTypes
149 GetDecodedDLLStorageClass(unsigned Val) {
151 default: // Map unknown values to default.
152 case 0: return GlobalValue::DefaultStorageClass;
153 case 1: return GlobalValue::DLLImportStorageClass;
154 case 2: return GlobalValue::DLLExportStorageClass;
158 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
160 case 0: return GlobalVariable::NotThreadLocal;
161 default: // Map unknown non-zero value to general dynamic.
162 case 1: return GlobalVariable::GeneralDynamicTLSModel;
163 case 2: return GlobalVariable::LocalDynamicTLSModel;
164 case 3: return GlobalVariable::InitialExecTLSModel;
165 case 4: return GlobalVariable::LocalExecTLSModel;
169 static int GetDecodedCastOpcode(unsigned Val) {
172 case bitc::CAST_TRUNC : return Instruction::Trunc;
173 case bitc::CAST_ZEXT : return Instruction::ZExt;
174 case bitc::CAST_SEXT : return Instruction::SExt;
175 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
176 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
177 case bitc::CAST_UITOFP : return Instruction::UIToFP;
178 case bitc::CAST_SITOFP : return Instruction::SIToFP;
179 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
180 case bitc::CAST_FPEXT : return Instruction::FPExt;
181 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
182 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
183 case bitc::CAST_BITCAST : return Instruction::BitCast;
184 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
187 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
190 case bitc::BINOP_ADD:
191 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
192 case bitc::BINOP_SUB:
193 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
194 case bitc::BINOP_MUL:
195 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
196 case bitc::BINOP_UDIV: return Instruction::UDiv;
197 case bitc::BINOP_SDIV:
198 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
199 case bitc::BINOP_UREM: return Instruction::URem;
200 case bitc::BINOP_SREM:
201 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
202 case bitc::BINOP_SHL: return Instruction::Shl;
203 case bitc::BINOP_LSHR: return Instruction::LShr;
204 case bitc::BINOP_ASHR: return Instruction::AShr;
205 case bitc::BINOP_AND: return Instruction::And;
206 case bitc::BINOP_OR: return Instruction::Or;
207 case bitc::BINOP_XOR: return Instruction::Xor;
211 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
213 default: return AtomicRMWInst::BAD_BINOP;
214 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
215 case bitc::RMW_ADD: return AtomicRMWInst::Add;
216 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
217 case bitc::RMW_AND: return AtomicRMWInst::And;
218 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
219 case bitc::RMW_OR: return AtomicRMWInst::Or;
220 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
221 case bitc::RMW_MAX: return AtomicRMWInst::Max;
222 case bitc::RMW_MIN: return AtomicRMWInst::Min;
223 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
224 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
228 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
230 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
231 case bitc::ORDERING_UNORDERED: return Unordered;
232 case bitc::ORDERING_MONOTONIC: return Monotonic;
233 case bitc::ORDERING_ACQUIRE: return Acquire;
234 case bitc::ORDERING_RELEASE: return Release;
235 case bitc::ORDERING_ACQREL: return AcquireRelease;
236 default: // Map unknown orderings to sequentially-consistent.
237 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
241 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
243 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
244 default: // Map unknown scopes to cross-thread.
245 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
249 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
251 default: // Map unknown selection kinds to any.
252 case bitc::COMDAT_SELECTION_KIND_ANY:
254 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
255 return Comdat::ExactMatch;
256 case bitc::COMDAT_SELECTION_KIND_LARGEST:
257 return Comdat::Largest;
258 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
259 return Comdat::NoDuplicates;
260 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
261 return Comdat::SameSize;
265 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
267 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
268 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
274 /// @brief A class for maintaining the slot number definition
275 /// as a placeholder for the actual definition for forward constants defs.
276 class ConstantPlaceHolder : public ConstantExpr {
277 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
279 // allocate space for exactly one operand
280 void *operator new(size_t s) {
281 return User::operator new(s, 1);
283 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
284 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
285 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
288 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
289 static bool classof(const Value *V) {
290 return isa<ConstantExpr>(V) &&
291 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
295 /// Provide fast operand accessors
296 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
300 // FIXME: can we inherit this from ConstantExpr?
302 struct OperandTraits<ConstantPlaceHolder> :
303 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
305 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
309 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
318 WeakVH &OldV = ValuePtrs[Idx];
324 // Handle constants and non-constants (e.g. instrs) differently for
326 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
327 ResolveConstants.push_back(std::make_pair(PHC, Idx));
330 // If there was a forward reference to this value, replace it.
331 Value *PrevVal = OldV;
332 OldV->replaceAllUsesWith(V);
338 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
343 if (Value *V = ValuePtrs[Idx]) {
344 assert(Ty == V->getType() && "Type mismatch in constant table!");
345 return cast<Constant>(V);
348 // Create and return a placeholder, which will later be RAUW'd.
349 Constant *C = new ConstantPlaceHolder(Ty, Context);
354 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
358 if (Value *V = ValuePtrs[Idx]) {
359 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
363 // No type specified, must be invalid reference.
364 if (!Ty) return nullptr;
366 // Create and return a placeholder, which will later be RAUW'd.
367 Value *V = new Argument(Ty);
372 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
373 /// resolves any forward references. The idea behind this is that we sometimes
374 /// get constants (such as large arrays) which reference *many* forward ref
375 /// constants. Replacing each of these causes a lot of thrashing when
376 /// building/reuniquing the constant. Instead of doing this, we look at all the
377 /// uses and rewrite all the place holders at once for any constant that uses
379 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
380 // Sort the values by-pointer so that they are efficient to look up with a
382 std::sort(ResolveConstants.begin(), ResolveConstants.end());
384 SmallVector<Constant*, 64> NewOps;
386 while (!ResolveConstants.empty()) {
387 Value *RealVal = operator[](ResolveConstants.back().second);
388 Constant *Placeholder = ResolveConstants.back().first;
389 ResolveConstants.pop_back();
391 // Loop over all users of the placeholder, updating them to reference the
392 // new value. If they reference more than one placeholder, update them all
394 while (!Placeholder->use_empty()) {
395 auto UI = Placeholder->user_begin();
398 // If the using object isn't uniqued, just update the operands. This
399 // handles instructions and initializers for global variables.
400 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
401 UI.getUse().set(RealVal);
405 // Otherwise, we have a constant that uses the placeholder. Replace that
406 // constant with a new constant that has *all* placeholder uses updated.
407 Constant *UserC = cast<Constant>(U);
408 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
411 if (!isa<ConstantPlaceHolder>(*I)) {
412 // Not a placeholder reference.
414 } else if (*I == Placeholder) {
415 // Common case is that it just references this one placeholder.
418 // Otherwise, look up the placeholder in ResolveConstants.
419 ResolveConstantsTy::iterator It =
420 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
421 std::pair<Constant*, unsigned>(cast<Constant>(*I),
423 assert(It != ResolveConstants.end() && It->first == *I);
424 NewOp = operator[](It->second);
427 NewOps.push_back(cast<Constant>(NewOp));
430 // Make the new constant.
432 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
433 NewC = ConstantArray::get(UserCA->getType(), NewOps);
434 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
435 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
436 } else if (isa<ConstantVector>(UserC)) {
437 NewC = ConstantVector::get(NewOps);
439 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
440 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
443 UserC->replaceAllUsesWith(NewC);
444 UserC->destroyConstant();
448 // Update all ValueHandles, they should be the only users at this point.
449 Placeholder->replaceAllUsesWith(RealVal);
454 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
463 TrackingMDRef &OldMD = MDValuePtrs[Idx];
469 // If there was a forward reference to this value, replace it.
470 MDNodeFwdDecl *PrevMD = cast<MDNodeFwdDecl>(OldMD.get());
471 PrevMD->replaceAllUsesWith(MD);
472 MDNode::deleteTemporary(PrevMD);
476 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
480 if (Metadata *MD = MDValuePtrs[Idx])
483 // Create and return a placeholder, which will later be RAUW'd.
486 Metadata *MD = MDNode::getTemporary(Context, None);
487 MDValuePtrs[Idx].reset(MD);
491 void BitcodeReaderMDValueList::tryToResolveCycles() {
497 // Still forward references... can't resolve cycles.
500 // Resolve any cycles.
501 for (auto &MD : MDValuePtrs) {
502 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Unexpected forward reference");
503 if (auto *G = dyn_cast_or_null<GenericMDNode>(MD))
508 Type *BitcodeReader::getTypeByID(unsigned ID) {
509 // The type table size is always specified correctly.
510 if (ID >= TypeList.size())
513 if (Type *Ty = TypeList[ID])
516 // If we have a forward reference, the only possible case is when it is to a
517 // named struct. Just create a placeholder for now.
518 return TypeList[ID] = createIdentifiedStructType(Context);
521 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
523 auto *Ret = StructType::create(Context, Name);
524 IdentifiedStructTypes.push_back(Ret);
528 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
529 auto *Ret = StructType::create(Context);
530 IdentifiedStructTypes.push_back(Ret);
535 //===----------------------------------------------------------------------===//
536 // Functions for parsing blocks from the bitcode file
537 //===----------------------------------------------------------------------===//
540 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
541 /// been decoded from the given integer. This function must stay in sync with
542 /// 'encodeLLVMAttributesForBitcode'.
543 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
544 uint64_t EncodedAttrs) {
545 // FIXME: Remove in 4.0.
547 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
548 // the bits above 31 down by 11 bits.
549 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
550 assert((!Alignment || isPowerOf2_32(Alignment)) &&
551 "Alignment must be a power of two.");
554 B.addAlignmentAttr(Alignment);
555 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
556 (EncodedAttrs & 0xffff));
559 std::error_code BitcodeReader::ParseAttributeBlock() {
560 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
561 return Error(BitcodeError::InvalidRecord);
563 if (!MAttributes.empty())
564 return Error(BitcodeError::InvalidMultipleBlocks);
566 SmallVector<uint64_t, 64> Record;
568 SmallVector<AttributeSet, 8> Attrs;
570 // Read all the records.
572 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
574 switch (Entry.Kind) {
575 case BitstreamEntry::SubBlock: // Handled for us already.
576 case BitstreamEntry::Error:
577 return Error(BitcodeError::MalformedBlock);
578 case BitstreamEntry::EndBlock:
579 return std::error_code();
580 case BitstreamEntry::Record:
581 // The interesting case.
587 switch (Stream.readRecord(Entry.ID, Record)) {
588 default: // Default behavior: ignore.
590 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
591 // FIXME: Remove in 4.0.
592 if (Record.size() & 1)
593 return Error(BitcodeError::InvalidRecord);
595 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
597 decodeLLVMAttributesForBitcode(B, Record[i+1]);
598 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
601 MAttributes.push_back(AttributeSet::get(Context, Attrs));
605 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
606 for (unsigned i = 0, e = Record.size(); i != e; ++i)
607 Attrs.push_back(MAttributeGroups[Record[i]]);
609 MAttributes.push_back(AttributeSet::get(Context, Attrs));
617 // Returns Attribute::None on unrecognized codes.
618 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
621 return Attribute::None;
622 case bitc::ATTR_KIND_ALIGNMENT:
623 return Attribute::Alignment;
624 case bitc::ATTR_KIND_ALWAYS_INLINE:
625 return Attribute::AlwaysInline;
626 case bitc::ATTR_KIND_BUILTIN:
627 return Attribute::Builtin;
628 case bitc::ATTR_KIND_BY_VAL:
629 return Attribute::ByVal;
630 case bitc::ATTR_KIND_IN_ALLOCA:
631 return Attribute::InAlloca;
632 case bitc::ATTR_KIND_COLD:
633 return Attribute::Cold;
634 case bitc::ATTR_KIND_INLINE_HINT:
635 return Attribute::InlineHint;
636 case bitc::ATTR_KIND_IN_REG:
637 return Attribute::InReg;
638 case bitc::ATTR_KIND_JUMP_TABLE:
639 return Attribute::JumpTable;
640 case bitc::ATTR_KIND_MIN_SIZE:
641 return Attribute::MinSize;
642 case bitc::ATTR_KIND_NAKED:
643 return Attribute::Naked;
644 case bitc::ATTR_KIND_NEST:
645 return Attribute::Nest;
646 case bitc::ATTR_KIND_NO_ALIAS:
647 return Attribute::NoAlias;
648 case bitc::ATTR_KIND_NO_BUILTIN:
649 return Attribute::NoBuiltin;
650 case bitc::ATTR_KIND_NO_CAPTURE:
651 return Attribute::NoCapture;
652 case bitc::ATTR_KIND_NO_DUPLICATE:
653 return Attribute::NoDuplicate;
654 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
655 return Attribute::NoImplicitFloat;
656 case bitc::ATTR_KIND_NO_INLINE:
657 return Attribute::NoInline;
658 case bitc::ATTR_KIND_NON_LAZY_BIND:
659 return Attribute::NonLazyBind;
660 case bitc::ATTR_KIND_NON_NULL:
661 return Attribute::NonNull;
662 case bitc::ATTR_KIND_DEREFERENCEABLE:
663 return Attribute::Dereferenceable;
664 case bitc::ATTR_KIND_NO_RED_ZONE:
665 return Attribute::NoRedZone;
666 case bitc::ATTR_KIND_NO_RETURN:
667 return Attribute::NoReturn;
668 case bitc::ATTR_KIND_NO_UNWIND:
669 return Attribute::NoUnwind;
670 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
671 return Attribute::OptimizeForSize;
672 case bitc::ATTR_KIND_OPTIMIZE_NONE:
673 return Attribute::OptimizeNone;
674 case bitc::ATTR_KIND_READ_NONE:
675 return Attribute::ReadNone;
676 case bitc::ATTR_KIND_READ_ONLY:
677 return Attribute::ReadOnly;
678 case bitc::ATTR_KIND_RETURNED:
679 return Attribute::Returned;
680 case bitc::ATTR_KIND_RETURNS_TWICE:
681 return Attribute::ReturnsTwice;
682 case bitc::ATTR_KIND_S_EXT:
683 return Attribute::SExt;
684 case bitc::ATTR_KIND_STACK_ALIGNMENT:
685 return Attribute::StackAlignment;
686 case bitc::ATTR_KIND_STACK_PROTECT:
687 return Attribute::StackProtect;
688 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
689 return Attribute::StackProtectReq;
690 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
691 return Attribute::StackProtectStrong;
692 case bitc::ATTR_KIND_STRUCT_RET:
693 return Attribute::StructRet;
694 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
695 return Attribute::SanitizeAddress;
696 case bitc::ATTR_KIND_SANITIZE_THREAD:
697 return Attribute::SanitizeThread;
698 case bitc::ATTR_KIND_SANITIZE_MEMORY:
699 return Attribute::SanitizeMemory;
700 case bitc::ATTR_KIND_UW_TABLE:
701 return Attribute::UWTable;
702 case bitc::ATTR_KIND_Z_EXT:
703 return Attribute::ZExt;
707 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
708 Attribute::AttrKind *Kind) {
709 *Kind = GetAttrFromCode(Code);
710 if (*Kind == Attribute::None)
711 return Error(BitcodeError::InvalidValue);
712 return std::error_code();
715 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
716 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
717 return Error(BitcodeError::InvalidRecord);
719 if (!MAttributeGroups.empty())
720 return Error(BitcodeError::InvalidMultipleBlocks);
722 SmallVector<uint64_t, 64> Record;
724 // Read all the records.
726 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
728 switch (Entry.Kind) {
729 case BitstreamEntry::SubBlock: // Handled for us already.
730 case BitstreamEntry::Error:
731 return Error(BitcodeError::MalformedBlock);
732 case BitstreamEntry::EndBlock:
733 return std::error_code();
734 case BitstreamEntry::Record:
735 // The interesting case.
741 switch (Stream.readRecord(Entry.ID, Record)) {
742 default: // Default behavior: ignore.
744 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
745 if (Record.size() < 3)
746 return Error(BitcodeError::InvalidRecord);
748 uint64_t GrpID = Record[0];
749 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
752 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
753 if (Record[i] == 0) { // Enum attribute
754 Attribute::AttrKind Kind;
755 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
758 B.addAttribute(Kind);
759 } else if (Record[i] == 1) { // Integer attribute
760 Attribute::AttrKind Kind;
761 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
763 if (Kind == Attribute::Alignment)
764 B.addAlignmentAttr(Record[++i]);
765 else if (Kind == Attribute::StackAlignment)
766 B.addStackAlignmentAttr(Record[++i]);
767 else if (Kind == Attribute::Dereferenceable)
768 B.addDereferenceableAttr(Record[++i]);
769 } else { // String attribute
770 assert((Record[i] == 3 || Record[i] == 4) &&
771 "Invalid attribute group entry");
772 bool HasValue = (Record[i++] == 4);
773 SmallString<64> KindStr;
774 SmallString<64> ValStr;
776 while (Record[i] != 0 && i != e)
777 KindStr += Record[i++];
778 assert(Record[i] == 0 && "Kind string not null terminated");
781 // Has a value associated with it.
782 ++i; // Skip the '0' that terminates the "kind" string.
783 while (Record[i] != 0 && i != e)
784 ValStr += Record[i++];
785 assert(Record[i] == 0 && "Value string not null terminated");
788 B.addAttribute(KindStr.str(), ValStr.str());
792 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
799 std::error_code BitcodeReader::ParseTypeTable() {
800 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
801 return Error(BitcodeError::InvalidRecord);
803 return ParseTypeTableBody();
806 std::error_code BitcodeReader::ParseTypeTableBody() {
807 if (!TypeList.empty())
808 return Error(BitcodeError::InvalidMultipleBlocks);
810 SmallVector<uint64_t, 64> Record;
811 unsigned NumRecords = 0;
813 SmallString<64> TypeName;
815 // Read all the records for this type table.
817 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
819 switch (Entry.Kind) {
820 case BitstreamEntry::SubBlock: // Handled for us already.
821 case BitstreamEntry::Error:
822 return Error(BitcodeError::MalformedBlock);
823 case BitstreamEntry::EndBlock:
824 if (NumRecords != TypeList.size())
825 return Error(BitcodeError::MalformedBlock);
826 return std::error_code();
827 case BitstreamEntry::Record:
828 // The interesting case.
834 Type *ResultTy = nullptr;
835 switch (Stream.readRecord(Entry.ID, Record)) {
837 return Error(BitcodeError::InvalidValue);
838 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
839 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
840 // type list. This allows us to reserve space.
841 if (Record.size() < 1)
842 return Error(BitcodeError::InvalidRecord);
843 TypeList.resize(Record[0]);
845 case bitc::TYPE_CODE_VOID: // VOID
846 ResultTy = Type::getVoidTy(Context);
848 case bitc::TYPE_CODE_HALF: // HALF
849 ResultTy = Type::getHalfTy(Context);
851 case bitc::TYPE_CODE_FLOAT: // FLOAT
852 ResultTy = Type::getFloatTy(Context);
854 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
855 ResultTy = Type::getDoubleTy(Context);
857 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
858 ResultTy = Type::getX86_FP80Ty(Context);
860 case bitc::TYPE_CODE_FP128: // FP128
861 ResultTy = Type::getFP128Ty(Context);
863 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
864 ResultTy = Type::getPPC_FP128Ty(Context);
866 case bitc::TYPE_CODE_LABEL: // LABEL
867 ResultTy = Type::getLabelTy(Context);
869 case bitc::TYPE_CODE_METADATA: // METADATA
870 ResultTy = Type::getMetadataTy(Context);
872 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
873 ResultTy = Type::getX86_MMXTy(Context);
875 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
876 if (Record.size() < 1)
877 return Error(BitcodeError::InvalidRecord);
879 ResultTy = IntegerType::get(Context, Record[0]);
881 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
882 // [pointee type, address space]
883 if (Record.size() < 1)
884 return Error(BitcodeError::InvalidRecord);
885 unsigned AddressSpace = 0;
886 if (Record.size() == 2)
887 AddressSpace = Record[1];
888 ResultTy = getTypeByID(Record[0]);
890 return Error(BitcodeError::InvalidType);
891 ResultTy = PointerType::get(ResultTy, AddressSpace);
894 case bitc::TYPE_CODE_FUNCTION_OLD: {
895 // FIXME: attrid is dead, remove it in LLVM 4.0
896 // FUNCTION: [vararg, attrid, retty, paramty x N]
897 if (Record.size() < 3)
898 return Error(BitcodeError::InvalidRecord);
899 SmallVector<Type*, 8> ArgTys;
900 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
901 if (Type *T = getTypeByID(Record[i]))
907 ResultTy = getTypeByID(Record[2]);
908 if (!ResultTy || ArgTys.size() < Record.size()-3)
909 return Error(BitcodeError::InvalidType);
911 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
914 case bitc::TYPE_CODE_FUNCTION: {
915 // FUNCTION: [vararg, retty, paramty x N]
916 if (Record.size() < 2)
917 return Error(BitcodeError::InvalidRecord);
918 SmallVector<Type*, 8> ArgTys;
919 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
920 if (Type *T = getTypeByID(Record[i]))
926 ResultTy = getTypeByID(Record[1]);
927 if (!ResultTy || ArgTys.size() < Record.size()-2)
928 return Error(BitcodeError::InvalidType);
930 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
933 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
934 if (Record.size() < 1)
935 return Error(BitcodeError::InvalidRecord);
936 SmallVector<Type*, 8> EltTys;
937 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
938 if (Type *T = getTypeByID(Record[i]))
943 if (EltTys.size() != Record.size()-1)
944 return Error(BitcodeError::InvalidType);
945 ResultTy = StructType::get(Context, EltTys, Record[0]);
948 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
949 if (ConvertToString(Record, 0, TypeName))
950 return Error(BitcodeError::InvalidRecord);
953 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
954 if (Record.size() < 1)
955 return Error(BitcodeError::InvalidRecord);
957 if (NumRecords >= TypeList.size())
958 return Error(BitcodeError::InvalidTYPETable);
960 // Check to see if this was forward referenced, if so fill in the temp.
961 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
963 Res->setName(TypeName);
964 TypeList[NumRecords] = nullptr;
965 } else // Otherwise, create a new struct.
966 Res = createIdentifiedStructType(Context, TypeName);
969 SmallVector<Type*, 8> EltTys;
970 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
971 if (Type *T = getTypeByID(Record[i]))
976 if (EltTys.size() != Record.size()-1)
977 return Error(BitcodeError::InvalidRecord);
978 Res->setBody(EltTys, Record[0]);
982 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
983 if (Record.size() != 1)
984 return Error(BitcodeError::InvalidRecord);
986 if (NumRecords >= TypeList.size())
987 return Error(BitcodeError::InvalidTYPETable);
989 // Check to see if this was forward referenced, if so fill in the temp.
990 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
992 Res->setName(TypeName);
993 TypeList[NumRecords] = nullptr;
994 } else // Otherwise, create a new struct with no body.
995 Res = createIdentifiedStructType(Context, TypeName);
1000 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1001 if (Record.size() < 2)
1002 return Error(BitcodeError::InvalidRecord);
1003 if ((ResultTy = getTypeByID(Record[1])))
1004 ResultTy = ArrayType::get(ResultTy, Record[0]);
1006 return Error(BitcodeError::InvalidType);
1008 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1009 if (Record.size() < 2)
1010 return Error(BitcodeError::InvalidRecord);
1011 if ((ResultTy = getTypeByID(Record[1])))
1012 ResultTy = VectorType::get(ResultTy, Record[0]);
1014 return Error(BitcodeError::InvalidType);
1018 if (NumRecords >= TypeList.size())
1019 return Error(BitcodeError::InvalidTYPETable);
1020 assert(ResultTy && "Didn't read a type?");
1021 assert(!TypeList[NumRecords] && "Already read type?");
1022 TypeList[NumRecords++] = ResultTy;
1026 std::error_code BitcodeReader::ParseValueSymbolTable() {
1027 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1028 return Error(BitcodeError::InvalidRecord);
1030 SmallVector<uint64_t, 64> Record;
1032 // Read all the records for this value table.
1033 SmallString<128> ValueName;
1035 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1037 switch (Entry.Kind) {
1038 case BitstreamEntry::SubBlock: // Handled for us already.
1039 case BitstreamEntry::Error:
1040 return Error(BitcodeError::MalformedBlock);
1041 case BitstreamEntry::EndBlock:
1042 return std::error_code();
1043 case BitstreamEntry::Record:
1044 // The interesting case.
1050 switch (Stream.readRecord(Entry.ID, Record)) {
1051 default: // Default behavior: unknown type.
1053 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1054 if (ConvertToString(Record, 1, ValueName))
1055 return Error(BitcodeError::InvalidRecord);
1056 unsigned ValueID = Record[0];
1057 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1058 return Error(BitcodeError::InvalidRecord);
1059 Value *V = ValueList[ValueID];
1061 V->setName(StringRef(ValueName.data(), ValueName.size()));
1065 case bitc::VST_CODE_BBENTRY: {
1066 if (ConvertToString(Record, 1, ValueName))
1067 return Error(BitcodeError::InvalidRecord);
1068 BasicBlock *BB = getBasicBlock(Record[0]);
1070 return Error(BitcodeError::InvalidRecord);
1072 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1080 std::error_code BitcodeReader::ParseMetadata() {
1081 unsigned NextMDValueNo = MDValueList.size();
1083 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1084 return Error(BitcodeError::InvalidRecord);
1086 SmallVector<uint64_t, 64> Record;
1088 // Read all the records.
1090 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1092 switch (Entry.Kind) {
1093 case BitstreamEntry::SubBlock: // Handled for us already.
1094 case BitstreamEntry::Error:
1095 return Error(BitcodeError::MalformedBlock);
1096 case BitstreamEntry::EndBlock:
1097 MDValueList.tryToResolveCycles();
1098 return std::error_code();
1099 case BitstreamEntry::Record:
1100 // The interesting case.
1106 unsigned Code = Stream.readRecord(Entry.ID, Record);
1108 default: // Default behavior: ignore.
1110 case bitc::METADATA_NAME: {
1111 // Read name of the named metadata.
1112 SmallString<8> Name(Record.begin(), Record.end());
1114 Code = Stream.ReadCode();
1116 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1117 unsigned NextBitCode = Stream.readRecord(Code, Record);
1118 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1120 // Read named metadata elements.
1121 unsigned Size = Record.size();
1122 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1123 for (unsigned i = 0; i != Size; ++i) {
1124 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1126 return Error(BitcodeError::InvalidRecord);
1127 NMD->addOperand(MD);
1131 case bitc::METADATA_OLD_FN_NODE: {
1132 // FIXME: Remove in 4.0.
1133 // This is a LocalAsMetadata record, the only type of function-local
1135 if (Record.size() % 2 == 1)
1136 return Error(BitcodeError::InvalidRecord);
1138 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1139 // to be legal, but there's no upgrade path.
1140 auto dropRecord = [&] {
1141 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1143 if (Record.size() != 2) {
1148 Type *Ty = getTypeByID(Record[0]);
1149 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1154 MDValueList.AssignValue(
1155 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1159 case bitc::METADATA_OLD_NODE: {
1160 // FIXME: Remove in 4.0.
1161 if (Record.size() % 2 == 1)
1162 return Error(BitcodeError::InvalidRecord);
1164 unsigned Size = Record.size();
1165 SmallVector<Metadata *, 8> Elts;
1166 for (unsigned i = 0; i != Size; i += 2) {
1167 Type *Ty = getTypeByID(Record[i]);
1169 return Error(BitcodeError::InvalidRecord);
1170 if (Ty->isMetadataTy())
1171 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1172 else if (!Ty->isVoidTy()) {
1174 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1175 assert(isa<ConstantAsMetadata>(MD) &&
1176 "Expected non-function-local metadata");
1179 Elts.push_back(nullptr);
1181 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1184 case bitc::METADATA_VALUE: {
1185 if (Record.size() != 2)
1186 return Error(BitcodeError::InvalidRecord);
1188 Type *Ty = getTypeByID(Record[0]);
1189 if (Ty->isMetadataTy() || Ty->isVoidTy())
1190 return Error(BitcodeError::InvalidRecord);
1192 MDValueList.AssignValue(
1193 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1197 case bitc::METADATA_NODE: {
1198 SmallVector<Metadata *, 8> Elts;
1199 Elts.reserve(Record.size());
1200 for (unsigned ID : Record)
1201 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1202 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1205 case bitc::METADATA_STRING: {
1206 std::string String(Record.begin(), Record.end());
1207 llvm::UpgradeMDStringConstant(String);
1208 Metadata *MD = MDString::get(Context, String);
1209 MDValueList.AssignValue(MD, NextMDValueNo++);
1212 case bitc::METADATA_KIND: {
1213 if (Record.size() < 2)
1214 return Error(BitcodeError::InvalidRecord);
1216 unsigned Kind = Record[0];
1217 SmallString<8> Name(Record.begin()+1, Record.end());
1219 unsigned NewKind = TheModule->getMDKindID(Name.str());
1220 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1221 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1228 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1229 /// the LSB for dense VBR encoding.
1230 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1235 // There is no such thing as -0 with integers. "-0" really means MININT.
1239 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1240 /// values and aliases that we can.
1241 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1242 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1243 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1244 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1245 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1247 GlobalInitWorklist.swap(GlobalInits);
1248 AliasInitWorklist.swap(AliasInits);
1249 FunctionPrefixWorklist.swap(FunctionPrefixes);
1250 FunctionPrologueWorklist.swap(FunctionPrologues);
1252 while (!GlobalInitWorklist.empty()) {
1253 unsigned ValID = GlobalInitWorklist.back().second;
1254 if (ValID >= ValueList.size()) {
1255 // Not ready to resolve this yet, it requires something later in the file.
1256 GlobalInits.push_back(GlobalInitWorklist.back());
1258 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1259 GlobalInitWorklist.back().first->setInitializer(C);
1261 return Error(BitcodeError::ExpectedConstant);
1263 GlobalInitWorklist.pop_back();
1266 while (!AliasInitWorklist.empty()) {
1267 unsigned ValID = AliasInitWorklist.back().second;
1268 if (ValID >= ValueList.size()) {
1269 AliasInits.push_back(AliasInitWorklist.back());
1271 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1272 AliasInitWorklist.back().first->setAliasee(C);
1274 return Error(BitcodeError::ExpectedConstant);
1276 AliasInitWorklist.pop_back();
1279 while (!FunctionPrefixWorklist.empty()) {
1280 unsigned ValID = FunctionPrefixWorklist.back().second;
1281 if (ValID >= ValueList.size()) {
1282 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1284 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1285 FunctionPrefixWorklist.back().first->setPrefixData(C);
1287 return Error(BitcodeError::ExpectedConstant);
1289 FunctionPrefixWorklist.pop_back();
1292 while (!FunctionPrologueWorklist.empty()) {
1293 unsigned ValID = FunctionPrologueWorklist.back().second;
1294 if (ValID >= ValueList.size()) {
1295 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1297 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1298 FunctionPrologueWorklist.back().first->setPrologueData(C);
1300 return Error(BitcodeError::ExpectedConstant);
1302 FunctionPrologueWorklist.pop_back();
1305 return std::error_code();
1308 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1309 SmallVector<uint64_t, 8> Words(Vals.size());
1310 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1311 BitcodeReader::decodeSignRotatedValue);
1313 return APInt(TypeBits, Words);
1316 std::error_code BitcodeReader::ParseConstants() {
1317 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1318 return Error(BitcodeError::InvalidRecord);
1320 SmallVector<uint64_t, 64> Record;
1322 // Read all the records for this value table.
1323 Type *CurTy = Type::getInt32Ty(Context);
1324 unsigned NextCstNo = ValueList.size();
1326 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1328 switch (Entry.Kind) {
1329 case BitstreamEntry::SubBlock: // Handled for us already.
1330 case BitstreamEntry::Error:
1331 return Error(BitcodeError::MalformedBlock);
1332 case BitstreamEntry::EndBlock:
1333 if (NextCstNo != ValueList.size())
1334 return Error(BitcodeError::InvalidConstantReference);
1336 // Once all the constants have been read, go through and resolve forward
1338 ValueList.ResolveConstantForwardRefs();
1339 return std::error_code();
1340 case BitstreamEntry::Record:
1341 // The interesting case.
1348 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1350 default: // Default behavior: unknown constant
1351 case bitc::CST_CODE_UNDEF: // UNDEF
1352 V = UndefValue::get(CurTy);
1354 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1356 return Error(BitcodeError::InvalidRecord);
1357 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1358 return Error(BitcodeError::InvalidRecord);
1359 CurTy = TypeList[Record[0]];
1360 continue; // Skip the ValueList manipulation.
1361 case bitc::CST_CODE_NULL: // NULL
1362 V = Constant::getNullValue(CurTy);
1364 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1365 if (!CurTy->isIntegerTy() || Record.empty())
1366 return Error(BitcodeError::InvalidRecord);
1367 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1369 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1370 if (!CurTy->isIntegerTy() || Record.empty())
1371 return Error(BitcodeError::InvalidRecord);
1373 APInt VInt = ReadWideAPInt(Record,
1374 cast<IntegerType>(CurTy)->getBitWidth());
1375 V = ConstantInt::get(Context, VInt);
1379 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1381 return Error(BitcodeError::InvalidRecord);
1382 if (CurTy->isHalfTy())
1383 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1384 APInt(16, (uint16_t)Record[0])));
1385 else if (CurTy->isFloatTy())
1386 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1387 APInt(32, (uint32_t)Record[0])));
1388 else if (CurTy->isDoubleTy())
1389 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1390 APInt(64, Record[0])));
1391 else if (CurTy->isX86_FP80Ty()) {
1392 // Bits are not stored the same way as a normal i80 APInt, compensate.
1393 uint64_t Rearrange[2];
1394 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1395 Rearrange[1] = Record[0] >> 48;
1396 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1397 APInt(80, Rearrange)));
1398 } else if (CurTy->isFP128Ty())
1399 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1400 APInt(128, Record)));
1401 else if (CurTy->isPPC_FP128Ty())
1402 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1403 APInt(128, Record)));
1405 V = UndefValue::get(CurTy);
1409 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1411 return Error(BitcodeError::InvalidRecord);
1413 unsigned Size = Record.size();
1414 SmallVector<Constant*, 16> Elts;
1416 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1417 for (unsigned i = 0; i != Size; ++i)
1418 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1419 STy->getElementType(i)));
1420 V = ConstantStruct::get(STy, Elts);
1421 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1422 Type *EltTy = ATy->getElementType();
1423 for (unsigned i = 0; i != Size; ++i)
1424 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1425 V = ConstantArray::get(ATy, Elts);
1426 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1427 Type *EltTy = VTy->getElementType();
1428 for (unsigned i = 0; i != Size; ++i)
1429 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1430 V = ConstantVector::get(Elts);
1432 V = UndefValue::get(CurTy);
1436 case bitc::CST_CODE_STRING: // STRING: [values]
1437 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1439 return Error(BitcodeError::InvalidRecord);
1441 SmallString<16> Elts(Record.begin(), Record.end());
1442 V = ConstantDataArray::getString(Context, Elts,
1443 BitCode == bitc::CST_CODE_CSTRING);
1446 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1448 return Error(BitcodeError::InvalidRecord);
1450 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1451 unsigned Size = Record.size();
1453 if (EltTy->isIntegerTy(8)) {
1454 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1455 if (isa<VectorType>(CurTy))
1456 V = ConstantDataVector::get(Context, Elts);
1458 V = ConstantDataArray::get(Context, Elts);
1459 } else if (EltTy->isIntegerTy(16)) {
1460 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1461 if (isa<VectorType>(CurTy))
1462 V = ConstantDataVector::get(Context, Elts);
1464 V = ConstantDataArray::get(Context, Elts);
1465 } else if (EltTy->isIntegerTy(32)) {
1466 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1467 if (isa<VectorType>(CurTy))
1468 V = ConstantDataVector::get(Context, Elts);
1470 V = ConstantDataArray::get(Context, Elts);
1471 } else if (EltTy->isIntegerTy(64)) {
1472 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1473 if (isa<VectorType>(CurTy))
1474 V = ConstantDataVector::get(Context, Elts);
1476 V = ConstantDataArray::get(Context, Elts);
1477 } else if (EltTy->isFloatTy()) {
1478 SmallVector<float, 16> Elts(Size);
1479 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1480 if (isa<VectorType>(CurTy))
1481 V = ConstantDataVector::get(Context, Elts);
1483 V = ConstantDataArray::get(Context, Elts);
1484 } else if (EltTy->isDoubleTy()) {
1485 SmallVector<double, 16> Elts(Size);
1486 std::transform(Record.begin(), Record.end(), Elts.begin(),
1488 if (isa<VectorType>(CurTy))
1489 V = ConstantDataVector::get(Context, Elts);
1491 V = ConstantDataArray::get(Context, Elts);
1493 return Error(BitcodeError::InvalidTypeForValue);
1498 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1499 if (Record.size() < 3)
1500 return Error(BitcodeError::InvalidRecord);
1501 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1503 V = UndefValue::get(CurTy); // Unknown binop.
1505 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1506 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1508 if (Record.size() >= 4) {
1509 if (Opc == Instruction::Add ||
1510 Opc == Instruction::Sub ||
1511 Opc == Instruction::Mul ||
1512 Opc == Instruction::Shl) {
1513 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1514 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1515 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1516 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1517 } else if (Opc == Instruction::SDiv ||
1518 Opc == Instruction::UDiv ||
1519 Opc == Instruction::LShr ||
1520 Opc == Instruction::AShr) {
1521 if (Record[3] & (1 << bitc::PEO_EXACT))
1522 Flags |= SDivOperator::IsExact;
1525 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1529 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1530 if (Record.size() < 3)
1531 return Error(BitcodeError::InvalidRecord);
1532 int Opc = GetDecodedCastOpcode(Record[0]);
1534 V = UndefValue::get(CurTy); // Unknown cast.
1536 Type *OpTy = getTypeByID(Record[1]);
1538 return Error(BitcodeError::InvalidRecord);
1539 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1540 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1541 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1545 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1546 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1547 if (Record.size() & 1)
1548 return Error(BitcodeError::InvalidRecord);
1549 SmallVector<Constant*, 16> Elts;
1550 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1551 Type *ElTy = getTypeByID(Record[i]);
1553 return Error(BitcodeError::InvalidRecord);
1554 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1556 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1557 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1559 bitc::CST_CODE_CE_INBOUNDS_GEP);
1562 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1563 if (Record.size() < 3)
1564 return Error(BitcodeError::InvalidRecord);
1566 Type *SelectorTy = Type::getInt1Ty(Context);
1568 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1569 // vector. Otherwise, it must be a single bit.
1570 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1571 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1572 VTy->getNumElements());
1574 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1576 ValueList.getConstantFwdRef(Record[1],CurTy),
1577 ValueList.getConstantFwdRef(Record[2],CurTy));
1580 case bitc::CST_CODE_CE_EXTRACTELT
1581 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1582 if (Record.size() < 3)
1583 return Error(BitcodeError::InvalidRecord);
1585 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1587 return Error(BitcodeError::InvalidRecord);
1588 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1589 Constant *Op1 = nullptr;
1590 if (Record.size() == 4) {
1591 Type *IdxTy = getTypeByID(Record[2]);
1593 return Error(BitcodeError::InvalidRecord);
1594 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1595 } else // TODO: Remove with llvm 4.0
1596 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1598 return Error(BitcodeError::InvalidRecord);
1599 V = ConstantExpr::getExtractElement(Op0, Op1);
1602 case bitc::CST_CODE_CE_INSERTELT
1603 : { // CE_INSERTELT: [opval, opval, opty, opval]
1604 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1605 if (Record.size() < 3 || !OpTy)
1606 return Error(BitcodeError::InvalidRecord);
1607 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1608 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1609 OpTy->getElementType());
1610 Constant *Op2 = nullptr;
1611 if (Record.size() == 4) {
1612 Type *IdxTy = getTypeByID(Record[2]);
1614 return Error(BitcodeError::InvalidRecord);
1615 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1616 } else // TODO: Remove with llvm 4.0
1617 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1619 return Error(BitcodeError::InvalidRecord);
1620 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1623 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1624 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1625 if (Record.size() < 3 || !OpTy)
1626 return Error(BitcodeError::InvalidRecord);
1627 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1628 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1629 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1630 OpTy->getNumElements());
1631 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1632 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1635 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1636 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1638 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1639 if (Record.size() < 4 || !RTy || !OpTy)
1640 return Error(BitcodeError::InvalidRecord);
1641 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1642 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1643 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1644 RTy->getNumElements());
1645 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1646 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1649 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1650 if (Record.size() < 4)
1651 return Error(BitcodeError::InvalidRecord);
1652 Type *OpTy = getTypeByID(Record[0]);
1654 return Error(BitcodeError::InvalidRecord);
1655 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1656 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1658 if (OpTy->isFPOrFPVectorTy())
1659 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1661 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1664 // This maintains backward compatibility, pre-asm dialect keywords.
1665 // FIXME: Remove with the 4.0 release.
1666 case bitc::CST_CODE_INLINEASM_OLD: {
1667 if (Record.size() < 2)
1668 return Error(BitcodeError::InvalidRecord);
1669 std::string AsmStr, ConstrStr;
1670 bool HasSideEffects = Record[0] & 1;
1671 bool IsAlignStack = Record[0] >> 1;
1672 unsigned AsmStrSize = Record[1];
1673 if (2+AsmStrSize >= Record.size())
1674 return Error(BitcodeError::InvalidRecord);
1675 unsigned ConstStrSize = Record[2+AsmStrSize];
1676 if (3+AsmStrSize+ConstStrSize > Record.size())
1677 return Error(BitcodeError::InvalidRecord);
1679 for (unsigned i = 0; i != AsmStrSize; ++i)
1680 AsmStr += (char)Record[2+i];
1681 for (unsigned i = 0; i != ConstStrSize; ++i)
1682 ConstrStr += (char)Record[3+AsmStrSize+i];
1683 PointerType *PTy = cast<PointerType>(CurTy);
1684 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1685 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1688 // This version adds support for the asm dialect keywords (e.g.,
1690 case bitc::CST_CODE_INLINEASM: {
1691 if (Record.size() < 2)
1692 return Error(BitcodeError::InvalidRecord);
1693 std::string AsmStr, ConstrStr;
1694 bool HasSideEffects = Record[0] & 1;
1695 bool IsAlignStack = (Record[0] >> 1) & 1;
1696 unsigned AsmDialect = Record[0] >> 2;
1697 unsigned AsmStrSize = Record[1];
1698 if (2+AsmStrSize >= Record.size())
1699 return Error(BitcodeError::InvalidRecord);
1700 unsigned ConstStrSize = Record[2+AsmStrSize];
1701 if (3+AsmStrSize+ConstStrSize > Record.size())
1702 return Error(BitcodeError::InvalidRecord);
1704 for (unsigned i = 0; i != AsmStrSize; ++i)
1705 AsmStr += (char)Record[2+i];
1706 for (unsigned i = 0; i != ConstStrSize; ++i)
1707 ConstrStr += (char)Record[3+AsmStrSize+i];
1708 PointerType *PTy = cast<PointerType>(CurTy);
1709 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1710 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1711 InlineAsm::AsmDialect(AsmDialect));
1714 case bitc::CST_CODE_BLOCKADDRESS:{
1715 if (Record.size() < 3)
1716 return Error(BitcodeError::InvalidRecord);
1717 Type *FnTy = getTypeByID(Record[0]);
1719 return Error(BitcodeError::InvalidRecord);
1721 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1723 return Error(BitcodeError::InvalidRecord);
1725 // Don't let Fn get dematerialized.
1726 BlockAddressesTaken.insert(Fn);
1728 // If the function is already parsed we can insert the block address right
1731 unsigned BBID = Record[2];
1733 // Invalid reference to entry block.
1734 return Error(BitcodeError::InvalidID);
1736 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1737 for (size_t I = 0, E = BBID; I != E; ++I) {
1739 return Error(BitcodeError::InvalidID);
1744 // Otherwise insert a placeholder and remember it so it can be inserted
1745 // when the function is parsed.
1746 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1748 BasicBlockFwdRefQueue.push_back(Fn);
1749 if (FwdBBs.size() < BBID + 1)
1750 FwdBBs.resize(BBID + 1);
1752 FwdBBs[BBID] = BasicBlock::Create(Context);
1755 V = BlockAddress::get(Fn, BB);
1760 ValueList.AssignValue(V, NextCstNo);
1765 std::error_code BitcodeReader::ParseUseLists() {
1766 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1767 return Error(BitcodeError::InvalidRecord);
1769 // Read all the records.
1770 SmallVector<uint64_t, 64> Record;
1772 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1774 switch (Entry.Kind) {
1775 case BitstreamEntry::SubBlock: // Handled for us already.
1776 case BitstreamEntry::Error:
1777 return Error(BitcodeError::MalformedBlock);
1778 case BitstreamEntry::EndBlock:
1779 return std::error_code();
1780 case BitstreamEntry::Record:
1781 // The interesting case.
1785 // Read a use list record.
1788 switch (Stream.readRecord(Entry.ID, Record)) {
1789 default: // Default behavior: unknown type.
1791 case bitc::USELIST_CODE_BB:
1794 case bitc::USELIST_CODE_DEFAULT: {
1795 unsigned RecordLength = Record.size();
1796 if (RecordLength < 3)
1797 // Records should have at least an ID and two indexes.
1798 return Error(BitcodeError::InvalidRecord);
1799 unsigned ID = Record.back();
1804 assert(ID < FunctionBBs.size() && "Basic block not found");
1805 V = FunctionBBs[ID];
1808 unsigned NumUses = 0;
1809 SmallDenseMap<const Use *, unsigned, 16> Order;
1810 for (const Use &U : V->uses()) {
1811 if (++NumUses > Record.size())
1813 Order[&U] = Record[NumUses - 1];
1815 if (Order.size() != Record.size() || NumUses > Record.size())
1816 // Mismatches can happen if the functions are being materialized lazily
1817 // (out-of-order), or a value has been upgraded.
1820 V->sortUseList([&](const Use &L, const Use &R) {
1821 return Order.lookup(&L) < Order.lookup(&R);
1829 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1830 /// remember where it is and then skip it. This lets us lazily deserialize the
1832 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1833 // Get the function we are talking about.
1834 if (FunctionsWithBodies.empty())
1835 return Error(BitcodeError::InsufficientFunctionProtos);
1837 Function *Fn = FunctionsWithBodies.back();
1838 FunctionsWithBodies.pop_back();
1840 // Save the current stream state.
1841 uint64_t CurBit = Stream.GetCurrentBitNo();
1842 DeferredFunctionInfo[Fn] = CurBit;
1844 // Skip over the function block for now.
1845 if (Stream.SkipBlock())
1846 return Error(BitcodeError::InvalidRecord);
1847 return std::error_code();
1850 std::error_code BitcodeReader::GlobalCleanup() {
1851 // Patch the initializers for globals and aliases up.
1852 ResolveGlobalAndAliasInits();
1853 if (!GlobalInits.empty() || !AliasInits.empty())
1854 return Error(BitcodeError::MalformedGlobalInitializerSet);
1856 // Look for intrinsic functions which need to be upgraded at some point
1857 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1860 if (UpgradeIntrinsicFunction(FI, NewFn))
1861 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1864 // Look for global variables which need to be renamed.
1865 for (Module::global_iterator
1866 GI = TheModule->global_begin(), GE = TheModule->global_end();
1868 GlobalVariable *GV = GI++;
1869 UpgradeGlobalVariable(GV);
1872 // Force deallocation of memory for these vectors to favor the client that
1873 // want lazy deserialization.
1874 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1875 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1876 return std::error_code();
1879 std::error_code BitcodeReader::ParseModule(bool Resume) {
1881 Stream.JumpToBit(NextUnreadBit);
1882 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1883 return Error(BitcodeError::InvalidRecord);
1885 SmallVector<uint64_t, 64> Record;
1886 std::vector<std::string> SectionTable;
1887 std::vector<std::string> GCTable;
1889 // Read all the records for this module.
1891 BitstreamEntry Entry = Stream.advance();
1893 switch (Entry.Kind) {
1894 case BitstreamEntry::Error:
1895 return Error(BitcodeError::MalformedBlock);
1896 case BitstreamEntry::EndBlock:
1897 return GlobalCleanup();
1899 case BitstreamEntry::SubBlock:
1901 default: // Skip unknown content.
1902 if (Stream.SkipBlock())
1903 return Error(BitcodeError::InvalidRecord);
1905 case bitc::BLOCKINFO_BLOCK_ID:
1906 if (Stream.ReadBlockInfoBlock())
1907 return Error(BitcodeError::MalformedBlock);
1909 case bitc::PARAMATTR_BLOCK_ID:
1910 if (std::error_code EC = ParseAttributeBlock())
1913 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1914 if (std::error_code EC = ParseAttributeGroupBlock())
1917 case bitc::TYPE_BLOCK_ID_NEW:
1918 if (std::error_code EC = ParseTypeTable())
1921 case bitc::VALUE_SYMTAB_BLOCK_ID:
1922 if (std::error_code EC = ParseValueSymbolTable())
1924 SeenValueSymbolTable = true;
1926 case bitc::CONSTANTS_BLOCK_ID:
1927 if (std::error_code EC = ParseConstants())
1929 if (std::error_code EC = ResolveGlobalAndAliasInits())
1932 case bitc::METADATA_BLOCK_ID:
1933 if (std::error_code EC = ParseMetadata())
1936 case bitc::FUNCTION_BLOCK_ID:
1937 // If this is the first function body we've seen, reverse the
1938 // FunctionsWithBodies list.
1939 if (!SeenFirstFunctionBody) {
1940 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1941 if (std::error_code EC = GlobalCleanup())
1943 SeenFirstFunctionBody = true;
1946 if (std::error_code EC = RememberAndSkipFunctionBody())
1948 // For streaming bitcode, suspend parsing when we reach the function
1949 // bodies. Subsequent materialization calls will resume it when
1950 // necessary. For streaming, the function bodies must be at the end of
1951 // the bitcode. If the bitcode file is old, the symbol table will be
1952 // at the end instead and will not have been seen yet. In this case,
1953 // just finish the parse now.
1954 if (LazyStreamer && SeenValueSymbolTable) {
1955 NextUnreadBit = Stream.GetCurrentBitNo();
1956 return std::error_code();
1959 case bitc::USELIST_BLOCK_ID:
1960 if (std::error_code EC = ParseUseLists())
1966 case BitstreamEntry::Record:
1967 // The interesting case.
1973 switch (Stream.readRecord(Entry.ID, Record)) {
1974 default: break; // Default behavior, ignore unknown content.
1975 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1976 if (Record.size() < 1)
1977 return Error(BitcodeError::InvalidRecord);
1978 // Only version #0 and #1 are supported so far.
1979 unsigned module_version = Record[0];
1980 switch (module_version) {
1982 return Error(BitcodeError::InvalidValue);
1984 UseRelativeIDs = false;
1987 UseRelativeIDs = true;
1992 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1994 if (ConvertToString(Record, 0, S))
1995 return Error(BitcodeError::InvalidRecord);
1996 TheModule->setTargetTriple(S);
1999 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2001 if (ConvertToString(Record, 0, S))
2002 return Error(BitcodeError::InvalidRecord);
2003 TheModule->setDataLayout(S);
2006 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2008 if (ConvertToString(Record, 0, S))
2009 return Error(BitcodeError::InvalidRecord);
2010 TheModule->setModuleInlineAsm(S);
2013 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2014 // FIXME: Remove in 4.0.
2016 if (ConvertToString(Record, 0, S))
2017 return Error(BitcodeError::InvalidRecord);
2021 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2023 if (ConvertToString(Record, 0, S))
2024 return Error(BitcodeError::InvalidRecord);
2025 SectionTable.push_back(S);
2028 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2030 if (ConvertToString(Record, 0, S))
2031 return Error(BitcodeError::InvalidRecord);
2032 GCTable.push_back(S);
2035 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2036 if (Record.size() < 2)
2037 return Error(BitcodeError::InvalidRecord);
2038 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2039 unsigned ComdatNameSize = Record[1];
2040 std::string ComdatName;
2041 ComdatName.reserve(ComdatNameSize);
2042 for (unsigned i = 0; i != ComdatNameSize; ++i)
2043 ComdatName += (char)Record[2 + i];
2044 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2045 C->setSelectionKind(SK);
2046 ComdatList.push_back(C);
2049 // GLOBALVAR: [pointer type, isconst, initid,
2050 // linkage, alignment, section, visibility, threadlocal,
2051 // unnamed_addr, dllstorageclass]
2052 case bitc::MODULE_CODE_GLOBALVAR: {
2053 if (Record.size() < 6)
2054 return Error(BitcodeError::InvalidRecord);
2055 Type *Ty = getTypeByID(Record[0]);
2057 return Error(BitcodeError::InvalidRecord);
2058 if (!Ty->isPointerTy())
2059 return Error(BitcodeError::InvalidTypeForValue);
2060 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2061 Ty = cast<PointerType>(Ty)->getElementType();
2063 bool isConstant = Record[1];
2064 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Record[3]);
2065 unsigned Alignment = (1 << Record[4]) >> 1;
2066 std::string Section;
2068 if (Record[5]-1 >= SectionTable.size())
2069 return Error(BitcodeError::InvalidID);
2070 Section = SectionTable[Record[5]-1];
2072 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2073 // Local linkage must have default visibility.
2074 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2075 // FIXME: Change to an error if non-default in 4.0.
2076 Visibility = GetDecodedVisibility(Record[6]);
2078 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2079 if (Record.size() > 7)
2080 TLM = GetDecodedThreadLocalMode(Record[7]);
2082 bool UnnamedAddr = false;
2083 if (Record.size() > 8)
2084 UnnamedAddr = Record[8];
2086 bool ExternallyInitialized = false;
2087 if (Record.size() > 9)
2088 ExternallyInitialized = Record[9];
2090 GlobalVariable *NewGV =
2091 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2092 TLM, AddressSpace, ExternallyInitialized);
2093 NewGV->setAlignment(Alignment);
2094 if (!Section.empty())
2095 NewGV->setSection(Section);
2096 NewGV->setVisibility(Visibility);
2097 NewGV->setUnnamedAddr(UnnamedAddr);
2099 if (Record.size() > 10)
2100 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2102 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2104 ValueList.push_back(NewGV);
2106 // Remember which value to use for the global initializer.
2107 if (unsigned InitID = Record[2])
2108 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2110 if (Record.size() > 11)
2111 if (unsigned ComdatID = Record[11]) {
2112 assert(ComdatID <= ComdatList.size());
2113 NewGV->setComdat(ComdatList[ComdatID - 1]);
2117 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2118 // alignment, section, visibility, gc, unnamed_addr,
2119 // prologuedata, dllstorageclass, comdat, prefixdata]
2120 case bitc::MODULE_CODE_FUNCTION: {
2121 if (Record.size() < 8)
2122 return Error(BitcodeError::InvalidRecord);
2123 Type *Ty = getTypeByID(Record[0]);
2125 return Error(BitcodeError::InvalidRecord);
2126 if (!Ty->isPointerTy())
2127 return Error(BitcodeError::InvalidTypeForValue);
2129 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2131 return Error(BitcodeError::InvalidTypeForValue);
2133 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2136 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2137 bool isProto = Record[2];
2138 Func->setLinkage(getDecodedLinkage(Record[3]));
2139 Func->setAttributes(getAttributes(Record[4]));
2141 Func->setAlignment((1 << Record[5]) >> 1);
2143 if (Record[6]-1 >= SectionTable.size())
2144 return Error(BitcodeError::InvalidID);
2145 Func->setSection(SectionTable[Record[6]-1]);
2147 // Local linkage must have default visibility.
2148 if (!Func->hasLocalLinkage())
2149 // FIXME: Change to an error if non-default in 4.0.
2150 Func->setVisibility(GetDecodedVisibility(Record[7]));
2151 if (Record.size() > 8 && Record[8]) {
2152 if (Record[8]-1 > GCTable.size())
2153 return Error(BitcodeError::InvalidID);
2154 Func->setGC(GCTable[Record[8]-1].c_str());
2156 bool UnnamedAddr = false;
2157 if (Record.size() > 9)
2158 UnnamedAddr = Record[9];
2159 Func->setUnnamedAddr(UnnamedAddr);
2160 if (Record.size() > 10 && Record[10] != 0)
2161 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2163 if (Record.size() > 11)
2164 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2166 UpgradeDLLImportExportLinkage(Func, Record[3]);
2168 if (Record.size() > 12)
2169 if (unsigned ComdatID = Record[12]) {
2170 assert(ComdatID <= ComdatList.size());
2171 Func->setComdat(ComdatList[ComdatID - 1]);
2174 if (Record.size() > 13 && Record[13] != 0)
2175 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2177 ValueList.push_back(Func);
2179 // If this is a function with a body, remember the prototype we are
2180 // creating now, so that we can match up the body with them later.
2182 Func->setIsMaterializable(true);
2183 FunctionsWithBodies.push_back(Func);
2185 DeferredFunctionInfo[Func] = 0;
2189 // ALIAS: [alias type, aliasee val#, linkage]
2190 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2191 case bitc::MODULE_CODE_ALIAS: {
2192 if (Record.size() < 3)
2193 return Error(BitcodeError::InvalidRecord);
2194 Type *Ty = getTypeByID(Record[0]);
2196 return Error(BitcodeError::InvalidRecord);
2197 auto *PTy = dyn_cast<PointerType>(Ty);
2199 return Error(BitcodeError::InvalidTypeForValue);
2202 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2203 getDecodedLinkage(Record[2]), "", TheModule);
2204 // Old bitcode files didn't have visibility field.
2205 // Local linkage must have default visibility.
2206 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2207 // FIXME: Change to an error if non-default in 4.0.
2208 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2209 if (Record.size() > 4)
2210 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2212 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2213 if (Record.size() > 5)
2214 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2215 if (Record.size() > 6)
2216 NewGA->setUnnamedAddr(Record[6]);
2217 ValueList.push_back(NewGA);
2218 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2221 /// MODULE_CODE_PURGEVALS: [numvals]
2222 case bitc::MODULE_CODE_PURGEVALS:
2223 // Trim down the value list to the specified size.
2224 if (Record.size() < 1 || Record[0] > ValueList.size())
2225 return Error(BitcodeError::InvalidRecord);
2226 ValueList.shrinkTo(Record[0]);
2233 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2234 TheModule = nullptr;
2236 if (std::error_code EC = InitStream())
2239 // Sniff for the signature.
2240 if (Stream.Read(8) != 'B' ||
2241 Stream.Read(8) != 'C' ||
2242 Stream.Read(4) != 0x0 ||
2243 Stream.Read(4) != 0xC ||
2244 Stream.Read(4) != 0xE ||
2245 Stream.Read(4) != 0xD)
2246 return Error(BitcodeError::InvalidBitcodeSignature);
2248 // We expect a number of well-defined blocks, though we don't necessarily
2249 // need to understand them all.
2251 if (Stream.AtEndOfStream())
2252 return std::error_code();
2254 BitstreamEntry Entry =
2255 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2257 switch (Entry.Kind) {
2258 case BitstreamEntry::Error:
2259 return Error(BitcodeError::MalformedBlock);
2260 case BitstreamEntry::EndBlock:
2261 return std::error_code();
2263 case BitstreamEntry::SubBlock:
2265 case bitc::BLOCKINFO_BLOCK_ID:
2266 if (Stream.ReadBlockInfoBlock())
2267 return Error(BitcodeError::MalformedBlock);
2269 case bitc::MODULE_BLOCK_ID:
2270 // Reject multiple MODULE_BLOCK's in a single bitstream.
2272 return Error(BitcodeError::InvalidMultipleBlocks);
2274 if (std::error_code EC = ParseModule(false))
2277 return std::error_code();
2280 if (Stream.SkipBlock())
2281 return Error(BitcodeError::InvalidRecord);
2285 case BitstreamEntry::Record:
2286 // There should be no records in the top-level of blocks.
2288 // The ranlib in Xcode 4 will align archive members by appending newlines
2289 // to the end of them. If this file size is a multiple of 4 but not 8, we
2290 // have to read and ignore these final 4 bytes :-(
2291 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2292 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2293 Stream.AtEndOfStream())
2294 return std::error_code();
2296 return Error(BitcodeError::InvalidRecord);
2301 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2302 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2303 return Error(BitcodeError::InvalidRecord);
2305 SmallVector<uint64_t, 64> Record;
2308 // Read all the records for this module.
2310 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2312 switch (Entry.Kind) {
2313 case BitstreamEntry::SubBlock: // Handled for us already.
2314 case BitstreamEntry::Error:
2315 return Error(BitcodeError::MalformedBlock);
2316 case BitstreamEntry::EndBlock:
2318 case BitstreamEntry::Record:
2319 // The interesting case.
2324 switch (Stream.readRecord(Entry.ID, Record)) {
2325 default: break; // Default behavior, ignore unknown content.
2326 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2328 if (ConvertToString(Record, 0, S))
2329 return Error(BitcodeError::InvalidRecord);
2336 llvm_unreachable("Exit infinite loop");
2339 ErrorOr<std::string> BitcodeReader::parseTriple() {
2340 if (std::error_code EC = InitStream())
2343 // Sniff for the signature.
2344 if (Stream.Read(8) != 'B' ||
2345 Stream.Read(8) != 'C' ||
2346 Stream.Read(4) != 0x0 ||
2347 Stream.Read(4) != 0xC ||
2348 Stream.Read(4) != 0xE ||
2349 Stream.Read(4) != 0xD)
2350 return Error(BitcodeError::InvalidBitcodeSignature);
2352 // We expect a number of well-defined blocks, though we don't necessarily
2353 // need to understand them all.
2355 BitstreamEntry Entry = Stream.advance();
2357 switch (Entry.Kind) {
2358 case BitstreamEntry::Error:
2359 return Error(BitcodeError::MalformedBlock);
2360 case BitstreamEntry::EndBlock:
2361 return std::error_code();
2363 case BitstreamEntry::SubBlock:
2364 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2365 return parseModuleTriple();
2367 // Ignore other sub-blocks.
2368 if (Stream.SkipBlock())
2369 return Error(BitcodeError::MalformedBlock);
2372 case BitstreamEntry::Record:
2373 Stream.skipRecord(Entry.ID);
2379 /// ParseMetadataAttachment - Parse metadata attachments.
2380 std::error_code BitcodeReader::ParseMetadataAttachment() {
2381 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2382 return Error(BitcodeError::InvalidRecord);
2384 SmallVector<uint64_t, 64> Record;
2386 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2388 switch (Entry.Kind) {
2389 case BitstreamEntry::SubBlock: // Handled for us already.
2390 case BitstreamEntry::Error:
2391 return Error(BitcodeError::MalformedBlock);
2392 case BitstreamEntry::EndBlock:
2393 return std::error_code();
2394 case BitstreamEntry::Record:
2395 // The interesting case.
2399 // Read a metadata attachment record.
2401 switch (Stream.readRecord(Entry.ID, Record)) {
2402 default: // Default behavior: ignore.
2404 case bitc::METADATA_ATTACHMENT: {
2405 unsigned RecordLength = Record.size();
2406 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2407 return Error(BitcodeError::InvalidRecord);
2408 Instruction *Inst = InstructionList[Record[0]];
2409 for (unsigned i = 1; i != RecordLength; i = i+2) {
2410 unsigned Kind = Record[i];
2411 DenseMap<unsigned, unsigned>::iterator I =
2412 MDKindMap.find(Kind);
2413 if (I == MDKindMap.end())
2414 return Error(BitcodeError::InvalidID);
2415 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2416 if (isa<LocalAsMetadata>(Node))
2417 // Drop the attachment. This used to be legal, but there's no
2420 Inst->setMetadata(I->second, cast<MDNode>(Node));
2421 if (I->second == LLVMContext::MD_tbaa)
2422 InstsWithTBAATag.push_back(Inst);
2430 /// ParseFunctionBody - Lazily parse the specified function body block.
2431 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2432 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2433 return Error(BitcodeError::InvalidRecord);
2435 InstructionList.clear();
2436 unsigned ModuleValueListSize = ValueList.size();
2437 unsigned ModuleMDValueListSize = MDValueList.size();
2439 // Add all the function arguments to the value table.
2440 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2441 ValueList.push_back(I);
2443 unsigned NextValueNo = ValueList.size();
2444 BasicBlock *CurBB = nullptr;
2445 unsigned CurBBNo = 0;
2449 // Read all the records.
2450 SmallVector<uint64_t, 64> Record;
2452 BitstreamEntry Entry = Stream.advance();
2454 switch (Entry.Kind) {
2455 case BitstreamEntry::Error:
2456 return Error(BitcodeError::MalformedBlock);
2457 case BitstreamEntry::EndBlock:
2458 goto OutOfRecordLoop;
2460 case BitstreamEntry::SubBlock:
2462 default: // Skip unknown content.
2463 if (Stream.SkipBlock())
2464 return Error(BitcodeError::InvalidRecord);
2466 case bitc::CONSTANTS_BLOCK_ID:
2467 if (std::error_code EC = ParseConstants())
2469 NextValueNo = ValueList.size();
2471 case bitc::VALUE_SYMTAB_BLOCK_ID:
2472 if (std::error_code EC = ParseValueSymbolTable())
2475 case bitc::METADATA_ATTACHMENT_ID:
2476 if (std::error_code EC = ParseMetadataAttachment())
2479 case bitc::METADATA_BLOCK_ID:
2480 if (std::error_code EC = ParseMetadata())
2483 case bitc::USELIST_BLOCK_ID:
2484 if (std::error_code EC = ParseUseLists())
2490 case BitstreamEntry::Record:
2491 // The interesting case.
2497 Instruction *I = nullptr;
2498 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2500 default: // Default behavior: reject
2501 return Error(BitcodeError::InvalidValue);
2502 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2503 if (Record.size() < 1 || Record[0] == 0)
2504 return Error(BitcodeError::InvalidRecord);
2505 // Create all the basic blocks for the function.
2506 FunctionBBs.resize(Record[0]);
2508 // See if anything took the address of blocks in this function.
2509 auto BBFRI = BasicBlockFwdRefs.find(F);
2510 if (BBFRI == BasicBlockFwdRefs.end()) {
2511 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2512 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2514 auto &BBRefs = BBFRI->second;
2515 // Check for invalid basic block references.
2516 if (BBRefs.size() > FunctionBBs.size())
2517 return Error(BitcodeError::InvalidID);
2518 assert(!BBRefs.empty() && "Unexpected empty array");
2519 assert(!BBRefs.front() && "Invalid reference to entry block");
2520 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2522 if (I < RE && BBRefs[I]) {
2523 BBRefs[I]->insertInto(F);
2524 FunctionBBs[I] = BBRefs[I];
2526 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2529 // Erase from the table.
2530 BasicBlockFwdRefs.erase(BBFRI);
2533 CurBB = FunctionBBs[0];
2537 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2538 // This record indicates that the last instruction is at the same
2539 // location as the previous instruction with a location.
2542 // Get the last instruction emitted.
2543 if (CurBB && !CurBB->empty())
2545 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2546 !FunctionBBs[CurBBNo-1]->empty())
2547 I = &FunctionBBs[CurBBNo-1]->back();
2550 return Error(BitcodeError::InvalidRecord);
2551 I->setDebugLoc(LastLoc);
2555 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2556 I = nullptr; // Get the last instruction emitted.
2557 if (CurBB && !CurBB->empty())
2559 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2560 !FunctionBBs[CurBBNo-1]->empty())
2561 I = &FunctionBBs[CurBBNo-1]->back();
2562 if (!I || Record.size() < 4)
2563 return Error(BitcodeError::InvalidRecord);
2565 unsigned Line = Record[0], Col = Record[1];
2566 unsigned ScopeID = Record[2], IAID = Record[3];
2568 MDNode *Scope = nullptr, *IA = nullptr;
2569 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2570 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2571 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2572 I->setDebugLoc(LastLoc);
2577 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2580 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2581 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2582 OpNum+1 > Record.size())
2583 return Error(BitcodeError::InvalidRecord);
2585 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2587 return Error(BitcodeError::InvalidRecord);
2588 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2589 InstructionList.push_back(I);
2590 if (OpNum < Record.size()) {
2591 if (Opc == Instruction::Add ||
2592 Opc == Instruction::Sub ||
2593 Opc == Instruction::Mul ||
2594 Opc == Instruction::Shl) {
2595 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2596 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2597 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2598 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2599 } else if (Opc == Instruction::SDiv ||
2600 Opc == Instruction::UDiv ||
2601 Opc == Instruction::LShr ||
2602 Opc == Instruction::AShr) {
2603 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2604 cast<BinaryOperator>(I)->setIsExact(true);
2605 } else if (isa<FPMathOperator>(I)) {
2607 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2608 FMF.setUnsafeAlgebra();
2609 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2611 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2613 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2614 FMF.setNoSignedZeros();
2615 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2616 FMF.setAllowReciprocal();
2618 I->setFastMathFlags(FMF);
2624 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2627 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2628 OpNum+2 != Record.size())
2629 return Error(BitcodeError::InvalidRecord);
2631 Type *ResTy = getTypeByID(Record[OpNum]);
2632 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2633 if (Opc == -1 || !ResTy)
2634 return Error(BitcodeError::InvalidRecord);
2635 Instruction *Temp = nullptr;
2636 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2638 InstructionList.push_back(Temp);
2639 CurBB->getInstList().push_back(Temp);
2642 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2644 InstructionList.push_back(I);
2647 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2648 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2651 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2652 return Error(BitcodeError::InvalidRecord);
2654 SmallVector<Value*, 16> GEPIdx;
2655 while (OpNum != Record.size()) {
2657 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2658 return Error(BitcodeError::InvalidRecord);
2659 GEPIdx.push_back(Op);
2662 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2663 InstructionList.push_back(I);
2664 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2665 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2669 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2670 // EXTRACTVAL: [opty, opval, n x indices]
2673 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2674 return Error(BitcodeError::InvalidRecord);
2676 SmallVector<unsigned, 4> EXTRACTVALIdx;
2677 for (unsigned RecSize = Record.size();
2678 OpNum != RecSize; ++OpNum) {
2679 uint64_t Index = Record[OpNum];
2680 if ((unsigned)Index != Index)
2681 return Error(BitcodeError::InvalidValue);
2682 EXTRACTVALIdx.push_back((unsigned)Index);
2685 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2686 InstructionList.push_back(I);
2690 case bitc::FUNC_CODE_INST_INSERTVAL: {
2691 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2694 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2695 return Error(BitcodeError::InvalidRecord);
2697 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2698 return Error(BitcodeError::InvalidRecord);
2700 SmallVector<unsigned, 4> INSERTVALIdx;
2701 for (unsigned RecSize = Record.size();
2702 OpNum != RecSize; ++OpNum) {
2703 uint64_t Index = Record[OpNum];
2704 if ((unsigned)Index != Index)
2705 return Error(BitcodeError::InvalidValue);
2706 INSERTVALIdx.push_back((unsigned)Index);
2709 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2710 InstructionList.push_back(I);
2714 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2715 // obsolete form of select
2716 // handles select i1 ... in old bitcode
2718 Value *TrueVal, *FalseVal, *Cond;
2719 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2720 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2721 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2722 return Error(BitcodeError::InvalidRecord);
2724 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2725 InstructionList.push_back(I);
2729 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2730 // new form of select
2731 // handles select i1 or select [N x i1]
2733 Value *TrueVal, *FalseVal, *Cond;
2734 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2735 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2736 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2737 return Error(BitcodeError::InvalidRecord);
2739 // select condition can be either i1 or [N x i1]
2740 if (VectorType* vector_type =
2741 dyn_cast<VectorType>(Cond->getType())) {
2743 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2744 return Error(BitcodeError::InvalidTypeForValue);
2747 if (Cond->getType() != Type::getInt1Ty(Context))
2748 return Error(BitcodeError::InvalidTypeForValue);
2751 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2752 InstructionList.push_back(I);
2756 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2759 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2760 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2761 return Error(BitcodeError::InvalidRecord);
2762 I = ExtractElementInst::Create(Vec, Idx);
2763 InstructionList.push_back(I);
2767 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2769 Value *Vec, *Elt, *Idx;
2770 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2771 popValue(Record, OpNum, NextValueNo,
2772 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2773 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2774 return Error(BitcodeError::InvalidRecord);
2775 I = InsertElementInst::Create(Vec, Elt, Idx);
2776 InstructionList.push_back(I);
2780 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2782 Value *Vec1, *Vec2, *Mask;
2783 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2784 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2785 return Error(BitcodeError::InvalidRecord);
2787 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2788 return Error(BitcodeError::InvalidRecord);
2789 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2790 InstructionList.push_back(I);
2794 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2795 // Old form of ICmp/FCmp returning bool
2796 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2797 // both legal on vectors but had different behaviour.
2798 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2799 // FCmp/ICmp returning bool or vector of bool
2803 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2804 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2805 OpNum+1 != Record.size())
2806 return Error(BitcodeError::InvalidRecord);
2808 if (LHS->getType()->isFPOrFPVectorTy())
2809 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2811 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2812 InstructionList.push_back(I);
2816 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2818 unsigned Size = Record.size();
2820 I = ReturnInst::Create(Context);
2821 InstructionList.push_back(I);
2826 Value *Op = nullptr;
2827 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2828 return Error(BitcodeError::InvalidRecord);
2829 if (OpNum != Record.size())
2830 return Error(BitcodeError::InvalidRecord);
2832 I = ReturnInst::Create(Context, Op);
2833 InstructionList.push_back(I);
2836 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2837 if (Record.size() != 1 && Record.size() != 3)
2838 return Error(BitcodeError::InvalidRecord);
2839 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2841 return Error(BitcodeError::InvalidRecord);
2843 if (Record.size() == 1) {
2844 I = BranchInst::Create(TrueDest);
2845 InstructionList.push_back(I);
2848 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2849 Value *Cond = getValue(Record, 2, NextValueNo,
2850 Type::getInt1Ty(Context));
2851 if (!FalseDest || !Cond)
2852 return Error(BitcodeError::InvalidRecord);
2853 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2854 InstructionList.push_back(I);
2858 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2860 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2861 // "New" SwitchInst format with case ranges. The changes to write this
2862 // format were reverted but we still recognize bitcode that uses it.
2863 // Hopefully someday we will have support for case ranges and can use
2864 // this format again.
2866 Type *OpTy = getTypeByID(Record[1]);
2867 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2869 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2870 BasicBlock *Default = getBasicBlock(Record[3]);
2871 if (!OpTy || !Cond || !Default)
2872 return Error(BitcodeError::InvalidRecord);
2874 unsigned NumCases = Record[4];
2876 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2877 InstructionList.push_back(SI);
2879 unsigned CurIdx = 5;
2880 for (unsigned i = 0; i != NumCases; ++i) {
2881 SmallVector<ConstantInt*, 1> CaseVals;
2882 unsigned NumItems = Record[CurIdx++];
2883 for (unsigned ci = 0; ci != NumItems; ++ci) {
2884 bool isSingleNumber = Record[CurIdx++];
2887 unsigned ActiveWords = 1;
2888 if (ValueBitWidth > 64)
2889 ActiveWords = Record[CurIdx++];
2890 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2892 CurIdx += ActiveWords;
2894 if (!isSingleNumber) {
2896 if (ValueBitWidth > 64)
2897 ActiveWords = Record[CurIdx++];
2899 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2901 CurIdx += ActiveWords;
2903 // FIXME: It is not clear whether values in the range should be
2904 // compared as signed or unsigned values. The partially
2905 // implemented changes that used this format in the past used
2906 // unsigned comparisons.
2907 for ( ; Low.ule(High); ++Low)
2908 CaseVals.push_back(ConstantInt::get(Context, Low));
2910 CaseVals.push_back(ConstantInt::get(Context, Low));
2912 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2913 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2914 cve = CaseVals.end(); cvi != cve; ++cvi)
2915 SI->addCase(*cvi, DestBB);
2921 // Old SwitchInst format without case ranges.
2923 if (Record.size() < 3 || (Record.size() & 1) == 0)
2924 return Error(BitcodeError::InvalidRecord);
2925 Type *OpTy = getTypeByID(Record[0]);
2926 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2927 BasicBlock *Default = getBasicBlock(Record[2]);
2928 if (!OpTy || !Cond || !Default)
2929 return Error(BitcodeError::InvalidRecord);
2930 unsigned NumCases = (Record.size()-3)/2;
2931 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2932 InstructionList.push_back(SI);
2933 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2934 ConstantInt *CaseVal =
2935 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2936 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2937 if (!CaseVal || !DestBB) {
2939 return Error(BitcodeError::InvalidRecord);
2941 SI->addCase(CaseVal, DestBB);
2946 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2947 if (Record.size() < 2)
2948 return Error(BitcodeError::InvalidRecord);
2949 Type *OpTy = getTypeByID(Record[0]);
2950 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2951 if (!OpTy || !Address)
2952 return Error(BitcodeError::InvalidRecord);
2953 unsigned NumDests = Record.size()-2;
2954 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2955 InstructionList.push_back(IBI);
2956 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2957 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2958 IBI->addDestination(DestBB);
2961 return Error(BitcodeError::InvalidRecord);
2968 case bitc::FUNC_CODE_INST_INVOKE: {
2969 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2970 if (Record.size() < 4)
2971 return Error(BitcodeError::InvalidRecord);
2972 AttributeSet PAL = getAttributes(Record[0]);
2973 unsigned CCInfo = Record[1];
2974 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2975 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2979 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2980 return Error(BitcodeError::InvalidRecord);
2982 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2983 FunctionType *FTy = !CalleeTy ? nullptr :
2984 dyn_cast<FunctionType>(CalleeTy->getElementType());
2986 // Check that the right number of fixed parameters are here.
2987 if (!FTy || !NormalBB || !UnwindBB ||
2988 Record.size() < OpNum+FTy->getNumParams())
2989 return Error(BitcodeError::InvalidRecord);
2991 SmallVector<Value*, 16> Ops;
2992 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2993 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2994 FTy->getParamType(i)));
2996 return Error(BitcodeError::InvalidRecord);
2999 if (!FTy->isVarArg()) {
3000 if (Record.size() != OpNum)
3001 return Error(BitcodeError::InvalidRecord);
3003 // Read type/value pairs for varargs params.
3004 while (OpNum != Record.size()) {
3006 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3007 return Error(BitcodeError::InvalidRecord);
3012 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3013 InstructionList.push_back(I);
3014 cast<InvokeInst>(I)->setCallingConv(
3015 static_cast<CallingConv::ID>(CCInfo));
3016 cast<InvokeInst>(I)->setAttributes(PAL);
3019 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3021 Value *Val = nullptr;
3022 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3023 return Error(BitcodeError::InvalidRecord);
3024 I = ResumeInst::Create(Val);
3025 InstructionList.push_back(I);
3028 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3029 I = new UnreachableInst(Context);
3030 InstructionList.push_back(I);
3032 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3033 if (Record.size() < 1 || ((Record.size()-1)&1))
3034 return Error(BitcodeError::InvalidRecord);
3035 Type *Ty = getTypeByID(Record[0]);
3037 return Error(BitcodeError::InvalidRecord);
3039 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3040 InstructionList.push_back(PN);
3042 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3044 // With the new function encoding, it is possible that operands have
3045 // negative IDs (for forward references). Use a signed VBR
3046 // representation to keep the encoding small.
3048 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3050 V = getValue(Record, 1+i, NextValueNo, Ty);
3051 BasicBlock *BB = getBasicBlock(Record[2+i]);
3053 return Error(BitcodeError::InvalidRecord);
3054 PN->addIncoming(V, BB);
3060 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3061 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3063 if (Record.size() < 4)
3064 return Error(BitcodeError::InvalidRecord);
3065 Type *Ty = getTypeByID(Record[Idx++]);
3067 return Error(BitcodeError::InvalidRecord);
3068 Value *PersFn = nullptr;
3069 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3070 return Error(BitcodeError::InvalidRecord);
3072 bool IsCleanup = !!Record[Idx++];
3073 unsigned NumClauses = Record[Idx++];
3074 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3075 LP->setCleanup(IsCleanup);
3076 for (unsigned J = 0; J != NumClauses; ++J) {
3077 LandingPadInst::ClauseType CT =
3078 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3081 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3083 return Error(BitcodeError::InvalidRecord);
3086 assert((CT != LandingPadInst::Catch ||
3087 !isa<ArrayType>(Val->getType())) &&
3088 "Catch clause has a invalid type!");
3089 assert((CT != LandingPadInst::Filter ||
3090 isa<ArrayType>(Val->getType())) &&
3091 "Filter clause has invalid type!");
3092 LP->addClause(cast<Constant>(Val));
3096 InstructionList.push_back(I);
3100 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3101 if (Record.size() != 4)
3102 return Error(BitcodeError::InvalidRecord);
3104 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3105 Type *OpTy = getTypeByID(Record[1]);
3106 Value *Size = getFnValueByID(Record[2], OpTy);
3107 unsigned AlignRecord = Record[3];
3108 bool InAlloca = AlignRecord & (1 << 5);
3109 unsigned Align = AlignRecord & ((1 << 5) - 1);
3111 return Error(BitcodeError::InvalidRecord);
3112 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3113 AI->setUsedWithInAlloca(InAlloca);
3115 InstructionList.push_back(I);
3118 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3121 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3122 OpNum+2 != Record.size())
3123 return Error(BitcodeError::InvalidRecord);
3125 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3126 InstructionList.push_back(I);
3129 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3130 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3133 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3134 OpNum+4 != Record.size())
3135 return Error(BitcodeError::InvalidRecord);
3137 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3138 if (Ordering == NotAtomic || Ordering == Release ||
3139 Ordering == AcquireRelease)
3140 return Error(BitcodeError::InvalidRecord);
3141 if (Ordering != NotAtomic && Record[OpNum] == 0)
3142 return Error(BitcodeError::InvalidRecord);
3143 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3145 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3146 Ordering, SynchScope);
3147 InstructionList.push_back(I);
3150 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3153 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3154 popValue(Record, OpNum, NextValueNo,
3155 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3156 OpNum+2 != Record.size())
3157 return Error(BitcodeError::InvalidRecord);
3159 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3160 InstructionList.push_back(I);
3163 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3164 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3167 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3168 popValue(Record, OpNum, NextValueNo,
3169 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3170 OpNum+4 != Record.size())
3171 return Error(BitcodeError::InvalidRecord);
3173 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3174 if (Ordering == NotAtomic || Ordering == Acquire ||
3175 Ordering == AcquireRelease)
3176 return Error(BitcodeError::InvalidRecord);
3177 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3178 if (Ordering != NotAtomic && Record[OpNum] == 0)
3179 return Error(BitcodeError::InvalidRecord);
3181 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3182 Ordering, SynchScope);
3183 InstructionList.push_back(I);
3186 case bitc::FUNC_CODE_INST_CMPXCHG: {
3187 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3188 // failureordering?, isweak?]
3190 Value *Ptr, *Cmp, *New;
3191 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3192 popValue(Record, OpNum, NextValueNo,
3193 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3194 popValue(Record, OpNum, NextValueNo,
3195 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3196 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3197 return Error(BitcodeError::InvalidRecord);
3198 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3199 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3200 return Error(BitcodeError::InvalidRecord);
3201 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3203 AtomicOrdering FailureOrdering;
3204 if (Record.size() < 7)
3206 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3208 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3210 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3212 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3214 if (Record.size() < 8) {
3215 // Before weak cmpxchgs existed, the instruction simply returned the
3216 // value loaded from memory, so bitcode files from that era will be
3217 // expecting the first component of a modern cmpxchg.
3218 CurBB->getInstList().push_back(I);
3219 I = ExtractValueInst::Create(I, 0);
3221 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3224 InstructionList.push_back(I);
3227 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3228 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3231 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3232 popValue(Record, OpNum, NextValueNo,
3233 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3234 OpNum+4 != Record.size())
3235 return Error(BitcodeError::InvalidRecord);
3236 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3237 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3238 Operation > AtomicRMWInst::LAST_BINOP)
3239 return Error(BitcodeError::InvalidRecord);
3240 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3241 if (Ordering == NotAtomic || Ordering == Unordered)
3242 return Error(BitcodeError::InvalidRecord);
3243 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3244 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3245 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3246 InstructionList.push_back(I);
3249 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3250 if (2 != Record.size())
3251 return Error(BitcodeError::InvalidRecord);
3252 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3253 if (Ordering == NotAtomic || Ordering == Unordered ||
3254 Ordering == Monotonic)
3255 return Error(BitcodeError::InvalidRecord);
3256 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3257 I = new FenceInst(Context, Ordering, SynchScope);
3258 InstructionList.push_back(I);
3261 case bitc::FUNC_CODE_INST_CALL: {
3262 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3263 if (Record.size() < 3)
3264 return Error(BitcodeError::InvalidRecord);
3266 AttributeSet PAL = getAttributes(Record[0]);
3267 unsigned CCInfo = Record[1];
3271 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3272 return Error(BitcodeError::InvalidRecord);
3274 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3275 FunctionType *FTy = nullptr;
3276 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3277 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3278 return Error(BitcodeError::InvalidRecord);
3280 SmallVector<Value*, 16> Args;
3281 // Read the fixed params.
3282 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3283 if (FTy->getParamType(i)->isLabelTy())
3284 Args.push_back(getBasicBlock(Record[OpNum]));
3286 Args.push_back(getValue(Record, OpNum, NextValueNo,
3287 FTy->getParamType(i)));
3289 return Error(BitcodeError::InvalidRecord);
3292 // Read type/value pairs for varargs params.
3293 if (!FTy->isVarArg()) {
3294 if (OpNum != Record.size())
3295 return Error(BitcodeError::InvalidRecord);
3297 while (OpNum != Record.size()) {
3299 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3300 return Error(BitcodeError::InvalidRecord);
3305 I = CallInst::Create(Callee, Args);
3306 InstructionList.push_back(I);
3307 cast<CallInst>(I)->setCallingConv(
3308 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3309 CallInst::TailCallKind TCK = CallInst::TCK_None;
3311 TCK = CallInst::TCK_Tail;
3312 if (CCInfo & (1 << 14))
3313 TCK = CallInst::TCK_MustTail;
3314 cast<CallInst>(I)->setTailCallKind(TCK);
3315 cast<CallInst>(I)->setAttributes(PAL);
3318 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3319 if (Record.size() < 3)
3320 return Error(BitcodeError::InvalidRecord);
3321 Type *OpTy = getTypeByID(Record[0]);
3322 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3323 Type *ResTy = getTypeByID(Record[2]);
3324 if (!OpTy || !Op || !ResTy)
3325 return Error(BitcodeError::InvalidRecord);
3326 I = new VAArgInst(Op, ResTy);
3327 InstructionList.push_back(I);
3332 // Add instruction to end of current BB. If there is no current BB, reject
3336 return Error(BitcodeError::InvalidInstructionWithNoBB);
3338 CurBB->getInstList().push_back(I);
3340 // If this was a terminator instruction, move to the next block.
3341 if (isa<TerminatorInst>(I)) {
3343 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3346 // Non-void values get registered in the value table for future use.
3347 if (I && !I->getType()->isVoidTy())
3348 ValueList.AssignValue(I, NextValueNo++);
3353 // Check the function list for unresolved values.
3354 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3355 if (!A->getParent()) {
3356 // We found at least one unresolved value. Nuke them all to avoid leaks.
3357 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3358 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3359 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3363 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3367 // FIXME: Check for unresolved forward-declared metadata references
3368 // and clean up leaks.
3370 // Trim the value list down to the size it was before we parsed this function.
3371 ValueList.shrinkTo(ModuleValueListSize);
3372 MDValueList.shrinkTo(ModuleMDValueListSize);
3373 std::vector<BasicBlock*>().swap(FunctionBBs);
3374 return std::error_code();
3377 /// Find the function body in the bitcode stream
3378 std::error_code BitcodeReader::FindFunctionInStream(
3380 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3381 while (DeferredFunctionInfoIterator->second == 0) {
3382 if (Stream.AtEndOfStream())
3383 return Error(BitcodeError::CouldNotFindFunctionInStream);
3384 // ParseModule will parse the next body in the stream and set its
3385 // position in the DeferredFunctionInfo map.
3386 if (std::error_code EC = ParseModule(true))
3389 return std::error_code();
3392 //===----------------------------------------------------------------------===//
3393 // GVMaterializer implementation
3394 //===----------------------------------------------------------------------===//
3396 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3398 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3399 Function *F = dyn_cast<Function>(GV);
3400 // If it's not a function or is already material, ignore the request.
3401 if (!F || !F->isMaterializable())
3402 return std::error_code();
3404 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3405 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3406 // If its position is recorded as 0, its body is somewhere in the stream
3407 // but we haven't seen it yet.
3408 if (DFII->second == 0 && LazyStreamer)
3409 if (std::error_code EC = FindFunctionInStream(F, DFII))
3412 // Move the bit stream to the saved position of the deferred function body.
3413 Stream.JumpToBit(DFII->second);
3415 if (std::error_code EC = ParseFunctionBody(F))
3417 F->setIsMaterializable(false);
3419 // Upgrade any old intrinsic calls in the function.
3420 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3421 E = UpgradedIntrinsics.end(); I != E; ++I) {
3422 if (I->first != I->second) {
3423 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3425 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3426 UpgradeIntrinsicCall(CI, I->second);
3431 // Bring in any functions that this function forward-referenced via
3433 return materializeForwardReferencedFunctions();
3436 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3437 const Function *F = dyn_cast<Function>(GV);
3438 if (!F || F->isDeclaration())
3441 // Dematerializing F would leave dangling references that wouldn't be
3442 // reconnected on re-materialization.
3443 if (BlockAddressesTaken.count(F))
3446 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3449 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3450 Function *F = dyn_cast<Function>(GV);
3451 // If this function isn't dematerializable, this is a noop.
3452 if (!F || !isDematerializable(F))
3455 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3457 // Just forget the function body, we can remat it later.
3458 F->dropAllReferences();
3459 F->setIsMaterializable(true);
3462 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3463 assert(M == TheModule &&
3464 "Can only Materialize the Module this BitcodeReader is attached to.");
3466 // Promise to materialize all forward references.
3467 WillMaterializeAllForwardRefs = true;
3469 // Iterate over the module, deserializing any functions that are still on
3471 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3473 if (std::error_code EC = materialize(F))
3476 // At this point, if there are any function bodies, the current bit is
3477 // pointing to the END_BLOCK record after them. Now make sure the rest
3478 // of the bits in the module have been read.
3482 // Check that all block address forward references got resolved (as we
3484 if (!BasicBlockFwdRefs.empty())
3485 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3487 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3488 // delete the old functions to clean up. We can't do this unless the entire
3489 // module is materialized because there could always be another function body
3490 // with calls to the old function.
3491 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3492 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3493 if (I->first != I->second) {
3494 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3496 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3497 UpgradeIntrinsicCall(CI, I->second);
3499 if (!I->first->use_empty())
3500 I->first->replaceAllUsesWith(I->second);
3501 I->first->eraseFromParent();
3504 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3506 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3507 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3509 UpgradeDebugInfo(*M);
3510 return std::error_code();
3513 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3514 return IdentifiedStructTypes;
3517 std::error_code BitcodeReader::InitStream() {
3519 return InitLazyStream();
3520 return InitStreamFromBuffer();
3523 std::error_code BitcodeReader::InitStreamFromBuffer() {
3524 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3525 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3527 if (Buffer->getBufferSize() & 3)
3528 return Error(BitcodeError::InvalidBitcodeSignature);
3530 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3531 // The magic number is 0x0B17C0DE stored in little endian.
3532 if (isBitcodeWrapper(BufPtr, BufEnd))
3533 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3534 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3536 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3537 Stream.init(&*StreamFile);
3539 return std::error_code();
3542 std::error_code BitcodeReader::InitLazyStream() {
3543 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3545 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3546 StreamingMemoryObject &Bytes = *OwnedBytes;
3547 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3548 Stream.init(&*StreamFile);
3550 unsigned char buf[16];
3551 if (Bytes.readBytes(buf, 16, 0) != 16)
3552 return Error(BitcodeError::InvalidBitcodeSignature);
3554 if (!isBitcode(buf, buf + 16))
3555 return Error(BitcodeError::InvalidBitcodeSignature);
3557 if (isBitcodeWrapper(buf, buf + 4)) {
3558 const unsigned char *bitcodeStart = buf;
3559 const unsigned char *bitcodeEnd = buf + 16;
3560 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3561 Bytes.dropLeadingBytes(bitcodeStart - buf);
3562 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3564 return std::error_code();
3568 class BitcodeErrorCategoryType : public std::error_category {
3569 const char *name() const LLVM_NOEXCEPT override {
3570 return "llvm.bitcode";
3572 std::string message(int IE) const override {
3573 BitcodeError E = static_cast<BitcodeError>(IE);
3575 case BitcodeError::ConflictingMETADATA_KINDRecords:
3576 return "Conflicting METADATA_KIND records";
3577 case BitcodeError::CouldNotFindFunctionInStream:
3578 return "Could not find function in stream";
3579 case BitcodeError::ExpectedConstant:
3580 return "Expected a constant";
3581 case BitcodeError::InsufficientFunctionProtos:
3582 return "Insufficient function protos";
3583 case BitcodeError::InvalidBitcodeSignature:
3584 return "Invalid bitcode signature";
3585 case BitcodeError::InvalidBitcodeWrapperHeader:
3586 return "Invalid bitcode wrapper header";
3587 case BitcodeError::InvalidConstantReference:
3588 return "Invalid ronstant reference";
3589 case BitcodeError::InvalidID:
3590 return "Invalid ID";
3591 case BitcodeError::InvalidInstructionWithNoBB:
3592 return "Invalid instruction with no BB";
3593 case BitcodeError::InvalidRecord:
3594 return "Invalid record";
3595 case BitcodeError::InvalidTypeForValue:
3596 return "Invalid type for value";
3597 case BitcodeError::InvalidTYPETable:
3598 return "Invalid TYPE table";
3599 case BitcodeError::InvalidType:
3600 return "Invalid type";
3601 case BitcodeError::MalformedBlock:
3602 return "Malformed block";
3603 case BitcodeError::MalformedGlobalInitializerSet:
3604 return "Malformed global initializer set";
3605 case BitcodeError::InvalidMultipleBlocks:
3606 return "Invalid multiple blocks";
3607 case BitcodeError::NeverResolvedValueFoundInFunction:
3608 return "Never resolved value found in function";
3609 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3610 return "Never resolved function from blockaddress";
3611 case BitcodeError::InvalidValue:
3612 return "Invalid value";
3614 llvm_unreachable("Unknown error type!");
3619 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3621 const std::error_category &llvm::BitcodeErrorCategory() {
3622 return *ErrorCategory;
3625 //===----------------------------------------------------------------------===//
3626 // External interface
3627 //===----------------------------------------------------------------------===//
3629 /// \brief Get a lazy one-at-time loading module from bitcode.
3631 /// This isn't always used in a lazy context. In particular, it's also used by
3632 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3633 /// in forward-referenced functions from block address references.
3635 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3636 /// materialize everything -- in particular, if this isn't truly lazy.
3637 static ErrorOr<Module *>
3638 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3639 LLVMContext &Context, bool WillMaterializeAll) {
3640 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3641 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3642 M->setMaterializer(R);
3644 auto cleanupOnError = [&](std::error_code EC) {
3645 R->releaseBuffer(); // Never take ownership on error.
3646 delete M; // Also deletes R.
3650 if (std::error_code EC = R->ParseBitcodeInto(M))
3651 return cleanupOnError(EC);
3653 if (!WillMaterializeAll)
3654 // Resolve forward references from blockaddresses.
3655 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3656 return cleanupOnError(EC);
3658 Buffer.release(); // The BitcodeReader owns it now.
3663 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3664 LLVMContext &Context) {
3665 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3668 ErrorOr<std::unique_ptr<Module>>
3669 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3670 LLVMContext &Context) {
3671 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3672 BitcodeReader *R = new BitcodeReader(Streamer, Context);
3673 M->setMaterializer(R);
3674 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3676 return std::move(M);
3679 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3680 LLVMContext &Context) {
3681 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3682 ErrorOr<Module *> ModuleOrErr =
3683 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3686 Module *M = ModuleOrErr.get();
3687 // Read in the entire module, and destroy the BitcodeReader.
3688 if (std::error_code EC = M->materializeAllPermanently()) {
3693 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3694 // written. We must defer until the Module has been fully materialized.
3699 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3700 LLVMContext &Context) {
3701 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3702 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3703 ErrorOr<std::string> Triple = R->parseTriple();
3704 if (Triple.getError())
3706 return Triple.get();