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/DiagnosticPrinter.h"
19 #include "llvm/IR/InlineAsm.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/OperandTraits.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/DataStream.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/ManagedStatic.h"
34 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
37 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
38 DiagnosticSeverity Severity,
40 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
42 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
44 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
45 std::error_code EC, const Twine &Message) {
46 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
47 DiagnosticHandler(DI);
51 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
53 return Error(DiagnosticHandler, EC, EC.message());
56 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
57 return ::Error(DiagnosticHandler, make_error_code(E), Message);
60 std::error_code BitcodeReader::Error(const Twine &Message) {
61 return ::Error(DiagnosticHandler,
62 make_error_code(BitcodeError::CorruptedBitcode), Message);
65 std::error_code BitcodeReader::Error(BitcodeError E) {
66 return ::Error(DiagnosticHandler, make_error_code(E));
69 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
73 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
76 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
77 DiagnosticHandlerFunction DiagnosticHandler)
78 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
79 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
80 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
81 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
82 WillMaterializeAllForwardRefs(false) {}
84 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
85 DiagnosticHandlerFunction DiagnosticHandler)
86 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
87 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
88 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
89 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
90 WillMaterializeAllForwardRefs(false) {}
92 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
93 if (WillMaterializeAllForwardRefs)
94 return std::error_code();
97 WillMaterializeAllForwardRefs = true;
99 while (!BasicBlockFwdRefQueue.empty()) {
100 Function *F = BasicBlockFwdRefQueue.front();
101 BasicBlockFwdRefQueue.pop_front();
102 assert(F && "Expected valid function");
103 if (!BasicBlockFwdRefs.count(F))
104 // Already materialized.
107 // Check for a function that isn't materializable to prevent an infinite
108 // loop. When parsing a blockaddress stored in a global variable, there
109 // isn't a trivial way to check if a function will have a body without a
110 // linear search through FunctionsWithBodies, so just check it here.
111 if (!F->isMaterializable())
112 return Error("Never resolved function from blockaddress");
114 // Try to materialize F.
115 if (std::error_code EC = materialize(F))
118 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
121 WillMaterializeAllForwardRefs = false;
122 return std::error_code();
125 void BitcodeReader::FreeState() {
127 std::vector<Type*>().swap(TypeList);
130 std::vector<Comdat *>().swap(ComdatList);
132 std::vector<AttributeSet>().swap(MAttributes);
133 std::vector<BasicBlock*>().swap(FunctionBBs);
134 std::vector<Function*>().swap(FunctionsWithBodies);
135 DeferredFunctionInfo.clear();
138 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
139 BasicBlockFwdRefQueue.clear();
142 //===----------------------------------------------------------------------===//
143 // Helper functions to implement forward reference resolution, etc.
144 //===----------------------------------------------------------------------===//
146 /// ConvertToString - Convert a string from a record into an std::string, return
148 template<typename StrTy>
149 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
151 if (Idx > Record.size())
154 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
155 Result += (char)Record[i];
159 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
161 default: // Map unknown/new linkages to external
163 return GlobalValue::ExternalLinkage;
165 return GlobalValue::WeakAnyLinkage;
167 return GlobalValue::AppendingLinkage;
169 return GlobalValue::InternalLinkage;
171 return GlobalValue::LinkOnceAnyLinkage;
173 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
175 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
177 return GlobalValue::ExternalWeakLinkage;
179 return GlobalValue::CommonLinkage;
181 return GlobalValue::PrivateLinkage;
183 return GlobalValue::WeakODRLinkage;
185 return GlobalValue::LinkOnceODRLinkage;
187 return GlobalValue::AvailableExternallyLinkage;
189 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
191 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
193 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
197 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
199 default: // Map unknown visibilities to default.
200 case 0: return GlobalValue::DefaultVisibility;
201 case 1: return GlobalValue::HiddenVisibility;
202 case 2: return GlobalValue::ProtectedVisibility;
206 static GlobalValue::DLLStorageClassTypes
207 GetDecodedDLLStorageClass(unsigned Val) {
209 default: // Map unknown values to default.
210 case 0: return GlobalValue::DefaultStorageClass;
211 case 1: return GlobalValue::DLLImportStorageClass;
212 case 2: return GlobalValue::DLLExportStorageClass;
216 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
218 case 0: return GlobalVariable::NotThreadLocal;
219 default: // Map unknown non-zero value to general dynamic.
220 case 1: return GlobalVariable::GeneralDynamicTLSModel;
221 case 2: return GlobalVariable::LocalDynamicTLSModel;
222 case 3: return GlobalVariable::InitialExecTLSModel;
223 case 4: return GlobalVariable::LocalExecTLSModel;
227 static int GetDecodedCastOpcode(unsigned Val) {
230 case bitc::CAST_TRUNC : return Instruction::Trunc;
231 case bitc::CAST_ZEXT : return Instruction::ZExt;
232 case bitc::CAST_SEXT : return Instruction::SExt;
233 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
234 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
235 case bitc::CAST_UITOFP : return Instruction::UIToFP;
236 case bitc::CAST_SITOFP : return Instruction::SIToFP;
237 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
238 case bitc::CAST_FPEXT : return Instruction::FPExt;
239 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
240 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
241 case bitc::CAST_BITCAST : return Instruction::BitCast;
242 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
245 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
248 case bitc::BINOP_ADD:
249 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
250 case bitc::BINOP_SUB:
251 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
252 case bitc::BINOP_MUL:
253 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
254 case bitc::BINOP_UDIV: return Instruction::UDiv;
255 case bitc::BINOP_SDIV:
256 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
257 case bitc::BINOP_UREM: return Instruction::URem;
258 case bitc::BINOP_SREM:
259 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
260 case bitc::BINOP_SHL: return Instruction::Shl;
261 case bitc::BINOP_LSHR: return Instruction::LShr;
262 case bitc::BINOP_ASHR: return Instruction::AShr;
263 case bitc::BINOP_AND: return Instruction::And;
264 case bitc::BINOP_OR: return Instruction::Or;
265 case bitc::BINOP_XOR: return Instruction::Xor;
269 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
271 default: return AtomicRMWInst::BAD_BINOP;
272 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
273 case bitc::RMW_ADD: return AtomicRMWInst::Add;
274 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
275 case bitc::RMW_AND: return AtomicRMWInst::And;
276 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
277 case bitc::RMW_OR: return AtomicRMWInst::Or;
278 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
279 case bitc::RMW_MAX: return AtomicRMWInst::Max;
280 case bitc::RMW_MIN: return AtomicRMWInst::Min;
281 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
282 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
286 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
288 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
289 case bitc::ORDERING_UNORDERED: return Unordered;
290 case bitc::ORDERING_MONOTONIC: return Monotonic;
291 case bitc::ORDERING_ACQUIRE: return Acquire;
292 case bitc::ORDERING_RELEASE: return Release;
293 case bitc::ORDERING_ACQREL: return AcquireRelease;
294 default: // Map unknown orderings to sequentially-consistent.
295 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
299 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
301 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
302 default: // Map unknown scopes to cross-thread.
303 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
307 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
309 default: // Map unknown selection kinds to any.
310 case bitc::COMDAT_SELECTION_KIND_ANY:
312 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
313 return Comdat::ExactMatch;
314 case bitc::COMDAT_SELECTION_KIND_LARGEST:
315 return Comdat::Largest;
316 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
317 return Comdat::NoDuplicates;
318 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
319 return Comdat::SameSize;
323 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
325 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
326 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
332 /// @brief A class for maintaining the slot number definition
333 /// as a placeholder for the actual definition for forward constants defs.
334 class ConstantPlaceHolder : public ConstantExpr {
335 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
337 // allocate space for exactly one operand
338 void *operator new(size_t s) {
339 return User::operator new(s, 1);
341 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
342 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
343 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
346 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
347 static bool classof(const Value *V) {
348 return isa<ConstantExpr>(V) &&
349 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
353 /// Provide fast operand accessors
354 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
358 // FIXME: can we inherit this from ConstantExpr?
360 struct OperandTraits<ConstantPlaceHolder> :
361 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
363 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
367 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
376 WeakVH &OldV = ValuePtrs[Idx];
382 // Handle constants and non-constants (e.g. instrs) differently for
384 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
385 ResolveConstants.push_back(std::make_pair(PHC, Idx));
388 // If there was a forward reference to this value, replace it.
389 Value *PrevVal = OldV;
390 OldV->replaceAllUsesWith(V);
396 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
401 if (Value *V = ValuePtrs[Idx]) {
402 assert(Ty == V->getType() && "Type mismatch in constant table!");
403 return cast<Constant>(V);
406 // Create and return a placeholder, which will later be RAUW'd.
407 Constant *C = new ConstantPlaceHolder(Ty, Context);
412 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
416 if (Value *V = ValuePtrs[Idx]) {
417 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
421 // No type specified, must be invalid reference.
422 if (!Ty) return nullptr;
424 // Create and return a placeholder, which will later be RAUW'd.
425 Value *V = new Argument(Ty);
430 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
431 /// resolves any forward references. The idea behind this is that we sometimes
432 /// get constants (such as large arrays) which reference *many* forward ref
433 /// constants. Replacing each of these causes a lot of thrashing when
434 /// building/reuniquing the constant. Instead of doing this, we look at all the
435 /// uses and rewrite all the place holders at once for any constant that uses
437 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
438 // Sort the values by-pointer so that they are efficient to look up with a
440 std::sort(ResolveConstants.begin(), ResolveConstants.end());
442 SmallVector<Constant*, 64> NewOps;
444 while (!ResolveConstants.empty()) {
445 Value *RealVal = operator[](ResolveConstants.back().second);
446 Constant *Placeholder = ResolveConstants.back().first;
447 ResolveConstants.pop_back();
449 // Loop over all users of the placeholder, updating them to reference the
450 // new value. If they reference more than one placeholder, update them all
452 while (!Placeholder->use_empty()) {
453 auto UI = Placeholder->user_begin();
456 // If the using object isn't uniqued, just update the operands. This
457 // handles instructions and initializers for global variables.
458 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
459 UI.getUse().set(RealVal);
463 // Otherwise, we have a constant that uses the placeholder. Replace that
464 // constant with a new constant that has *all* placeholder uses updated.
465 Constant *UserC = cast<Constant>(U);
466 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
469 if (!isa<ConstantPlaceHolder>(*I)) {
470 // Not a placeholder reference.
472 } else if (*I == Placeholder) {
473 // Common case is that it just references this one placeholder.
476 // Otherwise, look up the placeholder in ResolveConstants.
477 ResolveConstantsTy::iterator It =
478 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
479 std::pair<Constant*, unsigned>(cast<Constant>(*I),
481 assert(It != ResolveConstants.end() && It->first == *I);
482 NewOp = operator[](It->second);
485 NewOps.push_back(cast<Constant>(NewOp));
488 // Make the new constant.
490 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
491 NewC = ConstantArray::get(UserCA->getType(), NewOps);
492 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
493 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
494 } else if (isa<ConstantVector>(UserC)) {
495 NewC = ConstantVector::get(NewOps);
497 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
498 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
501 UserC->replaceAllUsesWith(NewC);
502 UserC->destroyConstant();
506 // Update all ValueHandles, they should be the only users at this point.
507 Placeholder->replaceAllUsesWith(RealVal);
512 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
521 TrackingMDRef &OldMD = MDValuePtrs[Idx];
527 // If there was a forward reference to this value, replace it.
528 MDNodeFwdDecl *PrevMD = cast<MDNodeFwdDecl>(OldMD.get());
529 PrevMD->replaceAllUsesWith(MD);
530 MDNode::deleteTemporary(PrevMD);
534 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
538 if (Metadata *MD = MDValuePtrs[Idx])
541 // Create and return a placeholder, which will later be RAUW'd.
544 Metadata *MD = MDNode::getTemporary(Context, None);
545 MDValuePtrs[Idx].reset(MD);
549 void BitcodeReaderMDValueList::tryToResolveCycles() {
555 // Still forward references... can't resolve cycles.
558 // Resolve any cycles.
559 for (auto &MD : MDValuePtrs) {
560 assert(!(MD && isa<MDNodeFwdDecl>(MD)) && "Unexpected forward reference");
561 if (auto *G = dyn_cast_or_null<GenericMDNode>(MD))
566 Type *BitcodeReader::getTypeByID(unsigned ID) {
567 // The type table size is always specified correctly.
568 if (ID >= TypeList.size())
571 if (Type *Ty = TypeList[ID])
574 // If we have a forward reference, the only possible case is when it is to a
575 // named struct. Just create a placeholder for now.
576 return TypeList[ID] = createIdentifiedStructType(Context);
579 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
581 auto *Ret = StructType::create(Context, Name);
582 IdentifiedStructTypes.push_back(Ret);
586 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
587 auto *Ret = StructType::create(Context);
588 IdentifiedStructTypes.push_back(Ret);
593 //===----------------------------------------------------------------------===//
594 // Functions for parsing blocks from the bitcode file
595 //===----------------------------------------------------------------------===//
598 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
599 /// been decoded from the given integer. This function must stay in sync with
600 /// 'encodeLLVMAttributesForBitcode'.
601 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
602 uint64_t EncodedAttrs) {
603 // FIXME: Remove in 4.0.
605 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
606 // the bits above 31 down by 11 bits.
607 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
608 assert((!Alignment || isPowerOf2_32(Alignment)) &&
609 "Alignment must be a power of two.");
612 B.addAlignmentAttr(Alignment);
613 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
614 (EncodedAttrs & 0xffff));
617 std::error_code BitcodeReader::ParseAttributeBlock() {
618 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
619 return Error("Invalid record");
621 if (!MAttributes.empty())
622 return Error("Invalid multiple blocks");
624 SmallVector<uint64_t, 64> Record;
626 SmallVector<AttributeSet, 8> Attrs;
628 // Read all the records.
630 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
632 switch (Entry.Kind) {
633 case BitstreamEntry::SubBlock: // Handled for us already.
634 case BitstreamEntry::Error:
635 return Error("Malformed block");
636 case BitstreamEntry::EndBlock:
637 return std::error_code();
638 case BitstreamEntry::Record:
639 // The interesting case.
645 switch (Stream.readRecord(Entry.ID, Record)) {
646 default: // Default behavior: ignore.
648 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
649 // FIXME: Remove in 4.0.
650 if (Record.size() & 1)
651 return Error("Invalid record");
653 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
655 decodeLLVMAttributesForBitcode(B, Record[i+1]);
656 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
659 MAttributes.push_back(AttributeSet::get(Context, Attrs));
663 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
664 for (unsigned i = 0, e = Record.size(); i != e; ++i)
665 Attrs.push_back(MAttributeGroups[Record[i]]);
667 MAttributes.push_back(AttributeSet::get(Context, Attrs));
675 // Returns Attribute::None on unrecognized codes.
676 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
679 return Attribute::None;
680 case bitc::ATTR_KIND_ALIGNMENT:
681 return Attribute::Alignment;
682 case bitc::ATTR_KIND_ALWAYS_INLINE:
683 return Attribute::AlwaysInline;
684 case bitc::ATTR_KIND_BUILTIN:
685 return Attribute::Builtin;
686 case bitc::ATTR_KIND_BY_VAL:
687 return Attribute::ByVal;
688 case bitc::ATTR_KIND_IN_ALLOCA:
689 return Attribute::InAlloca;
690 case bitc::ATTR_KIND_COLD:
691 return Attribute::Cold;
692 case bitc::ATTR_KIND_INLINE_HINT:
693 return Attribute::InlineHint;
694 case bitc::ATTR_KIND_IN_REG:
695 return Attribute::InReg;
696 case bitc::ATTR_KIND_JUMP_TABLE:
697 return Attribute::JumpTable;
698 case bitc::ATTR_KIND_MIN_SIZE:
699 return Attribute::MinSize;
700 case bitc::ATTR_KIND_NAKED:
701 return Attribute::Naked;
702 case bitc::ATTR_KIND_NEST:
703 return Attribute::Nest;
704 case bitc::ATTR_KIND_NO_ALIAS:
705 return Attribute::NoAlias;
706 case bitc::ATTR_KIND_NO_BUILTIN:
707 return Attribute::NoBuiltin;
708 case bitc::ATTR_KIND_NO_CAPTURE:
709 return Attribute::NoCapture;
710 case bitc::ATTR_KIND_NO_DUPLICATE:
711 return Attribute::NoDuplicate;
712 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
713 return Attribute::NoImplicitFloat;
714 case bitc::ATTR_KIND_NO_INLINE:
715 return Attribute::NoInline;
716 case bitc::ATTR_KIND_NON_LAZY_BIND:
717 return Attribute::NonLazyBind;
718 case bitc::ATTR_KIND_NON_NULL:
719 return Attribute::NonNull;
720 case bitc::ATTR_KIND_DEREFERENCEABLE:
721 return Attribute::Dereferenceable;
722 case bitc::ATTR_KIND_NO_RED_ZONE:
723 return Attribute::NoRedZone;
724 case bitc::ATTR_KIND_NO_RETURN:
725 return Attribute::NoReturn;
726 case bitc::ATTR_KIND_NO_UNWIND:
727 return Attribute::NoUnwind;
728 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
729 return Attribute::OptimizeForSize;
730 case bitc::ATTR_KIND_OPTIMIZE_NONE:
731 return Attribute::OptimizeNone;
732 case bitc::ATTR_KIND_READ_NONE:
733 return Attribute::ReadNone;
734 case bitc::ATTR_KIND_READ_ONLY:
735 return Attribute::ReadOnly;
736 case bitc::ATTR_KIND_RETURNED:
737 return Attribute::Returned;
738 case bitc::ATTR_KIND_RETURNS_TWICE:
739 return Attribute::ReturnsTwice;
740 case bitc::ATTR_KIND_S_EXT:
741 return Attribute::SExt;
742 case bitc::ATTR_KIND_STACK_ALIGNMENT:
743 return Attribute::StackAlignment;
744 case bitc::ATTR_KIND_STACK_PROTECT:
745 return Attribute::StackProtect;
746 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
747 return Attribute::StackProtectReq;
748 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
749 return Attribute::StackProtectStrong;
750 case bitc::ATTR_KIND_STRUCT_RET:
751 return Attribute::StructRet;
752 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
753 return Attribute::SanitizeAddress;
754 case bitc::ATTR_KIND_SANITIZE_THREAD:
755 return Attribute::SanitizeThread;
756 case bitc::ATTR_KIND_SANITIZE_MEMORY:
757 return Attribute::SanitizeMemory;
758 case bitc::ATTR_KIND_UW_TABLE:
759 return Attribute::UWTable;
760 case bitc::ATTR_KIND_Z_EXT:
761 return Attribute::ZExt;
765 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
766 Attribute::AttrKind *Kind) {
767 *Kind = GetAttrFromCode(Code);
768 if (*Kind == Attribute::None)
769 return Error(BitcodeError::CorruptedBitcode,
770 "Unknown attribute kind (" + Twine(Code) + ")");
771 return std::error_code();
774 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
775 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
776 return Error("Invalid record");
778 if (!MAttributeGroups.empty())
779 return Error("Invalid multiple blocks");
781 SmallVector<uint64_t, 64> Record;
783 // Read all the records.
785 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
787 switch (Entry.Kind) {
788 case BitstreamEntry::SubBlock: // Handled for us already.
789 case BitstreamEntry::Error:
790 return Error("Malformed block");
791 case BitstreamEntry::EndBlock:
792 return std::error_code();
793 case BitstreamEntry::Record:
794 // The interesting case.
800 switch (Stream.readRecord(Entry.ID, Record)) {
801 default: // Default behavior: ignore.
803 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
804 if (Record.size() < 3)
805 return Error("Invalid record");
807 uint64_t GrpID = Record[0];
808 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
811 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
812 if (Record[i] == 0) { // Enum attribute
813 Attribute::AttrKind Kind;
814 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
817 B.addAttribute(Kind);
818 } else if (Record[i] == 1) { // Integer attribute
819 Attribute::AttrKind Kind;
820 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
822 if (Kind == Attribute::Alignment)
823 B.addAlignmentAttr(Record[++i]);
824 else if (Kind == Attribute::StackAlignment)
825 B.addStackAlignmentAttr(Record[++i]);
826 else if (Kind == Attribute::Dereferenceable)
827 B.addDereferenceableAttr(Record[++i]);
828 } else { // String attribute
829 assert((Record[i] == 3 || Record[i] == 4) &&
830 "Invalid attribute group entry");
831 bool HasValue = (Record[i++] == 4);
832 SmallString<64> KindStr;
833 SmallString<64> ValStr;
835 while (Record[i] != 0 && i != e)
836 KindStr += Record[i++];
837 assert(Record[i] == 0 && "Kind string not null terminated");
840 // Has a value associated with it.
841 ++i; // Skip the '0' that terminates the "kind" string.
842 while (Record[i] != 0 && i != e)
843 ValStr += Record[i++];
844 assert(Record[i] == 0 && "Value string not null terminated");
847 B.addAttribute(KindStr.str(), ValStr.str());
851 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
858 std::error_code BitcodeReader::ParseTypeTable() {
859 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
860 return Error("Invalid record");
862 return ParseTypeTableBody();
865 std::error_code BitcodeReader::ParseTypeTableBody() {
866 if (!TypeList.empty())
867 return Error("Invalid multiple blocks");
869 SmallVector<uint64_t, 64> Record;
870 unsigned NumRecords = 0;
872 SmallString<64> TypeName;
874 // Read all the records for this type table.
876 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
878 switch (Entry.Kind) {
879 case BitstreamEntry::SubBlock: // Handled for us already.
880 case BitstreamEntry::Error:
881 return Error("Malformed block");
882 case BitstreamEntry::EndBlock:
883 if (NumRecords != TypeList.size())
884 return Error("Malformed block");
885 return std::error_code();
886 case BitstreamEntry::Record:
887 // The interesting case.
893 Type *ResultTy = nullptr;
894 switch (Stream.readRecord(Entry.ID, Record)) {
896 return Error("Invalid value");
897 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
898 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
899 // type list. This allows us to reserve space.
900 if (Record.size() < 1)
901 return Error("Invalid record");
902 TypeList.resize(Record[0]);
904 case bitc::TYPE_CODE_VOID: // VOID
905 ResultTy = Type::getVoidTy(Context);
907 case bitc::TYPE_CODE_HALF: // HALF
908 ResultTy = Type::getHalfTy(Context);
910 case bitc::TYPE_CODE_FLOAT: // FLOAT
911 ResultTy = Type::getFloatTy(Context);
913 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
914 ResultTy = Type::getDoubleTy(Context);
916 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
917 ResultTy = Type::getX86_FP80Ty(Context);
919 case bitc::TYPE_CODE_FP128: // FP128
920 ResultTy = Type::getFP128Ty(Context);
922 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
923 ResultTy = Type::getPPC_FP128Ty(Context);
925 case bitc::TYPE_CODE_LABEL: // LABEL
926 ResultTy = Type::getLabelTy(Context);
928 case bitc::TYPE_CODE_METADATA: // METADATA
929 ResultTy = Type::getMetadataTy(Context);
931 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
932 ResultTy = Type::getX86_MMXTy(Context);
934 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
935 if (Record.size() < 1)
936 return Error("Invalid record");
938 ResultTy = IntegerType::get(Context, Record[0]);
940 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
941 // [pointee type, address space]
942 if (Record.size() < 1)
943 return Error("Invalid record");
944 unsigned AddressSpace = 0;
945 if (Record.size() == 2)
946 AddressSpace = Record[1];
947 ResultTy = getTypeByID(Record[0]);
949 return Error("Invalid type");
950 ResultTy = PointerType::get(ResultTy, AddressSpace);
953 case bitc::TYPE_CODE_FUNCTION_OLD: {
954 // FIXME: attrid is dead, remove it in LLVM 4.0
955 // FUNCTION: [vararg, attrid, retty, paramty x N]
956 if (Record.size() < 3)
957 return Error("Invalid record");
958 SmallVector<Type*, 8> ArgTys;
959 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
960 if (Type *T = getTypeByID(Record[i]))
966 ResultTy = getTypeByID(Record[2]);
967 if (!ResultTy || ArgTys.size() < Record.size()-3)
968 return Error("Invalid type");
970 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
973 case bitc::TYPE_CODE_FUNCTION: {
974 // FUNCTION: [vararg, retty, paramty x N]
975 if (Record.size() < 2)
976 return Error("Invalid record");
977 SmallVector<Type*, 8> ArgTys;
978 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
979 if (Type *T = getTypeByID(Record[i]))
985 ResultTy = getTypeByID(Record[1]);
986 if (!ResultTy || ArgTys.size() < Record.size()-2)
987 return Error("Invalid type");
989 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
992 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
993 if (Record.size() < 1)
994 return Error("Invalid record");
995 SmallVector<Type*, 8> EltTys;
996 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
997 if (Type *T = getTypeByID(Record[i]))
1002 if (EltTys.size() != Record.size()-1)
1003 return Error("Invalid type");
1004 ResultTy = StructType::get(Context, EltTys, Record[0]);
1007 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1008 if (ConvertToString(Record, 0, TypeName))
1009 return Error("Invalid record");
1012 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1013 if (Record.size() < 1)
1014 return Error("Invalid record");
1016 if (NumRecords >= TypeList.size())
1017 return Error("Invalid TYPE table");
1019 // Check to see if this was forward referenced, if so fill in the temp.
1020 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1022 Res->setName(TypeName);
1023 TypeList[NumRecords] = nullptr;
1024 } else // Otherwise, create a new struct.
1025 Res = createIdentifiedStructType(Context, TypeName);
1028 SmallVector<Type*, 8> EltTys;
1029 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1030 if (Type *T = getTypeByID(Record[i]))
1031 EltTys.push_back(T);
1035 if (EltTys.size() != Record.size()-1)
1036 return Error("Invalid record");
1037 Res->setBody(EltTys, Record[0]);
1041 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1042 if (Record.size() != 1)
1043 return Error("Invalid record");
1045 if (NumRecords >= TypeList.size())
1046 return Error("Invalid TYPE table");
1048 // Check to see if this was forward referenced, if so fill in the temp.
1049 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1051 Res->setName(TypeName);
1052 TypeList[NumRecords] = nullptr;
1053 } else // Otherwise, create a new struct with no body.
1054 Res = createIdentifiedStructType(Context, TypeName);
1059 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1060 if (Record.size() < 2)
1061 return Error("Invalid record");
1062 if ((ResultTy = getTypeByID(Record[1])))
1063 ResultTy = ArrayType::get(ResultTy, Record[0]);
1065 return Error("Invalid type");
1067 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1068 if (Record.size() < 2)
1069 return Error("Invalid record");
1070 if ((ResultTy = getTypeByID(Record[1])))
1071 ResultTy = VectorType::get(ResultTy, Record[0]);
1073 return Error("Invalid type");
1077 if (NumRecords >= TypeList.size())
1078 return Error("Invalid TYPE table");
1079 assert(ResultTy && "Didn't read a type?");
1080 assert(!TypeList[NumRecords] && "Already read type?");
1081 TypeList[NumRecords++] = ResultTy;
1085 std::error_code BitcodeReader::ParseValueSymbolTable() {
1086 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1087 return Error("Invalid record");
1089 SmallVector<uint64_t, 64> Record;
1091 // Read all the records for this value table.
1092 SmallString<128> ValueName;
1094 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1096 switch (Entry.Kind) {
1097 case BitstreamEntry::SubBlock: // Handled for us already.
1098 case BitstreamEntry::Error:
1099 return Error("Malformed block");
1100 case BitstreamEntry::EndBlock:
1101 return std::error_code();
1102 case BitstreamEntry::Record:
1103 // The interesting case.
1109 switch (Stream.readRecord(Entry.ID, Record)) {
1110 default: // Default behavior: unknown type.
1112 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1113 if (ConvertToString(Record, 1, ValueName))
1114 return Error("Invalid record");
1115 unsigned ValueID = Record[0];
1116 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1117 return Error("Invalid record");
1118 Value *V = ValueList[ValueID];
1120 V->setName(StringRef(ValueName.data(), ValueName.size()));
1124 case bitc::VST_CODE_BBENTRY: {
1125 if (ConvertToString(Record, 1, ValueName))
1126 return Error("Invalid record");
1127 BasicBlock *BB = getBasicBlock(Record[0]);
1129 return Error("Invalid record");
1131 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1139 std::error_code BitcodeReader::ParseMetadata() {
1140 unsigned NextMDValueNo = MDValueList.size();
1142 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1143 return Error("Invalid record");
1145 SmallVector<uint64_t, 64> Record;
1147 // Read all the records.
1149 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1151 switch (Entry.Kind) {
1152 case BitstreamEntry::SubBlock: // Handled for us already.
1153 case BitstreamEntry::Error:
1154 return Error("Malformed block");
1155 case BitstreamEntry::EndBlock:
1156 MDValueList.tryToResolveCycles();
1157 return std::error_code();
1158 case BitstreamEntry::Record:
1159 // The interesting case.
1165 unsigned Code = Stream.readRecord(Entry.ID, Record);
1166 bool IsDistinct = false;
1168 default: // Default behavior: ignore.
1170 case bitc::METADATA_NAME: {
1171 // Read name of the named metadata.
1172 SmallString<8> Name(Record.begin(), Record.end());
1174 Code = Stream.ReadCode();
1176 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1177 unsigned NextBitCode = Stream.readRecord(Code, Record);
1178 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1180 // Read named metadata elements.
1181 unsigned Size = Record.size();
1182 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1183 for (unsigned i = 0; i != Size; ++i) {
1184 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1186 return Error("Invalid record");
1187 NMD->addOperand(MD);
1191 case bitc::METADATA_OLD_FN_NODE: {
1192 // FIXME: Remove in 4.0.
1193 // This is a LocalAsMetadata record, the only type of function-local
1195 if (Record.size() % 2 == 1)
1196 return Error("Invalid record");
1198 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1199 // to be legal, but there's no upgrade path.
1200 auto dropRecord = [&] {
1201 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1203 if (Record.size() != 2) {
1208 Type *Ty = getTypeByID(Record[0]);
1209 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1214 MDValueList.AssignValue(
1215 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1219 case bitc::METADATA_OLD_NODE: {
1220 // FIXME: Remove in 4.0.
1221 if (Record.size() % 2 == 1)
1222 return Error("Invalid record");
1224 unsigned Size = Record.size();
1225 SmallVector<Metadata *, 8> Elts;
1226 for (unsigned i = 0; i != Size; i += 2) {
1227 Type *Ty = getTypeByID(Record[i]);
1229 return Error("Invalid record");
1230 if (Ty->isMetadataTy())
1231 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1232 else if (!Ty->isVoidTy()) {
1234 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1235 assert(isa<ConstantAsMetadata>(MD) &&
1236 "Expected non-function-local metadata");
1239 Elts.push_back(nullptr);
1241 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1244 case bitc::METADATA_VALUE: {
1245 if (Record.size() != 2)
1246 return Error("Invalid record");
1248 Type *Ty = getTypeByID(Record[0]);
1249 if (Ty->isMetadataTy() || Ty->isVoidTy())
1250 return Error("Invalid record");
1252 MDValueList.AssignValue(
1253 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1257 case bitc::METADATA_DISTINCT_NODE:
1260 case bitc::METADATA_NODE: {
1261 SmallVector<Metadata *, 8> Elts;
1262 Elts.reserve(Record.size());
1263 for (unsigned ID : Record)
1264 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1265 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1266 : MDNode::get(Context, Elts),
1270 case bitc::METADATA_STRING: {
1271 std::string String(Record.begin(), Record.end());
1272 llvm::UpgradeMDStringConstant(String);
1273 Metadata *MD = MDString::get(Context, String);
1274 MDValueList.AssignValue(MD, NextMDValueNo++);
1277 case bitc::METADATA_KIND: {
1278 if (Record.size() < 2)
1279 return Error("Invalid record");
1281 unsigned Kind = Record[0];
1282 SmallString<8> Name(Record.begin()+1, Record.end());
1284 unsigned NewKind = TheModule->getMDKindID(Name.str());
1285 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1286 return Error("Conflicting METADATA_KIND records");
1293 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1294 /// the LSB for dense VBR encoding.
1295 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1300 // There is no such thing as -0 with integers. "-0" really means MININT.
1304 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1305 /// values and aliases that we can.
1306 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1307 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1308 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1309 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1310 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1312 GlobalInitWorklist.swap(GlobalInits);
1313 AliasInitWorklist.swap(AliasInits);
1314 FunctionPrefixWorklist.swap(FunctionPrefixes);
1315 FunctionPrologueWorklist.swap(FunctionPrologues);
1317 while (!GlobalInitWorklist.empty()) {
1318 unsigned ValID = GlobalInitWorklist.back().second;
1319 if (ValID >= ValueList.size()) {
1320 // Not ready to resolve this yet, it requires something later in the file.
1321 GlobalInits.push_back(GlobalInitWorklist.back());
1323 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1324 GlobalInitWorklist.back().first->setInitializer(C);
1326 return Error("Expected a constant");
1328 GlobalInitWorklist.pop_back();
1331 while (!AliasInitWorklist.empty()) {
1332 unsigned ValID = AliasInitWorklist.back().second;
1333 if (ValID >= ValueList.size()) {
1334 AliasInits.push_back(AliasInitWorklist.back());
1336 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1337 AliasInitWorklist.back().first->setAliasee(C);
1339 return Error("Expected a constant");
1341 AliasInitWorklist.pop_back();
1344 while (!FunctionPrefixWorklist.empty()) {
1345 unsigned ValID = FunctionPrefixWorklist.back().second;
1346 if (ValID >= ValueList.size()) {
1347 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1349 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1350 FunctionPrefixWorklist.back().first->setPrefixData(C);
1352 return Error("Expected a constant");
1354 FunctionPrefixWorklist.pop_back();
1357 while (!FunctionPrologueWorklist.empty()) {
1358 unsigned ValID = FunctionPrologueWorklist.back().second;
1359 if (ValID >= ValueList.size()) {
1360 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1362 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1363 FunctionPrologueWorklist.back().first->setPrologueData(C);
1365 return Error("Expected a constant");
1367 FunctionPrologueWorklist.pop_back();
1370 return std::error_code();
1373 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1374 SmallVector<uint64_t, 8> Words(Vals.size());
1375 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1376 BitcodeReader::decodeSignRotatedValue);
1378 return APInt(TypeBits, Words);
1381 std::error_code BitcodeReader::ParseConstants() {
1382 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1383 return Error("Invalid record");
1385 SmallVector<uint64_t, 64> Record;
1387 // Read all the records for this value table.
1388 Type *CurTy = Type::getInt32Ty(Context);
1389 unsigned NextCstNo = ValueList.size();
1391 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1393 switch (Entry.Kind) {
1394 case BitstreamEntry::SubBlock: // Handled for us already.
1395 case BitstreamEntry::Error:
1396 return Error("Malformed block");
1397 case BitstreamEntry::EndBlock:
1398 if (NextCstNo != ValueList.size())
1399 return Error("Invalid ronstant reference");
1401 // Once all the constants have been read, go through and resolve forward
1403 ValueList.ResolveConstantForwardRefs();
1404 return std::error_code();
1405 case BitstreamEntry::Record:
1406 // The interesting case.
1413 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1415 default: // Default behavior: unknown constant
1416 case bitc::CST_CODE_UNDEF: // UNDEF
1417 V = UndefValue::get(CurTy);
1419 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1421 return Error("Invalid record");
1422 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1423 return Error("Invalid record");
1424 CurTy = TypeList[Record[0]];
1425 continue; // Skip the ValueList manipulation.
1426 case bitc::CST_CODE_NULL: // NULL
1427 V = Constant::getNullValue(CurTy);
1429 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1430 if (!CurTy->isIntegerTy() || Record.empty())
1431 return Error("Invalid record");
1432 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1434 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1435 if (!CurTy->isIntegerTy() || Record.empty())
1436 return Error("Invalid record");
1438 APInt VInt = ReadWideAPInt(Record,
1439 cast<IntegerType>(CurTy)->getBitWidth());
1440 V = ConstantInt::get(Context, VInt);
1444 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1446 return Error("Invalid record");
1447 if (CurTy->isHalfTy())
1448 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1449 APInt(16, (uint16_t)Record[0])));
1450 else if (CurTy->isFloatTy())
1451 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1452 APInt(32, (uint32_t)Record[0])));
1453 else if (CurTy->isDoubleTy())
1454 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1455 APInt(64, Record[0])));
1456 else if (CurTy->isX86_FP80Ty()) {
1457 // Bits are not stored the same way as a normal i80 APInt, compensate.
1458 uint64_t Rearrange[2];
1459 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1460 Rearrange[1] = Record[0] >> 48;
1461 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1462 APInt(80, Rearrange)));
1463 } else if (CurTy->isFP128Ty())
1464 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1465 APInt(128, Record)));
1466 else if (CurTy->isPPC_FP128Ty())
1467 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1468 APInt(128, Record)));
1470 V = UndefValue::get(CurTy);
1474 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1476 return Error("Invalid record");
1478 unsigned Size = Record.size();
1479 SmallVector<Constant*, 16> Elts;
1481 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1482 for (unsigned i = 0; i != Size; ++i)
1483 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1484 STy->getElementType(i)));
1485 V = ConstantStruct::get(STy, Elts);
1486 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1487 Type *EltTy = ATy->getElementType();
1488 for (unsigned i = 0; i != Size; ++i)
1489 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1490 V = ConstantArray::get(ATy, Elts);
1491 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1492 Type *EltTy = VTy->getElementType();
1493 for (unsigned i = 0; i != Size; ++i)
1494 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1495 V = ConstantVector::get(Elts);
1497 V = UndefValue::get(CurTy);
1501 case bitc::CST_CODE_STRING: // STRING: [values]
1502 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1504 return Error("Invalid record");
1506 SmallString<16> Elts(Record.begin(), Record.end());
1507 V = ConstantDataArray::getString(Context, Elts,
1508 BitCode == bitc::CST_CODE_CSTRING);
1511 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1513 return Error("Invalid record");
1515 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1516 unsigned Size = Record.size();
1518 if (EltTy->isIntegerTy(8)) {
1519 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1520 if (isa<VectorType>(CurTy))
1521 V = ConstantDataVector::get(Context, Elts);
1523 V = ConstantDataArray::get(Context, Elts);
1524 } else if (EltTy->isIntegerTy(16)) {
1525 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1526 if (isa<VectorType>(CurTy))
1527 V = ConstantDataVector::get(Context, Elts);
1529 V = ConstantDataArray::get(Context, Elts);
1530 } else if (EltTy->isIntegerTy(32)) {
1531 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1532 if (isa<VectorType>(CurTy))
1533 V = ConstantDataVector::get(Context, Elts);
1535 V = ConstantDataArray::get(Context, Elts);
1536 } else if (EltTy->isIntegerTy(64)) {
1537 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1538 if (isa<VectorType>(CurTy))
1539 V = ConstantDataVector::get(Context, Elts);
1541 V = ConstantDataArray::get(Context, Elts);
1542 } else if (EltTy->isFloatTy()) {
1543 SmallVector<float, 16> Elts(Size);
1544 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1545 if (isa<VectorType>(CurTy))
1546 V = ConstantDataVector::get(Context, Elts);
1548 V = ConstantDataArray::get(Context, Elts);
1549 } else if (EltTy->isDoubleTy()) {
1550 SmallVector<double, 16> Elts(Size);
1551 std::transform(Record.begin(), Record.end(), Elts.begin(),
1553 if (isa<VectorType>(CurTy))
1554 V = ConstantDataVector::get(Context, Elts);
1556 V = ConstantDataArray::get(Context, Elts);
1558 return Error("Invalid type for value");
1563 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1564 if (Record.size() < 3)
1565 return Error("Invalid record");
1566 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1568 V = UndefValue::get(CurTy); // Unknown binop.
1570 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1571 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1573 if (Record.size() >= 4) {
1574 if (Opc == Instruction::Add ||
1575 Opc == Instruction::Sub ||
1576 Opc == Instruction::Mul ||
1577 Opc == Instruction::Shl) {
1578 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1579 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1580 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1581 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1582 } else if (Opc == Instruction::SDiv ||
1583 Opc == Instruction::UDiv ||
1584 Opc == Instruction::LShr ||
1585 Opc == Instruction::AShr) {
1586 if (Record[3] & (1 << bitc::PEO_EXACT))
1587 Flags |= SDivOperator::IsExact;
1590 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1594 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1595 if (Record.size() < 3)
1596 return Error("Invalid record");
1597 int Opc = GetDecodedCastOpcode(Record[0]);
1599 V = UndefValue::get(CurTy); // Unknown cast.
1601 Type *OpTy = getTypeByID(Record[1]);
1603 return Error("Invalid record");
1604 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1605 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1606 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1610 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1611 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1612 if (Record.size() & 1)
1613 return Error("Invalid record");
1614 SmallVector<Constant*, 16> Elts;
1615 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1616 Type *ElTy = getTypeByID(Record[i]);
1618 return Error("Invalid record");
1619 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1621 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1622 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1624 bitc::CST_CODE_CE_INBOUNDS_GEP);
1627 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1628 if (Record.size() < 3)
1629 return Error("Invalid record");
1631 Type *SelectorTy = Type::getInt1Ty(Context);
1633 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1634 // vector. Otherwise, it must be a single bit.
1635 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1636 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1637 VTy->getNumElements());
1639 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1641 ValueList.getConstantFwdRef(Record[1],CurTy),
1642 ValueList.getConstantFwdRef(Record[2],CurTy));
1645 case bitc::CST_CODE_CE_EXTRACTELT
1646 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1647 if (Record.size() < 3)
1648 return Error("Invalid record");
1650 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1652 return Error("Invalid record");
1653 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1654 Constant *Op1 = nullptr;
1655 if (Record.size() == 4) {
1656 Type *IdxTy = getTypeByID(Record[2]);
1658 return Error("Invalid record");
1659 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1660 } else // TODO: Remove with llvm 4.0
1661 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1663 return Error("Invalid record");
1664 V = ConstantExpr::getExtractElement(Op0, Op1);
1667 case bitc::CST_CODE_CE_INSERTELT
1668 : { // CE_INSERTELT: [opval, opval, opty, opval]
1669 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1670 if (Record.size() < 3 || !OpTy)
1671 return Error("Invalid record");
1672 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1673 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1674 OpTy->getElementType());
1675 Constant *Op2 = nullptr;
1676 if (Record.size() == 4) {
1677 Type *IdxTy = getTypeByID(Record[2]);
1679 return Error("Invalid record");
1680 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1681 } else // TODO: Remove with llvm 4.0
1682 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1684 return Error("Invalid record");
1685 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1688 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1689 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1690 if (Record.size() < 3 || !OpTy)
1691 return Error("Invalid record");
1692 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1693 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1694 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1695 OpTy->getNumElements());
1696 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1697 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1700 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1701 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1703 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1704 if (Record.size() < 4 || !RTy || !OpTy)
1705 return Error("Invalid record");
1706 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1707 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1708 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1709 RTy->getNumElements());
1710 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1711 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1714 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1715 if (Record.size() < 4)
1716 return Error("Invalid record");
1717 Type *OpTy = getTypeByID(Record[0]);
1719 return Error("Invalid record");
1720 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1721 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1723 if (OpTy->isFPOrFPVectorTy())
1724 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1726 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1729 // This maintains backward compatibility, pre-asm dialect keywords.
1730 // FIXME: Remove with the 4.0 release.
1731 case bitc::CST_CODE_INLINEASM_OLD: {
1732 if (Record.size() < 2)
1733 return Error("Invalid record");
1734 std::string AsmStr, ConstrStr;
1735 bool HasSideEffects = Record[0] & 1;
1736 bool IsAlignStack = Record[0] >> 1;
1737 unsigned AsmStrSize = Record[1];
1738 if (2+AsmStrSize >= Record.size())
1739 return Error("Invalid record");
1740 unsigned ConstStrSize = Record[2+AsmStrSize];
1741 if (3+AsmStrSize+ConstStrSize > Record.size())
1742 return Error("Invalid record");
1744 for (unsigned i = 0; i != AsmStrSize; ++i)
1745 AsmStr += (char)Record[2+i];
1746 for (unsigned i = 0; i != ConstStrSize; ++i)
1747 ConstrStr += (char)Record[3+AsmStrSize+i];
1748 PointerType *PTy = cast<PointerType>(CurTy);
1749 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1750 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1753 // This version adds support for the asm dialect keywords (e.g.,
1755 case bitc::CST_CODE_INLINEASM: {
1756 if (Record.size() < 2)
1757 return Error("Invalid record");
1758 std::string AsmStr, ConstrStr;
1759 bool HasSideEffects = Record[0] & 1;
1760 bool IsAlignStack = (Record[0] >> 1) & 1;
1761 unsigned AsmDialect = Record[0] >> 2;
1762 unsigned AsmStrSize = Record[1];
1763 if (2+AsmStrSize >= Record.size())
1764 return Error("Invalid record");
1765 unsigned ConstStrSize = Record[2+AsmStrSize];
1766 if (3+AsmStrSize+ConstStrSize > Record.size())
1767 return Error("Invalid record");
1769 for (unsigned i = 0; i != AsmStrSize; ++i)
1770 AsmStr += (char)Record[2+i];
1771 for (unsigned i = 0; i != ConstStrSize; ++i)
1772 ConstrStr += (char)Record[3+AsmStrSize+i];
1773 PointerType *PTy = cast<PointerType>(CurTy);
1774 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1775 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1776 InlineAsm::AsmDialect(AsmDialect));
1779 case bitc::CST_CODE_BLOCKADDRESS:{
1780 if (Record.size() < 3)
1781 return Error("Invalid record");
1782 Type *FnTy = getTypeByID(Record[0]);
1784 return Error("Invalid record");
1786 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1788 return Error("Invalid record");
1790 // Don't let Fn get dematerialized.
1791 BlockAddressesTaken.insert(Fn);
1793 // If the function is already parsed we can insert the block address right
1796 unsigned BBID = Record[2];
1798 // Invalid reference to entry block.
1799 return Error("Invalid ID");
1801 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1802 for (size_t I = 0, E = BBID; I != E; ++I) {
1804 return Error("Invalid ID");
1809 // Otherwise insert a placeholder and remember it so it can be inserted
1810 // when the function is parsed.
1811 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1813 BasicBlockFwdRefQueue.push_back(Fn);
1814 if (FwdBBs.size() < BBID + 1)
1815 FwdBBs.resize(BBID + 1);
1817 FwdBBs[BBID] = BasicBlock::Create(Context);
1820 V = BlockAddress::get(Fn, BB);
1825 ValueList.AssignValue(V, NextCstNo);
1830 std::error_code BitcodeReader::ParseUseLists() {
1831 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1832 return Error("Invalid record");
1834 // Read all the records.
1835 SmallVector<uint64_t, 64> Record;
1837 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1839 switch (Entry.Kind) {
1840 case BitstreamEntry::SubBlock: // Handled for us already.
1841 case BitstreamEntry::Error:
1842 return Error("Malformed block");
1843 case BitstreamEntry::EndBlock:
1844 return std::error_code();
1845 case BitstreamEntry::Record:
1846 // The interesting case.
1850 // Read a use list record.
1853 switch (Stream.readRecord(Entry.ID, Record)) {
1854 default: // Default behavior: unknown type.
1856 case bitc::USELIST_CODE_BB:
1859 case bitc::USELIST_CODE_DEFAULT: {
1860 unsigned RecordLength = Record.size();
1861 if (RecordLength < 3)
1862 // Records should have at least an ID and two indexes.
1863 return Error("Invalid record");
1864 unsigned ID = Record.back();
1869 assert(ID < FunctionBBs.size() && "Basic block not found");
1870 V = FunctionBBs[ID];
1873 unsigned NumUses = 0;
1874 SmallDenseMap<const Use *, unsigned, 16> Order;
1875 for (const Use &U : V->uses()) {
1876 if (++NumUses > Record.size())
1878 Order[&U] = Record[NumUses - 1];
1880 if (Order.size() != Record.size() || NumUses > Record.size())
1881 // Mismatches can happen if the functions are being materialized lazily
1882 // (out-of-order), or a value has been upgraded.
1885 V->sortUseList([&](const Use &L, const Use &R) {
1886 return Order.lookup(&L) < Order.lookup(&R);
1894 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1895 /// remember where it is and then skip it. This lets us lazily deserialize the
1897 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1898 // Get the function we are talking about.
1899 if (FunctionsWithBodies.empty())
1900 return Error("Insufficient function protos");
1902 Function *Fn = FunctionsWithBodies.back();
1903 FunctionsWithBodies.pop_back();
1905 // Save the current stream state.
1906 uint64_t CurBit = Stream.GetCurrentBitNo();
1907 DeferredFunctionInfo[Fn] = CurBit;
1909 // Skip over the function block for now.
1910 if (Stream.SkipBlock())
1911 return Error("Invalid record");
1912 return std::error_code();
1915 std::error_code BitcodeReader::GlobalCleanup() {
1916 // Patch the initializers for globals and aliases up.
1917 ResolveGlobalAndAliasInits();
1918 if (!GlobalInits.empty() || !AliasInits.empty())
1919 return Error("Malformed global initializer set");
1921 // Look for intrinsic functions which need to be upgraded at some point
1922 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1925 if (UpgradeIntrinsicFunction(FI, NewFn))
1926 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1929 // Look for global variables which need to be renamed.
1930 for (Module::global_iterator
1931 GI = TheModule->global_begin(), GE = TheModule->global_end();
1933 GlobalVariable *GV = GI++;
1934 UpgradeGlobalVariable(GV);
1937 // Force deallocation of memory for these vectors to favor the client that
1938 // want lazy deserialization.
1939 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1940 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1941 return std::error_code();
1944 std::error_code BitcodeReader::ParseModule(bool Resume) {
1946 Stream.JumpToBit(NextUnreadBit);
1947 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1948 return Error("Invalid record");
1950 SmallVector<uint64_t, 64> Record;
1951 std::vector<std::string> SectionTable;
1952 std::vector<std::string> GCTable;
1954 // Read all the records for this module.
1956 BitstreamEntry Entry = Stream.advance();
1958 switch (Entry.Kind) {
1959 case BitstreamEntry::Error:
1960 return Error("Malformed block");
1961 case BitstreamEntry::EndBlock:
1962 return GlobalCleanup();
1964 case BitstreamEntry::SubBlock:
1966 default: // Skip unknown content.
1967 if (Stream.SkipBlock())
1968 return Error("Invalid record");
1970 case bitc::BLOCKINFO_BLOCK_ID:
1971 if (Stream.ReadBlockInfoBlock())
1972 return Error("Malformed block");
1974 case bitc::PARAMATTR_BLOCK_ID:
1975 if (std::error_code EC = ParseAttributeBlock())
1978 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1979 if (std::error_code EC = ParseAttributeGroupBlock())
1982 case bitc::TYPE_BLOCK_ID_NEW:
1983 if (std::error_code EC = ParseTypeTable())
1986 case bitc::VALUE_SYMTAB_BLOCK_ID:
1987 if (std::error_code EC = ParseValueSymbolTable())
1989 SeenValueSymbolTable = true;
1991 case bitc::CONSTANTS_BLOCK_ID:
1992 if (std::error_code EC = ParseConstants())
1994 if (std::error_code EC = ResolveGlobalAndAliasInits())
1997 case bitc::METADATA_BLOCK_ID:
1998 if (std::error_code EC = ParseMetadata())
2001 case bitc::FUNCTION_BLOCK_ID:
2002 // If this is the first function body we've seen, reverse the
2003 // FunctionsWithBodies list.
2004 if (!SeenFirstFunctionBody) {
2005 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2006 if (std::error_code EC = GlobalCleanup())
2008 SeenFirstFunctionBody = true;
2011 if (std::error_code EC = RememberAndSkipFunctionBody())
2013 // For streaming bitcode, suspend parsing when we reach the function
2014 // bodies. Subsequent materialization calls will resume it when
2015 // necessary. For streaming, the function bodies must be at the end of
2016 // the bitcode. If the bitcode file is old, the symbol table will be
2017 // at the end instead and will not have been seen yet. In this case,
2018 // just finish the parse now.
2019 if (LazyStreamer && SeenValueSymbolTable) {
2020 NextUnreadBit = Stream.GetCurrentBitNo();
2021 return std::error_code();
2024 case bitc::USELIST_BLOCK_ID:
2025 if (std::error_code EC = ParseUseLists())
2031 case BitstreamEntry::Record:
2032 // The interesting case.
2038 switch (Stream.readRecord(Entry.ID, Record)) {
2039 default: break; // Default behavior, ignore unknown content.
2040 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2041 if (Record.size() < 1)
2042 return Error("Invalid record");
2043 // Only version #0 and #1 are supported so far.
2044 unsigned module_version = Record[0];
2045 switch (module_version) {
2047 return Error("Invalid value");
2049 UseRelativeIDs = false;
2052 UseRelativeIDs = true;
2057 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2059 if (ConvertToString(Record, 0, S))
2060 return Error("Invalid record");
2061 TheModule->setTargetTriple(S);
2064 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2066 if (ConvertToString(Record, 0, S))
2067 return Error("Invalid record");
2068 TheModule->setDataLayout(S);
2071 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2073 if (ConvertToString(Record, 0, S))
2074 return Error("Invalid record");
2075 TheModule->setModuleInlineAsm(S);
2078 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2079 // FIXME: Remove in 4.0.
2081 if (ConvertToString(Record, 0, S))
2082 return Error("Invalid record");
2086 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2088 if (ConvertToString(Record, 0, S))
2089 return Error("Invalid record");
2090 SectionTable.push_back(S);
2093 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2095 if (ConvertToString(Record, 0, S))
2096 return Error("Invalid record");
2097 GCTable.push_back(S);
2100 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2101 if (Record.size() < 2)
2102 return Error("Invalid record");
2103 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2104 unsigned ComdatNameSize = Record[1];
2105 std::string ComdatName;
2106 ComdatName.reserve(ComdatNameSize);
2107 for (unsigned i = 0; i != ComdatNameSize; ++i)
2108 ComdatName += (char)Record[2 + i];
2109 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2110 C->setSelectionKind(SK);
2111 ComdatList.push_back(C);
2114 // GLOBALVAR: [pointer type, isconst, initid,
2115 // linkage, alignment, section, visibility, threadlocal,
2116 // unnamed_addr, dllstorageclass]
2117 case bitc::MODULE_CODE_GLOBALVAR: {
2118 if (Record.size() < 6)
2119 return Error("Invalid record");
2120 Type *Ty = getTypeByID(Record[0]);
2122 return Error("Invalid record");
2123 if (!Ty->isPointerTy())
2124 return Error("Invalid type for value");
2125 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2126 Ty = cast<PointerType>(Ty)->getElementType();
2128 bool isConstant = Record[1];
2129 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Record[3]);
2130 unsigned Alignment = (1 << Record[4]) >> 1;
2131 std::string Section;
2133 if (Record[5]-1 >= SectionTable.size())
2134 return Error("Invalid ID");
2135 Section = SectionTable[Record[5]-1];
2137 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2138 // Local linkage must have default visibility.
2139 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2140 // FIXME: Change to an error if non-default in 4.0.
2141 Visibility = GetDecodedVisibility(Record[6]);
2143 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2144 if (Record.size() > 7)
2145 TLM = GetDecodedThreadLocalMode(Record[7]);
2147 bool UnnamedAddr = false;
2148 if (Record.size() > 8)
2149 UnnamedAddr = Record[8];
2151 bool ExternallyInitialized = false;
2152 if (Record.size() > 9)
2153 ExternallyInitialized = Record[9];
2155 GlobalVariable *NewGV =
2156 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2157 TLM, AddressSpace, ExternallyInitialized);
2158 NewGV->setAlignment(Alignment);
2159 if (!Section.empty())
2160 NewGV->setSection(Section);
2161 NewGV->setVisibility(Visibility);
2162 NewGV->setUnnamedAddr(UnnamedAddr);
2164 if (Record.size() > 10)
2165 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2167 UpgradeDLLImportExportLinkage(NewGV, Record[3]);
2169 ValueList.push_back(NewGV);
2171 // Remember which value to use for the global initializer.
2172 if (unsigned InitID = Record[2])
2173 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2175 if (Record.size() > 11)
2176 if (unsigned ComdatID = Record[11]) {
2177 assert(ComdatID <= ComdatList.size());
2178 NewGV->setComdat(ComdatList[ComdatID - 1]);
2182 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2183 // alignment, section, visibility, gc, unnamed_addr,
2184 // prologuedata, dllstorageclass, comdat, prefixdata]
2185 case bitc::MODULE_CODE_FUNCTION: {
2186 if (Record.size() < 8)
2187 return Error("Invalid record");
2188 Type *Ty = getTypeByID(Record[0]);
2190 return Error("Invalid record");
2191 if (!Ty->isPointerTy())
2192 return Error("Invalid type for value");
2194 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2196 return Error("Invalid type for value");
2198 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2201 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2202 bool isProto = Record[2];
2203 Func->setLinkage(getDecodedLinkage(Record[3]));
2204 Func->setAttributes(getAttributes(Record[4]));
2206 Func->setAlignment((1 << Record[5]) >> 1);
2208 if (Record[6]-1 >= SectionTable.size())
2209 return Error("Invalid ID");
2210 Func->setSection(SectionTable[Record[6]-1]);
2212 // Local linkage must have default visibility.
2213 if (!Func->hasLocalLinkage())
2214 // FIXME: Change to an error if non-default in 4.0.
2215 Func->setVisibility(GetDecodedVisibility(Record[7]));
2216 if (Record.size() > 8 && Record[8]) {
2217 if (Record[8]-1 > GCTable.size())
2218 return Error("Invalid ID");
2219 Func->setGC(GCTable[Record[8]-1].c_str());
2221 bool UnnamedAddr = false;
2222 if (Record.size() > 9)
2223 UnnamedAddr = Record[9];
2224 Func->setUnnamedAddr(UnnamedAddr);
2225 if (Record.size() > 10 && Record[10] != 0)
2226 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2228 if (Record.size() > 11)
2229 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2231 UpgradeDLLImportExportLinkage(Func, Record[3]);
2233 if (Record.size() > 12)
2234 if (unsigned ComdatID = Record[12]) {
2235 assert(ComdatID <= ComdatList.size());
2236 Func->setComdat(ComdatList[ComdatID - 1]);
2239 if (Record.size() > 13 && Record[13] != 0)
2240 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2242 ValueList.push_back(Func);
2244 // If this is a function with a body, remember the prototype we are
2245 // creating now, so that we can match up the body with them later.
2247 Func->setIsMaterializable(true);
2248 FunctionsWithBodies.push_back(Func);
2250 DeferredFunctionInfo[Func] = 0;
2254 // ALIAS: [alias type, aliasee val#, linkage]
2255 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2256 case bitc::MODULE_CODE_ALIAS: {
2257 if (Record.size() < 3)
2258 return Error("Invalid record");
2259 Type *Ty = getTypeByID(Record[0]);
2261 return Error("Invalid record");
2262 auto *PTy = dyn_cast<PointerType>(Ty);
2264 return Error("Invalid type for value");
2267 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2268 getDecodedLinkage(Record[2]), "", TheModule);
2269 // Old bitcode files didn't have visibility field.
2270 // Local linkage must have default visibility.
2271 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2272 // FIXME: Change to an error if non-default in 4.0.
2273 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2274 if (Record.size() > 4)
2275 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2277 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2278 if (Record.size() > 5)
2279 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2280 if (Record.size() > 6)
2281 NewGA->setUnnamedAddr(Record[6]);
2282 ValueList.push_back(NewGA);
2283 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2286 /// MODULE_CODE_PURGEVALS: [numvals]
2287 case bitc::MODULE_CODE_PURGEVALS:
2288 // Trim down the value list to the specified size.
2289 if (Record.size() < 1 || Record[0] > ValueList.size())
2290 return Error("Invalid record");
2291 ValueList.shrinkTo(Record[0]);
2298 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2299 TheModule = nullptr;
2301 if (std::error_code EC = InitStream())
2304 // Sniff for the signature.
2305 if (Stream.Read(8) != 'B' ||
2306 Stream.Read(8) != 'C' ||
2307 Stream.Read(4) != 0x0 ||
2308 Stream.Read(4) != 0xC ||
2309 Stream.Read(4) != 0xE ||
2310 Stream.Read(4) != 0xD)
2311 return Error("Invalid bitcode signature");
2313 // We expect a number of well-defined blocks, though we don't necessarily
2314 // need to understand them all.
2316 if (Stream.AtEndOfStream())
2317 return std::error_code();
2319 BitstreamEntry Entry =
2320 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2322 switch (Entry.Kind) {
2323 case BitstreamEntry::Error:
2324 return Error("Malformed block");
2325 case BitstreamEntry::EndBlock:
2326 return std::error_code();
2328 case BitstreamEntry::SubBlock:
2330 case bitc::BLOCKINFO_BLOCK_ID:
2331 if (Stream.ReadBlockInfoBlock())
2332 return Error("Malformed block");
2334 case bitc::MODULE_BLOCK_ID:
2335 // Reject multiple MODULE_BLOCK's in a single bitstream.
2337 return Error("Invalid multiple blocks");
2339 if (std::error_code EC = ParseModule(false))
2342 return std::error_code();
2345 if (Stream.SkipBlock())
2346 return Error("Invalid record");
2350 case BitstreamEntry::Record:
2351 // There should be no records in the top-level of blocks.
2353 // The ranlib in Xcode 4 will align archive members by appending newlines
2354 // to the end of them. If this file size is a multiple of 4 but not 8, we
2355 // have to read and ignore these final 4 bytes :-(
2356 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2357 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2358 Stream.AtEndOfStream())
2359 return std::error_code();
2361 return Error("Invalid record");
2366 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2367 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2368 return Error("Invalid record");
2370 SmallVector<uint64_t, 64> Record;
2373 // Read all the records for this module.
2375 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2377 switch (Entry.Kind) {
2378 case BitstreamEntry::SubBlock: // Handled for us already.
2379 case BitstreamEntry::Error:
2380 return Error("Malformed block");
2381 case BitstreamEntry::EndBlock:
2383 case BitstreamEntry::Record:
2384 // The interesting case.
2389 switch (Stream.readRecord(Entry.ID, Record)) {
2390 default: break; // Default behavior, ignore unknown content.
2391 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2393 if (ConvertToString(Record, 0, S))
2394 return Error("Invalid record");
2401 llvm_unreachable("Exit infinite loop");
2404 ErrorOr<std::string> BitcodeReader::parseTriple() {
2405 if (std::error_code EC = InitStream())
2408 // Sniff for the signature.
2409 if (Stream.Read(8) != 'B' ||
2410 Stream.Read(8) != 'C' ||
2411 Stream.Read(4) != 0x0 ||
2412 Stream.Read(4) != 0xC ||
2413 Stream.Read(4) != 0xE ||
2414 Stream.Read(4) != 0xD)
2415 return Error("Invalid bitcode signature");
2417 // We expect a number of well-defined blocks, though we don't necessarily
2418 // need to understand them all.
2420 BitstreamEntry Entry = Stream.advance();
2422 switch (Entry.Kind) {
2423 case BitstreamEntry::Error:
2424 return Error("Malformed block");
2425 case BitstreamEntry::EndBlock:
2426 return std::error_code();
2428 case BitstreamEntry::SubBlock:
2429 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2430 return parseModuleTriple();
2432 // Ignore other sub-blocks.
2433 if (Stream.SkipBlock())
2434 return Error("Malformed block");
2437 case BitstreamEntry::Record:
2438 Stream.skipRecord(Entry.ID);
2444 /// ParseMetadataAttachment - Parse metadata attachments.
2445 std::error_code BitcodeReader::ParseMetadataAttachment() {
2446 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2447 return Error("Invalid record");
2449 SmallVector<uint64_t, 64> Record;
2451 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2453 switch (Entry.Kind) {
2454 case BitstreamEntry::SubBlock: // Handled for us already.
2455 case BitstreamEntry::Error:
2456 return Error("Malformed block");
2457 case BitstreamEntry::EndBlock:
2458 return std::error_code();
2459 case BitstreamEntry::Record:
2460 // The interesting case.
2464 // Read a metadata attachment record.
2466 switch (Stream.readRecord(Entry.ID, Record)) {
2467 default: // Default behavior: ignore.
2469 case bitc::METADATA_ATTACHMENT: {
2470 unsigned RecordLength = Record.size();
2471 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2472 return Error("Invalid record");
2473 Instruction *Inst = InstructionList[Record[0]];
2474 for (unsigned i = 1; i != RecordLength; i = i+2) {
2475 unsigned Kind = Record[i];
2476 DenseMap<unsigned, unsigned>::iterator I =
2477 MDKindMap.find(Kind);
2478 if (I == MDKindMap.end())
2479 return Error("Invalid ID");
2480 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2481 if (isa<LocalAsMetadata>(Node))
2482 // Drop the attachment. This used to be legal, but there's no
2485 Inst->setMetadata(I->second, cast<MDNode>(Node));
2486 if (I->second == LLVMContext::MD_tbaa)
2487 InstsWithTBAATag.push_back(Inst);
2495 /// ParseFunctionBody - Lazily parse the specified function body block.
2496 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2497 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2498 return Error("Invalid record");
2500 InstructionList.clear();
2501 unsigned ModuleValueListSize = ValueList.size();
2502 unsigned ModuleMDValueListSize = MDValueList.size();
2504 // Add all the function arguments to the value table.
2505 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2506 ValueList.push_back(I);
2508 unsigned NextValueNo = ValueList.size();
2509 BasicBlock *CurBB = nullptr;
2510 unsigned CurBBNo = 0;
2513 auto getLastInstruction = [&]() -> Instruction * {
2514 if (CurBB && !CurBB->empty())
2515 return &CurBB->back();
2516 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2517 !FunctionBBs[CurBBNo - 1]->empty())
2518 return &FunctionBBs[CurBBNo - 1]->back();
2522 // Read all the records.
2523 SmallVector<uint64_t, 64> Record;
2525 BitstreamEntry Entry = Stream.advance();
2527 switch (Entry.Kind) {
2528 case BitstreamEntry::Error:
2529 return Error("Malformed block");
2530 case BitstreamEntry::EndBlock:
2531 goto OutOfRecordLoop;
2533 case BitstreamEntry::SubBlock:
2535 default: // Skip unknown content.
2536 if (Stream.SkipBlock())
2537 return Error("Invalid record");
2539 case bitc::CONSTANTS_BLOCK_ID:
2540 if (std::error_code EC = ParseConstants())
2542 NextValueNo = ValueList.size();
2544 case bitc::VALUE_SYMTAB_BLOCK_ID:
2545 if (std::error_code EC = ParseValueSymbolTable())
2548 case bitc::METADATA_ATTACHMENT_ID:
2549 if (std::error_code EC = ParseMetadataAttachment())
2552 case bitc::METADATA_BLOCK_ID:
2553 if (std::error_code EC = ParseMetadata())
2556 case bitc::USELIST_BLOCK_ID:
2557 if (std::error_code EC = ParseUseLists())
2563 case BitstreamEntry::Record:
2564 // The interesting case.
2570 Instruction *I = nullptr;
2571 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2573 default: // Default behavior: reject
2574 return Error("Invalid value");
2575 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2576 if (Record.size() < 1 || Record[0] == 0)
2577 return Error("Invalid record");
2578 // Create all the basic blocks for the function.
2579 FunctionBBs.resize(Record[0]);
2581 // See if anything took the address of blocks in this function.
2582 auto BBFRI = BasicBlockFwdRefs.find(F);
2583 if (BBFRI == BasicBlockFwdRefs.end()) {
2584 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2585 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2587 auto &BBRefs = BBFRI->second;
2588 // Check for invalid basic block references.
2589 if (BBRefs.size() > FunctionBBs.size())
2590 return Error("Invalid ID");
2591 assert(!BBRefs.empty() && "Unexpected empty array");
2592 assert(!BBRefs.front() && "Invalid reference to entry block");
2593 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2595 if (I < RE && BBRefs[I]) {
2596 BBRefs[I]->insertInto(F);
2597 FunctionBBs[I] = BBRefs[I];
2599 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2602 // Erase from the table.
2603 BasicBlockFwdRefs.erase(BBFRI);
2606 CurBB = FunctionBBs[0];
2610 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2611 // This record indicates that the last instruction is at the same
2612 // location as the previous instruction with a location.
2613 I = getLastInstruction();
2616 return Error("Invalid record");
2617 I->setDebugLoc(LastLoc);
2621 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2622 I = getLastInstruction();
2623 if (!I || Record.size() < 4)
2624 return Error("Invalid record");
2626 unsigned Line = Record[0], Col = Record[1];
2627 unsigned ScopeID = Record[2], IAID = Record[3];
2629 MDNode *Scope = nullptr, *IA = nullptr;
2630 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2631 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2632 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2633 I->setDebugLoc(LastLoc);
2638 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2641 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2642 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2643 OpNum+1 > Record.size())
2644 return Error("Invalid record");
2646 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2648 return Error("Invalid record");
2649 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2650 InstructionList.push_back(I);
2651 if (OpNum < Record.size()) {
2652 if (Opc == Instruction::Add ||
2653 Opc == Instruction::Sub ||
2654 Opc == Instruction::Mul ||
2655 Opc == Instruction::Shl) {
2656 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2657 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2658 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2659 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2660 } else if (Opc == Instruction::SDiv ||
2661 Opc == Instruction::UDiv ||
2662 Opc == Instruction::LShr ||
2663 Opc == Instruction::AShr) {
2664 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2665 cast<BinaryOperator>(I)->setIsExact(true);
2666 } else if (isa<FPMathOperator>(I)) {
2668 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2669 FMF.setUnsafeAlgebra();
2670 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2672 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2674 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2675 FMF.setNoSignedZeros();
2676 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2677 FMF.setAllowReciprocal();
2679 I->setFastMathFlags(FMF);
2685 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2688 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2689 OpNum+2 != Record.size())
2690 return Error("Invalid record");
2692 Type *ResTy = getTypeByID(Record[OpNum]);
2693 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2694 if (Opc == -1 || !ResTy)
2695 return Error("Invalid record");
2696 Instruction *Temp = nullptr;
2697 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2699 InstructionList.push_back(Temp);
2700 CurBB->getInstList().push_back(Temp);
2703 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2705 InstructionList.push_back(I);
2708 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2709 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2712 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2713 return Error("Invalid record");
2715 SmallVector<Value*, 16> GEPIdx;
2716 while (OpNum != Record.size()) {
2718 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2719 return Error("Invalid record");
2720 GEPIdx.push_back(Op);
2723 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2724 InstructionList.push_back(I);
2725 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2726 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2730 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2731 // EXTRACTVAL: [opty, opval, n x indices]
2734 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2735 return Error("Invalid record");
2737 SmallVector<unsigned, 4> EXTRACTVALIdx;
2738 for (unsigned RecSize = Record.size();
2739 OpNum != RecSize; ++OpNum) {
2740 uint64_t Index = Record[OpNum];
2741 if ((unsigned)Index != Index)
2742 return Error("Invalid value");
2743 EXTRACTVALIdx.push_back((unsigned)Index);
2746 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2747 InstructionList.push_back(I);
2751 case bitc::FUNC_CODE_INST_INSERTVAL: {
2752 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2755 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2756 return Error("Invalid record");
2758 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2759 return Error("Invalid record");
2761 SmallVector<unsigned, 4> INSERTVALIdx;
2762 for (unsigned RecSize = Record.size();
2763 OpNum != RecSize; ++OpNum) {
2764 uint64_t Index = Record[OpNum];
2765 if ((unsigned)Index != Index)
2766 return Error("Invalid value");
2767 INSERTVALIdx.push_back((unsigned)Index);
2770 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2771 InstructionList.push_back(I);
2775 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2776 // obsolete form of select
2777 // handles select i1 ... in old bitcode
2779 Value *TrueVal, *FalseVal, *Cond;
2780 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2781 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2782 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2783 return Error("Invalid record");
2785 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2786 InstructionList.push_back(I);
2790 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2791 // new form of select
2792 // handles select i1 or select [N x i1]
2794 Value *TrueVal, *FalseVal, *Cond;
2795 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2796 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2797 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2798 return Error("Invalid record");
2800 // select condition can be either i1 or [N x i1]
2801 if (VectorType* vector_type =
2802 dyn_cast<VectorType>(Cond->getType())) {
2804 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2805 return Error("Invalid type for value");
2808 if (Cond->getType() != Type::getInt1Ty(Context))
2809 return Error("Invalid type for value");
2812 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2813 InstructionList.push_back(I);
2817 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2820 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2821 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2822 return Error("Invalid record");
2823 I = ExtractElementInst::Create(Vec, Idx);
2824 InstructionList.push_back(I);
2828 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2830 Value *Vec, *Elt, *Idx;
2831 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2832 popValue(Record, OpNum, NextValueNo,
2833 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2834 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2835 return Error("Invalid record");
2836 I = InsertElementInst::Create(Vec, Elt, Idx);
2837 InstructionList.push_back(I);
2841 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2843 Value *Vec1, *Vec2, *Mask;
2844 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2845 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2846 return Error("Invalid record");
2848 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2849 return Error("Invalid record");
2850 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2851 InstructionList.push_back(I);
2855 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2856 // Old form of ICmp/FCmp returning bool
2857 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2858 // both legal on vectors but had different behaviour.
2859 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2860 // FCmp/ICmp returning bool or vector of bool
2864 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2865 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2866 OpNum+1 != Record.size())
2867 return Error("Invalid record");
2869 if (LHS->getType()->isFPOrFPVectorTy())
2870 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2872 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2873 InstructionList.push_back(I);
2877 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2879 unsigned Size = Record.size();
2881 I = ReturnInst::Create(Context);
2882 InstructionList.push_back(I);
2887 Value *Op = nullptr;
2888 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2889 return Error("Invalid record");
2890 if (OpNum != Record.size())
2891 return Error("Invalid record");
2893 I = ReturnInst::Create(Context, Op);
2894 InstructionList.push_back(I);
2897 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2898 if (Record.size() != 1 && Record.size() != 3)
2899 return Error("Invalid record");
2900 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2902 return Error("Invalid record");
2904 if (Record.size() == 1) {
2905 I = BranchInst::Create(TrueDest);
2906 InstructionList.push_back(I);
2909 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2910 Value *Cond = getValue(Record, 2, NextValueNo,
2911 Type::getInt1Ty(Context));
2912 if (!FalseDest || !Cond)
2913 return Error("Invalid record");
2914 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2915 InstructionList.push_back(I);
2919 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2921 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2922 // "New" SwitchInst format with case ranges. The changes to write this
2923 // format were reverted but we still recognize bitcode that uses it.
2924 // Hopefully someday we will have support for case ranges and can use
2925 // this format again.
2927 Type *OpTy = getTypeByID(Record[1]);
2928 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2930 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2931 BasicBlock *Default = getBasicBlock(Record[3]);
2932 if (!OpTy || !Cond || !Default)
2933 return Error("Invalid record");
2935 unsigned NumCases = Record[4];
2937 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2938 InstructionList.push_back(SI);
2940 unsigned CurIdx = 5;
2941 for (unsigned i = 0; i != NumCases; ++i) {
2942 SmallVector<ConstantInt*, 1> CaseVals;
2943 unsigned NumItems = Record[CurIdx++];
2944 for (unsigned ci = 0; ci != NumItems; ++ci) {
2945 bool isSingleNumber = Record[CurIdx++];
2948 unsigned ActiveWords = 1;
2949 if (ValueBitWidth > 64)
2950 ActiveWords = Record[CurIdx++];
2951 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2953 CurIdx += ActiveWords;
2955 if (!isSingleNumber) {
2957 if (ValueBitWidth > 64)
2958 ActiveWords = Record[CurIdx++];
2960 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2962 CurIdx += ActiveWords;
2964 // FIXME: It is not clear whether values in the range should be
2965 // compared as signed or unsigned values. The partially
2966 // implemented changes that used this format in the past used
2967 // unsigned comparisons.
2968 for ( ; Low.ule(High); ++Low)
2969 CaseVals.push_back(ConstantInt::get(Context, Low));
2971 CaseVals.push_back(ConstantInt::get(Context, Low));
2973 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2974 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2975 cve = CaseVals.end(); cvi != cve; ++cvi)
2976 SI->addCase(*cvi, DestBB);
2982 // Old SwitchInst format without case ranges.
2984 if (Record.size() < 3 || (Record.size() & 1) == 0)
2985 return Error("Invalid record");
2986 Type *OpTy = getTypeByID(Record[0]);
2987 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2988 BasicBlock *Default = getBasicBlock(Record[2]);
2989 if (!OpTy || !Cond || !Default)
2990 return Error("Invalid record");
2991 unsigned NumCases = (Record.size()-3)/2;
2992 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2993 InstructionList.push_back(SI);
2994 for (unsigned i = 0, e = NumCases; i != e; ++i) {
2995 ConstantInt *CaseVal =
2996 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2997 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2998 if (!CaseVal || !DestBB) {
3000 return Error("Invalid record");
3002 SI->addCase(CaseVal, DestBB);
3007 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3008 if (Record.size() < 2)
3009 return Error("Invalid record");
3010 Type *OpTy = getTypeByID(Record[0]);
3011 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3012 if (!OpTy || !Address)
3013 return Error("Invalid record");
3014 unsigned NumDests = Record.size()-2;
3015 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3016 InstructionList.push_back(IBI);
3017 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3018 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3019 IBI->addDestination(DestBB);
3022 return Error("Invalid record");
3029 case bitc::FUNC_CODE_INST_INVOKE: {
3030 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3031 if (Record.size() < 4)
3032 return Error("Invalid record");
3033 AttributeSet PAL = getAttributes(Record[0]);
3034 unsigned CCInfo = Record[1];
3035 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3036 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3040 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3041 return Error("Invalid record");
3043 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3044 FunctionType *FTy = !CalleeTy ? nullptr :
3045 dyn_cast<FunctionType>(CalleeTy->getElementType());
3047 // Check that the right number of fixed parameters are here.
3048 if (!FTy || !NormalBB || !UnwindBB ||
3049 Record.size() < OpNum+FTy->getNumParams())
3050 return Error("Invalid record");
3052 SmallVector<Value*, 16> Ops;
3053 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3054 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3055 FTy->getParamType(i)));
3057 return Error("Invalid record");
3060 if (!FTy->isVarArg()) {
3061 if (Record.size() != OpNum)
3062 return Error("Invalid record");
3064 // Read type/value pairs for varargs params.
3065 while (OpNum != Record.size()) {
3067 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3068 return Error("Invalid record");
3073 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3074 InstructionList.push_back(I);
3075 cast<InvokeInst>(I)->setCallingConv(
3076 static_cast<CallingConv::ID>(CCInfo));
3077 cast<InvokeInst>(I)->setAttributes(PAL);
3080 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3082 Value *Val = nullptr;
3083 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3084 return Error("Invalid record");
3085 I = ResumeInst::Create(Val);
3086 InstructionList.push_back(I);
3089 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3090 I = new UnreachableInst(Context);
3091 InstructionList.push_back(I);
3093 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3094 if (Record.size() < 1 || ((Record.size()-1)&1))
3095 return Error("Invalid record");
3096 Type *Ty = getTypeByID(Record[0]);
3098 return Error("Invalid record");
3100 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3101 InstructionList.push_back(PN);
3103 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3105 // With the new function encoding, it is possible that operands have
3106 // negative IDs (for forward references). Use a signed VBR
3107 // representation to keep the encoding small.
3109 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3111 V = getValue(Record, 1+i, NextValueNo, Ty);
3112 BasicBlock *BB = getBasicBlock(Record[2+i]);
3114 return Error("Invalid record");
3115 PN->addIncoming(V, BB);
3121 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3122 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3124 if (Record.size() < 4)
3125 return Error("Invalid record");
3126 Type *Ty = getTypeByID(Record[Idx++]);
3128 return Error("Invalid record");
3129 Value *PersFn = nullptr;
3130 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3131 return Error("Invalid record");
3133 bool IsCleanup = !!Record[Idx++];
3134 unsigned NumClauses = Record[Idx++];
3135 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3136 LP->setCleanup(IsCleanup);
3137 for (unsigned J = 0; J != NumClauses; ++J) {
3138 LandingPadInst::ClauseType CT =
3139 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3142 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3144 return Error("Invalid record");
3147 assert((CT != LandingPadInst::Catch ||
3148 !isa<ArrayType>(Val->getType())) &&
3149 "Catch clause has a invalid type!");
3150 assert((CT != LandingPadInst::Filter ||
3151 isa<ArrayType>(Val->getType())) &&
3152 "Filter clause has invalid type!");
3153 LP->addClause(cast<Constant>(Val));
3157 InstructionList.push_back(I);
3161 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3162 if (Record.size() != 4)
3163 return Error("Invalid record");
3165 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3166 Type *OpTy = getTypeByID(Record[1]);
3167 Value *Size = getFnValueByID(Record[2], OpTy);
3168 unsigned AlignRecord = Record[3];
3169 bool InAlloca = AlignRecord & (1 << 5);
3170 unsigned Align = AlignRecord & ((1 << 5) - 1);
3172 return Error("Invalid record");
3173 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3174 AI->setUsedWithInAlloca(InAlloca);
3176 InstructionList.push_back(I);
3179 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3182 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3183 OpNum+2 != Record.size())
3184 return Error("Invalid record");
3186 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3187 InstructionList.push_back(I);
3190 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3191 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3194 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3195 OpNum+4 != Record.size())
3196 return Error("Invalid record");
3198 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3199 if (Ordering == NotAtomic || Ordering == Release ||
3200 Ordering == AcquireRelease)
3201 return Error("Invalid record");
3202 if (Ordering != NotAtomic && Record[OpNum] == 0)
3203 return Error("Invalid record");
3204 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3206 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3207 Ordering, SynchScope);
3208 InstructionList.push_back(I);
3211 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3214 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3215 popValue(Record, OpNum, NextValueNo,
3216 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3217 OpNum+2 != Record.size())
3218 return Error("Invalid record");
3220 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3221 InstructionList.push_back(I);
3224 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3225 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3228 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3229 popValue(Record, OpNum, NextValueNo,
3230 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3231 OpNum+4 != Record.size())
3232 return Error("Invalid record");
3234 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3235 if (Ordering == NotAtomic || Ordering == Acquire ||
3236 Ordering == AcquireRelease)
3237 return Error("Invalid record");
3238 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3239 if (Ordering != NotAtomic && Record[OpNum] == 0)
3240 return Error("Invalid record");
3242 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3243 Ordering, SynchScope);
3244 InstructionList.push_back(I);
3247 case bitc::FUNC_CODE_INST_CMPXCHG: {
3248 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3249 // failureordering?, isweak?]
3251 Value *Ptr, *Cmp, *New;
3252 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3253 popValue(Record, OpNum, NextValueNo,
3254 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3255 popValue(Record, OpNum, NextValueNo,
3256 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3257 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3258 return Error("Invalid record");
3259 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3260 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3261 return Error("Invalid record");
3262 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3264 AtomicOrdering FailureOrdering;
3265 if (Record.size() < 7)
3267 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3269 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3271 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3273 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3275 if (Record.size() < 8) {
3276 // Before weak cmpxchgs existed, the instruction simply returned the
3277 // value loaded from memory, so bitcode files from that era will be
3278 // expecting the first component of a modern cmpxchg.
3279 CurBB->getInstList().push_back(I);
3280 I = ExtractValueInst::Create(I, 0);
3282 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3285 InstructionList.push_back(I);
3288 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3289 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3292 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3293 popValue(Record, OpNum, NextValueNo,
3294 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3295 OpNum+4 != Record.size())
3296 return Error("Invalid record");
3297 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3298 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3299 Operation > AtomicRMWInst::LAST_BINOP)
3300 return Error("Invalid record");
3301 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3302 if (Ordering == NotAtomic || Ordering == Unordered)
3303 return Error("Invalid record");
3304 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3305 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3306 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3307 InstructionList.push_back(I);
3310 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3311 if (2 != Record.size())
3312 return Error("Invalid record");
3313 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3314 if (Ordering == NotAtomic || Ordering == Unordered ||
3315 Ordering == Monotonic)
3316 return Error("Invalid record");
3317 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3318 I = new FenceInst(Context, Ordering, SynchScope);
3319 InstructionList.push_back(I);
3322 case bitc::FUNC_CODE_INST_CALL: {
3323 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3324 if (Record.size() < 3)
3325 return Error("Invalid record");
3327 AttributeSet PAL = getAttributes(Record[0]);
3328 unsigned CCInfo = Record[1];
3332 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3333 return Error("Invalid record");
3335 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3336 FunctionType *FTy = nullptr;
3337 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3338 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3339 return Error("Invalid record");
3341 SmallVector<Value*, 16> Args;
3342 // Read the fixed params.
3343 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3344 if (FTy->getParamType(i)->isLabelTy())
3345 Args.push_back(getBasicBlock(Record[OpNum]));
3347 Args.push_back(getValue(Record, OpNum, NextValueNo,
3348 FTy->getParamType(i)));
3350 return Error("Invalid record");
3353 // Read type/value pairs for varargs params.
3354 if (!FTy->isVarArg()) {
3355 if (OpNum != Record.size())
3356 return Error("Invalid record");
3358 while (OpNum != Record.size()) {
3360 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3361 return Error("Invalid record");
3366 I = CallInst::Create(Callee, Args);
3367 InstructionList.push_back(I);
3368 cast<CallInst>(I)->setCallingConv(
3369 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3370 CallInst::TailCallKind TCK = CallInst::TCK_None;
3372 TCK = CallInst::TCK_Tail;
3373 if (CCInfo & (1 << 14))
3374 TCK = CallInst::TCK_MustTail;
3375 cast<CallInst>(I)->setTailCallKind(TCK);
3376 cast<CallInst>(I)->setAttributes(PAL);
3379 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3380 if (Record.size() < 3)
3381 return Error("Invalid record");
3382 Type *OpTy = getTypeByID(Record[0]);
3383 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3384 Type *ResTy = getTypeByID(Record[2]);
3385 if (!OpTy || !Op || !ResTy)
3386 return Error("Invalid record");
3387 I = new VAArgInst(Op, ResTy);
3388 InstructionList.push_back(I);
3393 // Add instruction to end of current BB. If there is no current BB, reject
3397 return Error("Invalid instruction with no BB");
3399 CurBB->getInstList().push_back(I);
3401 // If this was a terminator instruction, move to the next block.
3402 if (isa<TerminatorInst>(I)) {
3404 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3407 // Non-void values get registered in the value table for future use.
3408 if (I && !I->getType()->isVoidTy())
3409 ValueList.AssignValue(I, NextValueNo++);
3414 // Check the function list for unresolved values.
3415 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3416 if (!A->getParent()) {
3417 // We found at least one unresolved value. Nuke them all to avoid leaks.
3418 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3419 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3420 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3424 return Error("Never resolved value found in function");
3428 // FIXME: Check for unresolved forward-declared metadata references
3429 // and clean up leaks.
3431 // Trim the value list down to the size it was before we parsed this function.
3432 ValueList.shrinkTo(ModuleValueListSize);
3433 MDValueList.shrinkTo(ModuleMDValueListSize);
3434 std::vector<BasicBlock*>().swap(FunctionBBs);
3435 return std::error_code();
3438 /// Find the function body in the bitcode stream
3439 std::error_code BitcodeReader::FindFunctionInStream(
3441 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3442 while (DeferredFunctionInfoIterator->second == 0) {
3443 if (Stream.AtEndOfStream())
3444 return Error("Could not find function in stream");
3445 // ParseModule will parse the next body in the stream and set its
3446 // position in the DeferredFunctionInfo map.
3447 if (std::error_code EC = ParseModule(true))
3450 return std::error_code();
3453 //===----------------------------------------------------------------------===//
3454 // GVMaterializer implementation
3455 //===----------------------------------------------------------------------===//
3457 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3459 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3460 Function *F = dyn_cast<Function>(GV);
3461 // If it's not a function or is already material, ignore the request.
3462 if (!F || !F->isMaterializable())
3463 return std::error_code();
3465 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3466 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3467 // If its position is recorded as 0, its body is somewhere in the stream
3468 // but we haven't seen it yet.
3469 if (DFII->second == 0 && LazyStreamer)
3470 if (std::error_code EC = FindFunctionInStream(F, DFII))
3473 // Move the bit stream to the saved position of the deferred function body.
3474 Stream.JumpToBit(DFII->second);
3476 if (std::error_code EC = ParseFunctionBody(F))
3478 F->setIsMaterializable(false);
3480 // Upgrade any old intrinsic calls in the function.
3481 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3482 E = UpgradedIntrinsics.end(); I != E; ++I) {
3483 if (I->first != I->second) {
3484 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3486 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3487 UpgradeIntrinsicCall(CI, I->second);
3492 // Bring in any functions that this function forward-referenced via
3494 return materializeForwardReferencedFunctions();
3497 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3498 const Function *F = dyn_cast<Function>(GV);
3499 if (!F || F->isDeclaration())
3502 // Dematerializing F would leave dangling references that wouldn't be
3503 // reconnected on re-materialization.
3504 if (BlockAddressesTaken.count(F))
3507 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3510 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3511 Function *F = dyn_cast<Function>(GV);
3512 // If this function isn't dematerializable, this is a noop.
3513 if (!F || !isDematerializable(F))
3516 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3518 // Just forget the function body, we can remat it later.
3519 F->dropAllReferences();
3520 F->setIsMaterializable(true);
3523 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3524 assert(M == TheModule &&
3525 "Can only Materialize the Module this BitcodeReader is attached to.");
3527 // Promise to materialize all forward references.
3528 WillMaterializeAllForwardRefs = true;
3530 // Iterate over the module, deserializing any functions that are still on
3532 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3534 if (std::error_code EC = materialize(F))
3537 // At this point, if there are any function bodies, the current bit is
3538 // pointing to the END_BLOCK record after them. Now make sure the rest
3539 // of the bits in the module have been read.
3543 // Check that all block address forward references got resolved (as we
3545 if (!BasicBlockFwdRefs.empty())
3546 return Error("Never resolved function from blockaddress");
3548 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3549 // delete the old functions to clean up. We can't do this unless the entire
3550 // module is materialized because there could always be another function body
3551 // with calls to the old function.
3552 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3553 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3554 if (I->first != I->second) {
3555 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3557 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3558 UpgradeIntrinsicCall(CI, I->second);
3560 if (!I->first->use_empty())
3561 I->first->replaceAllUsesWith(I->second);
3562 I->first->eraseFromParent();
3565 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3567 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3568 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3570 UpgradeDebugInfo(*M);
3571 return std::error_code();
3574 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3575 return IdentifiedStructTypes;
3578 std::error_code BitcodeReader::InitStream() {
3580 return InitLazyStream();
3581 return InitStreamFromBuffer();
3584 std::error_code BitcodeReader::InitStreamFromBuffer() {
3585 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3586 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3588 if (Buffer->getBufferSize() & 3)
3589 return Error("Invalid bitcode signature");
3591 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3592 // The magic number is 0x0B17C0DE stored in little endian.
3593 if (isBitcodeWrapper(BufPtr, BufEnd))
3594 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3595 return Error("Invalid bitcode wrapper header");
3597 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3598 Stream.init(&*StreamFile);
3600 return std::error_code();
3603 std::error_code BitcodeReader::InitLazyStream() {
3604 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3606 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3607 StreamingMemoryObject &Bytes = *OwnedBytes;
3608 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3609 Stream.init(&*StreamFile);
3611 unsigned char buf[16];
3612 if (Bytes.readBytes(buf, 16, 0) != 16)
3613 return Error("Invalid bitcode signature");
3615 if (!isBitcode(buf, buf + 16))
3616 return Error("Invalid bitcode signature");
3618 if (isBitcodeWrapper(buf, buf + 4)) {
3619 const unsigned char *bitcodeStart = buf;
3620 const unsigned char *bitcodeEnd = buf + 16;
3621 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3622 Bytes.dropLeadingBytes(bitcodeStart - buf);
3623 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3625 return std::error_code();
3629 class BitcodeErrorCategoryType : public std::error_category {
3630 const char *name() const LLVM_NOEXCEPT override {
3631 return "llvm.bitcode";
3633 std::string message(int IE) const override {
3634 BitcodeError E = static_cast<BitcodeError>(IE);
3636 case BitcodeError::InvalidBitcodeSignature:
3637 return "Invalid bitcode signature";
3638 case BitcodeError::CorruptedBitcode:
3639 return "Corrupted bitcode";
3641 llvm_unreachable("Unknown error type!");
3646 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3648 const std::error_category &llvm::BitcodeErrorCategory() {
3649 return *ErrorCategory;
3652 //===----------------------------------------------------------------------===//
3653 // External interface
3654 //===----------------------------------------------------------------------===//
3656 /// \brief Get a lazy one-at-time loading module from bitcode.
3658 /// This isn't always used in a lazy context. In particular, it's also used by
3659 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3660 /// in forward-referenced functions from block address references.
3662 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3663 /// materialize everything -- in particular, if this isn't truly lazy.
3664 static ErrorOr<Module *>
3665 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3666 LLVMContext &Context, bool WillMaterializeAll,
3667 DiagnosticHandlerFunction DiagnosticHandler) {
3668 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3670 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3671 M->setMaterializer(R);
3673 auto cleanupOnError = [&](std::error_code EC) {
3674 R->releaseBuffer(); // Never take ownership on error.
3675 delete M; // Also deletes R.
3679 if (std::error_code EC = R->ParseBitcodeInto(M))
3680 return cleanupOnError(EC);
3682 if (!WillMaterializeAll)
3683 // Resolve forward references from blockaddresses.
3684 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3685 return cleanupOnError(EC);
3687 Buffer.release(); // The BitcodeReader owns it now.
3692 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3693 LLVMContext &Context,
3694 DiagnosticHandlerFunction DiagnosticHandler) {
3695 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3699 ErrorOr<std::unique_ptr<Module>>
3700 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3701 LLVMContext &Context,
3702 DiagnosticHandlerFunction DiagnosticHandler) {
3703 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3704 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
3705 M->setMaterializer(R);
3706 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3708 return std::move(M);
3712 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3713 DiagnosticHandlerFunction DiagnosticHandler) {
3714 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3715 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3716 std::move(Buf), Context, true, DiagnosticHandler);
3719 Module *M = ModuleOrErr.get();
3720 // Read in the entire module, and destroy the BitcodeReader.
3721 if (std::error_code EC = M->materializeAllPermanently()) {
3726 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3727 // written. We must defer until the Module has been fully materialized.
3733 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3734 DiagnosticHandlerFunction DiagnosticHandler) {
3735 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3736 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3738 ErrorOr<std::string> Triple = R->parseTriple();
3739 if (Triple.getError())
3741 return Triple.get();