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
106 case 0: return GlobalValue::ExternalLinkage;
107 case 1: return GlobalValue::WeakAnyLinkage;
108 case 2: return GlobalValue::AppendingLinkage;
109 case 3: return GlobalValue::InternalLinkage;
110 case 4: return GlobalValue::LinkOnceAnyLinkage;
111 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
112 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
113 case 7: return GlobalValue::ExternalWeakLinkage;
114 case 8: return GlobalValue::CommonLinkage;
115 case 9: return GlobalValue::PrivateLinkage;
116 case 10: return GlobalValue::WeakODRLinkage;
117 case 11: return GlobalValue::LinkOnceODRLinkage;
118 case 12: return GlobalValue::AvailableExternallyLinkage;
120 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
122 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
126 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
128 default: // Map unknown visibilities to default.
129 case 0: return GlobalValue::DefaultVisibility;
130 case 1: return GlobalValue::HiddenVisibility;
131 case 2: return GlobalValue::ProtectedVisibility;
135 static GlobalValue::DLLStorageClassTypes
136 GetDecodedDLLStorageClass(unsigned Val) {
138 default: // Map unknown values to default.
139 case 0: return GlobalValue::DefaultStorageClass;
140 case 1: return GlobalValue::DLLImportStorageClass;
141 case 2: return GlobalValue::DLLExportStorageClass;
145 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
147 case 0: return GlobalVariable::NotThreadLocal;
148 default: // Map unknown non-zero value to general dynamic.
149 case 1: return GlobalVariable::GeneralDynamicTLSModel;
150 case 2: return GlobalVariable::LocalDynamicTLSModel;
151 case 3: return GlobalVariable::InitialExecTLSModel;
152 case 4: return GlobalVariable::LocalExecTLSModel;
156 static int GetDecodedCastOpcode(unsigned Val) {
159 case bitc::CAST_TRUNC : return Instruction::Trunc;
160 case bitc::CAST_ZEXT : return Instruction::ZExt;
161 case bitc::CAST_SEXT : return Instruction::SExt;
162 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
163 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
164 case bitc::CAST_UITOFP : return Instruction::UIToFP;
165 case bitc::CAST_SITOFP : return Instruction::SIToFP;
166 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
167 case bitc::CAST_FPEXT : return Instruction::FPExt;
168 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
169 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
170 case bitc::CAST_BITCAST : return Instruction::BitCast;
171 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
174 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
177 case bitc::BINOP_ADD:
178 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
179 case bitc::BINOP_SUB:
180 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
181 case bitc::BINOP_MUL:
182 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
183 case bitc::BINOP_UDIV: return Instruction::UDiv;
184 case bitc::BINOP_SDIV:
185 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
186 case bitc::BINOP_UREM: return Instruction::URem;
187 case bitc::BINOP_SREM:
188 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
189 case bitc::BINOP_SHL: return Instruction::Shl;
190 case bitc::BINOP_LSHR: return Instruction::LShr;
191 case bitc::BINOP_ASHR: return Instruction::AShr;
192 case bitc::BINOP_AND: return Instruction::And;
193 case bitc::BINOP_OR: return Instruction::Or;
194 case bitc::BINOP_XOR: return Instruction::Xor;
198 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
200 default: return AtomicRMWInst::BAD_BINOP;
201 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
202 case bitc::RMW_ADD: return AtomicRMWInst::Add;
203 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
204 case bitc::RMW_AND: return AtomicRMWInst::And;
205 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
206 case bitc::RMW_OR: return AtomicRMWInst::Or;
207 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
208 case bitc::RMW_MAX: return AtomicRMWInst::Max;
209 case bitc::RMW_MIN: return AtomicRMWInst::Min;
210 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
211 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
215 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
217 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
218 case bitc::ORDERING_UNORDERED: return Unordered;
219 case bitc::ORDERING_MONOTONIC: return Monotonic;
220 case bitc::ORDERING_ACQUIRE: return Acquire;
221 case bitc::ORDERING_RELEASE: return Release;
222 case bitc::ORDERING_ACQREL: return AcquireRelease;
223 default: // Map unknown orderings to sequentially-consistent.
224 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
228 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
230 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
231 default: // Map unknown scopes to cross-thread.
232 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
236 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
238 default: // Map unknown selection kinds to any.
239 case bitc::COMDAT_SELECTION_KIND_ANY:
241 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
242 return Comdat::ExactMatch;
243 case bitc::COMDAT_SELECTION_KIND_LARGEST:
244 return Comdat::Largest;
245 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
246 return Comdat::NoDuplicates;
247 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
248 return Comdat::SameSize;
252 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
254 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
255 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
261 /// @brief A class for maintaining the slot number definition
262 /// as a placeholder for the actual definition for forward constants defs.
263 class ConstantPlaceHolder : public ConstantExpr {
264 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
266 // allocate space for exactly one operand
267 void *operator new(size_t s) {
268 return User::operator new(s, 1);
270 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
271 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
272 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
275 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
276 static bool classof(const Value *V) {
277 return isa<ConstantExpr>(V) &&
278 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
282 /// Provide fast operand accessors
283 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
287 // FIXME: can we inherit this from ConstantExpr?
289 struct OperandTraits<ConstantPlaceHolder> :
290 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
292 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
296 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
305 WeakVH &OldV = ValuePtrs[Idx];
311 // Handle constants and non-constants (e.g. instrs) differently for
313 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
314 ResolveConstants.push_back(std::make_pair(PHC, Idx));
317 // If there was a forward reference to this value, replace it.
318 Value *PrevVal = OldV;
319 OldV->replaceAllUsesWith(V);
325 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
330 if (Value *V = ValuePtrs[Idx]) {
331 assert(Ty == V->getType() && "Type mismatch in constant table!");
332 return cast<Constant>(V);
335 // Create and return a placeholder, which will later be RAUW'd.
336 Constant *C = new ConstantPlaceHolder(Ty, Context);
341 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
345 if (Value *V = ValuePtrs[Idx]) {
346 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
350 // No type specified, must be invalid reference.
351 if (!Ty) return nullptr;
353 // Create and return a placeholder, which will later be RAUW'd.
354 Value *V = new Argument(Ty);
359 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
360 /// resolves any forward references. The idea behind this is that we sometimes
361 /// get constants (such as large arrays) which reference *many* forward ref
362 /// constants. Replacing each of these causes a lot of thrashing when
363 /// building/reuniquing the constant. Instead of doing this, we look at all the
364 /// uses and rewrite all the place holders at once for any constant that uses
366 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
367 // Sort the values by-pointer so that they are efficient to look up with a
369 std::sort(ResolveConstants.begin(), ResolveConstants.end());
371 SmallVector<Constant*, 64> NewOps;
373 while (!ResolveConstants.empty()) {
374 Value *RealVal = operator[](ResolveConstants.back().second);
375 Constant *Placeholder = ResolveConstants.back().first;
376 ResolveConstants.pop_back();
378 // Loop over all users of the placeholder, updating them to reference the
379 // new value. If they reference more than one placeholder, update them all
381 while (!Placeholder->use_empty()) {
382 auto UI = Placeholder->user_begin();
385 // If the using object isn't uniqued, just update the operands. This
386 // handles instructions and initializers for global variables.
387 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
388 UI.getUse().set(RealVal);
392 // Otherwise, we have a constant that uses the placeholder. Replace that
393 // constant with a new constant that has *all* placeholder uses updated.
394 Constant *UserC = cast<Constant>(U);
395 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
398 if (!isa<ConstantPlaceHolder>(*I)) {
399 // Not a placeholder reference.
401 } else if (*I == Placeholder) {
402 // Common case is that it just references this one placeholder.
405 // Otherwise, look up the placeholder in ResolveConstants.
406 ResolveConstantsTy::iterator It =
407 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
408 std::pair<Constant*, unsigned>(cast<Constant>(*I),
410 assert(It != ResolveConstants.end() && It->first == *I);
411 NewOp = operator[](It->second);
414 NewOps.push_back(cast<Constant>(NewOp));
417 // Make the new constant.
419 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
420 NewC = ConstantArray::get(UserCA->getType(), NewOps);
421 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
422 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
423 } else if (isa<ConstantVector>(UserC)) {
424 NewC = ConstantVector::get(NewOps);
426 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
427 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
430 UserC->replaceAllUsesWith(NewC);
431 UserC->destroyConstant();
435 // Update all ValueHandles, they should be the only users at this point.
436 Placeholder->replaceAllUsesWith(RealVal);
441 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
450 WeakVH &OldV = MDValuePtrs[Idx];
456 // If there was a forward reference to this value, replace it.
457 MDNode *PrevVal = cast<MDNode>(OldV);
458 OldV->replaceAllUsesWith(V);
459 MDNode::deleteTemporary(PrevVal);
460 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
462 MDValuePtrs[Idx] = V;
465 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
469 if (Value *V = MDValuePtrs[Idx]) {
470 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
474 // Create and return a placeholder, which will later be RAUW'd.
475 Value *V = MDNode::getTemporary(Context, None);
476 MDValuePtrs[Idx] = V;
480 Type *BitcodeReader::getTypeByID(unsigned ID) {
481 // The type table size is always specified correctly.
482 if (ID >= TypeList.size())
485 if (Type *Ty = TypeList[ID])
488 // If we have a forward reference, the only possible case is when it is to a
489 // named struct. Just create a placeholder for now.
490 return TypeList[ID] = StructType::create(Context);
494 //===----------------------------------------------------------------------===//
495 // Functions for parsing blocks from the bitcode file
496 //===----------------------------------------------------------------------===//
499 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
500 /// been decoded from the given integer. This function must stay in sync with
501 /// 'encodeLLVMAttributesForBitcode'.
502 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
503 uint64_t EncodedAttrs) {
504 // FIXME: Remove in 4.0.
506 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
507 // the bits above 31 down by 11 bits.
508 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
509 assert((!Alignment || isPowerOf2_32(Alignment)) &&
510 "Alignment must be a power of two.");
513 B.addAlignmentAttr(Alignment);
514 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
515 (EncodedAttrs & 0xffff));
518 std::error_code BitcodeReader::ParseAttributeBlock() {
519 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
520 return Error(BitcodeError::InvalidRecord);
522 if (!MAttributes.empty())
523 return Error(BitcodeError::InvalidMultipleBlocks);
525 SmallVector<uint64_t, 64> Record;
527 SmallVector<AttributeSet, 8> Attrs;
529 // Read all the records.
531 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
533 switch (Entry.Kind) {
534 case BitstreamEntry::SubBlock: // Handled for us already.
535 case BitstreamEntry::Error:
536 return Error(BitcodeError::MalformedBlock);
537 case BitstreamEntry::EndBlock:
538 return std::error_code();
539 case BitstreamEntry::Record:
540 // The interesting case.
546 switch (Stream.readRecord(Entry.ID, Record)) {
547 default: // Default behavior: ignore.
549 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
550 // FIXME: Remove in 4.0.
551 if (Record.size() & 1)
552 return Error(BitcodeError::InvalidRecord);
554 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
556 decodeLLVMAttributesForBitcode(B, Record[i+1]);
557 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
560 MAttributes.push_back(AttributeSet::get(Context, Attrs));
564 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
565 for (unsigned i = 0, e = Record.size(); i != e; ++i)
566 Attrs.push_back(MAttributeGroups[Record[i]]);
568 MAttributes.push_back(AttributeSet::get(Context, Attrs));
576 // Returns Attribute::None on unrecognized codes.
577 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
580 return Attribute::None;
581 case bitc::ATTR_KIND_ALIGNMENT:
582 return Attribute::Alignment;
583 case bitc::ATTR_KIND_ALWAYS_INLINE:
584 return Attribute::AlwaysInline;
585 case bitc::ATTR_KIND_BUILTIN:
586 return Attribute::Builtin;
587 case bitc::ATTR_KIND_BY_VAL:
588 return Attribute::ByVal;
589 case bitc::ATTR_KIND_IN_ALLOCA:
590 return Attribute::InAlloca;
591 case bitc::ATTR_KIND_COLD:
592 return Attribute::Cold;
593 case bitc::ATTR_KIND_INLINE_HINT:
594 return Attribute::InlineHint;
595 case bitc::ATTR_KIND_IN_REG:
596 return Attribute::InReg;
597 case bitc::ATTR_KIND_JUMP_TABLE:
598 return Attribute::JumpTable;
599 case bitc::ATTR_KIND_MIN_SIZE:
600 return Attribute::MinSize;
601 case bitc::ATTR_KIND_NAKED:
602 return Attribute::Naked;
603 case bitc::ATTR_KIND_NEST:
604 return Attribute::Nest;
605 case bitc::ATTR_KIND_NO_ALIAS:
606 return Attribute::NoAlias;
607 case bitc::ATTR_KIND_NO_BUILTIN:
608 return Attribute::NoBuiltin;
609 case bitc::ATTR_KIND_NO_CAPTURE:
610 return Attribute::NoCapture;
611 case bitc::ATTR_KIND_NO_DUPLICATE:
612 return Attribute::NoDuplicate;
613 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
614 return Attribute::NoImplicitFloat;
615 case bitc::ATTR_KIND_NO_INLINE:
616 return Attribute::NoInline;
617 case bitc::ATTR_KIND_NON_LAZY_BIND:
618 return Attribute::NonLazyBind;
619 case bitc::ATTR_KIND_NON_NULL:
620 return Attribute::NonNull;
621 case bitc::ATTR_KIND_DEREFERENCEABLE:
622 return Attribute::Dereferenceable;
623 case bitc::ATTR_KIND_NO_RED_ZONE:
624 return Attribute::NoRedZone;
625 case bitc::ATTR_KIND_NO_RETURN:
626 return Attribute::NoReturn;
627 case bitc::ATTR_KIND_NO_UNWIND:
628 return Attribute::NoUnwind;
629 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
630 return Attribute::OptimizeForSize;
631 case bitc::ATTR_KIND_OPTIMIZE_NONE:
632 return Attribute::OptimizeNone;
633 case bitc::ATTR_KIND_READ_NONE:
634 return Attribute::ReadNone;
635 case bitc::ATTR_KIND_READ_ONLY:
636 return Attribute::ReadOnly;
637 case bitc::ATTR_KIND_RETURNED:
638 return Attribute::Returned;
639 case bitc::ATTR_KIND_RETURNS_TWICE:
640 return Attribute::ReturnsTwice;
641 case bitc::ATTR_KIND_S_EXT:
642 return Attribute::SExt;
643 case bitc::ATTR_KIND_STACK_ALIGNMENT:
644 return Attribute::StackAlignment;
645 case bitc::ATTR_KIND_STACK_PROTECT:
646 return Attribute::StackProtect;
647 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
648 return Attribute::StackProtectReq;
649 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
650 return Attribute::StackProtectStrong;
651 case bitc::ATTR_KIND_STRUCT_RET:
652 return Attribute::StructRet;
653 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
654 return Attribute::SanitizeAddress;
655 case bitc::ATTR_KIND_SANITIZE_THREAD:
656 return Attribute::SanitizeThread;
657 case bitc::ATTR_KIND_SANITIZE_MEMORY:
658 return Attribute::SanitizeMemory;
659 case bitc::ATTR_KIND_UW_TABLE:
660 return Attribute::UWTable;
661 case bitc::ATTR_KIND_Z_EXT:
662 return Attribute::ZExt;
666 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
667 Attribute::AttrKind *Kind) {
668 *Kind = GetAttrFromCode(Code);
669 if (*Kind == Attribute::None)
670 return Error(BitcodeError::InvalidValue);
671 return std::error_code();
674 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
675 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
676 return Error(BitcodeError::InvalidRecord);
678 if (!MAttributeGroups.empty())
679 return Error(BitcodeError::InvalidMultipleBlocks);
681 SmallVector<uint64_t, 64> Record;
683 // Read all the records.
685 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
687 switch (Entry.Kind) {
688 case BitstreamEntry::SubBlock: // Handled for us already.
689 case BitstreamEntry::Error:
690 return Error(BitcodeError::MalformedBlock);
691 case BitstreamEntry::EndBlock:
692 return std::error_code();
693 case BitstreamEntry::Record:
694 // The interesting case.
700 switch (Stream.readRecord(Entry.ID, Record)) {
701 default: // Default behavior: ignore.
703 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
704 if (Record.size() < 3)
705 return Error(BitcodeError::InvalidRecord);
707 uint64_t GrpID = Record[0];
708 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
711 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
712 if (Record[i] == 0) { // Enum attribute
713 Attribute::AttrKind Kind;
714 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
717 B.addAttribute(Kind);
718 } else if (Record[i] == 1) { // Integer attribute
719 Attribute::AttrKind Kind;
720 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
722 if (Kind == Attribute::Alignment)
723 B.addAlignmentAttr(Record[++i]);
724 else if (Kind == Attribute::StackAlignment)
725 B.addStackAlignmentAttr(Record[++i]);
726 else if (Kind == Attribute::Dereferenceable)
727 B.addDereferenceableAttr(Record[++i]);
728 } else { // String attribute
729 assert((Record[i] == 3 || Record[i] == 4) &&
730 "Invalid attribute group entry");
731 bool HasValue = (Record[i++] == 4);
732 SmallString<64> KindStr;
733 SmallString<64> ValStr;
735 while (Record[i] != 0 && i != e)
736 KindStr += Record[i++];
737 assert(Record[i] == 0 && "Kind string not null terminated");
740 // Has a value associated with it.
741 ++i; // Skip the '0' that terminates the "kind" string.
742 while (Record[i] != 0 && i != e)
743 ValStr += Record[i++];
744 assert(Record[i] == 0 && "Value string not null terminated");
747 B.addAttribute(KindStr.str(), ValStr.str());
751 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
758 std::error_code BitcodeReader::ParseTypeTable() {
759 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
760 return Error(BitcodeError::InvalidRecord);
762 return ParseTypeTableBody();
765 std::error_code BitcodeReader::ParseTypeTableBody() {
766 if (!TypeList.empty())
767 return Error(BitcodeError::InvalidMultipleBlocks);
769 SmallVector<uint64_t, 64> Record;
770 unsigned NumRecords = 0;
772 SmallString<64> TypeName;
774 // Read all the records for this type table.
776 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
778 switch (Entry.Kind) {
779 case BitstreamEntry::SubBlock: // Handled for us already.
780 case BitstreamEntry::Error:
781 return Error(BitcodeError::MalformedBlock);
782 case BitstreamEntry::EndBlock:
783 if (NumRecords != TypeList.size())
784 return Error(BitcodeError::MalformedBlock);
785 return std::error_code();
786 case BitstreamEntry::Record:
787 // The interesting case.
793 Type *ResultTy = nullptr;
794 switch (Stream.readRecord(Entry.ID, Record)) {
796 return Error(BitcodeError::InvalidValue);
797 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
798 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
799 // type list. This allows us to reserve space.
800 if (Record.size() < 1)
801 return Error(BitcodeError::InvalidRecord);
802 TypeList.resize(Record[0]);
804 case bitc::TYPE_CODE_VOID: // VOID
805 ResultTy = Type::getVoidTy(Context);
807 case bitc::TYPE_CODE_HALF: // HALF
808 ResultTy = Type::getHalfTy(Context);
810 case bitc::TYPE_CODE_FLOAT: // FLOAT
811 ResultTy = Type::getFloatTy(Context);
813 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
814 ResultTy = Type::getDoubleTy(Context);
816 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
817 ResultTy = Type::getX86_FP80Ty(Context);
819 case bitc::TYPE_CODE_FP128: // FP128
820 ResultTy = Type::getFP128Ty(Context);
822 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
823 ResultTy = Type::getPPC_FP128Ty(Context);
825 case bitc::TYPE_CODE_LABEL: // LABEL
826 ResultTy = Type::getLabelTy(Context);
828 case bitc::TYPE_CODE_METADATA: // METADATA
829 ResultTy = Type::getMetadataTy(Context);
831 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
832 ResultTy = Type::getX86_MMXTy(Context);
834 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
835 if (Record.size() < 1)
836 return Error(BitcodeError::InvalidRecord);
838 ResultTy = IntegerType::get(Context, Record[0]);
840 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
841 // [pointee type, address space]
842 if (Record.size() < 1)
843 return Error(BitcodeError::InvalidRecord);
844 unsigned AddressSpace = 0;
845 if (Record.size() == 2)
846 AddressSpace = Record[1];
847 ResultTy = getTypeByID(Record[0]);
849 return Error(BitcodeError::InvalidType);
850 ResultTy = PointerType::get(ResultTy, AddressSpace);
853 case bitc::TYPE_CODE_FUNCTION_OLD: {
854 // FIXME: attrid is dead, remove it in LLVM 4.0
855 // FUNCTION: [vararg, attrid, retty, paramty x N]
856 if (Record.size() < 3)
857 return Error(BitcodeError::InvalidRecord);
858 SmallVector<Type*, 8> ArgTys;
859 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
860 if (Type *T = getTypeByID(Record[i]))
866 ResultTy = getTypeByID(Record[2]);
867 if (!ResultTy || ArgTys.size() < Record.size()-3)
868 return Error(BitcodeError::InvalidType);
870 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
873 case bitc::TYPE_CODE_FUNCTION: {
874 // FUNCTION: [vararg, retty, paramty x N]
875 if (Record.size() < 2)
876 return Error(BitcodeError::InvalidRecord);
877 SmallVector<Type*, 8> ArgTys;
878 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
879 if (Type *T = getTypeByID(Record[i]))
885 ResultTy = getTypeByID(Record[1]);
886 if (!ResultTy || ArgTys.size() < Record.size()-2)
887 return Error(BitcodeError::InvalidType);
889 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
892 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
893 if (Record.size() < 1)
894 return Error(BitcodeError::InvalidRecord);
895 SmallVector<Type*, 8> EltTys;
896 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
897 if (Type *T = getTypeByID(Record[i]))
902 if (EltTys.size() != Record.size()-1)
903 return Error(BitcodeError::InvalidType);
904 ResultTy = StructType::get(Context, EltTys, Record[0]);
907 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
908 if (ConvertToString(Record, 0, TypeName))
909 return Error(BitcodeError::InvalidRecord);
912 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
913 if (Record.size() < 1)
914 return Error(BitcodeError::InvalidRecord);
916 if (NumRecords >= TypeList.size())
917 return Error(BitcodeError::InvalidTYPETable);
919 // Check to see if this was forward referenced, if so fill in the temp.
920 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
922 Res->setName(TypeName);
923 TypeList[NumRecords] = nullptr;
924 } else // Otherwise, create a new struct.
925 Res = StructType::create(Context, TypeName);
928 SmallVector<Type*, 8> EltTys;
929 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
930 if (Type *T = getTypeByID(Record[i]))
935 if (EltTys.size() != Record.size()-1)
936 return Error(BitcodeError::InvalidRecord);
937 Res->setBody(EltTys, Record[0]);
941 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
942 if (Record.size() != 1)
943 return Error(BitcodeError::InvalidRecord);
945 if (NumRecords >= TypeList.size())
946 return Error(BitcodeError::InvalidTYPETable);
948 // Check to see if this was forward referenced, if so fill in the temp.
949 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
951 Res->setName(TypeName);
952 TypeList[NumRecords] = nullptr;
953 } else // Otherwise, create a new struct with no body.
954 Res = StructType::create(Context, TypeName);
959 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
960 if (Record.size() < 2)
961 return Error(BitcodeError::InvalidRecord);
962 if ((ResultTy = getTypeByID(Record[1])))
963 ResultTy = ArrayType::get(ResultTy, Record[0]);
965 return Error(BitcodeError::InvalidType);
967 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
968 if (Record.size() < 2)
969 return Error(BitcodeError::InvalidRecord);
970 if ((ResultTy = getTypeByID(Record[1])))
971 ResultTy = VectorType::get(ResultTy, Record[0]);
973 return Error(BitcodeError::InvalidType);
977 if (NumRecords >= TypeList.size())
978 return Error(BitcodeError::InvalidTYPETable);
979 assert(ResultTy && "Didn't read a type?");
980 assert(!TypeList[NumRecords] && "Already read type?");
981 TypeList[NumRecords++] = ResultTy;
985 std::error_code BitcodeReader::ParseValueSymbolTable() {
986 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
987 return Error(BitcodeError::InvalidRecord);
989 SmallVector<uint64_t, 64> Record;
991 // Read all the records for this value table.
992 SmallString<128> ValueName;
994 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
996 switch (Entry.Kind) {
997 case BitstreamEntry::SubBlock: // Handled for us already.
998 case BitstreamEntry::Error:
999 return Error(BitcodeError::MalformedBlock);
1000 case BitstreamEntry::EndBlock:
1001 return std::error_code();
1002 case BitstreamEntry::Record:
1003 // The interesting case.
1009 switch (Stream.readRecord(Entry.ID, Record)) {
1010 default: // Default behavior: unknown type.
1012 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1013 if (ConvertToString(Record, 1, ValueName))
1014 return Error(BitcodeError::InvalidRecord);
1015 unsigned ValueID = Record[0];
1016 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1017 return Error(BitcodeError::InvalidRecord);
1018 Value *V = ValueList[ValueID];
1020 V->setName(StringRef(ValueName.data(), ValueName.size()));
1024 case bitc::VST_CODE_BBENTRY: {
1025 if (ConvertToString(Record, 1, ValueName))
1026 return Error(BitcodeError::InvalidRecord);
1027 BasicBlock *BB = getBasicBlock(Record[0]);
1029 return Error(BitcodeError::InvalidRecord);
1031 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1039 std::error_code BitcodeReader::ParseMetadata() {
1040 unsigned NextMDValueNo = MDValueList.size();
1042 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1043 return Error(BitcodeError::InvalidRecord);
1045 SmallVector<uint64_t, 64> Record;
1047 // Read all the records.
1049 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1051 switch (Entry.Kind) {
1052 case BitstreamEntry::SubBlock: // Handled for us already.
1053 case BitstreamEntry::Error:
1054 return Error(BitcodeError::MalformedBlock);
1055 case BitstreamEntry::EndBlock:
1056 return std::error_code();
1057 case BitstreamEntry::Record:
1058 // The interesting case.
1062 bool IsFunctionLocal = false;
1065 unsigned Code = Stream.readRecord(Entry.ID, Record);
1067 default: // Default behavior: ignore.
1069 case bitc::METADATA_NAME: {
1070 // Read name of the named metadata.
1071 SmallString<8> Name(Record.begin(), Record.end());
1073 Code = Stream.ReadCode();
1075 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1076 unsigned NextBitCode = Stream.readRecord(Code, Record);
1077 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1079 // Read named metadata elements.
1080 unsigned Size = Record.size();
1081 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1082 for (unsigned i = 0; i != Size; ++i) {
1083 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1085 return Error(BitcodeError::InvalidRecord);
1086 NMD->addOperand(MD);
1090 case bitc::METADATA_FN_NODE:
1091 IsFunctionLocal = true;
1093 case bitc::METADATA_NODE: {
1094 if (Record.size() % 2 == 1)
1095 return Error(BitcodeError::InvalidRecord);
1097 unsigned Size = Record.size();
1098 SmallVector<Value*, 8> Elts;
1099 for (unsigned i = 0; i != Size; i += 2) {
1100 Type *Ty = getTypeByID(Record[i]);
1102 return Error(BitcodeError::InvalidRecord);
1103 if (Ty->isMetadataTy())
1104 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1105 else if (!Ty->isVoidTy())
1106 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1108 Elts.push_back(nullptr);
1110 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1111 IsFunctionLocal = false;
1112 MDValueList.AssignValue(V, NextMDValueNo++);
1115 case bitc::METADATA_STRING: {
1116 std::string String(Record.begin(), Record.end());
1117 llvm::UpgradeMDStringConstant(String);
1118 Value *V = MDString::get(Context, String);
1119 MDValueList.AssignValue(V, NextMDValueNo++);
1122 case bitc::METADATA_KIND: {
1123 if (Record.size() < 2)
1124 return Error(BitcodeError::InvalidRecord);
1126 unsigned Kind = Record[0];
1127 SmallString<8> Name(Record.begin()+1, Record.end());
1129 unsigned NewKind = TheModule->getMDKindID(Name.str());
1130 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1131 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1138 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1139 /// the LSB for dense VBR encoding.
1140 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1145 // There is no such thing as -0 with integers. "-0" really means MININT.
1149 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1150 /// values and aliases that we can.
1151 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1152 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1153 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1154 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1156 GlobalInitWorklist.swap(GlobalInits);
1157 AliasInitWorklist.swap(AliasInits);
1158 FunctionPrefixWorklist.swap(FunctionPrefixes);
1160 while (!GlobalInitWorklist.empty()) {
1161 unsigned ValID = GlobalInitWorklist.back().second;
1162 if (ValID >= ValueList.size()) {
1163 // Not ready to resolve this yet, it requires something later in the file.
1164 GlobalInits.push_back(GlobalInitWorklist.back());
1166 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1167 GlobalInitWorklist.back().first->setInitializer(C);
1169 return Error(BitcodeError::ExpectedConstant);
1171 GlobalInitWorklist.pop_back();
1174 while (!AliasInitWorklist.empty()) {
1175 unsigned ValID = AliasInitWorklist.back().second;
1176 if (ValID >= ValueList.size()) {
1177 AliasInits.push_back(AliasInitWorklist.back());
1179 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1180 AliasInitWorklist.back().first->setAliasee(C);
1182 return Error(BitcodeError::ExpectedConstant);
1184 AliasInitWorklist.pop_back();
1187 while (!FunctionPrefixWorklist.empty()) {
1188 unsigned ValID = FunctionPrefixWorklist.back().second;
1189 if (ValID >= ValueList.size()) {
1190 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1192 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1193 FunctionPrefixWorklist.back().first->setPrefixData(C);
1195 return Error(BitcodeError::ExpectedConstant);
1197 FunctionPrefixWorklist.pop_back();
1200 return std::error_code();
1203 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1204 SmallVector<uint64_t, 8> Words(Vals.size());
1205 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1206 BitcodeReader::decodeSignRotatedValue);
1208 return APInt(TypeBits, Words);
1211 std::error_code BitcodeReader::ParseConstants() {
1212 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1213 return Error(BitcodeError::InvalidRecord);
1215 SmallVector<uint64_t, 64> Record;
1217 // Read all the records for this value table.
1218 Type *CurTy = Type::getInt32Ty(Context);
1219 unsigned NextCstNo = ValueList.size();
1221 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1223 switch (Entry.Kind) {
1224 case BitstreamEntry::SubBlock: // Handled for us already.
1225 case BitstreamEntry::Error:
1226 return Error(BitcodeError::MalformedBlock);
1227 case BitstreamEntry::EndBlock:
1228 if (NextCstNo != ValueList.size())
1229 return Error(BitcodeError::InvalidConstantReference);
1231 // Once all the constants have been read, go through and resolve forward
1233 ValueList.ResolveConstantForwardRefs();
1234 return std::error_code();
1235 case BitstreamEntry::Record:
1236 // The interesting case.
1243 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1245 default: // Default behavior: unknown constant
1246 case bitc::CST_CODE_UNDEF: // UNDEF
1247 V = UndefValue::get(CurTy);
1249 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1251 return Error(BitcodeError::InvalidRecord);
1252 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1253 return Error(BitcodeError::InvalidRecord);
1254 CurTy = TypeList[Record[0]];
1255 continue; // Skip the ValueList manipulation.
1256 case bitc::CST_CODE_NULL: // NULL
1257 V = Constant::getNullValue(CurTy);
1259 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1260 if (!CurTy->isIntegerTy() || Record.empty())
1261 return Error(BitcodeError::InvalidRecord);
1262 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1264 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1265 if (!CurTy->isIntegerTy() || Record.empty())
1266 return Error(BitcodeError::InvalidRecord);
1268 APInt VInt = ReadWideAPInt(Record,
1269 cast<IntegerType>(CurTy)->getBitWidth());
1270 V = ConstantInt::get(Context, VInt);
1274 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1276 return Error(BitcodeError::InvalidRecord);
1277 if (CurTy->isHalfTy())
1278 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1279 APInt(16, (uint16_t)Record[0])));
1280 else if (CurTy->isFloatTy())
1281 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1282 APInt(32, (uint32_t)Record[0])));
1283 else if (CurTy->isDoubleTy())
1284 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1285 APInt(64, Record[0])));
1286 else if (CurTy->isX86_FP80Ty()) {
1287 // Bits are not stored the same way as a normal i80 APInt, compensate.
1288 uint64_t Rearrange[2];
1289 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1290 Rearrange[1] = Record[0] >> 48;
1291 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1292 APInt(80, Rearrange)));
1293 } else if (CurTy->isFP128Ty())
1294 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1295 APInt(128, Record)));
1296 else if (CurTy->isPPC_FP128Ty())
1297 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1298 APInt(128, Record)));
1300 V = UndefValue::get(CurTy);
1304 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1306 return Error(BitcodeError::InvalidRecord);
1308 unsigned Size = Record.size();
1309 SmallVector<Constant*, 16> Elts;
1311 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1312 for (unsigned i = 0; i != Size; ++i)
1313 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1314 STy->getElementType(i)));
1315 V = ConstantStruct::get(STy, Elts);
1316 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1317 Type *EltTy = ATy->getElementType();
1318 for (unsigned i = 0; i != Size; ++i)
1319 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1320 V = ConstantArray::get(ATy, Elts);
1321 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1322 Type *EltTy = VTy->getElementType();
1323 for (unsigned i = 0; i != Size; ++i)
1324 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1325 V = ConstantVector::get(Elts);
1327 V = UndefValue::get(CurTy);
1331 case bitc::CST_CODE_STRING: // STRING: [values]
1332 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1334 return Error(BitcodeError::InvalidRecord);
1336 SmallString<16> Elts(Record.begin(), Record.end());
1337 V = ConstantDataArray::getString(Context, Elts,
1338 BitCode == bitc::CST_CODE_CSTRING);
1341 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1343 return Error(BitcodeError::InvalidRecord);
1345 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1346 unsigned Size = Record.size();
1348 if (EltTy->isIntegerTy(8)) {
1349 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1350 if (isa<VectorType>(CurTy))
1351 V = ConstantDataVector::get(Context, Elts);
1353 V = ConstantDataArray::get(Context, Elts);
1354 } else if (EltTy->isIntegerTy(16)) {
1355 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1356 if (isa<VectorType>(CurTy))
1357 V = ConstantDataVector::get(Context, Elts);
1359 V = ConstantDataArray::get(Context, Elts);
1360 } else if (EltTy->isIntegerTy(32)) {
1361 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1362 if (isa<VectorType>(CurTy))
1363 V = ConstantDataVector::get(Context, Elts);
1365 V = ConstantDataArray::get(Context, Elts);
1366 } else if (EltTy->isIntegerTy(64)) {
1367 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1368 if (isa<VectorType>(CurTy))
1369 V = ConstantDataVector::get(Context, Elts);
1371 V = ConstantDataArray::get(Context, Elts);
1372 } else if (EltTy->isFloatTy()) {
1373 SmallVector<float, 16> Elts(Size);
1374 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1375 if (isa<VectorType>(CurTy))
1376 V = ConstantDataVector::get(Context, Elts);
1378 V = ConstantDataArray::get(Context, Elts);
1379 } else if (EltTy->isDoubleTy()) {
1380 SmallVector<double, 16> Elts(Size);
1381 std::transform(Record.begin(), Record.end(), Elts.begin(),
1383 if (isa<VectorType>(CurTy))
1384 V = ConstantDataVector::get(Context, Elts);
1386 V = ConstantDataArray::get(Context, Elts);
1388 return Error(BitcodeError::InvalidTypeForValue);
1393 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1394 if (Record.size() < 3)
1395 return Error(BitcodeError::InvalidRecord);
1396 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1398 V = UndefValue::get(CurTy); // Unknown binop.
1400 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1401 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1403 if (Record.size() >= 4) {
1404 if (Opc == Instruction::Add ||
1405 Opc == Instruction::Sub ||
1406 Opc == Instruction::Mul ||
1407 Opc == Instruction::Shl) {
1408 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1409 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1410 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1411 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1412 } else if (Opc == Instruction::SDiv ||
1413 Opc == Instruction::UDiv ||
1414 Opc == Instruction::LShr ||
1415 Opc == Instruction::AShr) {
1416 if (Record[3] & (1 << bitc::PEO_EXACT))
1417 Flags |= SDivOperator::IsExact;
1420 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1424 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1425 if (Record.size() < 3)
1426 return Error(BitcodeError::InvalidRecord);
1427 int Opc = GetDecodedCastOpcode(Record[0]);
1429 V = UndefValue::get(CurTy); // Unknown cast.
1431 Type *OpTy = getTypeByID(Record[1]);
1433 return Error(BitcodeError::InvalidRecord);
1434 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1435 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1436 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1440 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1441 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1442 if (Record.size() & 1)
1443 return Error(BitcodeError::InvalidRecord);
1444 SmallVector<Constant*, 16> Elts;
1445 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1446 Type *ElTy = getTypeByID(Record[i]);
1448 return Error(BitcodeError::InvalidRecord);
1449 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1451 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1452 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1454 bitc::CST_CODE_CE_INBOUNDS_GEP);
1457 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1458 if (Record.size() < 3)
1459 return Error(BitcodeError::InvalidRecord);
1461 Type *SelectorTy = Type::getInt1Ty(Context);
1463 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1464 // vector. Otherwise, it must be a single bit.
1465 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1466 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1467 VTy->getNumElements());
1469 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1471 ValueList.getConstantFwdRef(Record[1],CurTy),
1472 ValueList.getConstantFwdRef(Record[2],CurTy));
1475 case bitc::CST_CODE_CE_EXTRACTELT
1476 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1477 if (Record.size() < 3)
1478 return Error(BitcodeError::InvalidRecord);
1480 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1482 return Error(BitcodeError::InvalidRecord);
1483 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1484 Constant *Op1 = nullptr;
1485 if (Record.size() == 4) {
1486 Type *IdxTy = getTypeByID(Record[2]);
1488 return Error(BitcodeError::InvalidRecord);
1489 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1490 } else // TODO: Remove with llvm 4.0
1491 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1493 return Error(BitcodeError::InvalidRecord);
1494 V = ConstantExpr::getExtractElement(Op0, Op1);
1497 case bitc::CST_CODE_CE_INSERTELT
1498 : { // CE_INSERTELT: [opval, opval, opty, opval]
1499 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1500 if (Record.size() < 3 || !OpTy)
1501 return Error(BitcodeError::InvalidRecord);
1502 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1503 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1504 OpTy->getElementType());
1505 Constant *Op2 = nullptr;
1506 if (Record.size() == 4) {
1507 Type *IdxTy = getTypeByID(Record[2]);
1509 return Error(BitcodeError::InvalidRecord);
1510 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1511 } else // TODO: Remove with llvm 4.0
1512 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1514 return Error(BitcodeError::InvalidRecord);
1515 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1518 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1519 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1520 if (Record.size() < 3 || !OpTy)
1521 return Error(BitcodeError::InvalidRecord);
1522 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1523 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1524 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1525 OpTy->getNumElements());
1526 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1527 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1530 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1531 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1533 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1534 if (Record.size() < 4 || !RTy || !OpTy)
1535 return Error(BitcodeError::InvalidRecord);
1536 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1537 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1538 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1539 RTy->getNumElements());
1540 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1541 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1544 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1545 if (Record.size() < 4)
1546 return Error(BitcodeError::InvalidRecord);
1547 Type *OpTy = getTypeByID(Record[0]);
1549 return Error(BitcodeError::InvalidRecord);
1550 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1551 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1553 if (OpTy->isFPOrFPVectorTy())
1554 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1556 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1559 // This maintains backward compatibility, pre-asm dialect keywords.
1560 // FIXME: Remove with the 4.0 release.
1561 case bitc::CST_CODE_INLINEASM_OLD: {
1562 if (Record.size() < 2)
1563 return Error(BitcodeError::InvalidRecord);
1564 std::string AsmStr, ConstrStr;
1565 bool HasSideEffects = Record[0] & 1;
1566 bool IsAlignStack = Record[0] >> 1;
1567 unsigned AsmStrSize = Record[1];
1568 if (2+AsmStrSize >= Record.size())
1569 return Error(BitcodeError::InvalidRecord);
1570 unsigned ConstStrSize = Record[2+AsmStrSize];
1571 if (3+AsmStrSize+ConstStrSize > Record.size())
1572 return Error(BitcodeError::InvalidRecord);
1574 for (unsigned i = 0; i != AsmStrSize; ++i)
1575 AsmStr += (char)Record[2+i];
1576 for (unsigned i = 0; i != ConstStrSize; ++i)
1577 ConstrStr += (char)Record[3+AsmStrSize+i];
1578 PointerType *PTy = cast<PointerType>(CurTy);
1579 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1580 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1583 // This version adds support for the asm dialect keywords (e.g.,
1585 case bitc::CST_CODE_INLINEASM: {
1586 if (Record.size() < 2)
1587 return Error(BitcodeError::InvalidRecord);
1588 std::string AsmStr, ConstrStr;
1589 bool HasSideEffects = Record[0] & 1;
1590 bool IsAlignStack = (Record[0] >> 1) & 1;
1591 unsigned AsmDialect = Record[0] >> 2;
1592 unsigned AsmStrSize = Record[1];
1593 if (2+AsmStrSize >= Record.size())
1594 return Error(BitcodeError::InvalidRecord);
1595 unsigned ConstStrSize = Record[2+AsmStrSize];
1596 if (3+AsmStrSize+ConstStrSize > Record.size())
1597 return Error(BitcodeError::InvalidRecord);
1599 for (unsigned i = 0; i != AsmStrSize; ++i)
1600 AsmStr += (char)Record[2+i];
1601 for (unsigned i = 0; i != ConstStrSize; ++i)
1602 ConstrStr += (char)Record[3+AsmStrSize+i];
1603 PointerType *PTy = cast<PointerType>(CurTy);
1604 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1605 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1606 InlineAsm::AsmDialect(AsmDialect));
1609 case bitc::CST_CODE_BLOCKADDRESS:{
1610 if (Record.size() < 3)
1611 return Error(BitcodeError::InvalidRecord);
1612 Type *FnTy = getTypeByID(Record[0]);
1614 return Error(BitcodeError::InvalidRecord);
1616 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1618 return Error(BitcodeError::InvalidRecord);
1620 // Don't let Fn get dematerialized.
1621 BlockAddressesTaken.insert(Fn);
1623 // If the function is already parsed we can insert the block address right
1626 unsigned BBID = Record[2];
1628 // Invalid reference to entry block.
1629 return Error(BitcodeError::InvalidID);
1631 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1632 for (size_t I = 0, E = BBID; I != E; ++I) {
1634 return Error(BitcodeError::InvalidID);
1639 // Otherwise insert a placeholder and remember it so it can be inserted
1640 // when the function is parsed.
1641 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1643 BasicBlockFwdRefQueue.push_back(Fn);
1644 if (FwdBBs.size() < BBID + 1)
1645 FwdBBs.resize(BBID + 1);
1647 FwdBBs[BBID] = BasicBlock::Create(Context);
1650 V = BlockAddress::get(Fn, BB);
1655 ValueList.AssignValue(V, NextCstNo);
1660 std::error_code BitcodeReader::ParseUseLists() {
1661 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1662 return Error(BitcodeError::InvalidRecord);
1664 // Read all the records.
1665 SmallVector<uint64_t, 64> Record;
1667 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1669 switch (Entry.Kind) {
1670 case BitstreamEntry::SubBlock: // Handled for us already.
1671 case BitstreamEntry::Error:
1672 return Error(BitcodeError::MalformedBlock);
1673 case BitstreamEntry::EndBlock:
1674 return std::error_code();
1675 case BitstreamEntry::Record:
1676 // The interesting case.
1680 // Read a use list record.
1683 switch (Stream.readRecord(Entry.ID, Record)) {
1684 default: // Default behavior: unknown type.
1686 case bitc::USELIST_CODE_BB:
1689 case bitc::USELIST_CODE_DEFAULT: {
1690 unsigned RecordLength = Record.size();
1691 if (RecordLength < 3)
1692 // Records should have at least an ID and two indexes.
1693 return Error(BitcodeError::InvalidRecord);
1694 unsigned ID = Record.back();
1699 assert(ID < FunctionBBs.size() && "Basic block not found");
1700 V = FunctionBBs[ID];
1703 unsigned NumUses = 0;
1704 SmallDenseMap<const Use *, unsigned, 16> Order;
1705 for (const Use &U : V->uses()) {
1706 if (++NumUses > Record.size())
1708 Order[&U] = Record[NumUses - 1];
1710 if (Order.size() != Record.size() || NumUses > Record.size())
1711 // Mismatches can happen if the functions are being materialized lazily
1712 // (out-of-order), or a value has been upgraded.
1715 V->sortUseList([&](const Use &L, const Use &R) {
1716 return Order.lookup(&L) < Order.lookup(&R);
1724 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1725 /// remember where it is and then skip it. This lets us lazily deserialize the
1727 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1728 // Get the function we are talking about.
1729 if (FunctionsWithBodies.empty())
1730 return Error(BitcodeError::InsufficientFunctionProtos);
1732 Function *Fn = FunctionsWithBodies.back();
1733 FunctionsWithBodies.pop_back();
1735 // Save the current stream state.
1736 uint64_t CurBit = Stream.GetCurrentBitNo();
1737 DeferredFunctionInfo[Fn] = CurBit;
1739 // Skip over the function block for now.
1740 if (Stream.SkipBlock())
1741 return Error(BitcodeError::InvalidRecord);
1742 return std::error_code();
1745 std::error_code BitcodeReader::GlobalCleanup() {
1746 // Patch the initializers for globals and aliases up.
1747 ResolveGlobalAndAliasInits();
1748 if (!GlobalInits.empty() || !AliasInits.empty())
1749 return Error(BitcodeError::MalformedGlobalInitializerSet);
1751 // Look for intrinsic functions which need to be upgraded at some point
1752 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1755 if (UpgradeIntrinsicFunction(FI, NewFn))
1756 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1759 // Look for global variables which need to be renamed.
1760 for (Module::global_iterator
1761 GI = TheModule->global_begin(), GE = TheModule->global_end();
1763 GlobalVariable *GV = GI++;
1764 UpgradeGlobalVariable(GV);
1767 // Force deallocation of memory for these vectors to favor the client that
1768 // want lazy deserialization.
1769 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1770 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1771 return std::error_code();
1774 std::error_code BitcodeReader::ParseModule(bool Resume) {
1776 Stream.JumpToBit(NextUnreadBit);
1777 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1778 return Error(BitcodeError::InvalidRecord);
1780 SmallVector<uint64_t, 64> Record;
1781 std::vector<std::string> SectionTable;
1782 std::vector<std::string> GCTable;
1784 // Read all the records for this module.
1786 BitstreamEntry Entry = Stream.advance();
1788 switch (Entry.Kind) {
1789 case BitstreamEntry::Error:
1790 return Error(BitcodeError::MalformedBlock);
1791 case BitstreamEntry::EndBlock:
1792 return GlobalCleanup();
1794 case BitstreamEntry::SubBlock:
1796 default: // Skip unknown content.
1797 if (Stream.SkipBlock())
1798 return Error(BitcodeError::InvalidRecord);
1800 case bitc::BLOCKINFO_BLOCK_ID:
1801 if (Stream.ReadBlockInfoBlock())
1802 return Error(BitcodeError::MalformedBlock);
1804 case bitc::PARAMATTR_BLOCK_ID:
1805 if (std::error_code EC = ParseAttributeBlock())
1808 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1809 if (std::error_code EC = ParseAttributeGroupBlock())
1812 case bitc::TYPE_BLOCK_ID_NEW:
1813 if (std::error_code EC = ParseTypeTable())
1816 case bitc::VALUE_SYMTAB_BLOCK_ID:
1817 if (std::error_code EC = ParseValueSymbolTable())
1819 SeenValueSymbolTable = true;
1821 case bitc::CONSTANTS_BLOCK_ID:
1822 if (std::error_code EC = ParseConstants())
1824 if (std::error_code EC = ResolveGlobalAndAliasInits())
1827 case bitc::METADATA_BLOCK_ID:
1828 if (std::error_code EC = ParseMetadata())
1831 case bitc::FUNCTION_BLOCK_ID:
1832 // If this is the first function body we've seen, reverse the
1833 // FunctionsWithBodies list.
1834 if (!SeenFirstFunctionBody) {
1835 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1836 if (std::error_code EC = GlobalCleanup())
1838 SeenFirstFunctionBody = true;
1841 if (std::error_code EC = RememberAndSkipFunctionBody())
1843 // For streaming bitcode, suspend parsing when we reach the function
1844 // bodies. Subsequent materialization calls will resume it when
1845 // necessary. For streaming, the function bodies must be at the end of
1846 // the bitcode. If the bitcode file is old, the symbol table will be
1847 // at the end instead and will not have been seen yet. In this case,
1848 // just finish the parse now.
1849 if (LazyStreamer && SeenValueSymbolTable) {
1850 NextUnreadBit = Stream.GetCurrentBitNo();
1851 return std::error_code();
1854 case bitc::USELIST_BLOCK_ID:
1855 if (std::error_code EC = ParseUseLists())
1861 case BitstreamEntry::Record:
1862 // The interesting case.
1868 switch (Stream.readRecord(Entry.ID, Record)) {
1869 default: break; // Default behavior, ignore unknown content.
1870 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1871 if (Record.size() < 1)
1872 return Error(BitcodeError::InvalidRecord);
1873 // Only version #0 and #1 are supported so far.
1874 unsigned module_version = Record[0];
1875 switch (module_version) {
1877 return Error(BitcodeError::InvalidValue);
1879 UseRelativeIDs = false;
1882 UseRelativeIDs = true;
1887 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1889 if (ConvertToString(Record, 0, S))
1890 return Error(BitcodeError::InvalidRecord);
1891 TheModule->setTargetTriple(S);
1894 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1896 if (ConvertToString(Record, 0, S))
1897 return Error(BitcodeError::InvalidRecord);
1898 TheModule->setDataLayout(S);
1901 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1903 if (ConvertToString(Record, 0, S))
1904 return Error(BitcodeError::InvalidRecord);
1905 TheModule->setModuleInlineAsm(S);
1908 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1909 // FIXME: Remove in 4.0.
1911 if (ConvertToString(Record, 0, S))
1912 return Error(BitcodeError::InvalidRecord);
1916 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1918 if (ConvertToString(Record, 0, S))
1919 return Error(BitcodeError::InvalidRecord);
1920 SectionTable.push_back(S);
1923 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1925 if (ConvertToString(Record, 0, S))
1926 return Error(BitcodeError::InvalidRecord);
1927 GCTable.push_back(S);
1930 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1931 if (Record.size() < 2)
1932 return Error(BitcodeError::InvalidRecord);
1933 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1934 unsigned ComdatNameSize = Record[1];
1935 std::string ComdatName;
1936 ComdatName.reserve(ComdatNameSize);
1937 for (unsigned i = 0; i != ComdatNameSize; ++i)
1938 ComdatName += (char)Record[2 + i];
1939 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1940 C->setSelectionKind(SK);
1941 ComdatList.push_back(C);
1944 // GLOBALVAR: [pointer type, isconst, initid,
1945 // linkage, alignment, section, visibility, threadlocal,
1946 // unnamed_addr, dllstorageclass]
1947 case bitc::MODULE_CODE_GLOBALVAR: {
1948 if (Record.size() < 6)
1949 return Error(BitcodeError::InvalidRecord);
1950 Type *Ty = getTypeByID(Record[0]);
1952 return Error(BitcodeError::InvalidRecord);
1953 if (!Ty->isPointerTy())
1954 return Error(BitcodeError::InvalidTypeForValue);
1955 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1956 Ty = cast<PointerType>(Ty)->getElementType();
1958 bool isConstant = Record[1];
1959 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1960 unsigned Alignment = (1 << Record[4]) >> 1;
1961 std::string Section;
1963 if (Record[5]-1 >= SectionTable.size())
1964 return Error(BitcodeError::InvalidID);
1965 Section = SectionTable[Record[5]-1];
1967 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1968 // Local linkage must have default visibility.
1969 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1970 // FIXME: Change to an error if non-default in 4.0.
1971 Visibility = GetDecodedVisibility(Record[6]);
1973 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1974 if (Record.size() > 7)
1975 TLM = GetDecodedThreadLocalMode(Record[7]);
1977 bool UnnamedAddr = false;
1978 if (Record.size() > 8)
1979 UnnamedAddr = Record[8];
1981 bool ExternallyInitialized = false;
1982 if (Record.size() > 9)
1983 ExternallyInitialized = Record[9];
1985 GlobalVariable *NewGV =
1986 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1987 TLM, AddressSpace, ExternallyInitialized);
1988 NewGV->setAlignment(Alignment);
1989 if (!Section.empty())
1990 NewGV->setSection(Section);
1991 NewGV->setVisibility(Visibility);
1992 NewGV->setUnnamedAddr(UnnamedAddr);
1994 if (Record.size() > 10)
1995 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1997 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1999 ValueList.push_back(NewGV);
2001 // Remember which value to use for the global initializer.
2002 if (unsigned InitID = Record[2])
2003 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2005 if (Record.size() > 11)
2006 if (unsigned ComdatID = Record[11]) {
2007 assert(ComdatID <= ComdatList.size());
2008 NewGV->setComdat(ComdatList[ComdatID - 1]);
2012 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2013 // alignment, section, visibility, gc, unnamed_addr,
2015 case bitc::MODULE_CODE_FUNCTION: {
2016 if (Record.size() < 8)
2017 return Error(BitcodeError::InvalidRecord);
2018 Type *Ty = getTypeByID(Record[0]);
2020 return Error(BitcodeError::InvalidRecord);
2021 if (!Ty->isPointerTy())
2022 return Error(BitcodeError::InvalidTypeForValue);
2024 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2026 return Error(BitcodeError::InvalidTypeForValue);
2028 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2031 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2032 bool isProto = Record[2];
2033 Func->setLinkage(GetDecodedLinkage(Record[3]));
2034 Func->setAttributes(getAttributes(Record[4]));
2036 Func->setAlignment((1 << Record[5]) >> 1);
2038 if (Record[6]-1 >= SectionTable.size())
2039 return Error(BitcodeError::InvalidID);
2040 Func->setSection(SectionTable[Record[6]-1]);
2042 // Local linkage must have default visibility.
2043 if (!Func->hasLocalLinkage())
2044 // FIXME: Change to an error if non-default in 4.0.
2045 Func->setVisibility(GetDecodedVisibility(Record[7]));
2046 if (Record.size() > 8 && Record[8]) {
2047 if (Record[8]-1 > GCTable.size())
2048 return Error(BitcodeError::InvalidID);
2049 Func->setGC(GCTable[Record[8]-1].c_str());
2051 bool UnnamedAddr = false;
2052 if (Record.size() > 9)
2053 UnnamedAddr = Record[9];
2054 Func->setUnnamedAddr(UnnamedAddr);
2055 if (Record.size() > 10 && Record[10] != 0)
2056 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
2058 if (Record.size() > 11)
2059 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2061 UpgradeDLLImportExportLinkage(Func, Record[3]);
2063 if (Record.size() > 12)
2064 if (unsigned ComdatID = Record[12]) {
2065 assert(ComdatID <= ComdatList.size());
2066 Func->setComdat(ComdatList[ComdatID - 1]);
2069 ValueList.push_back(Func);
2071 // If this is a function with a body, remember the prototype we are
2072 // creating now, so that we can match up the body with them later.
2074 Func->setIsMaterializable(true);
2075 FunctionsWithBodies.push_back(Func);
2077 DeferredFunctionInfo[Func] = 0;
2081 // ALIAS: [alias type, aliasee val#, linkage]
2082 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2083 case bitc::MODULE_CODE_ALIAS: {
2084 if (Record.size() < 3)
2085 return Error(BitcodeError::InvalidRecord);
2086 Type *Ty = getTypeByID(Record[0]);
2088 return Error(BitcodeError::InvalidRecord);
2089 auto *PTy = dyn_cast<PointerType>(Ty);
2091 return Error(BitcodeError::InvalidTypeForValue);
2094 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2095 GetDecodedLinkage(Record[2]), "", TheModule);
2096 // Old bitcode files didn't have visibility field.
2097 // Local linkage must have default visibility.
2098 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2099 // FIXME: Change to an error if non-default in 4.0.
2100 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2101 if (Record.size() > 4)
2102 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2104 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2105 if (Record.size() > 5)
2106 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2107 if (Record.size() > 6)
2108 NewGA->setUnnamedAddr(Record[6]);
2109 ValueList.push_back(NewGA);
2110 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2113 /// MODULE_CODE_PURGEVALS: [numvals]
2114 case bitc::MODULE_CODE_PURGEVALS:
2115 // Trim down the value list to the specified size.
2116 if (Record.size() < 1 || Record[0] > ValueList.size())
2117 return Error(BitcodeError::InvalidRecord);
2118 ValueList.shrinkTo(Record[0]);
2125 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2126 TheModule = nullptr;
2128 if (std::error_code EC = InitStream())
2131 // Sniff for the signature.
2132 if (Stream.Read(8) != 'B' ||
2133 Stream.Read(8) != 'C' ||
2134 Stream.Read(4) != 0x0 ||
2135 Stream.Read(4) != 0xC ||
2136 Stream.Read(4) != 0xE ||
2137 Stream.Read(4) != 0xD)
2138 return Error(BitcodeError::InvalidBitcodeSignature);
2140 // We expect a number of well-defined blocks, though we don't necessarily
2141 // need to understand them all.
2143 if (Stream.AtEndOfStream())
2144 return std::error_code();
2146 BitstreamEntry Entry =
2147 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2149 switch (Entry.Kind) {
2150 case BitstreamEntry::Error:
2151 return Error(BitcodeError::MalformedBlock);
2152 case BitstreamEntry::EndBlock:
2153 return std::error_code();
2155 case BitstreamEntry::SubBlock:
2157 case bitc::BLOCKINFO_BLOCK_ID:
2158 if (Stream.ReadBlockInfoBlock())
2159 return Error(BitcodeError::MalformedBlock);
2161 case bitc::MODULE_BLOCK_ID:
2162 // Reject multiple MODULE_BLOCK's in a single bitstream.
2164 return Error(BitcodeError::InvalidMultipleBlocks);
2166 if (std::error_code EC = ParseModule(false))
2169 return std::error_code();
2172 if (Stream.SkipBlock())
2173 return Error(BitcodeError::InvalidRecord);
2177 case BitstreamEntry::Record:
2178 // There should be no records in the top-level of blocks.
2180 // The ranlib in Xcode 4 will align archive members by appending newlines
2181 // to the end of them. If this file size is a multiple of 4 but not 8, we
2182 // have to read and ignore these final 4 bytes :-(
2183 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2184 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2185 Stream.AtEndOfStream())
2186 return std::error_code();
2188 return Error(BitcodeError::InvalidRecord);
2193 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2194 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2195 return Error(BitcodeError::InvalidRecord);
2197 SmallVector<uint64_t, 64> Record;
2200 // Read all the records for this module.
2202 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2204 switch (Entry.Kind) {
2205 case BitstreamEntry::SubBlock: // Handled for us already.
2206 case BitstreamEntry::Error:
2207 return Error(BitcodeError::MalformedBlock);
2208 case BitstreamEntry::EndBlock:
2210 case BitstreamEntry::Record:
2211 // The interesting case.
2216 switch (Stream.readRecord(Entry.ID, Record)) {
2217 default: break; // Default behavior, ignore unknown content.
2218 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2220 if (ConvertToString(Record, 0, S))
2221 return Error(BitcodeError::InvalidRecord);
2228 llvm_unreachable("Exit infinite loop");
2231 ErrorOr<std::string> BitcodeReader::parseTriple() {
2232 if (std::error_code EC = InitStream())
2235 // Sniff for the signature.
2236 if (Stream.Read(8) != 'B' ||
2237 Stream.Read(8) != 'C' ||
2238 Stream.Read(4) != 0x0 ||
2239 Stream.Read(4) != 0xC ||
2240 Stream.Read(4) != 0xE ||
2241 Stream.Read(4) != 0xD)
2242 return Error(BitcodeError::InvalidBitcodeSignature);
2244 // We expect a number of well-defined blocks, though we don't necessarily
2245 // need to understand them all.
2247 BitstreamEntry Entry = Stream.advance();
2249 switch (Entry.Kind) {
2250 case BitstreamEntry::Error:
2251 return Error(BitcodeError::MalformedBlock);
2252 case BitstreamEntry::EndBlock:
2253 return std::error_code();
2255 case BitstreamEntry::SubBlock:
2256 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2257 return parseModuleTriple();
2259 // Ignore other sub-blocks.
2260 if (Stream.SkipBlock())
2261 return Error(BitcodeError::MalformedBlock);
2264 case BitstreamEntry::Record:
2265 Stream.skipRecord(Entry.ID);
2271 /// ParseMetadataAttachment - Parse metadata attachments.
2272 std::error_code BitcodeReader::ParseMetadataAttachment() {
2273 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2274 return Error(BitcodeError::InvalidRecord);
2276 SmallVector<uint64_t, 64> Record;
2278 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2280 switch (Entry.Kind) {
2281 case BitstreamEntry::SubBlock: // Handled for us already.
2282 case BitstreamEntry::Error:
2283 return Error(BitcodeError::MalformedBlock);
2284 case BitstreamEntry::EndBlock:
2285 return std::error_code();
2286 case BitstreamEntry::Record:
2287 // The interesting case.
2291 // Read a metadata attachment record.
2293 switch (Stream.readRecord(Entry.ID, Record)) {
2294 default: // Default behavior: ignore.
2296 case bitc::METADATA_ATTACHMENT: {
2297 unsigned RecordLength = Record.size();
2298 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2299 return Error(BitcodeError::InvalidRecord);
2300 Instruction *Inst = InstructionList[Record[0]];
2301 for (unsigned i = 1; i != RecordLength; i = i+2) {
2302 unsigned Kind = Record[i];
2303 DenseMap<unsigned, unsigned>::iterator I =
2304 MDKindMap.find(Kind);
2305 if (I == MDKindMap.end())
2306 return Error(BitcodeError::InvalidID);
2307 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2308 Inst->setMetadata(I->second, cast<MDNode>(Node));
2309 if (I->second == LLVMContext::MD_tbaa)
2310 InstsWithTBAATag.push_back(Inst);
2318 /// ParseFunctionBody - Lazily parse the specified function body block.
2319 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2320 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2321 return Error(BitcodeError::InvalidRecord);
2323 InstructionList.clear();
2324 unsigned ModuleValueListSize = ValueList.size();
2325 unsigned ModuleMDValueListSize = MDValueList.size();
2327 // Add all the function arguments to the value table.
2328 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2329 ValueList.push_back(I);
2331 unsigned NextValueNo = ValueList.size();
2332 BasicBlock *CurBB = nullptr;
2333 unsigned CurBBNo = 0;
2337 // Read all the records.
2338 SmallVector<uint64_t, 64> Record;
2340 BitstreamEntry Entry = Stream.advance();
2342 switch (Entry.Kind) {
2343 case BitstreamEntry::Error:
2344 return Error(BitcodeError::MalformedBlock);
2345 case BitstreamEntry::EndBlock:
2346 goto OutOfRecordLoop;
2348 case BitstreamEntry::SubBlock:
2350 default: // Skip unknown content.
2351 if (Stream.SkipBlock())
2352 return Error(BitcodeError::InvalidRecord);
2354 case bitc::CONSTANTS_BLOCK_ID:
2355 if (std::error_code EC = ParseConstants())
2357 NextValueNo = ValueList.size();
2359 case bitc::VALUE_SYMTAB_BLOCK_ID:
2360 if (std::error_code EC = ParseValueSymbolTable())
2363 case bitc::METADATA_ATTACHMENT_ID:
2364 if (std::error_code EC = ParseMetadataAttachment())
2367 case bitc::METADATA_BLOCK_ID:
2368 if (std::error_code EC = ParseMetadata())
2371 case bitc::USELIST_BLOCK_ID:
2372 if (std::error_code EC = ParseUseLists())
2378 case BitstreamEntry::Record:
2379 // The interesting case.
2385 Instruction *I = nullptr;
2386 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2388 default: // Default behavior: reject
2389 return Error(BitcodeError::InvalidValue);
2390 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2391 if (Record.size() < 1 || Record[0] == 0)
2392 return Error(BitcodeError::InvalidRecord);
2393 // Create all the basic blocks for the function.
2394 FunctionBBs.resize(Record[0]);
2396 // See if anything took the address of blocks in this function.
2397 auto BBFRI = BasicBlockFwdRefs.find(F);
2398 if (BBFRI == BasicBlockFwdRefs.end()) {
2399 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2400 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2402 auto &BBRefs = BBFRI->second;
2403 // Check for invalid basic block references.
2404 if (BBRefs.size() > FunctionBBs.size())
2405 return Error(BitcodeError::InvalidID);
2406 assert(!BBRefs.empty() && "Unexpected empty array");
2407 assert(!BBRefs.front() && "Invalid reference to entry block");
2408 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2410 if (I < RE && BBRefs[I]) {
2411 BBRefs[I]->insertInto(F);
2412 FunctionBBs[I] = BBRefs[I];
2414 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2417 // Erase from the table.
2418 BasicBlockFwdRefs.erase(BBFRI);
2421 CurBB = FunctionBBs[0];
2425 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2426 // This record indicates that the last instruction is at the same
2427 // location as the previous instruction with a location.
2430 // Get the last instruction emitted.
2431 if (CurBB && !CurBB->empty())
2433 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2434 !FunctionBBs[CurBBNo-1]->empty())
2435 I = &FunctionBBs[CurBBNo-1]->back();
2438 return Error(BitcodeError::InvalidRecord);
2439 I->setDebugLoc(LastLoc);
2443 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2444 I = nullptr; // Get the last instruction emitted.
2445 if (CurBB && !CurBB->empty())
2447 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2448 !FunctionBBs[CurBBNo-1]->empty())
2449 I = &FunctionBBs[CurBBNo-1]->back();
2450 if (!I || Record.size() < 4)
2451 return Error(BitcodeError::InvalidRecord);
2453 unsigned Line = Record[0], Col = Record[1];
2454 unsigned ScopeID = Record[2], IAID = Record[3];
2456 MDNode *Scope = nullptr, *IA = nullptr;
2457 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2458 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2459 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2460 I->setDebugLoc(LastLoc);
2465 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2468 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2469 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2470 OpNum+1 > Record.size())
2471 return Error(BitcodeError::InvalidRecord);
2473 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2475 return Error(BitcodeError::InvalidRecord);
2476 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2477 InstructionList.push_back(I);
2478 if (OpNum < Record.size()) {
2479 if (Opc == Instruction::Add ||
2480 Opc == Instruction::Sub ||
2481 Opc == Instruction::Mul ||
2482 Opc == Instruction::Shl) {
2483 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2484 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2485 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2486 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2487 } else if (Opc == Instruction::SDiv ||
2488 Opc == Instruction::UDiv ||
2489 Opc == Instruction::LShr ||
2490 Opc == Instruction::AShr) {
2491 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2492 cast<BinaryOperator>(I)->setIsExact(true);
2493 } else if (isa<FPMathOperator>(I)) {
2495 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2496 FMF.setUnsafeAlgebra();
2497 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2499 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2501 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2502 FMF.setNoSignedZeros();
2503 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2504 FMF.setAllowReciprocal();
2506 I->setFastMathFlags(FMF);
2512 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2515 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2516 OpNum+2 != Record.size())
2517 return Error(BitcodeError::InvalidRecord);
2519 Type *ResTy = getTypeByID(Record[OpNum]);
2520 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2521 if (Opc == -1 || !ResTy)
2522 return Error(BitcodeError::InvalidRecord);
2523 Instruction *Temp = nullptr;
2524 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2526 InstructionList.push_back(Temp);
2527 CurBB->getInstList().push_back(Temp);
2530 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2532 InstructionList.push_back(I);
2535 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2536 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2539 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2540 return Error(BitcodeError::InvalidRecord);
2542 SmallVector<Value*, 16> GEPIdx;
2543 while (OpNum != Record.size()) {
2545 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2546 return Error(BitcodeError::InvalidRecord);
2547 GEPIdx.push_back(Op);
2550 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2551 InstructionList.push_back(I);
2552 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2553 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2557 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2558 // EXTRACTVAL: [opty, opval, n x indices]
2561 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2562 return Error(BitcodeError::InvalidRecord);
2564 SmallVector<unsigned, 4> EXTRACTVALIdx;
2565 for (unsigned RecSize = Record.size();
2566 OpNum != RecSize; ++OpNum) {
2567 uint64_t Index = Record[OpNum];
2568 if ((unsigned)Index != Index)
2569 return Error(BitcodeError::InvalidValue);
2570 EXTRACTVALIdx.push_back((unsigned)Index);
2573 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2574 InstructionList.push_back(I);
2578 case bitc::FUNC_CODE_INST_INSERTVAL: {
2579 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2582 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2583 return Error(BitcodeError::InvalidRecord);
2585 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2586 return Error(BitcodeError::InvalidRecord);
2588 SmallVector<unsigned, 4> INSERTVALIdx;
2589 for (unsigned RecSize = Record.size();
2590 OpNum != RecSize; ++OpNum) {
2591 uint64_t Index = Record[OpNum];
2592 if ((unsigned)Index != Index)
2593 return Error(BitcodeError::InvalidValue);
2594 INSERTVALIdx.push_back((unsigned)Index);
2597 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2598 InstructionList.push_back(I);
2602 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2603 // obsolete form of select
2604 // handles select i1 ... in old bitcode
2606 Value *TrueVal, *FalseVal, *Cond;
2607 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2608 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2609 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2610 return Error(BitcodeError::InvalidRecord);
2612 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2613 InstructionList.push_back(I);
2617 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2618 // new form of select
2619 // handles select i1 or select [N x i1]
2621 Value *TrueVal, *FalseVal, *Cond;
2622 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2623 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2624 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2625 return Error(BitcodeError::InvalidRecord);
2627 // select condition can be either i1 or [N x i1]
2628 if (VectorType* vector_type =
2629 dyn_cast<VectorType>(Cond->getType())) {
2631 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2632 return Error(BitcodeError::InvalidTypeForValue);
2635 if (Cond->getType() != Type::getInt1Ty(Context))
2636 return Error(BitcodeError::InvalidTypeForValue);
2639 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2640 InstructionList.push_back(I);
2644 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2647 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2648 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2649 return Error(BitcodeError::InvalidRecord);
2650 I = ExtractElementInst::Create(Vec, Idx);
2651 InstructionList.push_back(I);
2655 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2657 Value *Vec, *Elt, *Idx;
2658 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2659 popValue(Record, OpNum, NextValueNo,
2660 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2661 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2662 return Error(BitcodeError::InvalidRecord);
2663 I = InsertElementInst::Create(Vec, Elt, Idx);
2664 InstructionList.push_back(I);
2668 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2670 Value *Vec1, *Vec2, *Mask;
2671 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2672 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2673 return Error(BitcodeError::InvalidRecord);
2675 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2676 return Error(BitcodeError::InvalidRecord);
2677 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2678 InstructionList.push_back(I);
2682 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2683 // Old form of ICmp/FCmp returning bool
2684 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2685 // both legal on vectors but had different behaviour.
2686 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2687 // FCmp/ICmp returning bool or vector of bool
2691 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2692 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2693 OpNum+1 != Record.size())
2694 return Error(BitcodeError::InvalidRecord);
2696 if (LHS->getType()->isFPOrFPVectorTy())
2697 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2699 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2700 InstructionList.push_back(I);
2704 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2706 unsigned Size = Record.size();
2708 I = ReturnInst::Create(Context);
2709 InstructionList.push_back(I);
2714 Value *Op = nullptr;
2715 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2716 return Error(BitcodeError::InvalidRecord);
2717 if (OpNum != Record.size())
2718 return Error(BitcodeError::InvalidRecord);
2720 I = ReturnInst::Create(Context, Op);
2721 InstructionList.push_back(I);
2724 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2725 if (Record.size() != 1 && Record.size() != 3)
2726 return Error(BitcodeError::InvalidRecord);
2727 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2729 return Error(BitcodeError::InvalidRecord);
2731 if (Record.size() == 1) {
2732 I = BranchInst::Create(TrueDest);
2733 InstructionList.push_back(I);
2736 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2737 Value *Cond = getValue(Record, 2, NextValueNo,
2738 Type::getInt1Ty(Context));
2739 if (!FalseDest || !Cond)
2740 return Error(BitcodeError::InvalidRecord);
2741 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2742 InstructionList.push_back(I);
2746 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2748 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2749 // "New" SwitchInst format with case ranges. The changes to write this
2750 // format were reverted but we still recognize bitcode that uses it.
2751 // Hopefully someday we will have support for case ranges and can use
2752 // this format again.
2754 Type *OpTy = getTypeByID(Record[1]);
2755 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2757 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2758 BasicBlock *Default = getBasicBlock(Record[3]);
2759 if (!OpTy || !Cond || !Default)
2760 return Error(BitcodeError::InvalidRecord);
2762 unsigned NumCases = Record[4];
2764 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2765 InstructionList.push_back(SI);
2767 unsigned CurIdx = 5;
2768 for (unsigned i = 0; i != NumCases; ++i) {
2769 SmallVector<ConstantInt*, 1> CaseVals;
2770 unsigned NumItems = Record[CurIdx++];
2771 for (unsigned ci = 0; ci != NumItems; ++ci) {
2772 bool isSingleNumber = Record[CurIdx++];
2775 unsigned ActiveWords = 1;
2776 if (ValueBitWidth > 64)
2777 ActiveWords = Record[CurIdx++];
2778 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2780 CurIdx += ActiveWords;
2782 if (!isSingleNumber) {
2784 if (ValueBitWidth > 64)
2785 ActiveWords = Record[CurIdx++];
2787 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2789 CurIdx += ActiveWords;
2791 // FIXME: It is not clear whether values in the range should be
2792 // compared as signed or unsigned values. The partially
2793 // implemented changes that used this format in the past used
2794 // unsigned comparisons.
2795 for ( ; Low.ule(High); ++Low)
2796 CaseVals.push_back(ConstantInt::get(Context, Low));
2798 CaseVals.push_back(ConstantInt::get(Context, Low));
2800 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2801 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2802 cve = CaseVals.end(); cvi != cve; ++cvi)
2803 SI->addCase(*cvi, DestBB);
2809 // Old SwitchInst format without case ranges.
2811 if (Record.size() < 3 || (Record.size() & 1) == 0)
2812 return Error(BitcodeError::InvalidRecord);
2813 Type *OpTy = getTypeByID(Record[0]);
2814 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2815 BasicBlock *Default = getBasicBlock(Record[2]);
2816 if (!OpTy || !Cond || !Default)
2817 return Error(BitcodeError::InvalidRecord);
2818 unsigned NumCases = (Record.size()-3)/2;
2819 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2820 InstructionList.push_back(SI);
2821 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2822 ConstantInt *CaseVal =
2823 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2824 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2825 if (!CaseVal || !DestBB) {
2827 return Error(BitcodeError::InvalidRecord);
2829 SI->addCase(CaseVal, DestBB);
2834 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2835 if (Record.size() < 2)
2836 return Error(BitcodeError::InvalidRecord);
2837 Type *OpTy = getTypeByID(Record[0]);
2838 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2839 if (!OpTy || !Address)
2840 return Error(BitcodeError::InvalidRecord);
2841 unsigned NumDests = Record.size()-2;
2842 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2843 InstructionList.push_back(IBI);
2844 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2845 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2846 IBI->addDestination(DestBB);
2849 return Error(BitcodeError::InvalidRecord);
2856 case bitc::FUNC_CODE_INST_INVOKE: {
2857 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2858 if (Record.size() < 4)
2859 return Error(BitcodeError::InvalidRecord);
2860 AttributeSet PAL = getAttributes(Record[0]);
2861 unsigned CCInfo = Record[1];
2862 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2863 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2867 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2868 return Error(BitcodeError::InvalidRecord);
2870 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2871 FunctionType *FTy = !CalleeTy ? nullptr :
2872 dyn_cast<FunctionType>(CalleeTy->getElementType());
2874 // Check that the right number of fixed parameters are here.
2875 if (!FTy || !NormalBB || !UnwindBB ||
2876 Record.size() < OpNum+FTy->getNumParams())
2877 return Error(BitcodeError::InvalidRecord);
2879 SmallVector<Value*, 16> Ops;
2880 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2881 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2882 FTy->getParamType(i)));
2884 return Error(BitcodeError::InvalidRecord);
2887 if (!FTy->isVarArg()) {
2888 if (Record.size() != OpNum)
2889 return Error(BitcodeError::InvalidRecord);
2891 // Read type/value pairs for varargs params.
2892 while (OpNum != Record.size()) {
2894 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2895 return Error(BitcodeError::InvalidRecord);
2900 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2901 InstructionList.push_back(I);
2902 cast<InvokeInst>(I)->setCallingConv(
2903 static_cast<CallingConv::ID>(CCInfo));
2904 cast<InvokeInst>(I)->setAttributes(PAL);
2907 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2909 Value *Val = nullptr;
2910 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2911 return Error(BitcodeError::InvalidRecord);
2912 I = ResumeInst::Create(Val);
2913 InstructionList.push_back(I);
2916 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2917 I = new UnreachableInst(Context);
2918 InstructionList.push_back(I);
2920 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2921 if (Record.size() < 1 || ((Record.size()-1)&1))
2922 return Error(BitcodeError::InvalidRecord);
2923 Type *Ty = getTypeByID(Record[0]);
2925 return Error(BitcodeError::InvalidRecord);
2927 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2928 InstructionList.push_back(PN);
2930 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2932 // With the new function encoding, it is possible that operands have
2933 // negative IDs (for forward references). Use a signed VBR
2934 // representation to keep the encoding small.
2936 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2938 V = getValue(Record, 1+i, NextValueNo, Ty);
2939 BasicBlock *BB = getBasicBlock(Record[2+i]);
2941 return Error(BitcodeError::InvalidRecord);
2942 PN->addIncoming(V, BB);
2948 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2949 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2951 if (Record.size() < 4)
2952 return Error(BitcodeError::InvalidRecord);
2953 Type *Ty = getTypeByID(Record[Idx++]);
2955 return Error(BitcodeError::InvalidRecord);
2956 Value *PersFn = nullptr;
2957 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2958 return Error(BitcodeError::InvalidRecord);
2960 bool IsCleanup = !!Record[Idx++];
2961 unsigned NumClauses = Record[Idx++];
2962 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2963 LP->setCleanup(IsCleanup);
2964 for (unsigned J = 0; J != NumClauses; ++J) {
2965 LandingPadInst::ClauseType CT =
2966 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2969 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2971 return Error(BitcodeError::InvalidRecord);
2974 assert((CT != LandingPadInst::Catch ||
2975 !isa<ArrayType>(Val->getType())) &&
2976 "Catch clause has a invalid type!");
2977 assert((CT != LandingPadInst::Filter ||
2978 isa<ArrayType>(Val->getType())) &&
2979 "Filter clause has invalid type!");
2980 LP->addClause(cast<Constant>(Val));
2984 InstructionList.push_back(I);
2988 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2989 if (Record.size() != 4)
2990 return Error(BitcodeError::InvalidRecord);
2992 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2993 Type *OpTy = getTypeByID(Record[1]);
2994 Value *Size = getFnValueByID(Record[2], OpTy);
2995 unsigned AlignRecord = Record[3];
2996 bool InAlloca = AlignRecord & (1 << 5);
2997 unsigned Align = AlignRecord & ((1 << 5) - 1);
2999 return Error(BitcodeError::InvalidRecord);
3000 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3001 AI->setUsedWithInAlloca(InAlloca);
3003 InstructionList.push_back(I);
3006 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3009 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3010 OpNum+2 != Record.size())
3011 return Error(BitcodeError::InvalidRecord);
3013 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3014 InstructionList.push_back(I);
3017 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3018 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3021 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3022 OpNum+4 != Record.size())
3023 return Error(BitcodeError::InvalidRecord);
3025 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3026 if (Ordering == NotAtomic || Ordering == Release ||
3027 Ordering == AcquireRelease)
3028 return Error(BitcodeError::InvalidRecord);
3029 if (Ordering != NotAtomic && Record[OpNum] == 0)
3030 return Error(BitcodeError::InvalidRecord);
3031 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3033 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3034 Ordering, SynchScope);
3035 InstructionList.push_back(I);
3038 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3041 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3042 popValue(Record, OpNum, NextValueNo,
3043 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3044 OpNum+2 != Record.size())
3045 return Error(BitcodeError::InvalidRecord);
3047 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3048 InstructionList.push_back(I);
3051 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3052 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3055 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3056 popValue(Record, OpNum, NextValueNo,
3057 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3058 OpNum+4 != Record.size())
3059 return Error(BitcodeError::InvalidRecord);
3061 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3062 if (Ordering == NotAtomic || Ordering == Acquire ||
3063 Ordering == AcquireRelease)
3064 return Error(BitcodeError::InvalidRecord);
3065 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3066 if (Ordering != NotAtomic && Record[OpNum] == 0)
3067 return Error(BitcodeError::InvalidRecord);
3069 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3070 Ordering, SynchScope);
3071 InstructionList.push_back(I);
3074 case bitc::FUNC_CODE_INST_CMPXCHG: {
3075 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3076 // failureordering?, isweak?]
3078 Value *Ptr, *Cmp, *New;
3079 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3080 popValue(Record, OpNum, NextValueNo,
3081 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3082 popValue(Record, OpNum, NextValueNo,
3083 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3084 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3085 return Error(BitcodeError::InvalidRecord);
3086 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3087 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3088 return Error(BitcodeError::InvalidRecord);
3089 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3091 AtomicOrdering FailureOrdering;
3092 if (Record.size() < 7)
3094 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3096 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3098 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3100 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3102 if (Record.size() < 8) {
3103 // Before weak cmpxchgs existed, the instruction simply returned the
3104 // value loaded from memory, so bitcode files from that era will be
3105 // expecting the first component of a modern cmpxchg.
3106 CurBB->getInstList().push_back(I);
3107 I = ExtractValueInst::Create(I, 0);
3109 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3112 InstructionList.push_back(I);
3115 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3116 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3119 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3120 popValue(Record, OpNum, NextValueNo,
3121 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3122 OpNum+4 != Record.size())
3123 return Error(BitcodeError::InvalidRecord);
3124 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3125 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3126 Operation > AtomicRMWInst::LAST_BINOP)
3127 return Error(BitcodeError::InvalidRecord);
3128 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3129 if (Ordering == NotAtomic || Ordering == Unordered)
3130 return Error(BitcodeError::InvalidRecord);
3131 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3132 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3133 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3134 InstructionList.push_back(I);
3137 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3138 if (2 != Record.size())
3139 return Error(BitcodeError::InvalidRecord);
3140 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3141 if (Ordering == NotAtomic || Ordering == Unordered ||
3142 Ordering == Monotonic)
3143 return Error(BitcodeError::InvalidRecord);
3144 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3145 I = new FenceInst(Context, Ordering, SynchScope);
3146 InstructionList.push_back(I);
3149 case bitc::FUNC_CODE_INST_CALL: {
3150 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3151 if (Record.size() < 3)
3152 return Error(BitcodeError::InvalidRecord);
3154 AttributeSet PAL = getAttributes(Record[0]);
3155 unsigned CCInfo = Record[1];
3159 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3160 return Error(BitcodeError::InvalidRecord);
3162 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3163 FunctionType *FTy = nullptr;
3164 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3165 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3166 return Error(BitcodeError::InvalidRecord);
3168 SmallVector<Value*, 16> Args;
3169 // Read the fixed params.
3170 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3171 if (FTy->getParamType(i)->isLabelTy())
3172 Args.push_back(getBasicBlock(Record[OpNum]));
3174 Args.push_back(getValue(Record, OpNum, NextValueNo,
3175 FTy->getParamType(i)));
3177 return Error(BitcodeError::InvalidRecord);
3180 // Read type/value pairs for varargs params.
3181 if (!FTy->isVarArg()) {
3182 if (OpNum != Record.size())
3183 return Error(BitcodeError::InvalidRecord);
3185 while (OpNum != Record.size()) {
3187 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3188 return Error(BitcodeError::InvalidRecord);
3193 I = CallInst::Create(Callee, Args);
3194 InstructionList.push_back(I);
3195 cast<CallInst>(I)->setCallingConv(
3196 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3197 CallInst::TailCallKind TCK = CallInst::TCK_None;
3199 TCK = CallInst::TCK_Tail;
3200 if (CCInfo & (1 << 14))
3201 TCK = CallInst::TCK_MustTail;
3202 cast<CallInst>(I)->setTailCallKind(TCK);
3203 cast<CallInst>(I)->setAttributes(PAL);
3206 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3207 if (Record.size() < 3)
3208 return Error(BitcodeError::InvalidRecord);
3209 Type *OpTy = getTypeByID(Record[0]);
3210 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3211 Type *ResTy = getTypeByID(Record[2]);
3212 if (!OpTy || !Op || !ResTy)
3213 return Error(BitcodeError::InvalidRecord);
3214 I = new VAArgInst(Op, ResTy);
3215 InstructionList.push_back(I);
3220 // Add instruction to end of current BB. If there is no current BB, reject
3224 return Error(BitcodeError::InvalidInstructionWithNoBB);
3226 CurBB->getInstList().push_back(I);
3228 // If this was a terminator instruction, move to the next block.
3229 if (isa<TerminatorInst>(I)) {
3231 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3234 // Non-void values get registered in the value table for future use.
3235 if (I && !I->getType()->isVoidTy())
3236 ValueList.AssignValue(I, NextValueNo++);
3241 // Check the function list for unresolved values.
3242 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3243 if (!A->getParent()) {
3244 // We found at least one unresolved value. Nuke them all to avoid leaks.
3245 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3246 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3247 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3251 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3255 // FIXME: Check for unresolved forward-declared metadata references
3256 // and clean up leaks.
3258 // Trim the value list down to the size it was before we parsed this function.
3259 ValueList.shrinkTo(ModuleValueListSize);
3260 MDValueList.shrinkTo(ModuleMDValueListSize);
3261 std::vector<BasicBlock*>().swap(FunctionBBs);
3262 return std::error_code();
3265 /// Find the function body in the bitcode stream
3266 std::error_code BitcodeReader::FindFunctionInStream(
3268 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3269 while (DeferredFunctionInfoIterator->second == 0) {
3270 if (Stream.AtEndOfStream())
3271 return Error(BitcodeError::CouldNotFindFunctionInStream);
3272 // ParseModule will parse the next body in the stream and set its
3273 // position in the DeferredFunctionInfo map.
3274 if (std::error_code EC = ParseModule(true))
3277 return std::error_code();
3280 //===----------------------------------------------------------------------===//
3281 // GVMaterializer implementation
3282 //===----------------------------------------------------------------------===//
3284 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3286 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3287 Function *F = dyn_cast<Function>(GV);
3288 // If it's not a function or is already material, ignore the request.
3289 if (!F || !F->isMaterializable())
3290 return std::error_code();
3292 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3293 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3294 // If its position is recorded as 0, its body is somewhere in the stream
3295 // but we haven't seen it yet.
3296 if (DFII->second == 0 && LazyStreamer)
3297 if (std::error_code EC = FindFunctionInStream(F, DFII))
3300 // Move the bit stream to the saved position of the deferred function body.
3301 Stream.JumpToBit(DFII->second);
3303 if (std::error_code EC = ParseFunctionBody(F))
3305 F->setIsMaterializable(false);
3307 // Upgrade any old intrinsic calls in the function.
3308 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3309 E = UpgradedIntrinsics.end(); I != E; ++I) {
3310 if (I->first != I->second) {
3311 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3313 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3314 UpgradeIntrinsicCall(CI, I->second);
3319 // Bring in any functions that this function forward-referenced via
3321 return materializeForwardReferencedFunctions();
3324 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3325 const Function *F = dyn_cast<Function>(GV);
3326 if (!F || F->isDeclaration())
3329 // Dematerializing F would leave dangling references that wouldn't be
3330 // reconnected on re-materialization.
3331 if (BlockAddressesTaken.count(F))
3334 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3337 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3338 Function *F = dyn_cast<Function>(GV);
3339 // If this function isn't dematerializable, this is a noop.
3340 if (!F || !isDematerializable(F))
3343 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3345 // Just forget the function body, we can remat it later.
3346 F->dropAllReferences();
3347 F->setIsMaterializable(true);
3350 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3351 assert(M == TheModule &&
3352 "Can only Materialize the Module this BitcodeReader is attached to.");
3354 // Promise to materialize all forward references.
3355 WillMaterializeAllForwardRefs = true;
3357 // Iterate over the module, deserializing any functions that are still on
3359 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3361 if (std::error_code EC = materialize(F))
3364 // At this point, if there are any function bodies, the current bit is
3365 // pointing to the END_BLOCK record after them. Now make sure the rest
3366 // of the bits in the module have been read.
3370 // Check that all block address forward references got resolved (as we
3372 if (!BasicBlockFwdRefs.empty())
3373 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3375 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3376 // delete the old functions to clean up. We can't do this unless the entire
3377 // module is materialized because there could always be another function body
3378 // with calls to the old function.
3379 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3380 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3381 if (I->first != I->second) {
3382 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3384 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3385 UpgradeIntrinsicCall(CI, I->second);
3387 if (!I->first->use_empty())
3388 I->first->replaceAllUsesWith(I->second);
3389 I->first->eraseFromParent();
3392 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3394 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3395 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3397 UpgradeDebugInfo(*M);
3398 return std::error_code();
3401 std::error_code BitcodeReader::InitStream() {
3403 return InitLazyStream();
3404 return InitStreamFromBuffer();
3407 std::error_code BitcodeReader::InitStreamFromBuffer() {
3408 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3409 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3411 if (Buffer->getBufferSize() & 3)
3412 return Error(BitcodeError::InvalidBitcodeSignature);
3414 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3415 // The magic number is 0x0B17C0DE stored in little endian.
3416 if (isBitcodeWrapper(BufPtr, BufEnd))
3417 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3418 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3420 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3421 Stream.init(&*StreamFile);
3423 return std::error_code();
3426 std::error_code BitcodeReader::InitLazyStream() {
3427 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3429 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3430 StreamFile.reset(new BitstreamReader(Bytes));
3431 Stream.init(&*StreamFile);
3433 unsigned char buf[16];
3434 if (Bytes->readBytes(buf, 16, 0) != 16)
3435 return Error(BitcodeError::InvalidBitcodeSignature);
3437 if (!isBitcode(buf, buf + 16))
3438 return Error(BitcodeError::InvalidBitcodeSignature);
3440 if (isBitcodeWrapper(buf, buf + 4)) {
3441 const unsigned char *bitcodeStart = buf;
3442 const unsigned char *bitcodeEnd = buf + 16;
3443 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3444 Bytes->dropLeadingBytes(bitcodeStart - buf);
3445 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3447 return std::error_code();
3451 class BitcodeErrorCategoryType : public std::error_category {
3452 const char *name() const LLVM_NOEXCEPT override {
3453 return "llvm.bitcode";
3455 std::string message(int IE) const override {
3456 BitcodeError E = static_cast<BitcodeError>(IE);
3458 case BitcodeError::ConflictingMETADATA_KINDRecords:
3459 return "Conflicting METADATA_KIND records";
3460 case BitcodeError::CouldNotFindFunctionInStream:
3461 return "Could not find function in stream";
3462 case BitcodeError::ExpectedConstant:
3463 return "Expected a constant";
3464 case BitcodeError::InsufficientFunctionProtos:
3465 return "Insufficient function protos";
3466 case BitcodeError::InvalidBitcodeSignature:
3467 return "Invalid bitcode signature";
3468 case BitcodeError::InvalidBitcodeWrapperHeader:
3469 return "Invalid bitcode wrapper header";
3470 case BitcodeError::InvalidConstantReference:
3471 return "Invalid ronstant reference";
3472 case BitcodeError::InvalidID:
3473 return "Invalid ID";
3474 case BitcodeError::InvalidInstructionWithNoBB:
3475 return "Invalid instruction with no BB";
3476 case BitcodeError::InvalidRecord:
3477 return "Invalid record";
3478 case BitcodeError::InvalidTypeForValue:
3479 return "Invalid type for value";
3480 case BitcodeError::InvalidTYPETable:
3481 return "Invalid TYPE table";
3482 case BitcodeError::InvalidType:
3483 return "Invalid type";
3484 case BitcodeError::MalformedBlock:
3485 return "Malformed block";
3486 case BitcodeError::MalformedGlobalInitializerSet:
3487 return "Malformed global initializer set";
3488 case BitcodeError::InvalidMultipleBlocks:
3489 return "Invalid multiple blocks";
3490 case BitcodeError::NeverResolvedValueFoundInFunction:
3491 return "Never resolved value found in function";
3492 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3493 return "Never resolved function from blockaddress";
3494 case BitcodeError::InvalidValue:
3495 return "Invalid value";
3497 llvm_unreachable("Unknown error type!");
3502 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3504 const std::error_category &llvm::BitcodeErrorCategory() {
3505 return *ErrorCategory;
3508 //===----------------------------------------------------------------------===//
3509 // External interface
3510 //===----------------------------------------------------------------------===//
3512 /// \brief Get a lazy one-at-time loading module from bitcode.
3514 /// This isn't always used in a lazy context. In particular, it's also used by
3515 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3516 /// in forward-referenced functions from block address references.
3518 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3519 /// materialize everything -- in particular, if this isn't truly lazy.
3520 static ErrorOr<Module *>
3521 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3522 LLVMContext &Context, bool WillMaterializeAll) {
3523 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3524 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3525 M->setMaterializer(R);
3527 auto cleanupOnError = [&](std::error_code EC) {
3528 R->releaseBuffer(); // Never take ownership on error.
3529 delete M; // Also deletes R.
3533 if (std::error_code EC = R->ParseBitcodeInto(M))
3534 return cleanupOnError(EC);
3536 if (!WillMaterializeAll)
3537 // Resolve forward references from blockaddresses.
3538 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3539 return cleanupOnError(EC);
3541 Buffer.release(); // The BitcodeReader owns it now.
3546 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3547 LLVMContext &Context) {
3548 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3551 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3552 DataStreamer *streamer,
3553 LLVMContext &Context,
3554 std::string *ErrMsg) {
3555 Module *M = new Module(name, Context);
3556 BitcodeReader *R = new BitcodeReader(streamer, Context);
3557 M->setMaterializer(R);
3558 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3560 *ErrMsg = EC.message();
3561 delete M; // Also deletes R.
3567 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3568 LLVMContext &Context) {
3569 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3570 ErrorOr<Module *> ModuleOrErr =
3571 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3574 Module *M = ModuleOrErr.get();
3575 // Read in the entire module, and destroy the BitcodeReader.
3576 if (std::error_code EC = M->materializeAllPermanently()) {
3581 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3582 // written. We must defer until the Module has been fully materialized.
3587 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3588 LLVMContext &Context) {
3589 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3590 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3591 ErrorOr<std::string> Triple = R->parseTriple();
3592 if (Triple.getError())
3594 return Triple.get();