1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/Bitcode/LLVMBitCodes.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
35 if (WillMaterializeAllForwardRefs)
36 return std::error_code();
39 WillMaterializeAllForwardRefs = true;
41 while (!BasicBlockFwdRefQueue.empty()) {
42 Function *F = BasicBlockFwdRefQueue.front();
43 BasicBlockFwdRefQueue.pop_front();
44 assert(F && "Expected valid function");
45 if (!BasicBlockFwdRefs.count(F))
46 // Already materialized.
49 // Check for a function that isn't materializable to prevent an infinite
50 // loop. When parsing a blockaddress stored in a global variable, there
51 // isn't a trivial way to check if a function will have a body without a
52 // linear search through FunctionsWithBodies, so just check it here.
53 if (!F->isMaterializable())
54 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
56 // Try to materialize F.
57 if (std::error_code EC = Materialize(F))
60 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
63 WillMaterializeAllForwardRefs = false;
64 return std::error_code();
67 void BitcodeReader::FreeState() {
69 std::vector<Type*>().swap(TypeList);
72 std::vector<Comdat *>().swap(ComdatList);
74 std::vector<AttributeSet>().swap(MAttributes);
75 std::vector<BasicBlock*>().swap(FunctionBBs);
76 std::vector<Function*>().swap(FunctionsWithBodies);
77 DeferredFunctionInfo.clear();
80 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
81 BasicBlockFwdRefQueue.clear();
84 //===----------------------------------------------------------------------===//
85 // Helper functions to implement forward reference resolution, etc.
86 //===----------------------------------------------------------------------===//
88 /// ConvertToString - Convert a string from a record into an std::string, return
90 template<typename StrTy>
91 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
93 if (Idx > Record.size())
96 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
97 Result += (char)Record[i];
101 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
103 default: // Map unknown/new linkages to external
104 case 0: return GlobalValue::ExternalLinkage;
105 case 1: return GlobalValue::WeakAnyLinkage;
106 case 2: return GlobalValue::AppendingLinkage;
107 case 3: return GlobalValue::InternalLinkage;
108 case 4: return GlobalValue::LinkOnceAnyLinkage;
109 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
110 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
111 case 7: return GlobalValue::ExternalWeakLinkage;
112 case 8: return GlobalValue::CommonLinkage;
113 case 9: return GlobalValue::PrivateLinkage;
114 case 10: return GlobalValue::WeakODRLinkage;
115 case 11: return GlobalValue::LinkOnceODRLinkage;
116 case 12: return GlobalValue::AvailableExternallyLinkage;
118 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
120 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
124 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
126 default: // Map unknown visibilities to default.
127 case 0: return GlobalValue::DefaultVisibility;
128 case 1: return GlobalValue::HiddenVisibility;
129 case 2: return GlobalValue::ProtectedVisibility;
133 static GlobalValue::DLLStorageClassTypes
134 GetDecodedDLLStorageClass(unsigned Val) {
136 default: // Map unknown values to default.
137 case 0: return GlobalValue::DefaultStorageClass;
138 case 1: return GlobalValue::DLLImportStorageClass;
139 case 2: return GlobalValue::DLLExportStorageClass;
143 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
145 case 0: return GlobalVariable::NotThreadLocal;
146 default: // Map unknown non-zero value to general dynamic.
147 case 1: return GlobalVariable::GeneralDynamicTLSModel;
148 case 2: return GlobalVariable::LocalDynamicTLSModel;
149 case 3: return GlobalVariable::InitialExecTLSModel;
150 case 4: return GlobalVariable::LocalExecTLSModel;
154 static int GetDecodedCastOpcode(unsigned Val) {
157 case bitc::CAST_TRUNC : return Instruction::Trunc;
158 case bitc::CAST_ZEXT : return Instruction::ZExt;
159 case bitc::CAST_SEXT : return Instruction::SExt;
160 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
161 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
162 case bitc::CAST_UITOFP : return Instruction::UIToFP;
163 case bitc::CAST_SITOFP : return Instruction::SIToFP;
164 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
165 case bitc::CAST_FPEXT : return Instruction::FPExt;
166 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
167 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
168 case bitc::CAST_BITCAST : return Instruction::BitCast;
169 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
172 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
175 case bitc::BINOP_ADD:
176 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
177 case bitc::BINOP_SUB:
178 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
179 case bitc::BINOP_MUL:
180 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
181 case bitc::BINOP_UDIV: return Instruction::UDiv;
182 case bitc::BINOP_SDIV:
183 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
184 case bitc::BINOP_UREM: return Instruction::URem;
185 case bitc::BINOP_SREM:
186 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
187 case bitc::BINOP_SHL: return Instruction::Shl;
188 case bitc::BINOP_LSHR: return Instruction::LShr;
189 case bitc::BINOP_ASHR: return Instruction::AShr;
190 case bitc::BINOP_AND: return Instruction::And;
191 case bitc::BINOP_OR: return Instruction::Or;
192 case bitc::BINOP_XOR: return Instruction::Xor;
196 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
198 default: return AtomicRMWInst::BAD_BINOP;
199 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
200 case bitc::RMW_ADD: return AtomicRMWInst::Add;
201 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
202 case bitc::RMW_AND: return AtomicRMWInst::And;
203 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
204 case bitc::RMW_OR: return AtomicRMWInst::Or;
205 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
206 case bitc::RMW_MAX: return AtomicRMWInst::Max;
207 case bitc::RMW_MIN: return AtomicRMWInst::Min;
208 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
209 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
213 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
215 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
216 case bitc::ORDERING_UNORDERED: return Unordered;
217 case bitc::ORDERING_MONOTONIC: return Monotonic;
218 case bitc::ORDERING_ACQUIRE: return Acquire;
219 case bitc::ORDERING_RELEASE: return Release;
220 case bitc::ORDERING_ACQREL: return AcquireRelease;
221 default: // Map unknown orderings to sequentially-consistent.
222 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
226 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
228 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
229 default: // Map unknown scopes to cross-thread.
230 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
234 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
236 default: // Map unknown selection kinds to any.
237 case bitc::COMDAT_SELECTION_KIND_ANY:
239 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
240 return Comdat::ExactMatch;
241 case bitc::COMDAT_SELECTION_KIND_LARGEST:
242 return Comdat::Largest;
243 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
244 return Comdat::NoDuplicates;
245 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
246 return Comdat::SameSize;
250 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
252 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
253 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
259 /// @brief A class for maintaining the slot number definition
260 /// as a placeholder for the actual definition for forward constants defs.
261 class ConstantPlaceHolder : public ConstantExpr {
262 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
264 // allocate space for exactly one operand
265 void *operator new(size_t s) {
266 return User::operator new(s, 1);
268 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
269 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
270 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
273 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
274 static bool classof(const Value *V) {
275 return isa<ConstantExpr>(V) &&
276 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
280 /// Provide fast operand accessors
281 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
285 // FIXME: can we inherit this from ConstantExpr?
287 struct OperandTraits<ConstantPlaceHolder> :
288 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
293 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
302 WeakVH &OldV = ValuePtrs[Idx];
308 // Handle constants and non-constants (e.g. instrs) differently for
310 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
311 ResolveConstants.push_back(std::make_pair(PHC, Idx));
314 // If there was a forward reference to this value, replace it.
315 Value *PrevVal = OldV;
316 OldV->replaceAllUsesWith(V);
322 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
327 if (Value *V = ValuePtrs[Idx]) {
328 assert(Ty == V->getType() && "Type mismatch in constant table!");
329 return cast<Constant>(V);
332 // Create and return a placeholder, which will later be RAUW'd.
333 Constant *C = new ConstantPlaceHolder(Ty, Context);
338 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
342 if (Value *V = ValuePtrs[Idx]) {
343 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
347 // No type specified, must be invalid reference.
348 if (!Ty) return nullptr;
350 // Create and return a placeholder, which will later be RAUW'd.
351 Value *V = new Argument(Ty);
356 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
357 /// resolves any forward references. The idea behind this is that we sometimes
358 /// get constants (such as large arrays) which reference *many* forward ref
359 /// constants. Replacing each of these causes a lot of thrashing when
360 /// building/reuniquing the constant. Instead of doing this, we look at all the
361 /// uses and rewrite all the place holders at once for any constant that uses
363 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
364 // Sort the values by-pointer so that they are efficient to look up with a
366 std::sort(ResolveConstants.begin(), ResolveConstants.end());
368 SmallVector<Constant*, 64> NewOps;
370 while (!ResolveConstants.empty()) {
371 Value *RealVal = operator[](ResolveConstants.back().second);
372 Constant *Placeholder = ResolveConstants.back().first;
373 ResolveConstants.pop_back();
375 // Loop over all users of the placeholder, updating them to reference the
376 // new value. If they reference more than one placeholder, update them all
378 while (!Placeholder->use_empty()) {
379 auto UI = Placeholder->user_begin();
382 // If the using object isn't uniqued, just update the operands. This
383 // handles instructions and initializers for global variables.
384 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
385 UI.getUse().set(RealVal);
389 // Otherwise, we have a constant that uses the placeholder. Replace that
390 // constant with a new constant that has *all* placeholder uses updated.
391 Constant *UserC = cast<Constant>(U);
392 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
395 if (!isa<ConstantPlaceHolder>(*I)) {
396 // Not a placeholder reference.
398 } else if (*I == Placeholder) {
399 // Common case is that it just references this one placeholder.
402 // Otherwise, look up the placeholder in ResolveConstants.
403 ResolveConstantsTy::iterator It =
404 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
405 std::pair<Constant*, unsigned>(cast<Constant>(*I),
407 assert(It != ResolveConstants.end() && It->first == *I);
408 NewOp = operator[](It->second);
411 NewOps.push_back(cast<Constant>(NewOp));
414 // Make the new constant.
416 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
417 NewC = ConstantArray::get(UserCA->getType(), NewOps);
418 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
419 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
420 } else if (isa<ConstantVector>(UserC)) {
421 NewC = ConstantVector::get(NewOps);
423 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
424 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
427 UserC->replaceAllUsesWith(NewC);
428 UserC->destroyConstant();
432 // Update all ValueHandles, they should be the only users at this point.
433 Placeholder->replaceAllUsesWith(RealVal);
438 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
447 WeakVH &OldV = MDValuePtrs[Idx];
453 // If there was a forward reference to this value, replace it.
454 MDNode *PrevVal = cast<MDNode>(OldV);
455 OldV->replaceAllUsesWith(V);
456 MDNode::deleteTemporary(PrevVal);
457 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
459 MDValuePtrs[Idx] = V;
462 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
466 if (Value *V = MDValuePtrs[Idx]) {
467 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
471 // Create and return a placeholder, which will later be RAUW'd.
472 Value *V = MDNode::getTemporary(Context, None);
473 MDValuePtrs[Idx] = V;
477 Type *BitcodeReader::getTypeByID(unsigned ID) {
478 // The type table size is always specified correctly.
479 if (ID >= TypeList.size())
482 if (Type *Ty = TypeList[ID])
485 // If we have a forward reference, the only possible case is when it is to a
486 // named struct. Just create a placeholder for now.
487 return TypeList[ID] = StructType::create(Context);
491 //===----------------------------------------------------------------------===//
492 // Functions for parsing blocks from the bitcode file
493 //===----------------------------------------------------------------------===//
496 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
497 /// been decoded from the given integer. This function must stay in sync with
498 /// 'encodeLLVMAttributesForBitcode'.
499 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
500 uint64_t EncodedAttrs) {
501 // FIXME: Remove in 4.0.
503 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
504 // the bits above 31 down by 11 bits.
505 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
506 assert((!Alignment || isPowerOf2_32(Alignment)) &&
507 "Alignment must be a power of two.");
510 B.addAlignmentAttr(Alignment);
511 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
512 (EncodedAttrs & 0xffff));
515 std::error_code BitcodeReader::ParseAttributeBlock() {
516 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
517 return Error(BitcodeError::InvalidRecord);
519 if (!MAttributes.empty())
520 return Error(BitcodeError::InvalidMultipleBlocks);
522 SmallVector<uint64_t, 64> Record;
524 SmallVector<AttributeSet, 8> Attrs;
526 // Read all the records.
528 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
530 switch (Entry.Kind) {
531 case BitstreamEntry::SubBlock: // Handled for us already.
532 case BitstreamEntry::Error:
533 return Error(BitcodeError::MalformedBlock);
534 case BitstreamEntry::EndBlock:
535 return std::error_code();
536 case BitstreamEntry::Record:
537 // The interesting case.
543 switch (Stream.readRecord(Entry.ID, Record)) {
544 default: // Default behavior: ignore.
546 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
547 // FIXME: Remove in 4.0.
548 if (Record.size() & 1)
549 return Error(BitcodeError::InvalidRecord);
551 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
553 decodeLLVMAttributesForBitcode(B, Record[i+1]);
554 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
557 MAttributes.push_back(AttributeSet::get(Context, Attrs));
561 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
562 for (unsigned i = 0, e = Record.size(); i != e; ++i)
563 Attrs.push_back(MAttributeGroups[Record[i]]);
565 MAttributes.push_back(AttributeSet::get(Context, Attrs));
573 // Returns Attribute::None on unrecognized codes.
574 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
577 return Attribute::None;
578 case bitc::ATTR_KIND_ALIGNMENT:
579 return Attribute::Alignment;
580 case bitc::ATTR_KIND_ALWAYS_INLINE:
581 return Attribute::AlwaysInline;
582 case bitc::ATTR_KIND_BUILTIN:
583 return Attribute::Builtin;
584 case bitc::ATTR_KIND_BY_VAL:
585 return Attribute::ByVal;
586 case bitc::ATTR_KIND_IN_ALLOCA:
587 return Attribute::InAlloca;
588 case bitc::ATTR_KIND_COLD:
589 return Attribute::Cold;
590 case bitc::ATTR_KIND_INLINE_HINT:
591 return Attribute::InlineHint;
592 case bitc::ATTR_KIND_IN_REG:
593 return Attribute::InReg;
594 case bitc::ATTR_KIND_JUMP_TABLE:
595 return Attribute::JumpTable;
596 case bitc::ATTR_KIND_MIN_SIZE:
597 return Attribute::MinSize;
598 case bitc::ATTR_KIND_NAKED:
599 return Attribute::Naked;
600 case bitc::ATTR_KIND_NEST:
601 return Attribute::Nest;
602 case bitc::ATTR_KIND_NO_ALIAS:
603 return Attribute::NoAlias;
604 case bitc::ATTR_KIND_NO_BUILTIN:
605 return Attribute::NoBuiltin;
606 case bitc::ATTR_KIND_NO_CAPTURE:
607 return Attribute::NoCapture;
608 case bitc::ATTR_KIND_NO_DUPLICATE:
609 return Attribute::NoDuplicate;
610 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
611 return Attribute::NoImplicitFloat;
612 case bitc::ATTR_KIND_NO_INLINE:
613 return Attribute::NoInline;
614 case bitc::ATTR_KIND_NON_LAZY_BIND:
615 return Attribute::NonLazyBind;
616 case bitc::ATTR_KIND_NON_NULL:
617 return Attribute::NonNull;
618 case bitc::ATTR_KIND_DEREFERENCEABLE:
619 return Attribute::Dereferenceable;
620 case bitc::ATTR_KIND_NO_RED_ZONE:
621 return Attribute::NoRedZone;
622 case bitc::ATTR_KIND_NO_RETURN:
623 return Attribute::NoReturn;
624 case bitc::ATTR_KIND_NO_UNWIND:
625 return Attribute::NoUnwind;
626 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
627 return Attribute::OptimizeForSize;
628 case bitc::ATTR_KIND_OPTIMIZE_NONE:
629 return Attribute::OptimizeNone;
630 case bitc::ATTR_KIND_READ_NONE:
631 return Attribute::ReadNone;
632 case bitc::ATTR_KIND_READ_ONLY:
633 return Attribute::ReadOnly;
634 case bitc::ATTR_KIND_RETURNED:
635 return Attribute::Returned;
636 case bitc::ATTR_KIND_RETURNS_TWICE:
637 return Attribute::ReturnsTwice;
638 case bitc::ATTR_KIND_S_EXT:
639 return Attribute::SExt;
640 case bitc::ATTR_KIND_STACK_ALIGNMENT:
641 return Attribute::StackAlignment;
642 case bitc::ATTR_KIND_STACK_PROTECT:
643 return Attribute::StackProtect;
644 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
645 return Attribute::StackProtectReq;
646 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
647 return Attribute::StackProtectStrong;
648 case bitc::ATTR_KIND_STRUCT_RET:
649 return Attribute::StructRet;
650 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
651 return Attribute::SanitizeAddress;
652 case bitc::ATTR_KIND_SANITIZE_THREAD:
653 return Attribute::SanitizeThread;
654 case bitc::ATTR_KIND_SANITIZE_MEMORY:
655 return Attribute::SanitizeMemory;
656 case bitc::ATTR_KIND_UW_TABLE:
657 return Attribute::UWTable;
658 case bitc::ATTR_KIND_Z_EXT:
659 return Attribute::ZExt;
663 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
664 Attribute::AttrKind *Kind) {
665 *Kind = GetAttrFromCode(Code);
666 if (*Kind == Attribute::None)
667 return Error(BitcodeError::InvalidValue);
668 return std::error_code();
671 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
672 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
673 return Error(BitcodeError::InvalidRecord);
675 if (!MAttributeGroups.empty())
676 return Error(BitcodeError::InvalidMultipleBlocks);
678 SmallVector<uint64_t, 64> Record;
680 // Read all the records.
682 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
684 switch (Entry.Kind) {
685 case BitstreamEntry::SubBlock: // Handled for us already.
686 case BitstreamEntry::Error:
687 return Error(BitcodeError::MalformedBlock);
688 case BitstreamEntry::EndBlock:
689 return std::error_code();
690 case BitstreamEntry::Record:
691 // The interesting case.
697 switch (Stream.readRecord(Entry.ID, Record)) {
698 default: // Default behavior: ignore.
700 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
701 if (Record.size() < 3)
702 return Error(BitcodeError::InvalidRecord);
704 uint64_t GrpID = Record[0];
705 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
708 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
709 if (Record[i] == 0) { // Enum attribute
710 Attribute::AttrKind Kind;
711 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
714 B.addAttribute(Kind);
715 } else if (Record[i] == 1) { // Integer attribute
716 Attribute::AttrKind Kind;
717 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
719 if (Kind == Attribute::Alignment)
720 B.addAlignmentAttr(Record[++i]);
721 else if (Kind == Attribute::StackAlignment)
722 B.addStackAlignmentAttr(Record[++i]);
723 else if (Kind == Attribute::Dereferenceable)
724 B.addDereferenceableAttr(Record[++i]);
725 } else { // String attribute
726 assert((Record[i] == 3 || Record[i] == 4) &&
727 "Invalid attribute group entry");
728 bool HasValue = (Record[i++] == 4);
729 SmallString<64> KindStr;
730 SmallString<64> ValStr;
732 while (Record[i] != 0 && i != e)
733 KindStr += Record[i++];
734 assert(Record[i] == 0 && "Kind string not null terminated");
737 // Has a value associated with it.
738 ++i; // Skip the '0' that terminates the "kind" string.
739 while (Record[i] != 0 && i != e)
740 ValStr += Record[i++];
741 assert(Record[i] == 0 && "Value string not null terminated");
744 B.addAttribute(KindStr.str(), ValStr.str());
748 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
755 std::error_code BitcodeReader::ParseTypeTable() {
756 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
757 return Error(BitcodeError::InvalidRecord);
759 return ParseTypeTableBody();
762 std::error_code BitcodeReader::ParseTypeTableBody() {
763 if (!TypeList.empty())
764 return Error(BitcodeError::InvalidMultipleBlocks);
766 SmallVector<uint64_t, 64> Record;
767 unsigned NumRecords = 0;
769 SmallString<64> TypeName;
771 // Read all the records for this type table.
773 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
775 switch (Entry.Kind) {
776 case BitstreamEntry::SubBlock: // Handled for us already.
777 case BitstreamEntry::Error:
778 return Error(BitcodeError::MalformedBlock);
779 case BitstreamEntry::EndBlock:
780 if (NumRecords != TypeList.size())
781 return Error(BitcodeError::MalformedBlock);
782 return std::error_code();
783 case BitstreamEntry::Record:
784 // The interesting case.
790 Type *ResultTy = nullptr;
791 switch (Stream.readRecord(Entry.ID, Record)) {
793 return Error(BitcodeError::InvalidValue);
794 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
795 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
796 // type list. This allows us to reserve space.
797 if (Record.size() < 1)
798 return Error(BitcodeError::InvalidRecord);
799 TypeList.resize(Record[0]);
801 case bitc::TYPE_CODE_VOID: // VOID
802 ResultTy = Type::getVoidTy(Context);
804 case bitc::TYPE_CODE_HALF: // HALF
805 ResultTy = Type::getHalfTy(Context);
807 case bitc::TYPE_CODE_FLOAT: // FLOAT
808 ResultTy = Type::getFloatTy(Context);
810 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
811 ResultTy = Type::getDoubleTy(Context);
813 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
814 ResultTy = Type::getX86_FP80Ty(Context);
816 case bitc::TYPE_CODE_FP128: // FP128
817 ResultTy = Type::getFP128Ty(Context);
819 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
820 ResultTy = Type::getPPC_FP128Ty(Context);
822 case bitc::TYPE_CODE_LABEL: // LABEL
823 ResultTy = Type::getLabelTy(Context);
825 case bitc::TYPE_CODE_METADATA: // METADATA
826 ResultTy = Type::getMetadataTy(Context);
828 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
829 ResultTy = Type::getX86_MMXTy(Context);
831 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
832 if (Record.size() < 1)
833 return Error(BitcodeError::InvalidRecord);
835 ResultTy = IntegerType::get(Context, Record[0]);
837 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
838 // [pointee type, address space]
839 if (Record.size() < 1)
840 return Error(BitcodeError::InvalidRecord);
841 unsigned AddressSpace = 0;
842 if (Record.size() == 2)
843 AddressSpace = Record[1];
844 ResultTy = getTypeByID(Record[0]);
846 return Error(BitcodeError::InvalidType);
847 ResultTy = PointerType::get(ResultTy, AddressSpace);
850 case bitc::TYPE_CODE_FUNCTION_OLD: {
851 // FIXME: attrid is dead, remove it in LLVM 4.0
852 // FUNCTION: [vararg, attrid, retty, paramty x N]
853 if (Record.size() < 3)
854 return Error(BitcodeError::InvalidRecord);
855 SmallVector<Type*, 8> ArgTys;
856 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
857 if (Type *T = getTypeByID(Record[i]))
863 ResultTy = getTypeByID(Record[2]);
864 if (!ResultTy || ArgTys.size() < Record.size()-3)
865 return Error(BitcodeError::InvalidType);
867 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
870 case bitc::TYPE_CODE_FUNCTION: {
871 // FUNCTION: [vararg, retty, paramty x N]
872 if (Record.size() < 2)
873 return Error(BitcodeError::InvalidRecord);
874 SmallVector<Type*, 8> ArgTys;
875 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
876 if (Type *T = getTypeByID(Record[i]))
882 ResultTy = getTypeByID(Record[1]);
883 if (!ResultTy || ArgTys.size() < Record.size()-2)
884 return Error(BitcodeError::InvalidType);
886 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
889 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
890 if (Record.size() < 1)
891 return Error(BitcodeError::InvalidRecord);
892 SmallVector<Type*, 8> EltTys;
893 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
894 if (Type *T = getTypeByID(Record[i]))
899 if (EltTys.size() != Record.size()-1)
900 return Error(BitcodeError::InvalidType);
901 ResultTy = StructType::get(Context, EltTys, Record[0]);
904 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
905 if (ConvertToString(Record, 0, TypeName))
906 return Error(BitcodeError::InvalidRecord);
909 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
910 if (Record.size() < 1)
911 return Error(BitcodeError::InvalidRecord);
913 if (NumRecords >= TypeList.size())
914 return Error(BitcodeError::InvalidTYPETable);
916 // Check to see if this was forward referenced, if so fill in the temp.
917 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
919 Res->setName(TypeName);
920 TypeList[NumRecords] = nullptr;
921 } else // Otherwise, create a new struct.
922 Res = StructType::create(Context, TypeName);
925 SmallVector<Type*, 8> EltTys;
926 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
927 if (Type *T = getTypeByID(Record[i]))
932 if (EltTys.size() != Record.size()-1)
933 return Error(BitcodeError::InvalidRecord);
934 Res->setBody(EltTys, Record[0]);
938 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
939 if (Record.size() != 1)
940 return Error(BitcodeError::InvalidRecord);
942 if (NumRecords >= TypeList.size())
943 return Error(BitcodeError::InvalidTYPETable);
945 // Check to see if this was forward referenced, if so fill in the temp.
946 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
948 Res->setName(TypeName);
949 TypeList[NumRecords] = nullptr;
950 } else // Otherwise, create a new struct with no body.
951 Res = StructType::create(Context, TypeName);
956 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
957 if (Record.size() < 2)
958 return Error(BitcodeError::InvalidRecord);
959 if ((ResultTy = getTypeByID(Record[1])))
960 ResultTy = ArrayType::get(ResultTy, Record[0]);
962 return Error(BitcodeError::InvalidType);
964 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
965 if (Record.size() < 2)
966 return Error(BitcodeError::InvalidRecord);
967 if ((ResultTy = getTypeByID(Record[1])))
968 ResultTy = VectorType::get(ResultTy, Record[0]);
970 return Error(BitcodeError::InvalidType);
974 if (NumRecords >= TypeList.size())
975 return Error(BitcodeError::InvalidTYPETable);
976 assert(ResultTy && "Didn't read a type?");
977 assert(!TypeList[NumRecords] && "Already read type?");
978 TypeList[NumRecords++] = ResultTy;
982 std::error_code BitcodeReader::ParseValueSymbolTable() {
983 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
984 return Error(BitcodeError::InvalidRecord);
986 SmallVector<uint64_t, 64> Record;
988 // Read all the records for this value table.
989 SmallString<128> ValueName;
991 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
993 switch (Entry.Kind) {
994 case BitstreamEntry::SubBlock: // Handled for us already.
995 case BitstreamEntry::Error:
996 return Error(BitcodeError::MalformedBlock);
997 case BitstreamEntry::EndBlock:
998 return std::error_code();
999 case BitstreamEntry::Record:
1000 // The interesting case.
1006 switch (Stream.readRecord(Entry.ID, Record)) {
1007 default: // Default behavior: unknown type.
1009 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1010 if (ConvertToString(Record, 1, ValueName))
1011 return Error(BitcodeError::InvalidRecord);
1012 unsigned ValueID = Record[0];
1013 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1014 return Error(BitcodeError::InvalidRecord);
1015 Value *V = ValueList[ValueID];
1017 V->setName(StringRef(ValueName.data(), ValueName.size()));
1021 case bitc::VST_CODE_BBENTRY: {
1022 if (ConvertToString(Record, 1, ValueName))
1023 return Error(BitcodeError::InvalidRecord);
1024 BasicBlock *BB = getBasicBlock(Record[0]);
1026 return Error(BitcodeError::InvalidRecord);
1028 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1036 std::error_code BitcodeReader::ParseMetadata() {
1037 unsigned NextMDValueNo = MDValueList.size();
1039 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1040 return Error(BitcodeError::InvalidRecord);
1042 SmallVector<uint64_t, 64> Record;
1044 // Read all the records.
1046 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1048 switch (Entry.Kind) {
1049 case BitstreamEntry::SubBlock: // Handled for us already.
1050 case BitstreamEntry::Error:
1051 return Error(BitcodeError::MalformedBlock);
1052 case BitstreamEntry::EndBlock:
1053 return std::error_code();
1054 case BitstreamEntry::Record:
1055 // The interesting case.
1059 bool IsFunctionLocal = false;
1062 unsigned Code = Stream.readRecord(Entry.ID, Record);
1064 default: // Default behavior: ignore.
1066 case bitc::METADATA_NAME: {
1067 // Read name of the named metadata.
1068 SmallString<8> Name(Record.begin(), Record.end());
1070 Code = Stream.ReadCode();
1072 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1073 unsigned NextBitCode = Stream.readRecord(Code, Record);
1074 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1076 // Read named metadata elements.
1077 unsigned Size = Record.size();
1078 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1079 for (unsigned i = 0; i != Size; ++i) {
1080 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1082 return Error(BitcodeError::InvalidRecord);
1083 NMD->addOperand(MD);
1087 case bitc::METADATA_FN_NODE:
1088 IsFunctionLocal = true;
1090 case bitc::METADATA_NODE: {
1091 if (Record.size() % 2 == 1)
1092 return Error(BitcodeError::InvalidRecord);
1094 unsigned Size = Record.size();
1095 SmallVector<Value*, 8> Elts;
1096 for (unsigned i = 0; i != Size; i += 2) {
1097 Type *Ty = getTypeByID(Record[i]);
1099 return Error(BitcodeError::InvalidRecord);
1100 if (Ty->isMetadataTy())
1101 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1102 else if (!Ty->isVoidTy())
1103 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1105 Elts.push_back(nullptr);
1107 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1108 IsFunctionLocal = false;
1109 MDValueList.AssignValue(V, NextMDValueNo++);
1112 case bitc::METADATA_STRING: {
1113 std::string String(Record.begin(), Record.end());
1114 llvm::UpgradeMDStringConstant(String);
1115 Value *V = MDString::get(Context, String);
1116 MDValueList.AssignValue(V, NextMDValueNo++);
1119 case bitc::METADATA_KIND: {
1120 if (Record.size() < 2)
1121 return Error(BitcodeError::InvalidRecord);
1123 unsigned Kind = Record[0];
1124 SmallString<8> Name(Record.begin()+1, Record.end());
1126 unsigned NewKind = TheModule->getMDKindID(Name.str());
1127 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1128 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1135 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1136 /// the LSB for dense VBR encoding.
1137 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1142 // There is no such thing as -0 with integers. "-0" really means MININT.
1146 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1147 /// values and aliases that we can.
1148 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1149 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1150 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1151 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1153 GlobalInitWorklist.swap(GlobalInits);
1154 AliasInitWorklist.swap(AliasInits);
1155 FunctionPrefixWorklist.swap(FunctionPrefixes);
1157 while (!GlobalInitWorklist.empty()) {
1158 unsigned ValID = GlobalInitWorklist.back().second;
1159 if (ValID >= ValueList.size()) {
1160 // Not ready to resolve this yet, it requires something later in the file.
1161 GlobalInits.push_back(GlobalInitWorklist.back());
1163 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1164 GlobalInitWorklist.back().first->setInitializer(C);
1166 return Error(BitcodeError::ExpectedConstant);
1168 GlobalInitWorklist.pop_back();
1171 while (!AliasInitWorklist.empty()) {
1172 unsigned ValID = AliasInitWorklist.back().second;
1173 if (ValID >= ValueList.size()) {
1174 AliasInits.push_back(AliasInitWorklist.back());
1176 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1177 AliasInitWorklist.back().first->setAliasee(C);
1179 return Error(BitcodeError::ExpectedConstant);
1181 AliasInitWorklist.pop_back();
1184 while (!FunctionPrefixWorklist.empty()) {
1185 unsigned ValID = FunctionPrefixWorklist.back().second;
1186 if (ValID >= ValueList.size()) {
1187 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1189 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1190 FunctionPrefixWorklist.back().first->setPrefixData(C);
1192 return Error(BitcodeError::ExpectedConstant);
1194 FunctionPrefixWorklist.pop_back();
1197 return std::error_code();
1200 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1201 SmallVector<uint64_t, 8> Words(Vals.size());
1202 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1203 BitcodeReader::decodeSignRotatedValue);
1205 return APInt(TypeBits, Words);
1208 std::error_code BitcodeReader::ParseConstants() {
1209 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1210 return Error(BitcodeError::InvalidRecord);
1212 SmallVector<uint64_t, 64> Record;
1214 // Read all the records for this value table.
1215 Type *CurTy = Type::getInt32Ty(Context);
1216 unsigned NextCstNo = ValueList.size();
1218 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1220 switch (Entry.Kind) {
1221 case BitstreamEntry::SubBlock: // Handled for us already.
1222 case BitstreamEntry::Error:
1223 return Error(BitcodeError::MalformedBlock);
1224 case BitstreamEntry::EndBlock:
1225 if (NextCstNo != ValueList.size())
1226 return Error(BitcodeError::InvalidConstantReference);
1228 // Once all the constants have been read, go through and resolve forward
1230 ValueList.ResolveConstantForwardRefs();
1231 return std::error_code();
1232 case BitstreamEntry::Record:
1233 // The interesting case.
1240 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1242 default: // Default behavior: unknown constant
1243 case bitc::CST_CODE_UNDEF: // UNDEF
1244 V = UndefValue::get(CurTy);
1246 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1248 return Error(BitcodeError::InvalidRecord);
1249 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1250 return Error(BitcodeError::InvalidRecord);
1251 CurTy = TypeList[Record[0]];
1252 continue; // Skip the ValueList manipulation.
1253 case bitc::CST_CODE_NULL: // NULL
1254 V = Constant::getNullValue(CurTy);
1256 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1257 if (!CurTy->isIntegerTy() || Record.empty())
1258 return Error(BitcodeError::InvalidRecord);
1259 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1261 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1262 if (!CurTy->isIntegerTy() || Record.empty())
1263 return Error(BitcodeError::InvalidRecord);
1265 APInt VInt = ReadWideAPInt(Record,
1266 cast<IntegerType>(CurTy)->getBitWidth());
1267 V = ConstantInt::get(Context, VInt);
1271 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1273 return Error(BitcodeError::InvalidRecord);
1274 if (CurTy->isHalfTy())
1275 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1276 APInt(16, (uint16_t)Record[0])));
1277 else if (CurTy->isFloatTy())
1278 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1279 APInt(32, (uint32_t)Record[0])));
1280 else if (CurTy->isDoubleTy())
1281 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1282 APInt(64, Record[0])));
1283 else if (CurTy->isX86_FP80Ty()) {
1284 // Bits are not stored the same way as a normal i80 APInt, compensate.
1285 uint64_t Rearrange[2];
1286 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1287 Rearrange[1] = Record[0] >> 48;
1288 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1289 APInt(80, Rearrange)));
1290 } else if (CurTy->isFP128Ty())
1291 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1292 APInt(128, Record)));
1293 else if (CurTy->isPPC_FP128Ty())
1294 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1295 APInt(128, Record)));
1297 V = UndefValue::get(CurTy);
1301 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1303 return Error(BitcodeError::InvalidRecord);
1305 unsigned Size = Record.size();
1306 SmallVector<Constant*, 16> Elts;
1308 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1309 for (unsigned i = 0; i != Size; ++i)
1310 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1311 STy->getElementType(i)));
1312 V = ConstantStruct::get(STy, Elts);
1313 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1314 Type *EltTy = ATy->getElementType();
1315 for (unsigned i = 0; i != Size; ++i)
1316 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1317 V = ConstantArray::get(ATy, Elts);
1318 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1319 Type *EltTy = VTy->getElementType();
1320 for (unsigned i = 0; i != Size; ++i)
1321 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1322 V = ConstantVector::get(Elts);
1324 V = UndefValue::get(CurTy);
1328 case bitc::CST_CODE_STRING: // STRING: [values]
1329 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1331 return Error(BitcodeError::InvalidRecord);
1333 SmallString<16> Elts(Record.begin(), Record.end());
1334 V = ConstantDataArray::getString(Context, Elts,
1335 BitCode == bitc::CST_CODE_CSTRING);
1338 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1340 return Error(BitcodeError::InvalidRecord);
1342 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1343 unsigned Size = Record.size();
1345 if (EltTy->isIntegerTy(8)) {
1346 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1347 if (isa<VectorType>(CurTy))
1348 V = ConstantDataVector::get(Context, Elts);
1350 V = ConstantDataArray::get(Context, Elts);
1351 } else if (EltTy->isIntegerTy(16)) {
1352 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1353 if (isa<VectorType>(CurTy))
1354 V = ConstantDataVector::get(Context, Elts);
1356 V = ConstantDataArray::get(Context, Elts);
1357 } else if (EltTy->isIntegerTy(32)) {
1358 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1359 if (isa<VectorType>(CurTy))
1360 V = ConstantDataVector::get(Context, Elts);
1362 V = ConstantDataArray::get(Context, Elts);
1363 } else if (EltTy->isIntegerTy(64)) {
1364 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1365 if (isa<VectorType>(CurTy))
1366 V = ConstantDataVector::get(Context, Elts);
1368 V = ConstantDataArray::get(Context, Elts);
1369 } else if (EltTy->isFloatTy()) {
1370 SmallVector<float, 16> Elts(Size);
1371 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1372 if (isa<VectorType>(CurTy))
1373 V = ConstantDataVector::get(Context, Elts);
1375 V = ConstantDataArray::get(Context, Elts);
1376 } else if (EltTy->isDoubleTy()) {
1377 SmallVector<double, 16> Elts(Size);
1378 std::transform(Record.begin(), Record.end(), Elts.begin(),
1380 if (isa<VectorType>(CurTy))
1381 V = ConstantDataVector::get(Context, Elts);
1383 V = ConstantDataArray::get(Context, Elts);
1385 return Error(BitcodeError::InvalidTypeForValue);
1390 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1391 if (Record.size() < 3)
1392 return Error(BitcodeError::InvalidRecord);
1393 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1395 V = UndefValue::get(CurTy); // Unknown binop.
1397 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1398 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1400 if (Record.size() >= 4) {
1401 if (Opc == Instruction::Add ||
1402 Opc == Instruction::Sub ||
1403 Opc == Instruction::Mul ||
1404 Opc == Instruction::Shl) {
1405 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1406 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1407 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1408 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1409 } else if (Opc == Instruction::SDiv ||
1410 Opc == Instruction::UDiv ||
1411 Opc == Instruction::LShr ||
1412 Opc == Instruction::AShr) {
1413 if (Record[3] & (1 << bitc::PEO_EXACT))
1414 Flags |= SDivOperator::IsExact;
1417 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1421 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1422 if (Record.size() < 3)
1423 return Error(BitcodeError::InvalidRecord);
1424 int Opc = GetDecodedCastOpcode(Record[0]);
1426 V = UndefValue::get(CurTy); // Unknown cast.
1428 Type *OpTy = getTypeByID(Record[1]);
1430 return Error(BitcodeError::InvalidRecord);
1431 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1432 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1433 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1437 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1438 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1439 if (Record.size() & 1)
1440 return Error(BitcodeError::InvalidRecord);
1441 SmallVector<Constant*, 16> Elts;
1442 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1443 Type *ElTy = getTypeByID(Record[i]);
1445 return Error(BitcodeError::InvalidRecord);
1446 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1448 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1449 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1451 bitc::CST_CODE_CE_INBOUNDS_GEP);
1454 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1455 if (Record.size() < 3)
1456 return Error(BitcodeError::InvalidRecord);
1458 Type *SelectorTy = Type::getInt1Ty(Context);
1460 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1461 // vector. Otherwise, it must be a single bit.
1462 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1463 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1464 VTy->getNumElements());
1466 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1468 ValueList.getConstantFwdRef(Record[1],CurTy),
1469 ValueList.getConstantFwdRef(Record[2],CurTy));
1472 case bitc::CST_CODE_CE_EXTRACTELT
1473 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1474 if (Record.size() < 3)
1475 return Error(BitcodeError::InvalidRecord);
1477 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1479 return Error(BitcodeError::InvalidRecord);
1480 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1481 Constant *Op1 = nullptr;
1482 if (Record.size() == 4) {
1483 Type *IdxTy = getTypeByID(Record[2]);
1485 return Error(BitcodeError::InvalidRecord);
1486 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1487 } else // TODO: Remove with llvm 4.0
1488 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1490 return Error(BitcodeError::InvalidRecord);
1491 V = ConstantExpr::getExtractElement(Op0, Op1);
1494 case bitc::CST_CODE_CE_INSERTELT
1495 : { // CE_INSERTELT: [opval, opval, opty, opval]
1496 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1497 if (Record.size() < 3 || !OpTy)
1498 return Error(BitcodeError::InvalidRecord);
1499 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1500 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1501 OpTy->getElementType());
1502 Constant *Op2 = nullptr;
1503 if (Record.size() == 4) {
1504 Type *IdxTy = getTypeByID(Record[2]);
1506 return Error(BitcodeError::InvalidRecord);
1507 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1508 } else // TODO: Remove with llvm 4.0
1509 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1511 return Error(BitcodeError::InvalidRecord);
1512 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1515 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1516 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1517 if (Record.size() < 3 || !OpTy)
1518 return Error(BitcodeError::InvalidRecord);
1519 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1520 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1521 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1522 OpTy->getNumElements());
1523 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1524 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1527 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1528 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1530 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1531 if (Record.size() < 4 || !RTy || !OpTy)
1532 return Error(BitcodeError::InvalidRecord);
1533 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1534 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1535 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1536 RTy->getNumElements());
1537 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1538 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1541 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1542 if (Record.size() < 4)
1543 return Error(BitcodeError::InvalidRecord);
1544 Type *OpTy = getTypeByID(Record[0]);
1546 return Error(BitcodeError::InvalidRecord);
1547 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1548 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1550 if (OpTy->isFPOrFPVectorTy())
1551 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1553 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1556 // This maintains backward compatibility, pre-asm dialect keywords.
1557 // FIXME: Remove with the 4.0 release.
1558 case bitc::CST_CODE_INLINEASM_OLD: {
1559 if (Record.size() < 2)
1560 return Error(BitcodeError::InvalidRecord);
1561 std::string AsmStr, ConstrStr;
1562 bool HasSideEffects = Record[0] & 1;
1563 bool IsAlignStack = Record[0] >> 1;
1564 unsigned AsmStrSize = Record[1];
1565 if (2+AsmStrSize >= Record.size())
1566 return Error(BitcodeError::InvalidRecord);
1567 unsigned ConstStrSize = Record[2+AsmStrSize];
1568 if (3+AsmStrSize+ConstStrSize > Record.size())
1569 return Error(BitcodeError::InvalidRecord);
1571 for (unsigned i = 0; i != AsmStrSize; ++i)
1572 AsmStr += (char)Record[2+i];
1573 for (unsigned i = 0; i != ConstStrSize; ++i)
1574 ConstrStr += (char)Record[3+AsmStrSize+i];
1575 PointerType *PTy = cast<PointerType>(CurTy);
1576 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1577 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1580 // This version adds support for the asm dialect keywords (e.g.,
1582 case bitc::CST_CODE_INLINEASM: {
1583 if (Record.size() < 2)
1584 return Error(BitcodeError::InvalidRecord);
1585 std::string AsmStr, ConstrStr;
1586 bool HasSideEffects = Record[0] & 1;
1587 bool IsAlignStack = (Record[0] >> 1) & 1;
1588 unsigned AsmDialect = Record[0] >> 2;
1589 unsigned AsmStrSize = Record[1];
1590 if (2+AsmStrSize >= Record.size())
1591 return Error(BitcodeError::InvalidRecord);
1592 unsigned ConstStrSize = Record[2+AsmStrSize];
1593 if (3+AsmStrSize+ConstStrSize > Record.size())
1594 return Error(BitcodeError::InvalidRecord);
1596 for (unsigned i = 0; i != AsmStrSize; ++i)
1597 AsmStr += (char)Record[2+i];
1598 for (unsigned i = 0; i != ConstStrSize; ++i)
1599 ConstrStr += (char)Record[3+AsmStrSize+i];
1600 PointerType *PTy = cast<PointerType>(CurTy);
1601 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1602 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1603 InlineAsm::AsmDialect(AsmDialect));
1606 case bitc::CST_CODE_BLOCKADDRESS:{
1607 if (Record.size() < 3)
1608 return Error(BitcodeError::InvalidRecord);
1609 Type *FnTy = getTypeByID(Record[0]);
1611 return Error(BitcodeError::InvalidRecord);
1613 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1615 return Error(BitcodeError::InvalidRecord);
1617 // Don't let Fn get dematerialized.
1618 BlockAddressesTaken.insert(Fn);
1620 // If the function is already parsed we can insert the block address right
1623 unsigned BBID = Record[2];
1625 // Invalid reference to entry block.
1626 return Error(BitcodeError::InvalidID);
1628 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1629 for (size_t I = 0, E = BBID; I != E; ++I) {
1631 return Error(BitcodeError::InvalidID);
1636 // Otherwise insert a placeholder and remember it so it can be inserted
1637 // when the function is parsed.
1638 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1640 BasicBlockFwdRefQueue.push_back(Fn);
1641 if (FwdBBs.size() < BBID + 1)
1642 FwdBBs.resize(BBID + 1);
1644 FwdBBs[BBID] = BasicBlock::Create(Context);
1647 V = BlockAddress::get(Fn, BB);
1652 ValueList.AssignValue(V, NextCstNo);
1657 std::error_code BitcodeReader::ParseUseLists() {
1658 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1659 return Error(BitcodeError::InvalidRecord);
1661 // Read all the records.
1662 SmallVector<uint64_t, 64> Record;
1664 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1666 switch (Entry.Kind) {
1667 case BitstreamEntry::SubBlock: // Handled for us already.
1668 case BitstreamEntry::Error:
1669 return Error(BitcodeError::MalformedBlock);
1670 case BitstreamEntry::EndBlock:
1671 return std::error_code();
1672 case BitstreamEntry::Record:
1673 // The interesting case.
1677 // Read a use list record.
1680 switch (Stream.readRecord(Entry.ID, Record)) {
1681 default: // Default behavior: unknown type.
1683 case bitc::USELIST_CODE_BB:
1686 case bitc::USELIST_CODE_DEFAULT: {
1687 unsigned RecordLength = Record.size();
1688 if (RecordLength < 3)
1689 // Records should have at least an ID and two indexes.
1690 return Error(BitcodeError::InvalidRecord);
1691 unsigned ID = Record.back();
1696 assert(ID < FunctionBBs.size() && "Basic block not found");
1697 V = FunctionBBs[ID];
1700 unsigned NumUses = 0;
1701 SmallDenseMap<const Use *, unsigned, 16> Order;
1702 for (const Use &U : V->uses()) {
1703 if (++NumUses > Record.size())
1705 Order[&U] = Record[NumUses - 1];
1707 if (Order.size() != Record.size() || NumUses > Record.size())
1708 // Mismatches can happen if the functions are being materialized lazily
1709 // (out-of-order), or a value has been upgraded.
1712 V->sortUseList([&](const Use &L, const Use &R) {
1713 return Order.lookup(&L) < Order.lookup(&R);
1721 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1722 /// remember where it is and then skip it. This lets us lazily deserialize the
1724 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1725 // Get the function we are talking about.
1726 if (FunctionsWithBodies.empty())
1727 return Error(BitcodeError::InsufficientFunctionProtos);
1729 Function *Fn = FunctionsWithBodies.back();
1730 FunctionsWithBodies.pop_back();
1732 // Save the current stream state.
1733 uint64_t CurBit = Stream.GetCurrentBitNo();
1734 DeferredFunctionInfo[Fn] = CurBit;
1736 // Skip over the function block for now.
1737 if (Stream.SkipBlock())
1738 return Error(BitcodeError::InvalidRecord);
1739 return std::error_code();
1742 std::error_code BitcodeReader::GlobalCleanup() {
1743 // Patch the initializers for globals and aliases up.
1744 ResolveGlobalAndAliasInits();
1745 if (!GlobalInits.empty() || !AliasInits.empty())
1746 return Error(BitcodeError::MalformedGlobalInitializerSet);
1748 // Look for intrinsic functions which need to be upgraded at some point
1749 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1752 if (UpgradeIntrinsicFunction(FI, NewFn))
1753 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1756 // Look for global variables which need to be renamed.
1757 for (Module::global_iterator
1758 GI = TheModule->global_begin(), GE = TheModule->global_end();
1760 GlobalVariable *GV = GI++;
1761 UpgradeGlobalVariable(GV);
1764 // Force deallocation of memory for these vectors to favor the client that
1765 // want lazy deserialization.
1766 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1767 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1768 return std::error_code();
1771 std::error_code BitcodeReader::ParseModule(bool Resume) {
1773 Stream.JumpToBit(NextUnreadBit);
1774 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1775 return Error(BitcodeError::InvalidRecord);
1777 SmallVector<uint64_t, 64> Record;
1778 std::vector<std::string> SectionTable;
1779 std::vector<std::string> GCTable;
1781 // Read all the records for this module.
1783 BitstreamEntry Entry = Stream.advance();
1785 switch (Entry.Kind) {
1786 case BitstreamEntry::Error:
1787 return Error(BitcodeError::MalformedBlock);
1788 case BitstreamEntry::EndBlock:
1789 return GlobalCleanup();
1791 case BitstreamEntry::SubBlock:
1793 default: // Skip unknown content.
1794 if (Stream.SkipBlock())
1795 return Error(BitcodeError::InvalidRecord);
1797 case bitc::BLOCKINFO_BLOCK_ID:
1798 if (Stream.ReadBlockInfoBlock())
1799 return Error(BitcodeError::MalformedBlock);
1801 case bitc::PARAMATTR_BLOCK_ID:
1802 if (std::error_code EC = ParseAttributeBlock())
1805 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1806 if (std::error_code EC = ParseAttributeGroupBlock())
1809 case bitc::TYPE_BLOCK_ID_NEW:
1810 if (std::error_code EC = ParseTypeTable())
1813 case bitc::VALUE_SYMTAB_BLOCK_ID:
1814 if (std::error_code EC = ParseValueSymbolTable())
1816 SeenValueSymbolTable = true;
1818 case bitc::CONSTANTS_BLOCK_ID:
1819 if (std::error_code EC = ParseConstants())
1821 if (std::error_code EC = ResolveGlobalAndAliasInits())
1824 case bitc::METADATA_BLOCK_ID:
1825 if (std::error_code EC = ParseMetadata())
1828 case bitc::FUNCTION_BLOCK_ID:
1829 // If this is the first function body we've seen, reverse the
1830 // FunctionsWithBodies list.
1831 if (!SeenFirstFunctionBody) {
1832 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1833 if (std::error_code EC = GlobalCleanup())
1835 SeenFirstFunctionBody = true;
1838 if (std::error_code EC = RememberAndSkipFunctionBody())
1840 // For streaming bitcode, suspend parsing when we reach the function
1841 // bodies. Subsequent materialization calls will resume it when
1842 // necessary. For streaming, the function bodies must be at the end of
1843 // the bitcode. If the bitcode file is old, the symbol table will be
1844 // at the end instead and will not have been seen yet. In this case,
1845 // just finish the parse now.
1846 if (LazyStreamer && SeenValueSymbolTable) {
1847 NextUnreadBit = Stream.GetCurrentBitNo();
1848 return std::error_code();
1851 case bitc::USELIST_BLOCK_ID:
1852 if (std::error_code EC = ParseUseLists())
1858 case BitstreamEntry::Record:
1859 // The interesting case.
1865 switch (Stream.readRecord(Entry.ID, Record)) {
1866 default: break; // Default behavior, ignore unknown content.
1867 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
1868 if (Record.size() < 1)
1869 return Error(BitcodeError::InvalidRecord);
1870 // Only version #0 and #1 are supported so far.
1871 unsigned module_version = Record[0];
1872 switch (module_version) {
1874 return Error(BitcodeError::InvalidValue);
1876 UseRelativeIDs = false;
1879 UseRelativeIDs = true;
1884 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1886 if (ConvertToString(Record, 0, S))
1887 return Error(BitcodeError::InvalidRecord);
1888 TheModule->setTargetTriple(S);
1891 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1893 if (ConvertToString(Record, 0, S))
1894 return Error(BitcodeError::InvalidRecord);
1895 TheModule->setDataLayout(S);
1898 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1900 if (ConvertToString(Record, 0, S))
1901 return Error(BitcodeError::InvalidRecord);
1902 TheModule->setModuleInlineAsm(S);
1905 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1906 // FIXME: Remove in 4.0.
1908 if (ConvertToString(Record, 0, S))
1909 return Error(BitcodeError::InvalidRecord);
1913 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1915 if (ConvertToString(Record, 0, S))
1916 return Error(BitcodeError::InvalidRecord);
1917 SectionTable.push_back(S);
1920 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
1922 if (ConvertToString(Record, 0, S))
1923 return Error(BitcodeError::InvalidRecord);
1924 GCTable.push_back(S);
1927 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1928 if (Record.size() < 2)
1929 return Error(BitcodeError::InvalidRecord);
1930 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1931 unsigned ComdatNameSize = Record[1];
1932 std::string ComdatName;
1933 ComdatName.reserve(ComdatNameSize);
1934 for (unsigned i = 0; i != ComdatNameSize; ++i)
1935 ComdatName += (char)Record[2 + i];
1936 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1937 C->setSelectionKind(SK);
1938 ComdatList.push_back(C);
1941 // GLOBALVAR: [pointer type, isconst, initid,
1942 // linkage, alignment, section, visibility, threadlocal,
1943 // unnamed_addr, dllstorageclass]
1944 case bitc::MODULE_CODE_GLOBALVAR: {
1945 if (Record.size() < 6)
1946 return Error(BitcodeError::InvalidRecord);
1947 Type *Ty = getTypeByID(Record[0]);
1949 return Error(BitcodeError::InvalidRecord);
1950 if (!Ty->isPointerTy())
1951 return Error(BitcodeError::InvalidTypeForValue);
1952 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1953 Ty = cast<PointerType>(Ty)->getElementType();
1955 bool isConstant = Record[1];
1956 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1957 unsigned Alignment = (1 << Record[4]) >> 1;
1958 std::string Section;
1960 if (Record[5]-1 >= SectionTable.size())
1961 return Error(BitcodeError::InvalidID);
1962 Section = SectionTable[Record[5]-1];
1964 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1965 // Local linkage must have default visibility.
1966 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1967 // FIXME: Change to an error if non-default in 4.0.
1968 Visibility = GetDecodedVisibility(Record[6]);
1970 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1971 if (Record.size() > 7)
1972 TLM = GetDecodedThreadLocalMode(Record[7]);
1974 bool UnnamedAddr = false;
1975 if (Record.size() > 8)
1976 UnnamedAddr = Record[8];
1978 bool ExternallyInitialized = false;
1979 if (Record.size() > 9)
1980 ExternallyInitialized = Record[9];
1982 GlobalVariable *NewGV =
1983 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1984 TLM, AddressSpace, ExternallyInitialized);
1985 NewGV->setAlignment(Alignment);
1986 if (!Section.empty())
1987 NewGV->setSection(Section);
1988 NewGV->setVisibility(Visibility);
1989 NewGV->setUnnamedAddr(UnnamedAddr);
1991 if (Record.size() > 10)
1992 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1994 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1996 ValueList.push_back(NewGV);
1998 // Remember which value to use for the global initializer.
1999 if (unsigned InitID = Record[2])
2000 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2002 if (Record.size() > 11)
2003 if (unsigned ComdatID = Record[11]) {
2004 assert(ComdatID <= ComdatList.size());
2005 NewGV->setComdat(ComdatList[ComdatID - 1]);
2009 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2010 // alignment, section, visibility, gc, unnamed_addr,
2012 case bitc::MODULE_CODE_FUNCTION: {
2013 if (Record.size() < 8)
2014 return Error(BitcodeError::InvalidRecord);
2015 Type *Ty = getTypeByID(Record[0]);
2017 return Error(BitcodeError::InvalidRecord);
2018 if (!Ty->isPointerTy())
2019 return Error(BitcodeError::InvalidTypeForValue);
2021 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2023 return Error(BitcodeError::InvalidTypeForValue);
2025 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2028 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2029 bool isProto = Record[2];
2030 Func->setLinkage(GetDecodedLinkage(Record[3]));
2031 Func->setAttributes(getAttributes(Record[4]));
2033 Func->setAlignment((1 << Record[5]) >> 1);
2035 if (Record[6]-1 >= SectionTable.size())
2036 return Error(BitcodeError::InvalidID);
2037 Func->setSection(SectionTable[Record[6]-1]);
2039 // Local linkage must have default visibility.
2040 if (!Func->hasLocalLinkage())
2041 // FIXME: Change to an error if non-default in 4.0.
2042 Func->setVisibility(GetDecodedVisibility(Record[7]));
2043 if (Record.size() > 8 && Record[8]) {
2044 if (Record[8]-1 > GCTable.size())
2045 return Error(BitcodeError::InvalidID);
2046 Func->setGC(GCTable[Record[8]-1].c_str());
2048 bool UnnamedAddr = false;
2049 if (Record.size() > 9)
2050 UnnamedAddr = Record[9];
2051 Func->setUnnamedAddr(UnnamedAddr);
2052 if (Record.size() > 10 && Record[10] != 0)
2053 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
2055 if (Record.size() > 11)
2056 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2058 UpgradeDLLImportExportLinkage(Func, Record[3]);
2060 if (Record.size() > 12)
2061 if (unsigned ComdatID = Record[12]) {
2062 assert(ComdatID <= ComdatList.size());
2063 Func->setComdat(ComdatList[ComdatID - 1]);
2066 ValueList.push_back(Func);
2068 // If this is a function with a body, remember the prototype we are
2069 // creating now, so that we can match up the body with them later.
2071 FunctionsWithBodies.push_back(Func);
2072 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
2076 // ALIAS: [alias type, aliasee val#, linkage]
2077 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2078 case bitc::MODULE_CODE_ALIAS: {
2079 if (Record.size() < 3)
2080 return Error(BitcodeError::InvalidRecord);
2081 Type *Ty = getTypeByID(Record[0]);
2083 return Error(BitcodeError::InvalidRecord);
2084 auto *PTy = dyn_cast<PointerType>(Ty);
2086 return Error(BitcodeError::InvalidTypeForValue);
2089 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2090 GetDecodedLinkage(Record[2]), "", TheModule);
2091 // Old bitcode files didn't have visibility field.
2092 // Local linkage must have default visibility.
2093 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2094 // FIXME: Change to an error if non-default in 4.0.
2095 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2096 if (Record.size() > 4)
2097 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2099 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2100 if (Record.size() > 5)
2101 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2102 if (Record.size() > 6)
2103 NewGA->setUnnamedAddr(Record[6]);
2104 ValueList.push_back(NewGA);
2105 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2108 /// MODULE_CODE_PURGEVALS: [numvals]
2109 case bitc::MODULE_CODE_PURGEVALS:
2110 // Trim down the value list to the specified size.
2111 if (Record.size() < 1 || Record[0] > ValueList.size())
2112 return Error(BitcodeError::InvalidRecord);
2113 ValueList.shrinkTo(Record[0]);
2120 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2121 TheModule = nullptr;
2123 if (std::error_code EC = InitStream())
2126 // Sniff for the signature.
2127 if (Stream.Read(8) != 'B' ||
2128 Stream.Read(8) != 'C' ||
2129 Stream.Read(4) != 0x0 ||
2130 Stream.Read(4) != 0xC ||
2131 Stream.Read(4) != 0xE ||
2132 Stream.Read(4) != 0xD)
2133 return Error(BitcodeError::InvalidBitcodeSignature);
2135 // We expect a number of well-defined blocks, though we don't necessarily
2136 // need to understand them all.
2138 if (Stream.AtEndOfStream())
2139 return std::error_code();
2141 BitstreamEntry Entry =
2142 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2144 switch (Entry.Kind) {
2145 case BitstreamEntry::Error:
2146 return Error(BitcodeError::MalformedBlock);
2147 case BitstreamEntry::EndBlock:
2148 return std::error_code();
2150 case BitstreamEntry::SubBlock:
2152 case bitc::BLOCKINFO_BLOCK_ID:
2153 if (Stream.ReadBlockInfoBlock())
2154 return Error(BitcodeError::MalformedBlock);
2156 case bitc::MODULE_BLOCK_ID:
2157 // Reject multiple MODULE_BLOCK's in a single bitstream.
2159 return Error(BitcodeError::InvalidMultipleBlocks);
2161 if (std::error_code EC = ParseModule(false))
2164 return std::error_code();
2167 if (Stream.SkipBlock())
2168 return Error(BitcodeError::InvalidRecord);
2172 case BitstreamEntry::Record:
2173 // There should be no records in the top-level of blocks.
2175 // The ranlib in Xcode 4 will align archive members by appending newlines
2176 // to the end of them. If this file size is a multiple of 4 but not 8, we
2177 // have to read and ignore these final 4 bytes :-(
2178 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2179 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2180 Stream.AtEndOfStream())
2181 return std::error_code();
2183 return Error(BitcodeError::InvalidRecord);
2188 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2189 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2190 return Error(BitcodeError::InvalidRecord);
2192 SmallVector<uint64_t, 64> Record;
2195 // Read all the records for this module.
2197 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2199 switch (Entry.Kind) {
2200 case BitstreamEntry::SubBlock: // Handled for us already.
2201 case BitstreamEntry::Error:
2202 return Error(BitcodeError::MalformedBlock);
2203 case BitstreamEntry::EndBlock:
2205 case BitstreamEntry::Record:
2206 // The interesting case.
2211 switch (Stream.readRecord(Entry.ID, Record)) {
2212 default: break; // Default behavior, ignore unknown content.
2213 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2215 if (ConvertToString(Record, 0, S))
2216 return Error(BitcodeError::InvalidRecord);
2223 llvm_unreachable("Exit infinite loop");
2226 ErrorOr<std::string> BitcodeReader::parseTriple() {
2227 if (std::error_code EC = InitStream())
2230 // Sniff for the signature.
2231 if (Stream.Read(8) != 'B' ||
2232 Stream.Read(8) != 'C' ||
2233 Stream.Read(4) != 0x0 ||
2234 Stream.Read(4) != 0xC ||
2235 Stream.Read(4) != 0xE ||
2236 Stream.Read(4) != 0xD)
2237 return Error(BitcodeError::InvalidBitcodeSignature);
2239 // We expect a number of well-defined blocks, though we don't necessarily
2240 // need to understand them all.
2242 BitstreamEntry Entry = Stream.advance();
2244 switch (Entry.Kind) {
2245 case BitstreamEntry::Error:
2246 return Error(BitcodeError::MalformedBlock);
2247 case BitstreamEntry::EndBlock:
2248 return std::error_code();
2250 case BitstreamEntry::SubBlock:
2251 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2252 return parseModuleTriple();
2254 // Ignore other sub-blocks.
2255 if (Stream.SkipBlock())
2256 return Error(BitcodeError::MalformedBlock);
2259 case BitstreamEntry::Record:
2260 Stream.skipRecord(Entry.ID);
2266 /// ParseMetadataAttachment - Parse metadata attachments.
2267 std::error_code BitcodeReader::ParseMetadataAttachment() {
2268 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2269 return Error(BitcodeError::InvalidRecord);
2271 SmallVector<uint64_t, 64> Record;
2273 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2275 switch (Entry.Kind) {
2276 case BitstreamEntry::SubBlock: // Handled for us already.
2277 case BitstreamEntry::Error:
2278 return Error(BitcodeError::MalformedBlock);
2279 case BitstreamEntry::EndBlock:
2280 return std::error_code();
2281 case BitstreamEntry::Record:
2282 // The interesting case.
2286 // Read a metadata attachment record.
2288 switch (Stream.readRecord(Entry.ID, Record)) {
2289 default: // Default behavior: ignore.
2291 case bitc::METADATA_ATTACHMENT: {
2292 unsigned RecordLength = Record.size();
2293 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2294 return Error(BitcodeError::InvalidRecord);
2295 Instruction *Inst = InstructionList[Record[0]];
2296 for (unsigned i = 1; i != RecordLength; i = i+2) {
2297 unsigned Kind = Record[i];
2298 DenseMap<unsigned, unsigned>::iterator I =
2299 MDKindMap.find(Kind);
2300 if (I == MDKindMap.end())
2301 return Error(BitcodeError::InvalidID);
2302 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2303 Inst->setMetadata(I->second, cast<MDNode>(Node));
2304 if (I->second == LLVMContext::MD_tbaa)
2305 InstsWithTBAATag.push_back(Inst);
2313 /// ParseFunctionBody - Lazily parse the specified function body block.
2314 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2315 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2316 return Error(BitcodeError::InvalidRecord);
2318 InstructionList.clear();
2319 unsigned ModuleValueListSize = ValueList.size();
2320 unsigned ModuleMDValueListSize = MDValueList.size();
2322 // Add all the function arguments to the value table.
2323 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2324 ValueList.push_back(I);
2326 unsigned NextValueNo = ValueList.size();
2327 BasicBlock *CurBB = nullptr;
2328 unsigned CurBBNo = 0;
2332 // Read all the records.
2333 SmallVector<uint64_t, 64> Record;
2335 BitstreamEntry Entry = Stream.advance();
2337 switch (Entry.Kind) {
2338 case BitstreamEntry::Error:
2339 return Error(BitcodeError::MalformedBlock);
2340 case BitstreamEntry::EndBlock:
2341 goto OutOfRecordLoop;
2343 case BitstreamEntry::SubBlock:
2345 default: // Skip unknown content.
2346 if (Stream.SkipBlock())
2347 return Error(BitcodeError::InvalidRecord);
2349 case bitc::CONSTANTS_BLOCK_ID:
2350 if (std::error_code EC = ParseConstants())
2352 NextValueNo = ValueList.size();
2354 case bitc::VALUE_SYMTAB_BLOCK_ID:
2355 if (std::error_code EC = ParseValueSymbolTable())
2358 case bitc::METADATA_ATTACHMENT_ID:
2359 if (std::error_code EC = ParseMetadataAttachment())
2362 case bitc::METADATA_BLOCK_ID:
2363 if (std::error_code EC = ParseMetadata())
2366 case bitc::USELIST_BLOCK_ID:
2367 if (std::error_code EC = ParseUseLists())
2373 case BitstreamEntry::Record:
2374 // The interesting case.
2380 Instruction *I = nullptr;
2381 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2383 default: // Default behavior: reject
2384 return Error(BitcodeError::InvalidValue);
2385 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2386 if (Record.size() < 1 || Record[0] == 0)
2387 return Error(BitcodeError::InvalidRecord);
2388 // Create all the basic blocks for the function.
2389 FunctionBBs.resize(Record[0]);
2391 // See if anything took the address of blocks in this function.
2392 auto BBFRI = BasicBlockFwdRefs.find(F);
2393 if (BBFRI == BasicBlockFwdRefs.end()) {
2394 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2395 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2397 auto &BBRefs = BBFRI->second;
2398 // Check for invalid basic block references.
2399 if (BBRefs.size() > FunctionBBs.size())
2400 return Error(BitcodeError::InvalidID);
2401 assert(!BBRefs.empty() && "Unexpected empty array");
2402 assert(!BBRefs.front() && "Invalid reference to entry block");
2403 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2405 if (I < RE && BBRefs[I]) {
2406 BBRefs[I]->insertInto(F);
2407 FunctionBBs[I] = BBRefs[I];
2409 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2412 // Erase from the table.
2413 BasicBlockFwdRefs.erase(BBFRI);
2416 CurBB = FunctionBBs[0];
2420 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2421 // This record indicates that the last instruction is at the same
2422 // location as the previous instruction with a location.
2425 // Get the last instruction emitted.
2426 if (CurBB && !CurBB->empty())
2428 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2429 !FunctionBBs[CurBBNo-1]->empty())
2430 I = &FunctionBBs[CurBBNo-1]->back();
2433 return Error(BitcodeError::InvalidRecord);
2434 I->setDebugLoc(LastLoc);
2438 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2439 I = nullptr; // Get the last instruction emitted.
2440 if (CurBB && !CurBB->empty())
2442 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2443 !FunctionBBs[CurBBNo-1]->empty())
2444 I = &FunctionBBs[CurBBNo-1]->back();
2445 if (!I || Record.size() < 4)
2446 return Error(BitcodeError::InvalidRecord);
2448 unsigned Line = Record[0], Col = Record[1];
2449 unsigned ScopeID = Record[2], IAID = Record[3];
2451 MDNode *Scope = nullptr, *IA = nullptr;
2452 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2453 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2454 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2455 I->setDebugLoc(LastLoc);
2460 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2463 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2464 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2465 OpNum+1 > Record.size())
2466 return Error(BitcodeError::InvalidRecord);
2468 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2470 return Error(BitcodeError::InvalidRecord);
2471 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2472 InstructionList.push_back(I);
2473 if (OpNum < Record.size()) {
2474 if (Opc == Instruction::Add ||
2475 Opc == Instruction::Sub ||
2476 Opc == Instruction::Mul ||
2477 Opc == Instruction::Shl) {
2478 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2479 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2480 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2481 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2482 } else if (Opc == Instruction::SDiv ||
2483 Opc == Instruction::UDiv ||
2484 Opc == Instruction::LShr ||
2485 Opc == Instruction::AShr) {
2486 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2487 cast<BinaryOperator>(I)->setIsExact(true);
2488 } else if (isa<FPMathOperator>(I)) {
2490 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2491 FMF.setUnsafeAlgebra();
2492 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2494 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2496 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2497 FMF.setNoSignedZeros();
2498 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2499 FMF.setAllowReciprocal();
2501 I->setFastMathFlags(FMF);
2507 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2510 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2511 OpNum+2 != Record.size())
2512 return Error(BitcodeError::InvalidRecord);
2514 Type *ResTy = getTypeByID(Record[OpNum]);
2515 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2516 if (Opc == -1 || !ResTy)
2517 return Error(BitcodeError::InvalidRecord);
2518 Instruction *Temp = nullptr;
2519 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2521 InstructionList.push_back(Temp);
2522 CurBB->getInstList().push_back(Temp);
2525 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2527 InstructionList.push_back(I);
2530 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2531 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2534 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2535 return Error(BitcodeError::InvalidRecord);
2537 SmallVector<Value*, 16> GEPIdx;
2538 while (OpNum != Record.size()) {
2540 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2541 return Error(BitcodeError::InvalidRecord);
2542 GEPIdx.push_back(Op);
2545 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2546 InstructionList.push_back(I);
2547 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2548 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2552 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2553 // EXTRACTVAL: [opty, opval, n x indices]
2556 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2557 return Error(BitcodeError::InvalidRecord);
2559 SmallVector<unsigned, 4> EXTRACTVALIdx;
2560 for (unsigned RecSize = Record.size();
2561 OpNum != RecSize; ++OpNum) {
2562 uint64_t Index = Record[OpNum];
2563 if ((unsigned)Index != Index)
2564 return Error(BitcodeError::InvalidValue);
2565 EXTRACTVALIdx.push_back((unsigned)Index);
2568 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2569 InstructionList.push_back(I);
2573 case bitc::FUNC_CODE_INST_INSERTVAL: {
2574 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2577 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2578 return Error(BitcodeError::InvalidRecord);
2580 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2581 return Error(BitcodeError::InvalidRecord);
2583 SmallVector<unsigned, 4> INSERTVALIdx;
2584 for (unsigned RecSize = Record.size();
2585 OpNum != RecSize; ++OpNum) {
2586 uint64_t Index = Record[OpNum];
2587 if ((unsigned)Index != Index)
2588 return Error(BitcodeError::InvalidValue);
2589 INSERTVALIdx.push_back((unsigned)Index);
2592 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2593 InstructionList.push_back(I);
2597 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2598 // obsolete form of select
2599 // handles select i1 ... in old bitcode
2601 Value *TrueVal, *FalseVal, *Cond;
2602 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2603 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2604 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2605 return Error(BitcodeError::InvalidRecord);
2607 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2608 InstructionList.push_back(I);
2612 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2613 // new form of select
2614 // handles select i1 or select [N x i1]
2616 Value *TrueVal, *FalseVal, *Cond;
2617 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2618 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2619 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2620 return Error(BitcodeError::InvalidRecord);
2622 // select condition can be either i1 or [N x i1]
2623 if (VectorType* vector_type =
2624 dyn_cast<VectorType>(Cond->getType())) {
2626 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2627 return Error(BitcodeError::InvalidTypeForValue);
2630 if (Cond->getType() != Type::getInt1Ty(Context))
2631 return Error(BitcodeError::InvalidTypeForValue);
2634 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2635 InstructionList.push_back(I);
2639 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2642 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2643 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2644 return Error(BitcodeError::InvalidRecord);
2645 I = ExtractElementInst::Create(Vec, Idx);
2646 InstructionList.push_back(I);
2650 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2652 Value *Vec, *Elt, *Idx;
2653 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2654 popValue(Record, OpNum, NextValueNo,
2655 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2656 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2657 return Error(BitcodeError::InvalidRecord);
2658 I = InsertElementInst::Create(Vec, Elt, Idx);
2659 InstructionList.push_back(I);
2663 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2665 Value *Vec1, *Vec2, *Mask;
2666 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2667 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2668 return Error(BitcodeError::InvalidRecord);
2670 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2671 return Error(BitcodeError::InvalidRecord);
2672 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2673 InstructionList.push_back(I);
2677 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2678 // Old form of ICmp/FCmp returning bool
2679 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2680 // both legal on vectors but had different behaviour.
2681 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2682 // FCmp/ICmp returning bool or vector of bool
2686 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2687 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2688 OpNum+1 != Record.size())
2689 return Error(BitcodeError::InvalidRecord);
2691 if (LHS->getType()->isFPOrFPVectorTy())
2692 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2694 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2695 InstructionList.push_back(I);
2699 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2701 unsigned Size = Record.size();
2703 I = ReturnInst::Create(Context);
2704 InstructionList.push_back(I);
2709 Value *Op = nullptr;
2710 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2711 return Error(BitcodeError::InvalidRecord);
2712 if (OpNum != Record.size())
2713 return Error(BitcodeError::InvalidRecord);
2715 I = ReturnInst::Create(Context, Op);
2716 InstructionList.push_back(I);
2719 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2720 if (Record.size() != 1 && Record.size() != 3)
2721 return Error(BitcodeError::InvalidRecord);
2722 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2724 return Error(BitcodeError::InvalidRecord);
2726 if (Record.size() == 1) {
2727 I = BranchInst::Create(TrueDest);
2728 InstructionList.push_back(I);
2731 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2732 Value *Cond = getValue(Record, 2, NextValueNo,
2733 Type::getInt1Ty(Context));
2734 if (!FalseDest || !Cond)
2735 return Error(BitcodeError::InvalidRecord);
2736 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2737 InstructionList.push_back(I);
2741 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2743 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2744 // "New" SwitchInst format with case ranges. The changes to write this
2745 // format were reverted but we still recognize bitcode that uses it.
2746 // Hopefully someday we will have support for case ranges and can use
2747 // this format again.
2749 Type *OpTy = getTypeByID(Record[1]);
2750 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2752 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2753 BasicBlock *Default = getBasicBlock(Record[3]);
2754 if (!OpTy || !Cond || !Default)
2755 return Error(BitcodeError::InvalidRecord);
2757 unsigned NumCases = Record[4];
2759 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2760 InstructionList.push_back(SI);
2762 unsigned CurIdx = 5;
2763 for (unsigned i = 0; i != NumCases; ++i) {
2764 SmallVector<ConstantInt*, 1> CaseVals;
2765 unsigned NumItems = Record[CurIdx++];
2766 for (unsigned ci = 0; ci != NumItems; ++ci) {
2767 bool isSingleNumber = Record[CurIdx++];
2770 unsigned ActiveWords = 1;
2771 if (ValueBitWidth > 64)
2772 ActiveWords = Record[CurIdx++];
2773 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2775 CurIdx += ActiveWords;
2777 if (!isSingleNumber) {
2779 if (ValueBitWidth > 64)
2780 ActiveWords = Record[CurIdx++];
2782 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2784 CurIdx += ActiveWords;
2786 // FIXME: It is not clear whether values in the range should be
2787 // compared as signed or unsigned values. The partially
2788 // implemented changes that used this format in the past used
2789 // unsigned comparisons.
2790 for ( ; Low.ule(High); ++Low)
2791 CaseVals.push_back(ConstantInt::get(Context, Low));
2793 CaseVals.push_back(ConstantInt::get(Context, Low));
2795 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2796 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2797 cve = CaseVals.end(); cvi != cve; ++cvi)
2798 SI->addCase(*cvi, DestBB);
2804 // Old SwitchInst format without case ranges.
2806 if (Record.size() < 3 || (Record.size() & 1) == 0)
2807 return Error(BitcodeError::InvalidRecord);
2808 Type *OpTy = getTypeByID(Record[0]);
2809 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2810 BasicBlock *Default = getBasicBlock(Record[2]);
2811 if (!OpTy || !Cond || !Default)
2812 return Error(BitcodeError::InvalidRecord);
2813 unsigned NumCases = (Record.size()-3)/2;
2814 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2815 InstructionList.push_back(SI);
2816 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2817 ConstantInt *CaseVal =
2818 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2819 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2820 if (!CaseVal || !DestBB) {
2822 return Error(BitcodeError::InvalidRecord);
2824 SI->addCase(CaseVal, DestBB);
2829 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2830 if (Record.size() < 2)
2831 return Error(BitcodeError::InvalidRecord);
2832 Type *OpTy = getTypeByID(Record[0]);
2833 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2834 if (!OpTy || !Address)
2835 return Error(BitcodeError::InvalidRecord);
2836 unsigned NumDests = Record.size()-2;
2837 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2838 InstructionList.push_back(IBI);
2839 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2840 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2841 IBI->addDestination(DestBB);
2844 return Error(BitcodeError::InvalidRecord);
2851 case bitc::FUNC_CODE_INST_INVOKE: {
2852 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2853 if (Record.size() < 4)
2854 return Error(BitcodeError::InvalidRecord);
2855 AttributeSet PAL = getAttributes(Record[0]);
2856 unsigned CCInfo = Record[1];
2857 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2858 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2862 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2863 return Error(BitcodeError::InvalidRecord);
2865 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2866 FunctionType *FTy = !CalleeTy ? nullptr :
2867 dyn_cast<FunctionType>(CalleeTy->getElementType());
2869 // Check that the right number of fixed parameters are here.
2870 if (!FTy || !NormalBB || !UnwindBB ||
2871 Record.size() < OpNum+FTy->getNumParams())
2872 return Error(BitcodeError::InvalidRecord);
2874 SmallVector<Value*, 16> Ops;
2875 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2876 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2877 FTy->getParamType(i)));
2879 return Error(BitcodeError::InvalidRecord);
2882 if (!FTy->isVarArg()) {
2883 if (Record.size() != OpNum)
2884 return Error(BitcodeError::InvalidRecord);
2886 // Read type/value pairs for varargs params.
2887 while (OpNum != Record.size()) {
2889 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2890 return Error(BitcodeError::InvalidRecord);
2895 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2896 InstructionList.push_back(I);
2897 cast<InvokeInst>(I)->setCallingConv(
2898 static_cast<CallingConv::ID>(CCInfo));
2899 cast<InvokeInst>(I)->setAttributes(PAL);
2902 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2904 Value *Val = nullptr;
2905 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2906 return Error(BitcodeError::InvalidRecord);
2907 I = ResumeInst::Create(Val);
2908 InstructionList.push_back(I);
2911 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2912 I = new UnreachableInst(Context);
2913 InstructionList.push_back(I);
2915 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2916 if (Record.size() < 1 || ((Record.size()-1)&1))
2917 return Error(BitcodeError::InvalidRecord);
2918 Type *Ty = getTypeByID(Record[0]);
2920 return Error(BitcodeError::InvalidRecord);
2922 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2923 InstructionList.push_back(PN);
2925 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2927 // With the new function encoding, it is possible that operands have
2928 // negative IDs (for forward references). Use a signed VBR
2929 // representation to keep the encoding small.
2931 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2933 V = getValue(Record, 1+i, NextValueNo, Ty);
2934 BasicBlock *BB = getBasicBlock(Record[2+i]);
2936 return Error(BitcodeError::InvalidRecord);
2937 PN->addIncoming(V, BB);
2943 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2944 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2946 if (Record.size() < 4)
2947 return Error(BitcodeError::InvalidRecord);
2948 Type *Ty = getTypeByID(Record[Idx++]);
2950 return Error(BitcodeError::InvalidRecord);
2951 Value *PersFn = nullptr;
2952 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2953 return Error(BitcodeError::InvalidRecord);
2955 bool IsCleanup = !!Record[Idx++];
2956 unsigned NumClauses = Record[Idx++];
2957 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2958 LP->setCleanup(IsCleanup);
2959 for (unsigned J = 0; J != NumClauses; ++J) {
2960 LandingPadInst::ClauseType CT =
2961 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2964 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2966 return Error(BitcodeError::InvalidRecord);
2969 assert((CT != LandingPadInst::Catch ||
2970 !isa<ArrayType>(Val->getType())) &&
2971 "Catch clause has a invalid type!");
2972 assert((CT != LandingPadInst::Filter ||
2973 isa<ArrayType>(Val->getType())) &&
2974 "Filter clause has invalid type!");
2975 LP->addClause(cast<Constant>(Val));
2979 InstructionList.push_back(I);
2983 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2984 if (Record.size() != 4)
2985 return Error(BitcodeError::InvalidRecord);
2987 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2988 Type *OpTy = getTypeByID(Record[1]);
2989 Value *Size = getFnValueByID(Record[2], OpTy);
2990 unsigned AlignRecord = Record[3];
2991 bool InAlloca = AlignRecord & (1 << 5);
2992 unsigned Align = AlignRecord & ((1 << 5) - 1);
2994 return Error(BitcodeError::InvalidRecord);
2995 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2996 AI->setUsedWithInAlloca(InAlloca);
2998 InstructionList.push_back(I);
3001 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3004 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3005 OpNum+2 != Record.size())
3006 return Error(BitcodeError::InvalidRecord);
3008 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3009 InstructionList.push_back(I);
3012 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3013 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3016 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3017 OpNum+4 != Record.size())
3018 return Error(BitcodeError::InvalidRecord);
3020 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3021 if (Ordering == NotAtomic || Ordering == Release ||
3022 Ordering == AcquireRelease)
3023 return Error(BitcodeError::InvalidRecord);
3024 if (Ordering != NotAtomic && Record[OpNum] == 0)
3025 return Error(BitcodeError::InvalidRecord);
3026 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3028 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3029 Ordering, SynchScope);
3030 InstructionList.push_back(I);
3033 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3036 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3037 popValue(Record, OpNum, NextValueNo,
3038 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3039 OpNum+2 != Record.size())
3040 return Error(BitcodeError::InvalidRecord);
3042 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3043 InstructionList.push_back(I);
3046 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3047 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3050 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3051 popValue(Record, OpNum, NextValueNo,
3052 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3053 OpNum+4 != Record.size())
3054 return Error(BitcodeError::InvalidRecord);
3056 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3057 if (Ordering == NotAtomic || Ordering == Acquire ||
3058 Ordering == AcquireRelease)
3059 return Error(BitcodeError::InvalidRecord);
3060 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3061 if (Ordering != NotAtomic && Record[OpNum] == 0)
3062 return Error(BitcodeError::InvalidRecord);
3064 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3065 Ordering, SynchScope);
3066 InstructionList.push_back(I);
3069 case bitc::FUNC_CODE_INST_CMPXCHG: {
3070 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3071 // failureordering?, isweak?]
3073 Value *Ptr, *Cmp, *New;
3074 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3075 popValue(Record, OpNum, NextValueNo,
3076 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3077 popValue(Record, OpNum, NextValueNo,
3078 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3079 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3080 return Error(BitcodeError::InvalidRecord);
3081 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3082 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3083 return Error(BitcodeError::InvalidRecord);
3084 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3086 AtomicOrdering FailureOrdering;
3087 if (Record.size() < 7)
3089 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3091 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3093 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3095 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3097 if (Record.size() < 8) {
3098 // Before weak cmpxchgs existed, the instruction simply returned the
3099 // value loaded from memory, so bitcode files from that era will be
3100 // expecting the first component of a modern cmpxchg.
3101 CurBB->getInstList().push_back(I);
3102 I = ExtractValueInst::Create(I, 0);
3104 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3107 InstructionList.push_back(I);
3110 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3111 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3114 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3115 popValue(Record, OpNum, NextValueNo,
3116 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3117 OpNum+4 != Record.size())
3118 return Error(BitcodeError::InvalidRecord);
3119 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3120 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3121 Operation > AtomicRMWInst::LAST_BINOP)
3122 return Error(BitcodeError::InvalidRecord);
3123 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3124 if (Ordering == NotAtomic || Ordering == Unordered)
3125 return Error(BitcodeError::InvalidRecord);
3126 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3127 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3128 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3129 InstructionList.push_back(I);
3132 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3133 if (2 != Record.size())
3134 return Error(BitcodeError::InvalidRecord);
3135 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3136 if (Ordering == NotAtomic || Ordering == Unordered ||
3137 Ordering == Monotonic)
3138 return Error(BitcodeError::InvalidRecord);
3139 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3140 I = new FenceInst(Context, Ordering, SynchScope);
3141 InstructionList.push_back(I);
3144 case bitc::FUNC_CODE_INST_CALL: {
3145 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3146 if (Record.size() < 3)
3147 return Error(BitcodeError::InvalidRecord);
3149 AttributeSet PAL = getAttributes(Record[0]);
3150 unsigned CCInfo = Record[1];
3154 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3155 return Error(BitcodeError::InvalidRecord);
3157 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3158 FunctionType *FTy = nullptr;
3159 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3160 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3161 return Error(BitcodeError::InvalidRecord);
3163 SmallVector<Value*, 16> Args;
3164 // Read the fixed params.
3165 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3166 if (FTy->getParamType(i)->isLabelTy())
3167 Args.push_back(getBasicBlock(Record[OpNum]));
3169 Args.push_back(getValue(Record, OpNum, NextValueNo,
3170 FTy->getParamType(i)));
3172 return Error(BitcodeError::InvalidRecord);
3175 // Read type/value pairs for varargs params.
3176 if (!FTy->isVarArg()) {
3177 if (OpNum != Record.size())
3178 return Error(BitcodeError::InvalidRecord);
3180 while (OpNum != Record.size()) {
3182 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3183 return Error(BitcodeError::InvalidRecord);
3188 I = CallInst::Create(Callee, Args);
3189 InstructionList.push_back(I);
3190 cast<CallInst>(I)->setCallingConv(
3191 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3192 CallInst::TailCallKind TCK = CallInst::TCK_None;
3194 TCK = CallInst::TCK_Tail;
3195 if (CCInfo & (1 << 14))
3196 TCK = CallInst::TCK_MustTail;
3197 cast<CallInst>(I)->setTailCallKind(TCK);
3198 cast<CallInst>(I)->setAttributes(PAL);
3201 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3202 if (Record.size() < 3)
3203 return Error(BitcodeError::InvalidRecord);
3204 Type *OpTy = getTypeByID(Record[0]);
3205 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3206 Type *ResTy = getTypeByID(Record[2]);
3207 if (!OpTy || !Op || !ResTy)
3208 return Error(BitcodeError::InvalidRecord);
3209 I = new VAArgInst(Op, ResTy);
3210 InstructionList.push_back(I);
3215 // Add instruction to end of current BB. If there is no current BB, reject
3219 return Error(BitcodeError::InvalidInstructionWithNoBB);
3221 CurBB->getInstList().push_back(I);
3223 // If this was a terminator instruction, move to the next block.
3224 if (isa<TerminatorInst>(I)) {
3226 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3229 // Non-void values get registered in the value table for future use.
3230 if (I && !I->getType()->isVoidTy())
3231 ValueList.AssignValue(I, NextValueNo++);
3236 // Check the function list for unresolved values.
3237 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3238 if (!A->getParent()) {
3239 // We found at least one unresolved value. Nuke them all to avoid leaks.
3240 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3241 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3242 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3246 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3250 // FIXME: Check for unresolved forward-declared metadata references
3251 // and clean up leaks.
3253 // Trim the value list down to the size it was before we parsed this function.
3254 ValueList.shrinkTo(ModuleValueListSize);
3255 MDValueList.shrinkTo(ModuleMDValueListSize);
3256 std::vector<BasicBlock*>().swap(FunctionBBs);
3257 return std::error_code();
3260 /// Find the function body in the bitcode stream
3261 std::error_code BitcodeReader::FindFunctionInStream(
3263 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3264 while (DeferredFunctionInfoIterator->second == 0) {
3265 if (Stream.AtEndOfStream())
3266 return Error(BitcodeError::CouldNotFindFunctionInStream);
3267 // ParseModule will parse the next body in the stream and set its
3268 // position in the DeferredFunctionInfo map.
3269 if (std::error_code EC = ParseModule(true))
3272 return std::error_code();
3275 //===----------------------------------------------------------------------===//
3276 // GVMaterializer implementation
3277 //===----------------------------------------------------------------------===//
3279 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3281 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3282 if (const Function *F = dyn_cast<Function>(GV)) {
3283 return F->isDeclaration() &&
3284 DeferredFunctionInfo.count(const_cast<Function*>(F));
3289 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
3290 Function *F = dyn_cast<Function>(GV);
3291 // If it's not a function or is already material, ignore the request.
3292 if (!F || !F->isMaterializable())
3293 return std::error_code();
3295 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3296 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3297 // If its position is recorded as 0, its body is somewhere in the stream
3298 // but we haven't seen it yet.
3299 if (DFII->second == 0 && LazyStreamer)
3300 if (std::error_code EC = FindFunctionInStream(F, DFII))
3303 // Move the bit stream to the saved position of the deferred function body.
3304 Stream.JumpToBit(DFII->second);
3306 if (std::error_code EC = ParseFunctionBody(F))
3309 // Upgrade any old intrinsic calls in the function.
3310 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3311 E = UpgradedIntrinsics.end(); I != E; ++I) {
3312 if (I->first != I->second) {
3313 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3315 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3316 UpgradeIntrinsicCall(CI, I->second);
3321 // Bring in any functions that this function forward-referenced via
3323 return materializeForwardReferencedFunctions();
3326 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3327 const Function *F = dyn_cast<Function>(GV);
3328 if (!F || F->isDeclaration())
3331 // Dematerializing F would leave dangling references that wouldn't be
3332 // reconnected on re-materialization.
3333 if (BlockAddressesTaken.count(F))
3336 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3339 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3340 Function *F = dyn_cast<Function>(GV);
3341 // If this function isn't dematerializable, this is a noop.
3342 if (!F || !isDematerializable(F))
3345 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3347 // Just forget the function body, we can remat it later.
3351 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3352 assert(M == TheModule &&
3353 "Can only Materialize the Module this BitcodeReader is attached to.");
3355 // Promise to materialize all forward references.
3356 WillMaterializeAllForwardRefs = true;
3358 // Iterate over the module, deserializing any functions that are still on
3360 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3362 if (F->isMaterializable()) {
3363 if (std::error_code EC = Materialize(F))
3367 // At this point, if there are any function bodies, the current bit is
3368 // pointing to the END_BLOCK record after them. Now make sure the rest
3369 // of the bits in the module have been read.
3373 // Check that all block address forward references got resolved (as we
3375 if (!BasicBlockFwdRefs.empty())
3376 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3378 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3379 // delete the old functions to clean up. We can't do this unless the entire
3380 // module is materialized because there could always be another function body
3381 // with calls to the old function.
3382 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3383 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3384 if (I->first != I->second) {
3385 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3387 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3388 UpgradeIntrinsicCall(CI, I->second);
3390 if (!I->first->use_empty())
3391 I->first->replaceAllUsesWith(I->second);
3392 I->first->eraseFromParent();
3395 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3397 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3398 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3400 UpgradeDebugInfo(*M);
3401 return std::error_code();
3404 std::error_code BitcodeReader::InitStream() {
3406 return InitLazyStream();
3407 return InitStreamFromBuffer();
3410 std::error_code BitcodeReader::InitStreamFromBuffer() {
3411 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3412 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3414 if (Buffer->getBufferSize() & 3)
3415 return Error(BitcodeError::InvalidBitcodeSignature);
3417 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3418 // The magic number is 0x0B17C0DE stored in little endian.
3419 if (isBitcodeWrapper(BufPtr, BufEnd))
3420 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3421 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3423 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3424 Stream.init(*StreamFile);
3426 return std::error_code();
3429 std::error_code BitcodeReader::InitLazyStream() {
3430 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3432 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3433 StreamFile.reset(new BitstreamReader(Bytes));
3434 Stream.init(*StreamFile);
3436 unsigned char buf[16];
3437 if (Bytes->readBytes(0, 16, buf) == -1)
3438 return Error(BitcodeError::InvalidBitcodeSignature);
3440 if (!isBitcode(buf, buf + 16))
3441 return Error(BitcodeError::InvalidBitcodeSignature);
3443 if (isBitcodeWrapper(buf, buf + 4)) {
3444 const unsigned char *bitcodeStart = buf;
3445 const unsigned char *bitcodeEnd = buf + 16;
3446 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3447 Bytes->dropLeadingBytes(bitcodeStart - buf);
3448 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3450 return std::error_code();
3454 class BitcodeErrorCategoryType : public std::error_category {
3455 const char *name() const LLVM_NOEXCEPT override {
3456 return "llvm.bitcode";
3458 std::string message(int IE) const override {
3459 BitcodeError E = static_cast<BitcodeError>(IE);
3461 case BitcodeError::ConflictingMETADATA_KINDRecords:
3462 return "Conflicting METADATA_KIND records";
3463 case BitcodeError::CouldNotFindFunctionInStream:
3464 return "Could not find function in stream";
3465 case BitcodeError::ExpectedConstant:
3466 return "Expected a constant";
3467 case BitcodeError::InsufficientFunctionProtos:
3468 return "Insufficient function protos";
3469 case BitcodeError::InvalidBitcodeSignature:
3470 return "Invalid bitcode signature";
3471 case BitcodeError::InvalidBitcodeWrapperHeader:
3472 return "Invalid bitcode wrapper header";
3473 case BitcodeError::InvalidConstantReference:
3474 return "Invalid ronstant reference";
3475 case BitcodeError::InvalidID:
3476 return "Invalid ID";
3477 case BitcodeError::InvalidInstructionWithNoBB:
3478 return "Invalid instruction with no BB";
3479 case BitcodeError::InvalidRecord:
3480 return "Invalid record";
3481 case BitcodeError::InvalidTypeForValue:
3482 return "Invalid type for value";
3483 case BitcodeError::InvalidTYPETable:
3484 return "Invalid TYPE table";
3485 case BitcodeError::InvalidType:
3486 return "Invalid type";
3487 case BitcodeError::MalformedBlock:
3488 return "Malformed block";
3489 case BitcodeError::MalformedGlobalInitializerSet:
3490 return "Malformed global initializer set";
3491 case BitcodeError::InvalidMultipleBlocks:
3492 return "Invalid multiple blocks";
3493 case BitcodeError::NeverResolvedValueFoundInFunction:
3494 return "Never resolved value found in function";
3495 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3496 return "Never resolved function from blockaddress";
3497 case BitcodeError::InvalidValue:
3498 return "Invalid value";
3500 llvm_unreachable("Unknown error type!");
3505 const std::error_category &llvm::BitcodeErrorCategory() {
3506 static BitcodeErrorCategoryType O;
3510 //===----------------------------------------------------------------------===//
3511 // External interface
3512 //===----------------------------------------------------------------------===//
3514 /// \brief Get a lazy one-at-time loading module from bitcode.
3516 /// This isn't always used in a lazy context. In particular, it's also used by
3517 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3518 /// in forward-referenced functions from block address references.
3520 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3521 /// materialize everything -- in particular, if this isn't truly lazy.
3522 static ErrorOr<Module *>
3523 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3524 LLVMContext &Context, bool WillMaterializeAll) {
3525 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3526 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3527 M->setMaterializer(R);
3529 auto cleanupOnError = [&](std::error_code EC) {
3530 R->releaseBuffer(); // Never take ownership on error.
3531 delete M; // Also deletes R.
3535 if (std::error_code EC = R->ParseBitcodeInto(M))
3536 return cleanupOnError(EC);
3538 if (!WillMaterializeAll)
3539 // Resolve forward references from blockaddresses.
3540 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3541 return cleanupOnError(EC);
3543 Buffer.release(); // The BitcodeReader owns it now.
3548 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3549 LLVMContext &Context) {
3550 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3553 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3554 DataStreamer *streamer,
3555 LLVMContext &Context,
3556 std::string *ErrMsg) {
3557 Module *M = new Module(name, Context);
3558 BitcodeReader *R = new BitcodeReader(streamer, Context);
3559 M->setMaterializer(R);
3560 if (std::error_code EC = R->ParseBitcodeInto(M)) {
3562 *ErrMsg = EC.message();
3563 delete M; // Also deletes R.
3569 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3570 LLVMContext &Context) {
3571 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3572 ErrorOr<Module *> ModuleOrErr =
3573 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3576 Module *M = ModuleOrErr.get();
3577 // Read in the entire module, and destroy the BitcodeReader.
3578 if (std::error_code EC = M->materializeAllPermanently()) {
3583 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3584 // written. We must defer until the Module has been fully materialized.
3589 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3590 LLVMContext &Context) {
3591 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3592 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3593 ErrorOr<std::string> Triple = R->parseTriple();
3594 if (Triple.getError())
3596 return Triple.get();