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/ManagedStatic.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.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 bool hasImplicitComdat(size_t Val) {
163 case 1: // Old WeakAnyLinkage
164 case 4: // Old LinkOnceAnyLinkage
165 case 10: // Old WeakODRLinkage
166 case 11: // Old LinkOnceODRLinkage
171 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
173 default: // Map unknown/new linkages to external
175 return GlobalValue::ExternalLinkage;
177 return GlobalValue::AppendingLinkage;
179 return GlobalValue::InternalLinkage;
181 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
183 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
185 return GlobalValue::ExternalWeakLinkage;
187 return GlobalValue::CommonLinkage;
189 return GlobalValue::PrivateLinkage;
191 return GlobalValue::AvailableExternallyLinkage;
193 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
195 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
197 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
198 case 1: // Old value with implicit comdat.
200 return GlobalValue::WeakAnyLinkage;
201 case 10: // Old value with implicit comdat.
203 return GlobalValue::WeakODRLinkage;
204 case 4: // Old value with implicit comdat.
206 return GlobalValue::LinkOnceAnyLinkage;
207 case 11: // Old value with implicit comdat.
209 return GlobalValue::LinkOnceODRLinkage;
213 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
215 default: // Map unknown visibilities to default.
216 case 0: return GlobalValue::DefaultVisibility;
217 case 1: return GlobalValue::HiddenVisibility;
218 case 2: return GlobalValue::ProtectedVisibility;
222 static GlobalValue::DLLStorageClassTypes
223 GetDecodedDLLStorageClass(unsigned Val) {
225 default: // Map unknown values to default.
226 case 0: return GlobalValue::DefaultStorageClass;
227 case 1: return GlobalValue::DLLImportStorageClass;
228 case 2: return GlobalValue::DLLExportStorageClass;
232 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
234 case 0: return GlobalVariable::NotThreadLocal;
235 default: // Map unknown non-zero value to general dynamic.
236 case 1: return GlobalVariable::GeneralDynamicTLSModel;
237 case 2: return GlobalVariable::LocalDynamicTLSModel;
238 case 3: return GlobalVariable::InitialExecTLSModel;
239 case 4: return GlobalVariable::LocalExecTLSModel;
243 static int GetDecodedCastOpcode(unsigned Val) {
246 case bitc::CAST_TRUNC : return Instruction::Trunc;
247 case bitc::CAST_ZEXT : return Instruction::ZExt;
248 case bitc::CAST_SEXT : return Instruction::SExt;
249 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
250 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
251 case bitc::CAST_UITOFP : return Instruction::UIToFP;
252 case bitc::CAST_SITOFP : return Instruction::SIToFP;
253 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
254 case bitc::CAST_FPEXT : return Instruction::FPExt;
255 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
256 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
257 case bitc::CAST_BITCAST : return Instruction::BitCast;
258 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
261 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
264 case bitc::BINOP_ADD:
265 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
266 case bitc::BINOP_SUB:
267 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
268 case bitc::BINOP_MUL:
269 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
270 case bitc::BINOP_UDIV: return Instruction::UDiv;
271 case bitc::BINOP_SDIV:
272 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
273 case bitc::BINOP_UREM: return Instruction::URem;
274 case bitc::BINOP_SREM:
275 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
276 case bitc::BINOP_SHL: return Instruction::Shl;
277 case bitc::BINOP_LSHR: return Instruction::LShr;
278 case bitc::BINOP_ASHR: return Instruction::AShr;
279 case bitc::BINOP_AND: return Instruction::And;
280 case bitc::BINOP_OR: return Instruction::Or;
281 case bitc::BINOP_XOR: return Instruction::Xor;
285 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
287 default: return AtomicRMWInst::BAD_BINOP;
288 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
289 case bitc::RMW_ADD: return AtomicRMWInst::Add;
290 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
291 case bitc::RMW_AND: return AtomicRMWInst::And;
292 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
293 case bitc::RMW_OR: return AtomicRMWInst::Or;
294 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
295 case bitc::RMW_MAX: return AtomicRMWInst::Max;
296 case bitc::RMW_MIN: return AtomicRMWInst::Min;
297 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
298 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
302 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
304 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
305 case bitc::ORDERING_UNORDERED: return Unordered;
306 case bitc::ORDERING_MONOTONIC: return Monotonic;
307 case bitc::ORDERING_ACQUIRE: return Acquire;
308 case bitc::ORDERING_RELEASE: return Release;
309 case bitc::ORDERING_ACQREL: return AcquireRelease;
310 default: // Map unknown orderings to sequentially-consistent.
311 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
315 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
317 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
318 default: // Map unknown scopes to cross-thread.
319 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
323 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
325 default: // Map unknown selection kinds to any.
326 case bitc::COMDAT_SELECTION_KIND_ANY:
328 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
329 return Comdat::ExactMatch;
330 case bitc::COMDAT_SELECTION_KIND_LARGEST:
331 return Comdat::Largest;
332 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
333 return Comdat::NoDuplicates;
334 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
335 return Comdat::SameSize;
339 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
341 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
342 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
348 /// @brief A class for maintaining the slot number definition
349 /// as a placeholder for the actual definition for forward constants defs.
350 class ConstantPlaceHolder : public ConstantExpr {
351 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
353 // allocate space for exactly one operand
354 void *operator new(size_t s) {
355 return User::operator new(s, 1);
357 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
358 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
359 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
362 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
363 static bool classof(const Value *V) {
364 return isa<ConstantExpr>(V) &&
365 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
369 /// Provide fast operand accessors
370 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
374 // FIXME: can we inherit this from ConstantExpr?
376 struct OperandTraits<ConstantPlaceHolder> :
377 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
379 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
383 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
392 WeakVH &OldV = ValuePtrs[Idx];
398 // Handle constants and non-constants (e.g. instrs) differently for
400 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
401 ResolveConstants.push_back(std::make_pair(PHC, Idx));
404 // If there was a forward reference to this value, replace it.
405 Value *PrevVal = OldV;
406 OldV->replaceAllUsesWith(V);
412 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
417 if (Value *V = ValuePtrs[Idx]) {
418 assert(Ty == V->getType() && "Type mismatch in constant table!");
419 return cast<Constant>(V);
422 // Create and return a placeholder, which will later be RAUW'd.
423 Constant *C = new ConstantPlaceHolder(Ty, Context);
428 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
432 if (Value *V = ValuePtrs[Idx]) {
433 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
437 // No type specified, must be invalid reference.
438 if (!Ty) return nullptr;
440 // Create and return a placeholder, which will later be RAUW'd.
441 Value *V = new Argument(Ty);
446 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
447 /// resolves any forward references. The idea behind this is that we sometimes
448 /// get constants (such as large arrays) which reference *many* forward ref
449 /// constants. Replacing each of these causes a lot of thrashing when
450 /// building/reuniquing the constant. Instead of doing this, we look at all the
451 /// uses and rewrite all the place holders at once for any constant that uses
453 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
454 // Sort the values by-pointer so that they are efficient to look up with a
456 std::sort(ResolveConstants.begin(), ResolveConstants.end());
458 SmallVector<Constant*, 64> NewOps;
460 while (!ResolveConstants.empty()) {
461 Value *RealVal = operator[](ResolveConstants.back().second);
462 Constant *Placeholder = ResolveConstants.back().first;
463 ResolveConstants.pop_back();
465 // Loop over all users of the placeholder, updating them to reference the
466 // new value. If they reference more than one placeholder, update them all
468 while (!Placeholder->use_empty()) {
469 auto UI = Placeholder->user_begin();
472 // If the using object isn't uniqued, just update the operands. This
473 // handles instructions and initializers for global variables.
474 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
475 UI.getUse().set(RealVal);
479 // Otherwise, we have a constant that uses the placeholder. Replace that
480 // constant with a new constant that has *all* placeholder uses updated.
481 Constant *UserC = cast<Constant>(U);
482 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
485 if (!isa<ConstantPlaceHolder>(*I)) {
486 // Not a placeholder reference.
488 } else if (*I == Placeholder) {
489 // Common case is that it just references this one placeholder.
492 // Otherwise, look up the placeholder in ResolveConstants.
493 ResolveConstantsTy::iterator It =
494 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
495 std::pair<Constant*, unsigned>(cast<Constant>(*I),
497 assert(It != ResolveConstants.end() && It->first == *I);
498 NewOp = operator[](It->second);
501 NewOps.push_back(cast<Constant>(NewOp));
504 // Make the new constant.
506 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
507 NewC = ConstantArray::get(UserCA->getType(), NewOps);
508 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
509 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
510 } else if (isa<ConstantVector>(UserC)) {
511 NewC = ConstantVector::get(NewOps);
513 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
514 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
517 UserC->replaceAllUsesWith(NewC);
518 UserC->destroyConstant();
522 // Update all ValueHandles, they should be the only users at this point.
523 Placeholder->replaceAllUsesWith(RealVal);
528 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
537 TrackingMDRef &OldMD = MDValuePtrs[Idx];
543 // If there was a forward reference to this value, replace it.
544 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
545 PrevMD->replaceAllUsesWith(MD);
549 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
553 if (Metadata *MD = MDValuePtrs[Idx])
556 // Create and return a placeholder, which will later be RAUW'd.
559 Metadata *MD = MDNode::getTemporary(Context, None).release();
560 MDValuePtrs[Idx].reset(MD);
564 void BitcodeReaderMDValueList::tryToResolveCycles() {
570 // Still forward references... can't resolve cycles.
573 // Resolve any cycles.
574 for (auto &MD : MDValuePtrs) {
575 auto *N = dyn_cast_or_null<UniquableMDNode>(MD);
579 assert(!N->isTemporary() && "Unexpected forward reference");
584 Type *BitcodeReader::getTypeByID(unsigned ID) {
585 // The type table size is always specified correctly.
586 if (ID >= TypeList.size())
589 if (Type *Ty = TypeList[ID])
592 // If we have a forward reference, the only possible case is when it is to a
593 // named struct. Just create a placeholder for now.
594 return TypeList[ID] = createIdentifiedStructType(Context);
597 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
599 auto *Ret = StructType::create(Context, Name);
600 IdentifiedStructTypes.push_back(Ret);
604 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
605 auto *Ret = StructType::create(Context);
606 IdentifiedStructTypes.push_back(Ret);
611 //===----------------------------------------------------------------------===//
612 // Functions for parsing blocks from the bitcode file
613 //===----------------------------------------------------------------------===//
616 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
617 /// been decoded from the given integer. This function must stay in sync with
618 /// 'encodeLLVMAttributesForBitcode'.
619 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
620 uint64_t EncodedAttrs) {
621 // FIXME: Remove in 4.0.
623 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
624 // the bits above 31 down by 11 bits.
625 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
626 assert((!Alignment || isPowerOf2_32(Alignment)) &&
627 "Alignment must be a power of two.");
630 B.addAlignmentAttr(Alignment);
631 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
632 (EncodedAttrs & 0xffff));
635 std::error_code BitcodeReader::ParseAttributeBlock() {
636 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
637 return Error("Invalid record");
639 if (!MAttributes.empty())
640 return Error("Invalid multiple blocks");
642 SmallVector<uint64_t, 64> Record;
644 SmallVector<AttributeSet, 8> Attrs;
646 // Read all the records.
648 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
650 switch (Entry.Kind) {
651 case BitstreamEntry::SubBlock: // Handled for us already.
652 case BitstreamEntry::Error:
653 return Error("Malformed block");
654 case BitstreamEntry::EndBlock:
655 return std::error_code();
656 case BitstreamEntry::Record:
657 // The interesting case.
663 switch (Stream.readRecord(Entry.ID, Record)) {
664 default: // Default behavior: ignore.
666 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
667 // FIXME: Remove in 4.0.
668 if (Record.size() & 1)
669 return Error("Invalid record");
671 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
673 decodeLLVMAttributesForBitcode(B, Record[i+1]);
674 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
677 MAttributes.push_back(AttributeSet::get(Context, Attrs));
681 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
682 for (unsigned i = 0, e = Record.size(); i != e; ++i)
683 Attrs.push_back(MAttributeGroups[Record[i]]);
685 MAttributes.push_back(AttributeSet::get(Context, Attrs));
693 // Returns Attribute::None on unrecognized codes.
694 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
697 return Attribute::None;
698 case bitc::ATTR_KIND_ALIGNMENT:
699 return Attribute::Alignment;
700 case bitc::ATTR_KIND_ALWAYS_INLINE:
701 return Attribute::AlwaysInline;
702 case bitc::ATTR_KIND_BUILTIN:
703 return Attribute::Builtin;
704 case bitc::ATTR_KIND_BY_VAL:
705 return Attribute::ByVal;
706 case bitc::ATTR_KIND_IN_ALLOCA:
707 return Attribute::InAlloca;
708 case bitc::ATTR_KIND_COLD:
709 return Attribute::Cold;
710 case bitc::ATTR_KIND_INLINE_HINT:
711 return Attribute::InlineHint;
712 case bitc::ATTR_KIND_IN_REG:
713 return Attribute::InReg;
714 case bitc::ATTR_KIND_JUMP_TABLE:
715 return Attribute::JumpTable;
716 case bitc::ATTR_KIND_MIN_SIZE:
717 return Attribute::MinSize;
718 case bitc::ATTR_KIND_NAKED:
719 return Attribute::Naked;
720 case bitc::ATTR_KIND_NEST:
721 return Attribute::Nest;
722 case bitc::ATTR_KIND_NO_ALIAS:
723 return Attribute::NoAlias;
724 case bitc::ATTR_KIND_NO_BUILTIN:
725 return Attribute::NoBuiltin;
726 case bitc::ATTR_KIND_NO_CAPTURE:
727 return Attribute::NoCapture;
728 case bitc::ATTR_KIND_NO_DUPLICATE:
729 return Attribute::NoDuplicate;
730 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
731 return Attribute::NoImplicitFloat;
732 case bitc::ATTR_KIND_NO_INLINE:
733 return Attribute::NoInline;
734 case bitc::ATTR_KIND_NON_LAZY_BIND:
735 return Attribute::NonLazyBind;
736 case bitc::ATTR_KIND_NON_NULL:
737 return Attribute::NonNull;
738 case bitc::ATTR_KIND_DEREFERENCEABLE:
739 return Attribute::Dereferenceable;
740 case bitc::ATTR_KIND_NO_RED_ZONE:
741 return Attribute::NoRedZone;
742 case bitc::ATTR_KIND_NO_RETURN:
743 return Attribute::NoReturn;
744 case bitc::ATTR_KIND_NO_UNWIND:
745 return Attribute::NoUnwind;
746 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
747 return Attribute::OptimizeForSize;
748 case bitc::ATTR_KIND_OPTIMIZE_NONE:
749 return Attribute::OptimizeNone;
750 case bitc::ATTR_KIND_READ_NONE:
751 return Attribute::ReadNone;
752 case bitc::ATTR_KIND_READ_ONLY:
753 return Attribute::ReadOnly;
754 case bitc::ATTR_KIND_RETURNED:
755 return Attribute::Returned;
756 case bitc::ATTR_KIND_RETURNS_TWICE:
757 return Attribute::ReturnsTwice;
758 case bitc::ATTR_KIND_S_EXT:
759 return Attribute::SExt;
760 case bitc::ATTR_KIND_STACK_ALIGNMENT:
761 return Attribute::StackAlignment;
762 case bitc::ATTR_KIND_STACK_PROTECT:
763 return Attribute::StackProtect;
764 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
765 return Attribute::StackProtectReq;
766 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
767 return Attribute::StackProtectStrong;
768 case bitc::ATTR_KIND_STRUCT_RET:
769 return Attribute::StructRet;
770 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
771 return Attribute::SanitizeAddress;
772 case bitc::ATTR_KIND_SANITIZE_THREAD:
773 return Attribute::SanitizeThread;
774 case bitc::ATTR_KIND_SANITIZE_MEMORY:
775 return Attribute::SanitizeMemory;
776 case bitc::ATTR_KIND_UW_TABLE:
777 return Attribute::UWTable;
778 case bitc::ATTR_KIND_Z_EXT:
779 return Attribute::ZExt;
783 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
784 Attribute::AttrKind *Kind) {
785 *Kind = GetAttrFromCode(Code);
786 if (*Kind == Attribute::None)
787 return Error(BitcodeError::CorruptedBitcode,
788 "Unknown attribute kind (" + Twine(Code) + ")");
789 return std::error_code();
792 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
793 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
794 return Error("Invalid record");
796 if (!MAttributeGroups.empty())
797 return Error("Invalid multiple blocks");
799 SmallVector<uint64_t, 64> Record;
801 // Read all the records.
803 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
805 switch (Entry.Kind) {
806 case BitstreamEntry::SubBlock: // Handled for us already.
807 case BitstreamEntry::Error:
808 return Error("Malformed block");
809 case BitstreamEntry::EndBlock:
810 return std::error_code();
811 case BitstreamEntry::Record:
812 // The interesting case.
818 switch (Stream.readRecord(Entry.ID, Record)) {
819 default: // Default behavior: ignore.
821 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
822 if (Record.size() < 3)
823 return Error("Invalid record");
825 uint64_t GrpID = Record[0];
826 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
829 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
830 if (Record[i] == 0) { // Enum attribute
831 Attribute::AttrKind Kind;
832 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
835 B.addAttribute(Kind);
836 } else if (Record[i] == 1) { // Integer attribute
837 Attribute::AttrKind Kind;
838 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
840 if (Kind == Attribute::Alignment)
841 B.addAlignmentAttr(Record[++i]);
842 else if (Kind == Attribute::StackAlignment)
843 B.addStackAlignmentAttr(Record[++i]);
844 else if (Kind == Attribute::Dereferenceable)
845 B.addDereferenceableAttr(Record[++i]);
846 } else { // String attribute
847 assert((Record[i] == 3 || Record[i] == 4) &&
848 "Invalid attribute group entry");
849 bool HasValue = (Record[i++] == 4);
850 SmallString<64> KindStr;
851 SmallString<64> ValStr;
853 while (Record[i] != 0 && i != e)
854 KindStr += Record[i++];
855 assert(Record[i] == 0 && "Kind string not null terminated");
858 // Has a value associated with it.
859 ++i; // Skip the '0' that terminates the "kind" string.
860 while (Record[i] != 0 && i != e)
861 ValStr += Record[i++];
862 assert(Record[i] == 0 && "Value string not null terminated");
865 B.addAttribute(KindStr.str(), ValStr.str());
869 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
876 std::error_code BitcodeReader::ParseTypeTable() {
877 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
878 return Error("Invalid record");
880 return ParseTypeTableBody();
883 std::error_code BitcodeReader::ParseTypeTableBody() {
884 if (!TypeList.empty())
885 return Error("Invalid multiple blocks");
887 SmallVector<uint64_t, 64> Record;
888 unsigned NumRecords = 0;
890 SmallString<64> TypeName;
892 // Read all the records for this type table.
894 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
896 switch (Entry.Kind) {
897 case BitstreamEntry::SubBlock: // Handled for us already.
898 case BitstreamEntry::Error:
899 return Error("Malformed block");
900 case BitstreamEntry::EndBlock:
901 if (NumRecords != TypeList.size())
902 return Error("Malformed block");
903 return std::error_code();
904 case BitstreamEntry::Record:
905 // The interesting case.
911 Type *ResultTy = nullptr;
912 switch (Stream.readRecord(Entry.ID, Record)) {
914 return Error("Invalid value");
915 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
916 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
917 // type list. This allows us to reserve space.
918 if (Record.size() < 1)
919 return Error("Invalid record");
920 TypeList.resize(Record[0]);
922 case bitc::TYPE_CODE_VOID: // VOID
923 ResultTy = Type::getVoidTy(Context);
925 case bitc::TYPE_CODE_HALF: // HALF
926 ResultTy = Type::getHalfTy(Context);
928 case bitc::TYPE_CODE_FLOAT: // FLOAT
929 ResultTy = Type::getFloatTy(Context);
931 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
932 ResultTy = Type::getDoubleTy(Context);
934 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
935 ResultTy = Type::getX86_FP80Ty(Context);
937 case bitc::TYPE_CODE_FP128: // FP128
938 ResultTy = Type::getFP128Ty(Context);
940 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
941 ResultTy = Type::getPPC_FP128Ty(Context);
943 case bitc::TYPE_CODE_LABEL: // LABEL
944 ResultTy = Type::getLabelTy(Context);
946 case bitc::TYPE_CODE_METADATA: // METADATA
947 ResultTy = Type::getMetadataTy(Context);
949 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
950 ResultTy = Type::getX86_MMXTy(Context);
952 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
953 if (Record.size() < 1)
954 return Error("Invalid record");
956 ResultTy = IntegerType::get(Context, Record[0]);
958 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
959 // [pointee type, address space]
960 if (Record.size() < 1)
961 return Error("Invalid record");
962 unsigned AddressSpace = 0;
963 if (Record.size() == 2)
964 AddressSpace = Record[1];
965 ResultTy = getTypeByID(Record[0]);
967 return Error("Invalid type");
968 ResultTy = PointerType::get(ResultTy, AddressSpace);
971 case bitc::TYPE_CODE_FUNCTION_OLD: {
972 // FIXME: attrid is dead, remove it in LLVM 4.0
973 // FUNCTION: [vararg, attrid, retty, paramty x N]
974 if (Record.size() < 3)
975 return Error("Invalid record");
976 SmallVector<Type*, 8> ArgTys;
977 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
978 if (Type *T = getTypeByID(Record[i]))
984 ResultTy = getTypeByID(Record[2]);
985 if (!ResultTy || ArgTys.size() < Record.size()-3)
986 return Error("Invalid type");
988 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
991 case bitc::TYPE_CODE_FUNCTION: {
992 // FUNCTION: [vararg, retty, paramty x N]
993 if (Record.size() < 2)
994 return Error("Invalid record");
995 SmallVector<Type*, 8> ArgTys;
996 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
997 if (Type *T = getTypeByID(Record[i]))
1003 ResultTy = getTypeByID(Record[1]);
1004 if (!ResultTy || ArgTys.size() < Record.size()-2)
1005 return Error("Invalid type");
1007 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1010 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1011 if (Record.size() < 1)
1012 return Error("Invalid record");
1013 SmallVector<Type*, 8> EltTys;
1014 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1015 if (Type *T = getTypeByID(Record[i]))
1016 EltTys.push_back(T);
1020 if (EltTys.size() != Record.size()-1)
1021 return Error("Invalid type");
1022 ResultTy = StructType::get(Context, EltTys, Record[0]);
1025 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1026 if (ConvertToString(Record, 0, TypeName))
1027 return Error("Invalid record");
1030 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1031 if (Record.size() < 1)
1032 return Error("Invalid record");
1034 if (NumRecords >= TypeList.size())
1035 return Error("Invalid TYPE table");
1037 // Check to see if this was forward referenced, if so fill in the temp.
1038 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1040 Res->setName(TypeName);
1041 TypeList[NumRecords] = nullptr;
1042 } else // Otherwise, create a new struct.
1043 Res = createIdentifiedStructType(Context, TypeName);
1046 SmallVector<Type*, 8> EltTys;
1047 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1048 if (Type *T = getTypeByID(Record[i]))
1049 EltTys.push_back(T);
1053 if (EltTys.size() != Record.size()-1)
1054 return Error("Invalid record");
1055 Res->setBody(EltTys, Record[0]);
1059 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1060 if (Record.size() != 1)
1061 return Error("Invalid record");
1063 if (NumRecords >= TypeList.size())
1064 return Error("Invalid TYPE table");
1066 // Check to see if this was forward referenced, if so fill in the temp.
1067 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1069 Res->setName(TypeName);
1070 TypeList[NumRecords] = nullptr;
1071 } else // Otherwise, create a new struct with no body.
1072 Res = createIdentifiedStructType(Context, TypeName);
1077 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1078 if (Record.size() < 2)
1079 return Error("Invalid record");
1080 if ((ResultTy = getTypeByID(Record[1])))
1081 ResultTy = ArrayType::get(ResultTy, Record[0]);
1083 return Error("Invalid type");
1085 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1086 if (Record.size() < 2)
1087 return Error("Invalid record");
1088 if ((ResultTy = getTypeByID(Record[1])))
1089 ResultTy = VectorType::get(ResultTy, Record[0]);
1091 return Error("Invalid type");
1095 if (NumRecords >= TypeList.size())
1096 return Error("Invalid TYPE table");
1097 assert(ResultTy && "Didn't read a type?");
1098 assert(!TypeList[NumRecords] && "Already read type?");
1099 TypeList[NumRecords++] = ResultTy;
1103 std::error_code BitcodeReader::ParseValueSymbolTable() {
1104 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1105 return Error("Invalid record");
1107 SmallVector<uint64_t, 64> Record;
1109 // Read all the records for this value table.
1110 SmallString<128> ValueName;
1112 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1114 switch (Entry.Kind) {
1115 case BitstreamEntry::SubBlock: // Handled for us already.
1116 case BitstreamEntry::Error:
1117 return Error("Malformed block");
1118 case BitstreamEntry::EndBlock:
1119 return std::error_code();
1120 case BitstreamEntry::Record:
1121 // The interesting case.
1127 switch (Stream.readRecord(Entry.ID, Record)) {
1128 default: // Default behavior: unknown type.
1130 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1131 if (ConvertToString(Record, 1, ValueName))
1132 return Error("Invalid record");
1133 unsigned ValueID = Record[0];
1134 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1135 return Error("Invalid record");
1136 Value *V = ValueList[ValueID];
1138 V->setName(StringRef(ValueName.data(), ValueName.size()));
1139 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1140 if (GO->getComdat() == reinterpret_cast<Comdat *>(1))
1141 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1146 case bitc::VST_CODE_BBENTRY: {
1147 if (ConvertToString(Record, 1, ValueName))
1148 return Error("Invalid record");
1149 BasicBlock *BB = getBasicBlock(Record[0]);
1151 return Error("Invalid record");
1153 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1161 std::error_code BitcodeReader::ParseMetadata() {
1162 unsigned NextMDValueNo = MDValueList.size();
1164 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1165 return Error("Invalid record");
1167 SmallVector<uint64_t, 64> Record;
1169 // Read all the records.
1171 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1173 switch (Entry.Kind) {
1174 case BitstreamEntry::SubBlock: // Handled for us already.
1175 case BitstreamEntry::Error:
1176 return Error("Malformed block");
1177 case BitstreamEntry::EndBlock:
1178 MDValueList.tryToResolveCycles();
1179 return std::error_code();
1180 case BitstreamEntry::Record:
1181 // The interesting case.
1187 unsigned Code = Stream.readRecord(Entry.ID, Record);
1188 bool IsDistinct = false;
1190 default: // Default behavior: ignore.
1192 case bitc::METADATA_NAME: {
1193 // Read name of the named metadata.
1194 SmallString<8> Name(Record.begin(), Record.end());
1196 Code = Stream.ReadCode();
1198 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1199 unsigned NextBitCode = Stream.readRecord(Code, Record);
1200 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1202 // Read named metadata elements.
1203 unsigned Size = Record.size();
1204 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1205 for (unsigned i = 0; i != Size; ++i) {
1206 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1208 return Error("Invalid record");
1209 NMD->addOperand(MD);
1213 case bitc::METADATA_OLD_FN_NODE: {
1214 // FIXME: Remove in 4.0.
1215 // This is a LocalAsMetadata record, the only type of function-local
1217 if (Record.size() % 2 == 1)
1218 return Error("Invalid record");
1220 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1221 // to be legal, but there's no upgrade path.
1222 auto dropRecord = [&] {
1223 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1225 if (Record.size() != 2) {
1230 Type *Ty = getTypeByID(Record[0]);
1231 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1236 MDValueList.AssignValue(
1237 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1241 case bitc::METADATA_OLD_NODE: {
1242 // FIXME: Remove in 4.0.
1243 if (Record.size() % 2 == 1)
1244 return Error("Invalid record");
1246 unsigned Size = Record.size();
1247 SmallVector<Metadata *, 8> Elts;
1248 for (unsigned i = 0; i != Size; i += 2) {
1249 Type *Ty = getTypeByID(Record[i]);
1251 return Error("Invalid record");
1252 if (Ty->isMetadataTy())
1253 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1254 else if (!Ty->isVoidTy()) {
1256 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1257 assert(isa<ConstantAsMetadata>(MD) &&
1258 "Expected non-function-local metadata");
1261 Elts.push_back(nullptr);
1263 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1266 case bitc::METADATA_VALUE: {
1267 if (Record.size() != 2)
1268 return Error("Invalid record");
1270 Type *Ty = getTypeByID(Record[0]);
1271 if (Ty->isMetadataTy() || Ty->isVoidTy())
1272 return Error("Invalid record");
1274 MDValueList.AssignValue(
1275 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1279 case bitc::METADATA_DISTINCT_NODE:
1282 case bitc::METADATA_NODE: {
1283 SmallVector<Metadata *, 8> Elts;
1284 Elts.reserve(Record.size());
1285 for (unsigned ID : Record)
1286 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1287 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1288 : MDNode::get(Context, Elts),
1292 case bitc::METADATA_LOCATION: {
1293 if (Record.size() != 5)
1294 return Error("Invalid record");
1296 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1297 unsigned Line = Record[1];
1298 unsigned Column = Record[2];
1299 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1300 Metadata *InlinedAt =
1301 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1302 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1306 case bitc::METADATA_STRING: {
1307 std::string String(Record.begin(), Record.end());
1308 llvm::UpgradeMDStringConstant(String);
1309 Metadata *MD = MDString::get(Context, String);
1310 MDValueList.AssignValue(MD, NextMDValueNo++);
1313 case bitc::METADATA_KIND: {
1314 if (Record.size() < 2)
1315 return Error("Invalid record");
1317 unsigned Kind = Record[0];
1318 SmallString<8> Name(Record.begin()+1, Record.end());
1320 unsigned NewKind = TheModule->getMDKindID(Name.str());
1321 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1322 return Error("Conflicting METADATA_KIND records");
1329 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1330 /// the LSB for dense VBR encoding.
1331 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1336 // There is no such thing as -0 with integers. "-0" really means MININT.
1340 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1341 /// values and aliases that we can.
1342 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1343 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1344 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1345 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1346 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1348 GlobalInitWorklist.swap(GlobalInits);
1349 AliasInitWorklist.swap(AliasInits);
1350 FunctionPrefixWorklist.swap(FunctionPrefixes);
1351 FunctionPrologueWorklist.swap(FunctionPrologues);
1353 while (!GlobalInitWorklist.empty()) {
1354 unsigned ValID = GlobalInitWorklist.back().second;
1355 if (ValID >= ValueList.size()) {
1356 // Not ready to resolve this yet, it requires something later in the file.
1357 GlobalInits.push_back(GlobalInitWorklist.back());
1359 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1360 GlobalInitWorklist.back().first->setInitializer(C);
1362 return Error("Expected a constant");
1364 GlobalInitWorklist.pop_back();
1367 while (!AliasInitWorklist.empty()) {
1368 unsigned ValID = AliasInitWorklist.back().second;
1369 if (ValID >= ValueList.size()) {
1370 AliasInits.push_back(AliasInitWorklist.back());
1372 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1373 AliasInitWorklist.back().first->setAliasee(C);
1375 return Error("Expected a constant");
1377 AliasInitWorklist.pop_back();
1380 while (!FunctionPrefixWorklist.empty()) {
1381 unsigned ValID = FunctionPrefixWorklist.back().second;
1382 if (ValID >= ValueList.size()) {
1383 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1385 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1386 FunctionPrefixWorklist.back().first->setPrefixData(C);
1388 return Error("Expected a constant");
1390 FunctionPrefixWorklist.pop_back();
1393 while (!FunctionPrologueWorklist.empty()) {
1394 unsigned ValID = FunctionPrologueWorklist.back().second;
1395 if (ValID >= ValueList.size()) {
1396 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1398 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1399 FunctionPrologueWorklist.back().first->setPrologueData(C);
1401 return Error("Expected a constant");
1403 FunctionPrologueWorklist.pop_back();
1406 return std::error_code();
1409 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1410 SmallVector<uint64_t, 8> Words(Vals.size());
1411 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1412 BitcodeReader::decodeSignRotatedValue);
1414 return APInt(TypeBits, Words);
1417 std::error_code BitcodeReader::ParseConstants() {
1418 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1419 return Error("Invalid record");
1421 SmallVector<uint64_t, 64> Record;
1423 // Read all the records for this value table.
1424 Type *CurTy = Type::getInt32Ty(Context);
1425 unsigned NextCstNo = ValueList.size();
1427 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1429 switch (Entry.Kind) {
1430 case BitstreamEntry::SubBlock: // Handled for us already.
1431 case BitstreamEntry::Error:
1432 return Error("Malformed block");
1433 case BitstreamEntry::EndBlock:
1434 if (NextCstNo != ValueList.size())
1435 return Error("Invalid ronstant reference");
1437 // Once all the constants have been read, go through and resolve forward
1439 ValueList.ResolveConstantForwardRefs();
1440 return std::error_code();
1441 case BitstreamEntry::Record:
1442 // The interesting case.
1449 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1451 default: // Default behavior: unknown constant
1452 case bitc::CST_CODE_UNDEF: // UNDEF
1453 V = UndefValue::get(CurTy);
1455 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1457 return Error("Invalid record");
1458 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1459 return Error("Invalid record");
1460 CurTy = TypeList[Record[0]];
1461 continue; // Skip the ValueList manipulation.
1462 case bitc::CST_CODE_NULL: // NULL
1463 V = Constant::getNullValue(CurTy);
1465 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1466 if (!CurTy->isIntegerTy() || Record.empty())
1467 return Error("Invalid record");
1468 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1470 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1471 if (!CurTy->isIntegerTy() || Record.empty())
1472 return Error("Invalid record");
1474 APInt VInt = ReadWideAPInt(Record,
1475 cast<IntegerType>(CurTy)->getBitWidth());
1476 V = ConstantInt::get(Context, VInt);
1480 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1482 return Error("Invalid record");
1483 if (CurTy->isHalfTy())
1484 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1485 APInt(16, (uint16_t)Record[0])));
1486 else if (CurTy->isFloatTy())
1487 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1488 APInt(32, (uint32_t)Record[0])));
1489 else if (CurTy->isDoubleTy())
1490 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1491 APInt(64, Record[0])));
1492 else if (CurTy->isX86_FP80Ty()) {
1493 // Bits are not stored the same way as a normal i80 APInt, compensate.
1494 uint64_t Rearrange[2];
1495 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1496 Rearrange[1] = Record[0] >> 48;
1497 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1498 APInt(80, Rearrange)));
1499 } else if (CurTy->isFP128Ty())
1500 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1501 APInt(128, Record)));
1502 else if (CurTy->isPPC_FP128Ty())
1503 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1504 APInt(128, Record)));
1506 V = UndefValue::get(CurTy);
1510 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1512 return Error("Invalid record");
1514 unsigned Size = Record.size();
1515 SmallVector<Constant*, 16> Elts;
1517 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1518 for (unsigned i = 0; i != Size; ++i)
1519 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1520 STy->getElementType(i)));
1521 V = ConstantStruct::get(STy, Elts);
1522 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1523 Type *EltTy = ATy->getElementType();
1524 for (unsigned i = 0; i != Size; ++i)
1525 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1526 V = ConstantArray::get(ATy, Elts);
1527 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1528 Type *EltTy = VTy->getElementType();
1529 for (unsigned i = 0; i != Size; ++i)
1530 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1531 V = ConstantVector::get(Elts);
1533 V = UndefValue::get(CurTy);
1537 case bitc::CST_CODE_STRING: // STRING: [values]
1538 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1540 return Error("Invalid record");
1542 SmallString<16> Elts(Record.begin(), Record.end());
1543 V = ConstantDataArray::getString(Context, Elts,
1544 BitCode == bitc::CST_CODE_CSTRING);
1547 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1549 return Error("Invalid record");
1551 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1552 unsigned Size = Record.size();
1554 if (EltTy->isIntegerTy(8)) {
1555 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1556 if (isa<VectorType>(CurTy))
1557 V = ConstantDataVector::get(Context, Elts);
1559 V = ConstantDataArray::get(Context, Elts);
1560 } else if (EltTy->isIntegerTy(16)) {
1561 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1562 if (isa<VectorType>(CurTy))
1563 V = ConstantDataVector::get(Context, Elts);
1565 V = ConstantDataArray::get(Context, Elts);
1566 } else if (EltTy->isIntegerTy(32)) {
1567 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1568 if (isa<VectorType>(CurTy))
1569 V = ConstantDataVector::get(Context, Elts);
1571 V = ConstantDataArray::get(Context, Elts);
1572 } else if (EltTy->isIntegerTy(64)) {
1573 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1574 if (isa<VectorType>(CurTy))
1575 V = ConstantDataVector::get(Context, Elts);
1577 V = ConstantDataArray::get(Context, Elts);
1578 } else if (EltTy->isFloatTy()) {
1579 SmallVector<float, 16> Elts(Size);
1580 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1581 if (isa<VectorType>(CurTy))
1582 V = ConstantDataVector::get(Context, Elts);
1584 V = ConstantDataArray::get(Context, Elts);
1585 } else if (EltTy->isDoubleTy()) {
1586 SmallVector<double, 16> Elts(Size);
1587 std::transform(Record.begin(), Record.end(), Elts.begin(),
1589 if (isa<VectorType>(CurTy))
1590 V = ConstantDataVector::get(Context, Elts);
1592 V = ConstantDataArray::get(Context, Elts);
1594 return Error("Invalid type for value");
1599 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1600 if (Record.size() < 3)
1601 return Error("Invalid record");
1602 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1604 V = UndefValue::get(CurTy); // Unknown binop.
1606 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1607 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1609 if (Record.size() >= 4) {
1610 if (Opc == Instruction::Add ||
1611 Opc == Instruction::Sub ||
1612 Opc == Instruction::Mul ||
1613 Opc == Instruction::Shl) {
1614 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1615 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1616 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1617 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1618 } else if (Opc == Instruction::SDiv ||
1619 Opc == Instruction::UDiv ||
1620 Opc == Instruction::LShr ||
1621 Opc == Instruction::AShr) {
1622 if (Record[3] & (1 << bitc::PEO_EXACT))
1623 Flags |= SDivOperator::IsExact;
1626 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1630 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1631 if (Record.size() < 3)
1632 return Error("Invalid record");
1633 int Opc = GetDecodedCastOpcode(Record[0]);
1635 V = UndefValue::get(CurTy); // Unknown cast.
1637 Type *OpTy = getTypeByID(Record[1]);
1639 return Error("Invalid record");
1640 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1641 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1642 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1646 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1647 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1648 if (Record.size() & 1)
1649 return Error("Invalid record");
1650 SmallVector<Constant*, 16> Elts;
1651 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1652 Type *ElTy = getTypeByID(Record[i]);
1654 return Error("Invalid record");
1655 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1657 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1658 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1660 bitc::CST_CODE_CE_INBOUNDS_GEP);
1663 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1664 if (Record.size() < 3)
1665 return Error("Invalid record");
1667 Type *SelectorTy = Type::getInt1Ty(Context);
1669 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1670 // vector. Otherwise, it must be a single bit.
1671 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1672 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1673 VTy->getNumElements());
1675 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1677 ValueList.getConstantFwdRef(Record[1],CurTy),
1678 ValueList.getConstantFwdRef(Record[2],CurTy));
1681 case bitc::CST_CODE_CE_EXTRACTELT
1682 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1683 if (Record.size() < 3)
1684 return Error("Invalid record");
1686 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1688 return Error("Invalid record");
1689 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1690 Constant *Op1 = nullptr;
1691 if (Record.size() == 4) {
1692 Type *IdxTy = getTypeByID(Record[2]);
1694 return Error("Invalid record");
1695 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1696 } else // TODO: Remove with llvm 4.0
1697 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1699 return Error("Invalid record");
1700 V = ConstantExpr::getExtractElement(Op0, Op1);
1703 case bitc::CST_CODE_CE_INSERTELT
1704 : { // CE_INSERTELT: [opval, opval, opty, opval]
1705 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1706 if (Record.size() < 3 || !OpTy)
1707 return Error("Invalid record");
1708 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1709 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1710 OpTy->getElementType());
1711 Constant *Op2 = nullptr;
1712 if (Record.size() == 4) {
1713 Type *IdxTy = getTypeByID(Record[2]);
1715 return Error("Invalid record");
1716 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1717 } else // TODO: Remove with llvm 4.0
1718 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1720 return Error("Invalid record");
1721 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1724 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1725 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1726 if (Record.size() < 3 || !OpTy)
1727 return Error("Invalid record");
1728 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1729 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1730 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1731 OpTy->getNumElements());
1732 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1733 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1736 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1737 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1739 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1740 if (Record.size() < 4 || !RTy || !OpTy)
1741 return Error("Invalid record");
1742 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1743 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1744 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1745 RTy->getNumElements());
1746 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1747 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1750 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1751 if (Record.size() < 4)
1752 return Error("Invalid record");
1753 Type *OpTy = getTypeByID(Record[0]);
1755 return Error("Invalid record");
1756 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1757 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1759 if (OpTy->isFPOrFPVectorTy())
1760 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1762 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1765 // This maintains backward compatibility, pre-asm dialect keywords.
1766 // FIXME: Remove with the 4.0 release.
1767 case bitc::CST_CODE_INLINEASM_OLD: {
1768 if (Record.size() < 2)
1769 return Error("Invalid record");
1770 std::string AsmStr, ConstrStr;
1771 bool HasSideEffects = Record[0] & 1;
1772 bool IsAlignStack = Record[0] >> 1;
1773 unsigned AsmStrSize = Record[1];
1774 if (2+AsmStrSize >= Record.size())
1775 return Error("Invalid record");
1776 unsigned ConstStrSize = Record[2+AsmStrSize];
1777 if (3+AsmStrSize+ConstStrSize > Record.size())
1778 return Error("Invalid record");
1780 for (unsigned i = 0; i != AsmStrSize; ++i)
1781 AsmStr += (char)Record[2+i];
1782 for (unsigned i = 0; i != ConstStrSize; ++i)
1783 ConstrStr += (char)Record[3+AsmStrSize+i];
1784 PointerType *PTy = cast<PointerType>(CurTy);
1785 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1786 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1789 // This version adds support for the asm dialect keywords (e.g.,
1791 case bitc::CST_CODE_INLINEASM: {
1792 if (Record.size() < 2)
1793 return Error("Invalid record");
1794 std::string AsmStr, ConstrStr;
1795 bool HasSideEffects = Record[0] & 1;
1796 bool IsAlignStack = (Record[0] >> 1) & 1;
1797 unsigned AsmDialect = Record[0] >> 2;
1798 unsigned AsmStrSize = Record[1];
1799 if (2+AsmStrSize >= Record.size())
1800 return Error("Invalid record");
1801 unsigned ConstStrSize = Record[2+AsmStrSize];
1802 if (3+AsmStrSize+ConstStrSize > Record.size())
1803 return Error("Invalid record");
1805 for (unsigned i = 0; i != AsmStrSize; ++i)
1806 AsmStr += (char)Record[2+i];
1807 for (unsigned i = 0; i != ConstStrSize; ++i)
1808 ConstrStr += (char)Record[3+AsmStrSize+i];
1809 PointerType *PTy = cast<PointerType>(CurTy);
1810 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1811 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1812 InlineAsm::AsmDialect(AsmDialect));
1815 case bitc::CST_CODE_BLOCKADDRESS:{
1816 if (Record.size() < 3)
1817 return Error("Invalid record");
1818 Type *FnTy = getTypeByID(Record[0]);
1820 return Error("Invalid record");
1822 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1824 return Error("Invalid record");
1826 // Don't let Fn get dematerialized.
1827 BlockAddressesTaken.insert(Fn);
1829 // If the function is already parsed we can insert the block address right
1832 unsigned BBID = Record[2];
1834 // Invalid reference to entry block.
1835 return Error("Invalid ID");
1837 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1838 for (size_t I = 0, E = BBID; I != E; ++I) {
1840 return Error("Invalid ID");
1845 // Otherwise insert a placeholder and remember it so it can be inserted
1846 // when the function is parsed.
1847 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1849 BasicBlockFwdRefQueue.push_back(Fn);
1850 if (FwdBBs.size() < BBID + 1)
1851 FwdBBs.resize(BBID + 1);
1853 FwdBBs[BBID] = BasicBlock::Create(Context);
1856 V = BlockAddress::get(Fn, BB);
1861 ValueList.AssignValue(V, NextCstNo);
1866 std::error_code BitcodeReader::ParseUseLists() {
1867 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1868 return Error("Invalid record");
1870 // Read all the records.
1871 SmallVector<uint64_t, 64> Record;
1873 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1875 switch (Entry.Kind) {
1876 case BitstreamEntry::SubBlock: // Handled for us already.
1877 case BitstreamEntry::Error:
1878 return Error("Malformed block");
1879 case BitstreamEntry::EndBlock:
1880 return std::error_code();
1881 case BitstreamEntry::Record:
1882 // The interesting case.
1886 // Read a use list record.
1889 switch (Stream.readRecord(Entry.ID, Record)) {
1890 default: // Default behavior: unknown type.
1892 case bitc::USELIST_CODE_BB:
1895 case bitc::USELIST_CODE_DEFAULT: {
1896 unsigned RecordLength = Record.size();
1897 if (RecordLength < 3)
1898 // Records should have at least an ID and two indexes.
1899 return Error("Invalid record");
1900 unsigned ID = Record.back();
1905 assert(ID < FunctionBBs.size() && "Basic block not found");
1906 V = FunctionBBs[ID];
1909 unsigned NumUses = 0;
1910 SmallDenseMap<const Use *, unsigned, 16> Order;
1911 for (const Use &U : V->uses()) {
1912 if (++NumUses > Record.size())
1914 Order[&U] = Record[NumUses - 1];
1916 if (Order.size() != Record.size() || NumUses > Record.size())
1917 // Mismatches can happen if the functions are being materialized lazily
1918 // (out-of-order), or a value has been upgraded.
1921 V->sortUseList([&](const Use &L, const Use &R) {
1922 return Order.lookup(&L) < Order.lookup(&R);
1930 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1931 /// remember where it is and then skip it. This lets us lazily deserialize the
1933 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1934 // Get the function we are talking about.
1935 if (FunctionsWithBodies.empty())
1936 return Error("Insufficient function protos");
1938 Function *Fn = FunctionsWithBodies.back();
1939 FunctionsWithBodies.pop_back();
1941 // Save the current stream state.
1942 uint64_t CurBit = Stream.GetCurrentBitNo();
1943 DeferredFunctionInfo[Fn] = CurBit;
1945 // Skip over the function block for now.
1946 if (Stream.SkipBlock())
1947 return Error("Invalid record");
1948 return std::error_code();
1951 std::error_code BitcodeReader::GlobalCleanup() {
1952 // Patch the initializers for globals and aliases up.
1953 ResolveGlobalAndAliasInits();
1954 if (!GlobalInits.empty() || !AliasInits.empty())
1955 return Error("Malformed global initializer set");
1957 // Look for intrinsic functions which need to be upgraded at some point
1958 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1961 if (UpgradeIntrinsicFunction(FI, NewFn))
1962 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1965 // Look for global variables which need to be renamed.
1966 for (Module::global_iterator
1967 GI = TheModule->global_begin(), GE = TheModule->global_end();
1969 GlobalVariable *GV = GI++;
1970 UpgradeGlobalVariable(GV);
1973 // Force deallocation of memory for these vectors to favor the client that
1974 // want lazy deserialization.
1975 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1976 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1977 return std::error_code();
1980 std::error_code BitcodeReader::ParseModule(bool Resume) {
1982 Stream.JumpToBit(NextUnreadBit);
1983 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1984 return Error("Invalid record");
1986 SmallVector<uint64_t, 64> Record;
1987 std::vector<std::string> SectionTable;
1988 std::vector<std::string> GCTable;
1990 // Read all the records for this module.
1992 BitstreamEntry Entry = Stream.advance();
1994 switch (Entry.Kind) {
1995 case BitstreamEntry::Error:
1996 return Error("Malformed block");
1997 case BitstreamEntry::EndBlock:
1998 return GlobalCleanup();
2000 case BitstreamEntry::SubBlock:
2002 default: // Skip unknown content.
2003 if (Stream.SkipBlock())
2004 return Error("Invalid record");
2006 case bitc::BLOCKINFO_BLOCK_ID:
2007 if (Stream.ReadBlockInfoBlock())
2008 return Error("Malformed block");
2010 case bitc::PARAMATTR_BLOCK_ID:
2011 if (std::error_code EC = ParseAttributeBlock())
2014 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2015 if (std::error_code EC = ParseAttributeGroupBlock())
2018 case bitc::TYPE_BLOCK_ID_NEW:
2019 if (std::error_code EC = ParseTypeTable())
2022 case bitc::VALUE_SYMTAB_BLOCK_ID:
2023 if (std::error_code EC = ParseValueSymbolTable())
2025 SeenValueSymbolTable = true;
2027 case bitc::CONSTANTS_BLOCK_ID:
2028 if (std::error_code EC = ParseConstants())
2030 if (std::error_code EC = ResolveGlobalAndAliasInits())
2033 case bitc::METADATA_BLOCK_ID:
2034 if (std::error_code EC = ParseMetadata())
2037 case bitc::FUNCTION_BLOCK_ID:
2038 // If this is the first function body we've seen, reverse the
2039 // FunctionsWithBodies list.
2040 if (!SeenFirstFunctionBody) {
2041 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2042 if (std::error_code EC = GlobalCleanup())
2044 SeenFirstFunctionBody = true;
2047 if (std::error_code EC = RememberAndSkipFunctionBody())
2049 // For streaming bitcode, suspend parsing when we reach the function
2050 // bodies. Subsequent materialization calls will resume it when
2051 // necessary. For streaming, the function bodies must be at the end of
2052 // the bitcode. If the bitcode file is old, the symbol table will be
2053 // at the end instead and will not have been seen yet. In this case,
2054 // just finish the parse now.
2055 if (LazyStreamer && SeenValueSymbolTable) {
2056 NextUnreadBit = Stream.GetCurrentBitNo();
2057 return std::error_code();
2060 case bitc::USELIST_BLOCK_ID:
2061 if (std::error_code EC = ParseUseLists())
2067 case BitstreamEntry::Record:
2068 // The interesting case.
2074 switch (Stream.readRecord(Entry.ID, Record)) {
2075 default: break; // Default behavior, ignore unknown content.
2076 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2077 if (Record.size() < 1)
2078 return Error("Invalid record");
2079 // Only version #0 and #1 are supported so far.
2080 unsigned module_version = Record[0];
2081 switch (module_version) {
2083 return Error("Invalid value");
2085 UseRelativeIDs = false;
2088 UseRelativeIDs = true;
2093 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2095 if (ConvertToString(Record, 0, S))
2096 return Error("Invalid record");
2097 TheModule->setTargetTriple(S);
2100 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2102 if (ConvertToString(Record, 0, S))
2103 return Error("Invalid record");
2104 TheModule->setDataLayout(S);
2107 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2109 if (ConvertToString(Record, 0, S))
2110 return Error("Invalid record");
2111 TheModule->setModuleInlineAsm(S);
2114 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2115 // FIXME: Remove in 4.0.
2117 if (ConvertToString(Record, 0, S))
2118 return Error("Invalid record");
2122 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2124 if (ConvertToString(Record, 0, S))
2125 return Error("Invalid record");
2126 SectionTable.push_back(S);
2129 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2131 if (ConvertToString(Record, 0, S))
2132 return Error("Invalid record");
2133 GCTable.push_back(S);
2136 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2137 if (Record.size() < 2)
2138 return Error("Invalid record");
2139 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2140 unsigned ComdatNameSize = Record[1];
2141 std::string ComdatName;
2142 ComdatName.reserve(ComdatNameSize);
2143 for (unsigned i = 0; i != ComdatNameSize; ++i)
2144 ComdatName += (char)Record[2 + i];
2145 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2146 C->setSelectionKind(SK);
2147 ComdatList.push_back(C);
2150 // GLOBALVAR: [pointer type, isconst, initid,
2151 // linkage, alignment, section, visibility, threadlocal,
2152 // unnamed_addr, dllstorageclass]
2153 case bitc::MODULE_CODE_GLOBALVAR: {
2154 if (Record.size() < 6)
2155 return Error("Invalid record");
2156 Type *Ty = getTypeByID(Record[0]);
2158 return Error("Invalid record");
2159 if (!Ty->isPointerTy())
2160 return Error("Invalid type for value");
2161 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2162 Ty = cast<PointerType>(Ty)->getElementType();
2164 bool isConstant = Record[1];
2165 uint64_t RawLinkage = Record[3];
2166 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2167 unsigned Alignment = (1 << Record[4]) >> 1;
2168 std::string Section;
2170 if (Record[5]-1 >= SectionTable.size())
2171 return Error("Invalid ID");
2172 Section = SectionTable[Record[5]-1];
2174 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2175 // Local linkage must have default visibility.
2176 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2177 // FIXME: Change to an error if non-default in 4.0.
2178 Visibility = GetDecodedVisibility(Record[6]);
2180 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2181 if (Record.size() > 7)
2182 TLM = GetDecodedThreadLocalMode(Record[7]);
2184 bool UnnamedAddr = false;
2185 if (Record.size() > 8)
2186 UnnamedAddr = Record[8];
2188 bool ExternallyInitialized = false;
2189 if (Record.size() > 9)
2190 ExternallyInitialized = Record[9];
2192 GlobalVariable *NewGV =
2193 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2194 TLM, AddressSpace, ExternallyInitialized);
2195 NewGV->setAlignment(Alignment);
2196 if (!Section.empty())
2197 NewGV->setSection(Section);
2198 NewGV->setVisibility(Visibility);
2199 NewGV->setUnnamedAddr(UnnamedAddr);
2201 if (Record.size() > 10)
2202 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2204 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2206 ValueList.push_back(NewGV);
2208 // Remember which value to use for the global initializer.
2209 if (unsigned InitID = Record[2])
2210 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2212 if (Record.size() > 11) {
2213 if (unsigned ComdatID = Record[11]) {
2214 assert(ComdatID <= ComdatList.size());
2215 NewGV->setComdat(ComdatList[ComdatID - 1]);
2217 } else if (hasImplicitComdat(RawLinkage)) {
2218 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2222 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2223 // alignment, section, visibility, gc, unnamed_addr,
2224 // prologuedata, dllstorageclass, comdat, prefixdata]
2225 case bitc::MODULE_CODE_FUNCTION: {
2226 if (Record.size() < 8)
2227 return Error("Invalid record");
2228 Type *Ty = getTypeByID(Record[0]);
2230 return Error("Invalid record");
2231 if (!Ty->isPointerTy())
2232 return Error("Invalid type for value");
2234 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2236 return Error("Invalid type for value");
2238 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2241 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2242 bool isProto = Record[2];
2243 uint64_t RawLinkage = Record[3];
2244 Func->setLinkage(getDecodedLinkage(RawLinkage));
2245 Func->setAttributes(getAttributes(Record[4]));
2247 Func->setAlignment((1 << Record[5]) >> 1);
2249 if (Record[6]-1 >= SectionTable.size())
2250 return Error("Invalid ID");
2251 Func->setSection(SectionTable[Record[6]-1]);
2253 // Local linkage must have default visibility.
2254 if (!Func->hasLocalLinkage())
2255 // FIXME: Change to an error if non-default in 4.0.
2256 Func->setVisibility(GetDecodedVisibility(Record[7]));
2257 if (Record.size() > 8 && Record[8]) {
2258 if (Record[8]-1 > GCTable.size())
2259 return Error("Invalid ID");
2260 Func->setGC(GCTable[Record[8]-1].c_str());
2262 bool UnnamedAddr = false;
2263 if (Record.size() > 9)
2264 UnnamedAddr = Record[9];
2265 Func->setUnnamedAddr(UnnamedAddr);
2266 if (Record.size() > 10 && Record[10] != 0)
2267 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2269 if (Record.size() > 11)
2270 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2272 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2274 if (Record.size() > 12) {
2275 if (unsigned ComdatID = Record[12]) {
2276 assert(ComdatID <= ComdatList.size());
2277 Func->setComdat(ComdatList[ComdatID - 1]);
2279 } else if (hasImplicitComdat(RawLinkage)) {
2280 Func->setComdat(reinterpret_cast<Comdat *>(1));
2283 if (Record.size() > 13 && Record[13] != 0)
2284 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2286 ValueList.push_back(Func);
2288 // If this is a function with a body, remember the prototype we are
2289 // creating now, so that we can match up the body with them later.
2291 Func->setIsMaterializable(true);
2292 FunctionsWithBodies.push_back(Func);
2294 DeferredFunctionInfo[Func] = 0;
2298 // ALIAS: [alias type, aliasee val#, linkage]
2299 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2300 case bitc::MODULE_CODE_ALIAS: {
2301 if (Record.size() < 3)
2302 return Error("Invalid record");
2303 Type *Ty = getTypeByID(Record[0]);
2305 return Error("Invalid record");
2306 auto *PTy = dyn_cast<PointerType>(Ty);
2308 return Error("Invalid type for value");
2311 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2312 getDecodedLinkage(Record[2]), "", TheModule);
2313 // Old bitcode files didn't have visibility field.
2314 // Local linkage must have default visibility.
2315 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2316 // FIXME: Change to an error if non-default in 4.0.
2317 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2318 if (Record.size() > 4)
2319 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2321 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2322 if (Record.size() > 5)
2323 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2324 if (Record.size() > 6)
2325 NewGA->setUnnamedAddr(Record[6]);
2326 ValueList.push_back(NewGA);
2327 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2330 /// MODULE_CODE_PURGEVALS: [numvals]
2331 case bitc::MODULE_CODE_PURGEVALS:
2332 // Trim down the value list to the specified size.
2333 if (Record.size() < 1 || Record[0] > ValueList.size())
2334 return Error("Invalid record");
2335 ValueList.shrinkTo(Record[0]);
2342 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2343 TheModule = nullptr;
2345 if (std::error_code EC = InitStream())
2348 // Sniff for the signature.
2349 if (Stream.Read(8) != 'B' ||
2350 Stream.Read(8) != 'C' ||
2351 Stream.Read(4) != 0x0 ||
2352 Stream.Read(4) != 0xC ||
2353 Stream.Read(4) != 0xE ||
2354 Stream.Read(4) != 0xD)
2355 return Error("Invalid bitcode signature");
2357 // We expect a number of well-defined blocks, though we don't necessarily
2358 // need to understand them all.
2360 if (Stream.AtEndOfStream())
2361 return std::error_code();
2363 BitstreamEntry Entry =
2364 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2366 switch (Entry.Kind) {
2367 case BitstreamEntry::Error:
2368 return Error("Malformed block");
2369 case BitstreamEntry::EndBlock:
2370 return std::error_code();
2372 case BitstreamEntry::SubBlock:
2374 case bitc::BLOCKINFO_BLOCK_ID:
2375 if (Stream.ReadBlockInfoBlock())
2376 return Error("Malformed block");
2378 case bitc::MODULE_BLOCK_ID:
2379 // Reject multiple MODULE_BLOCK's in a single bitstream.
2381 return Error("Invalid multiple blocks");
2383 if (std::error_code EC = ParseModule(false))
2386 return std::error_code();
2389 if (Stream.SkipBlock())
2390 return Error("Invalid record");
2394 case BitstreamEntry::Record:
2395 // There should be no records in the top-level of blocks.
2397 // The ranlib in Xcode 4 will align archive members by appending newlines
2398 // to the end of them. If this file size is a multiple of 4 but not 8, we
2399 // have to read and ignore these final 4 bytes :-(
2400 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2401 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2402 Stream.AtEndOfStream())
2403 return std::error_code();
2405 return Error("Invalid record");
2410 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2411 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2412 return Error("Invalid record");
2414 SmallVector<uint64_t, 64> Record;
2417 // Read all the records for this module.
2419 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2421 switch (Entry.Kind) {
2422 case BitstreamEntry::SubBlock: // Handled for us already.
2423 case BitstreamEntry::Error:
2424 return Error("Malformed block");
2425 case BitstreamEntry::EndBlock:
2427 case BitstreamEntry::Record:
2428 // The interesting case.
2433 switch (Stream.readRecord(Entry.ID, Record)) {
2434 default: break; // Default behavior, ignore unknown content.
2435 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2437 if (ConvertToString(Record, 0, S))
2438 return Error("Invalid record");
2445 llvm_unreachable("Exit infinite loop");
2448 ErrorOr<std::string> BitcodeReader::parseTriple() {
2449 if (std::error_code EC = InitStream())
2452 // Sniff for the signature.
2453 if (Stream.Read(8) != 'B' ||
2454 Stream.Read(8) != 'C' ||
2455 Stream.Read(4) != 0x0 ||
2456 Stream.Read(4) != 0xC ||
2457 Stream.Read(4) != 0xE ||
2458 Stream.Read(4) != 0xD)
2459 return Error("Invalid bitcode signature");
2461 // We expect a number of well-defined blocks, though we don't necessarily
2462 // need to understand them all.
2464 BitstreamEntry Entry = Stream.advance();
2466 switch (Entry.Kind) {
2467 case BitstreamEntry::Error:
2468 return Error("Malformed block");
2469 case BitstreamEntry::EndBlock:
2470 return std::error_code();
2472 case BitstreamEntry::SubBlock:
2473 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2474 return parseModuleTriple();
2476 // Ignore other sub-blocks.
2477 if (Stream.SkipBlock())
2478 return Error("Malformed block");
2481 case BitstreamEntry::Record:
2482 Stream.skipRecord(Entry.ID);
2488 /// ParseMetadataAttachment - Parse metadata attachments.
2489 std::error_code BitcodeReader::ParseMetadataAttachment() {
2490 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2491 return Error("Invalid record");
2493 SmallVector<uint64_t, 64> Record;
2495 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2497 switch (Entry.Kind) {
2498 case BitstreamEntry::SubBlock: // Handled for us already.
2499 case BitstreamEntry::Error:
2500 return Error("Malformed block");
2501 case BitstreamEntry::EndBlock:
2502 return std::error_code();
2503 case BitstreamEntry::Record:
2504 // The interesting case.
2508 // Read a metadata attachment record.
2510 switch (Stream.readRecord(Entry.ID, Record)) {
2511 default: // Default behavior: ignore.
2513 case bitc::METADATA_ATTACHMENT: {
2514 unsigned RecordLength = Record.size();
2515 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2516 return Error("Invalid record");
2517 Instruction *Inst = InstructionList[Record[0]];
2518 for (unsigned i = 1; i != RecordLength; i = i+2) {
2519 unsigned Kind = Record[i];
2520 DenseMap<unsigned, unsigned>::iterator I =
2521 MDKindMap.find(Kind);
2522 if (I == MDKindMap.end())
2523 return Error("Invalid ID");
2524 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2525 if (isa<LocalAsMetadata>(Node))
2526 // Drop the attachment. This used to be legal, but there's no
2529 Inst->setMetadata(I->second, cast<MDNode>(Node));
2530 if (I->second == LLVMContext::MD_tbaa)
2531 InstsWithTBAATag.push_back(Inst);
2539 /// ParseFunctionBody - Lazily parse the specified function body block.
2540 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2541 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2542 return Error("Invalid record");
2544 InstructionList.clear();
2545 unsigned ModuleValueListSize = ValueList.size();
2546 unsigned ModuleMDValueListSize = MDValueList.size();
2548 // Add all the function arguments to the value table.
2549 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2550 ValueList.push_back(I);
2552 unsigned NextValueNo = ValueList.size();
2553 BasicBlock *CurBB = nullptr;
2554 unsigned CurBBNo = 0;
2557 auto getLastInstruction = [&]() -> Instruction * {
2558 if (CurBB && !CurBB->empty())
2559 return &CurBB->back();
2560 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2561 !FunctionBBs[CurBBNo - 1]->empty())
2562 return &FunctionBBs[CurBBNo - 1]->back();
2566 // Read all the records.
2567 SmallVector<uint64_t, 64> Record;
2569 BitstreamEntry Entry = Stream.advance();
2571 switch (Entry.Kind) {
2572 case BitstreamEntry::Error:
2573 return Error("Malformed block");
2574 case BitstreamEntry::EndBlock:
2575 goto OutOfRecordLoop;
2577 case BitstreamEntry::SubBlock:
2579 default: // Skip unknown content.
2580 if (Stream.SkipBlock())
2581 return Error("Invalid record");
2583 case bitc::CONSTANTS_BLOCK_ID:
2584 if (std::error_code EC = ParseConstants())
2586 NextValueNo = ValueList.size();
2588 case bitc::VALUE_SYMTAB_BLOCK_ID:
2589 if (std::error_code EC = ParseValueSymbolTable())
2592 case bitc::METADATA_ATTACHMENT_ID:
2593 if (std::error_code EC = ParseMetadataAttachment())
2596 case bitc::METADATA_BLOCK_ID:
2597 if (std::error_code EC = ParseMetadata())
2600 case bitc::USELIST_BLOCK_ID:
2601 if (std::error_code EC = ParseUseLists())
2607 case BitstreamEntry::Record:
2608 // The interesting case.
2614 Instruction *I = nullptr;
2615 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2617 default: // Default behavior: reject
2618 return Error("Invalid value");
2619 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2620 if (Record.size() < 1 || Record[0] == 0)
2621 return Error("Invalid record");
2622 // Create all the basic blocks for the function.
2623 FunctionBBs.resize(Record[0]);
2625 // See if anything took the address of blocks in this function.
2626 auto BBFRI = BasicBlockFwdRefs.find(F);
2627 if (BBFRI == BasicBlockFwdRefs.end()) {
2628 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2629 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2631 auto &BBRefs = BBFRI->second;
2632 // Check for invalid basic block references.
2633 if (BBRefs.size() > FunctionBBs.size())
2634 return Error("Invalid ID");
2635 assert(!BBRefs.empty() && "Unexpected empty array");
2636 assert(!BBRefs.front() && "Invalid reference to entry block");
2637 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2639 if (I < RE && BBRefs[I]) {
2640 BBRefs[I]->insertInto(F);
2641 FunctionBBs[I] = BBRefs[I];
2643 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2646 // Erase from the table.
2647 BasicBlockFwdRefs.erase(BBFRI);
2650 CurBB = FunctionBBs[0];
2654 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2655 // This record indicates that the last instruction is at the same
2656 // location as the previous instruction with a location.
2657 I = getLastInstruction();
2660 return Error("Invalid record");
2661 I->setDebugLoc(LastLoc);
2665 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2666 I = getLastInstruction();
2667 if (!I || Record.size() < 4)
2668 return Error("Invalid record");
2670 unsigned Line = Record[0], Col = Record[1];
2671 unsigned ScopeID = Record[2], IAID = Record[3];
2673 MDNode *Scope = nullptr, *IA = nullptr;
2674 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2675 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2676 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2677 I->setDebugLoc(LastLoc);
2682 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2685 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2686 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2687 OpNum+1 > Record.size())
2688 return Error("Invalid record");
2690 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2692 return Error("Invalid record");
2693 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2694 InstructionList.push_back(I);
2695 if (OpNum < Record.size()) {
2696 if (Opc == Instruction::Add ||
2697 Opc == Instruction::Sub ||
2698 Opc == Instruction::Mul ||
2699 Opc == Instruction::Shl) {
2700 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2701 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2702 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2703 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2704 } else if (Opc == Instruction::SDiv ||
2705 Opc == Instruction::UDiv ||
2706 Opc == Instruction::LShr ||
2707 Opc == Instruction::AShr) {
2708 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2709 cast<BinaryOperator>(I)->setIsExact(true);
2710 } else if (isa<FPMathOperator>(I)) {
2712 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2713 FMF.setUnsafeAlgebra();
2714 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2716 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2718 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2719 FMF.setNoSignedZeros();
2720 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2721 FMF.setAllowReciprocal();
2723 I->setFastMathFlags(FMF);
2729 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2732 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2733 OpNum+2 != Record.size())
2734 return Error("Invalid record");
2736 Type *ResTy = getTypeByID(Record[OpNum]);
2737 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2738 if (Opc == -1 || !ResTy)
2739 return Error("Invalid record");
2740 Instruction *Temp = nullptr;
2741 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2743 InstructionList.push_back(Temp);
2744 CurBB->getInstList().push_back(Temp);
2747 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2749 InstructionList.push_back(I);
2752 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2753 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2756 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2757 return Error("Invalid record");
2759 SmallVector<Value*, 16> GEPIdx;
2760 while (OpNum != Record.size()) {
2762 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2763 return Error("Invalid record");
2764 GEPIdx.push_back(Op);
2767 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2768 InstructionList.push_back(I);
2769 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2770 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2774 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2775 // EXTRACTVAL: [opty, opval, n x indices]
2778 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2779 return Error("Invalid record");
2781 SmallVector<unsigned, 4> EXTRACTVALIdx;
2782 for (unsigned RecSize = Record.size();
2783 OpNum != RecSize; ++OpNum) {
2784 uint64_t Index = Record[OpNum];
2785 if ((unsigned)Index != Index)
2786 return Error("Invalid value");
2787 EXTRACTVALIdx.push_back((unsigned)Index);
2790 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2791 InstructionList.push_back(I);
2795 case bitc::FUNC_CODE_INST_INSERTVAL: {
2796 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2799 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2800 return Error("Invalid record");
2802 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2803 return Error("Invalid record");
2805 SmallVector<unsigned, 4> INSERTVALIdx;
2806 for (unsigned RecSize = Record.size();
2807 OpNum != RecSize; ++OpNum) {
2808 uint64_t Index = Record[OpNum];
2809 if ((unsigned)Index != Index)
2810 return Error("Invalid value");
2811 INSERTVALIdx.push_back((unsigned)Index);
2814 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2815 InstructionList.push_back(I);
2819 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2820 // obsolete form of select
2821 // handles select i1 ... in old bitcode
2823 Value *TrueVal, *FalseVal, *Cond;
2824 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2825 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2826 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2827 return Error("Invalid record");
2829 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2830 InstructionList.push_back(I);
2834 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2835 // new form of select
2836 // handles select i1 or select [N x i1]
2838 Value *TrueVal, *FalseVal, *Cond;
2839 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2840 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2841 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2842 return Error("Invalid record");
2844 // select condition can be either i1 or [N x i1]
2845 if (VectorType* vector_type =
2846 dyn_cast<VectorType>(Cond->getType())) {
2848 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2849 return Error("Invalid type for value");
2852 if (Cond->getType() != Type::getInt1Ty(Context))
2853 return Error("Invalid type for value");
2856 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2857 InstructionList.push_back(I);
2861 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2864 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2865 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2866 return Error("Invalid record");
2867 I = ExtractElementInst::Create(Vec, Idx);
2868 InstructionList.push_back(I);
2872 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2874 Value *Vec, *Elt, *Idx;
2875 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2876 popValue(Record, OpNum, NextValueNo,
2877 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2878 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2879 return Error("Invalid record");
2880 I = InsertElementInst::Create(Vec, Elt, Idx);
2881 InstructionList.push_back(I);
2885 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2887 Value *Vec1, *Vec2, *Mask;
2888 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2889 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2890 return Error("Invalid record");
2892 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2893 return Error("Invalid record");
2894 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2895 InstructionList.push_back(I);
2899 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2900 // Old form of ICmp/FCmp returning bool
2901 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2902 // both legal on vectors but had different behaviour.
2903 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2904 // FCmp/ICmp returning bool or vector of bool
2908 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2909 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2910 OpNum+1 != Record.size())
2911 return Error("Invalid record");
2913 if (LHS->getType()->isFPOrFPVectorTy())
2914 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2916 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2917 InstructionList.push_back(I);
2921 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2923 unsigned Size = Record.size();
2925 I = ReturnInst::Create(Context);
2926 InstructionList.push_back(I);
2931 Value *Op = nullptr;
2932 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2933 return Error("Invalid record");
2934 if (OpNum != Record.size())
2935 return Error("Invalid record");
2937 I = ReturnInst::Create(Context, Op);
2938 InstructionList.push_back(I);
2941 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2942 if (Record.size() != 1 && Record.size() != 3)
2943 return Error("Invalid record");
2944 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2946 return Error("Invalid record");
2948 if (Record.size() == 1) {
2949 I = BranchInst::Create(TrueDest);
2950 InstructionList.push_back(I);
2953 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2954 Value *Cond = getValue(Record, 2, NextValueNo,
2955 Type::getInt1Ty(Context));
2956 if (!FalseDest || !Cond)
2957 return Error("Invalid record");
2958 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2959 InstructionList.push_back(I);
2963 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2965 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2966 // "New" SwitchInst format with case ranges. The changes to write this
2967 // format were reverted but we still recognize bitcode that uses it.
2968 // Hopefully someday we will have support for case ranges and can use
2969 // this format again.
2971 Type *OpTy = getTypeByID(Record[1]);
2972 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2974 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2975 BasicBlock *Default = getBasicBlock(Record[3]);
2976 if (!OpTy || !Cond || !Default)
2977 return Error("Invalid record");
2979 unsigned NumCases = Record[4];
2981 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2982 InstructionList.push_back(SI);
2984 unsigned CurIdx = 5;
2985 for (unsigned i = 0; i != NumCases; ++i) {
2986 SmallVector<ConstantInt*, 1> CaseVals;
2987 unsigned NumItems = Record[CurIdx++];
2988 for (unsigned ci = 0; ci != NumItems; ++ci) {
2989 bool isSingleNumber = Record[CurIdx++];
2992 unsigned ActiveWords = 1;
2993 if (ValueBitWidth > 64)
2994 ActiveWords = Record[CurIdx++];
2995 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2997 CurIdx += ActiveWords;
2999 if (!isSingleNumber) {
3001 if (ValueBitWidth > 64)
3002 ActiveWords = Record[CurIdx++];
3004 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3006 CurIdx += ActiveWords;
3008 // FIXME: It is not clear whether values in the range should be
3009 // compared as signed or unsigned values. The partially
3010 // implemented changes that used this format in the past used
3011 // unsigned comparisons.
3012 for ( ; Low.ule(High); ++Low)
3013 CaseVals.push_back(ConstantInt::get(Context, Low));
3015 CaseVals.push_back(ConstantInt::get(Context, Low));
3017 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3018 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3019 cve = CaseVals.end(); cvi != cve; ++cvi)
3020 SI->addCase(*cvi, DestBB);
3026 // Old SwitchInst format without case ranges.
3028 if (Record.size() < 3 || (Record.size() & 1) == 0)
3029 return Error("Invalid record");
3030 Type *OpTy = getTypeByID(Record[0]);
3031 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3032 BasicBlock *Default = getBasicBlock(Record[2]);
3033 if (!OpTy || !Cond || !Default)
3034 return Error("Invalid record");
3035 unsigned NumCases = (Record.size()-3)/2;
3036 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3037 InstructionList.push_back(SI);
3038 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3039 ConstantInt *CaseVal =
3040 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3041 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3042 if (!CaseVal || !DestBB) {
3044 return Error("Invalid record");
3046 SI->addCase(CaseVal, DestBB);
3051 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3052 if (Record.size() < 2)
3053 return Error("Invalid record");
3054 Type *OpTy = getTypeByID(Record[0]);
3055 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3056 if (!OpTy || !Address)
3057 return Error("Invalid record");
3058 unsigned NumDests = Record.size()-2;
3059 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3060 InstructionList.push_back(IBI);
3061 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3062 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3063 IBI->addDestination(DestBB);
3066 return Error("Invalid record");
3073 case bitc::FUNC_CODE_INST_INVOKE: {
3074 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3075 if (Record.size() < 4)
3076 return Error("Invalid record");
3077 AttributeSet PAL = getAttributes(Record[0]);
3078 unsigned CCInfo = Record[1];
3079 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3080 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3084 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3085 return Error("Invalid record");
3087 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3088 FunctionType *FTy = !CalleeTy ? nullptr :
3089 dyn_cast<FunctionType>(CalleeTy->getElementType());
3091 // Check that the right number of fixed parameters are here.
3092 if (!FTy || !NormalBB || !UnwindBB ||
3093 Record.size() < OpNum+FTy->getNumParams())
3094 return Error("Invalid record");
3096 SmallVector<Value*, 16> Ops;
3097 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3098 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3099 FTy->getParamType(i)));
3101 return Error("Invalid record");
3104 if (!FTy->isVarArg()) {
3105 if (Record.size() != OpNum)
3106 return Error("Invalid record");
3108 // Read type/value pairs for varargs params.
3109 while (OpNum != Record.size()) {
3111 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3112 return Error("Invalid record");
3117 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3118 InstructionList.push_back(I);
3119 cast<InvokeInst>(I)->setCallingConv(
3120 static_cast<CallingConv::ID>(CCInfo));
3121 cast<InvokeInst>(I)->setAttributes(PAL);
3124 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3126 Value *Val = nullptr;
3127 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3128 return Error("Invalid record");
3129 I = ResumeInst::Create(Val);
3130 InstructionList.push_back(I);
3133 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3134 I = new UnreachableInst(Context);
3135 InstructionList.push_back(I);
3137 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3138 if (Record.size() < 1 || ((Record.size()-1)&1))
3139 return Error("Invalid record");
3140 Type *Ty = getTypeByID(Record[0]);
3142 return Error("Invalid record");
3144 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3145 InstructionList.push_back(PN);
3147 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3149 // With the new function encoding, it is possible that operands have
3150 // negative IDs (for forward references). Use a signed VBR
3151 // representation to keep the encoding small.
3153 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3155 V = getValue(Record, 1+i, NextValueNo, Ty);
3156 BasicBlock *BB = getBasicBlock(Record[2+i]);
3158 return Error("Invalid record");
3159 PN->addIncoming(V, BB);
3165 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3166 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3168 if (Record.size() < 4)
3169 return Error("Invalid record");
3170 Type *Ty = getTypeByID(Record[Idx++]);
3172 return Error("Invalid record");
3173 Value *PersFn = nullptr;
3174 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3175 return Error("Invalid record");
3177 bool IsCleanup = !!Record[Idx++];
3178 unsigned NumClauses = Record[Idx++];
3179 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3180 LP->setCleanup(IsCleanup);
3181 for (unsigned J = 0; J != NumClauses; ++J) {
3182 LandingPadInst::ClauseType CT =
3183 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3186 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3188 return Error("Invalid record");
3191 assert((CT != LandingPadInst::Catch ||
3192 !isa<ArrayType>(Val->getType())) &&
3193 "Catch clause has a invalid type!");
3194 assert((CT != LandingPadInst::Filter ||
3195 isa<ArrayType>(Val->getType())) &&
3196 "Filter clause has invalid type!");
3197 LP->addClause(cast<Constant>(Val));
3201 InstructionList.push_back(I);
3205 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3206 if (Record.size() != 4)
3207 return Error("Invalid record");
3209 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3210 Type *OpTy = getTypeByID(Record[1]);
3211 Value *Size = getFnValueByID(Record[2], OpTy);
3212 unsigned AlignRecord = Record[3];
3213 bool InAlloca = AlignRecord & (1 << 5);
3214 unsigned Align = AlignRecord & ((1 << 5) - 1);
3216 return Error("Invalid record");
3217 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3218 AI->setUsedWithInAlloca(InAlloca);
3220 InstructionList.push_back(I);
3223 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3226 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3227 OpNum+2 != Record.size())
3228 return Error("Invalid record");
3230 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3231 InstructionList.push_back(I);
3234 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3235 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3238 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3239 OpNum+4 != Record.size())
3240 return Error("Invalid record");
3242 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3243 if (Ordering == NotAtomic || Ordering == Release ||
3244 Ordering == AcquireRelease)
3245 return Error("Invalid record");
3246 if (Ordering != NotAtomic && Record[OpNum] == 0)
3247 return Error("Invalid record");
3248 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3250 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3251 Ordering, SynchScope);
3252 InstructionList.push_back(I);
3255 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3258 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3259 popValue(Record, OpNum, NextValueNo,
3260 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3261 OpNum+2 != Record.size())
3262 return Error("Invalid record");
3264 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3265 InstructionList.push_back(I);
3268 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3269 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3272 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3273 popValue(Record, OpNum, NextValueNo,
3274 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3275 OpNum+4 != Record.size())
3276 return Error("Invalid record");
3278 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3279 if (Ordering == NotAtomic || Ordering == Acquire ||
3280 Ordering == AcquireRelease)
3281 return Error("Invalid record");
3282 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3283 if (Ordering != NotAtomic && Record[OpNum] == 0)
3284 return Error("Invalid record");
3286 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3287 Ordering, SynchScope);
3288 InstructionList.push_back(I);
3291 case bitc::FUNC_CODE_INST_CMPXCHG: {
3292 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3293 // failureordering?, isweak?]
3295 Value *Ptr, *Cmp, *New;
3296 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3297 popValue(Record, OpNum, NextValueNo,
3298 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3299 popValue(Record, OpNum, NextValueNo,
3300 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3301 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3302 return Error("Invalid record");
3303 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3304 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3305 return Error("Invalid record");
3306 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3308 AtomicOrdering FailureOrdering;
3309 if (Record.size() < 7)
3311 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3313 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3315 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3317 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3319 if (Record.size() < 8) {
3320 // Before weak cmpxchgs existed, the instruction simply returned the
3321 // value loaded from memory, so bitcode files from that era will be
3322 // expecting the first component of a modern cmpxchg.
3323 CurBB->getInstList().push_back(I);
3324 I = ExtractValueInst::Create(I, 0);
3326 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3329 InstructionList.push_back(I);
3332 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3333 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3336 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3337 popValue(Record, OpNum, NextValueNo,
3338 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3339 OpNum+4 != Record.size())
3340 return Error("Invalid record");
3341 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3342 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3343 Operation > AtomicRMWInst::LAST_BINOP)
3344 return Error("Invalid record");
3345 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3346 if (Ordering == NotAtomic || Ordering == Unordered)
3347 return Error("Invalid record");
3348 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3349 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3350 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3351 InstructionList.push_back(I);
3354 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3355 if (2 != Record.size())
3356 return Error("Invalid record");
3357 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3358 if (Ordering == NotAtomic || Ordering == Unordered ||
3359 Ordering == Monotonic)
3360 return Error("Invalid record");
3361 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3362 I = new FenceInst(Context, Ordering, SynchScope);
3363 InstructionList.push_back(I);
3366 case bitc::FUNC_CODE_INST_CALL: {
3367 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3368 if (Record.size() < 3)
3369 return Error("Invalid record");
3371 AttributeSet PAL = getAttributes(Record[0]);
3372 unsigned CCInfo = Record[1];
3376 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3377 return Error("Invalid record");
3379 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3380 FunctionType *FTy = nullptr;
3381 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3382 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3383 return Error("Invalid record");
3385 SmallVector<Value*, 16> Args;
3386 // Read the fixed params.
3387 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3388 if (FTy->getParamType(i)->isLabelTy())
3389 Args.push_back(getBasicBlock(Record[OpNum]));
3391 Args.push_back(getValue(Record, OpNum, NextValueNo,
3392 FTy->getParamType(i)));
3394 return Error("Invalid record");
3397 // Read type/value pairs for varargs params.
3398 if (!FTy->isVarArg()) {
3399 if (OpNum != Record.size())
3400 return Error("Invalid record");
3402 while (OpNum != Record.size()) {
3404 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3405 return Error("Invalid record");
3410 I = CallInst::Create(Callee, Args);
3411 InstructionList.push_back(I);
3412 cast<CallInst>(I)->setCallingConv(
3413 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3414 CallInst::TailCallKind TCK = CallInst::TCK_None;
3416 TCK = CallInst::TCK_Tail;
3417 if (CCInfo & (1 << 14))
3418 TCK = CallInst::TCK_MustTail;
3419 cast<CallInst>(I)->setTailCallKind(TCK);
3420 cast<CallInst>(I)->setAttributes(PAL);
3423 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3424 if (Record.size() < 3)
3425 return Error("Invalid record");
3426 Type *OpTy = getTypeByID(Record[0]);
3427 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3428 Type *ResTy = getTypeByID(Record[2]);
3429 if (!OpTy || !Op || !ResTy)
3430 return Error("Invalid record");
3431 I = new VAArgInst(Op, ResTy);
3432 InstructionList.push_back(I);
3437 // Add instruction to end of current BB. If there is no current BB, reject
3441 return Error("Invalid instruction with no BB");
3443 CurBB->getInstList().push_back(I);
3445 // If this was a terminator instruction, move to the next block.
3446 if (isa<TerminatorInst>(I)) {
3448 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3451 // Non-void values get registered in the value table for future use.
3452 if (I && !I->getType()->isVoidTy())
3453 ValueList.AssignValue(I, NextValueNo++);
3458 // Check the function list for unresolved values.
3459 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3460 if (!A->getParent()) {
3461 // We found at least one unresolved value. Nuke them all to avoid leaks.
3462 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3463 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3464 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3468 return Error("Never resolved value found in function");
3472 // FIXME: Check for unresolved forward-declared metadata references
3473 // and clean up leaks.
3475 // Trim the value list down to the size it was before we parsed this function.
3476 ValueList.shrinkTo(ModuleValueListSize);
3477 MDValueList.shrinkTo(ModuleMDValueListSize);
3478 std::vector<BasicBlock*>().swap(FunctionBBs);
3479 return std::error_code();
3482 /// Find the function body in the bitcode stream
3483 std::error_code BitcodeReader::FindFunctionInStream(
3485 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3486 while (DeferredFunctionInfoIterator->second == 0) {
3487 if (Stream.AtEndOfStream())
3488 return Error("Could not find function in stream");
3489 // ParseModule will parse the next body in the stream and set its
3490 // position in the DeferredFunctionInfo map.
3491 if (std::error_code EC = ParseModule(true))
3494 return std::error_code();
3497 //===----------------------------------------------------------------------===//
3498 // GVMaterializer implementation
3499 //===----------------------------------------------------------------------===//
3501 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3503 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3504 Function *F = dyn_cast<Function>(GV);
3505 // If it's not a function or is already material, ignore the request.
3506 if (!F || !F->isMaterializable())
3507 return std::error_code();
3509 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3510 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3511 // If its position is recorded as 0, its body is somewhere in the stream
3512 // but we haven't seen it yet.
3513 if (DFII->second == 0 && LazyStreamer)
3514 if (std::error_code EC = FindFunctionInStream(F, DFII))
3517 // Move the bit stream to the saved position of the deferred function body.
3518 Stream.JumpToBit(DFII->second);
3520 if (std::error_code EC = ParseFunctionBody(F))
3522 F->setIsMaterializable(false);
3524 // Upgrade any old intrinsic calls in the function.
3525 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3526 E = UpgradedIntrinsics.end(); I != E; ++I) {
3527 if (I->first != I->second) {
3528 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3530 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3531 UpgradeIntrinsicCall(CI, I->second);
3536 // Bring in any functions that this function forward-referenced via
3538 return materializeForwardReferencedFunctions();
3541 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3542 const Function *F = dyn_cast<Function>(GV);
3543 if (!F || F->isDeclaration())
3546 // Dematerializing F would leave dangling references that wouldn't be
3547 // reconnected on re-materialization.
3548 if (BlockAddressesTaken.count(F))
3551 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3554 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3555 Function *F = dyn_cast<Function>(GV);
3556 // If this function isn't dematerializable, this is a noop.
3557 if (!F || !isDematerializable(F))
3560 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3562 // Just forget the function body, we can remat it later.
3563 F->dropAllReferences();
3564 F->setIsMaterializable(true);
3567 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3568 assert(M == TheModule &&
3569 "Can only Materialize the Module this BitcodeReader is attached to.");
3571 // Promise to materialize all forward references.
3572 WillMaterializeAllForwardRefs = true;
3574 // Iterate over the module, deserializing any functions that are still on
3576 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3578 if (std::error_code EC = materialize(F))
3581 // At this point, if there are any function bodies, the current bit is
3582 // pointing to the END_BLOCK record after them. Now make sure the rest
3583 // of the bits in the module have been read.
3587 // Check that all block address forward references got resolved (as we
3589 if (!BasicBlockFwdRefs.empty())
3590 return Error("Never resolved function from blockaddress");
3592 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3593 // delete the old functions to clean up. We can't do this unless the entire
3594 // module is materialized because there could always be another function body
3595 // with calls to the old function.
3596 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3597 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3598 if (I->first != I->second) {
3599 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3601 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3602 UpgradeIntrinsicCall(CI, I->second);
3604 if (!I->first->use_empty())
3605 I->first->replaceAllUsesWith(I->second);
3606 I->first->eraseFromParent();
3609 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3611 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3612 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3614 UpgradeDebugInfo(*M);
3615 return std::error_code();
3618 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3619 return IdentifiedStructTypes;
3622 std::error_code BitcodeReader::InitStream() {
3624 return InitLazyStream();
3625 return InitStreamFromBuffer();
3628 std::error_code BitcodeReader::InitStreamFromBuffer() {
3629 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3630 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3632 if (Buffer->getBufferSize() & 3)
3633 return Error("Invalid bitcode signature");
3635 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3636 // The magic number is 0x0B17C0DE stored in little endian.
3637 if (isBitcodeWrapper(BufPtr, BufEnd))
3638 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3639 return Error("Invalid bitcode wrapper header");
3641 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3642 Stream.init(&*StreamFile);
3644 return std::error_code();
3647 std::error_code BitcodeReader::InitLazyStream() {
3648 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3650 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3651 StreamingMemoryObject &Bytes = *OwnedBytes;
3652 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3653 Stream.init(&*StreamFile);
3655 unsigned char buf[16];
3656 if (Bytes.readBytes(buf, 16, 0) != 16)
3657 return Error("Invalid bitcode signature");
3659 if (!isBitcode(buf, buf + 16))
3660 return Error("Invalid bitcode signature");
3662 if (isBitcodeWrapper(buf, buf + 4)) {
3663 const unsigned char *bitcodeStart = buf;
3664 const unsigned char *bitcodeEnd = buf + 16;
3665 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3666 Bytes.dropLeadingBytes(bitcodeStart - buf);
3667 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3669 return std::error_code();
3673 class BitcodeErrorCategoryType : public std::error_category {
3674 const char *name() const LLVM_NOEXCEPT override {
3675 return "llvm.bitcode";
3677 std::string message(int IE) const override {
3678 BitcodeError E = static_cast<BitcodeError>(IE);
3680 case BitcodeError::InvalidBitcodeSignature:
3681 return "Invalid bitcode signature";
3682 case BitcodeError::CorruptedBitcode:
3683 return "Corrupted bitcode";
3685 llvm_unreachable("Unknown error type!");
3690 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3692 const std::error_category &llvm::BitcodeErrorCategory() {
3693 return *ErrorCategory;
3696 //===----------------------------------------------------------------------===//
3697 // External interface
3698 //===----------------------------------------------------------------------===//
3700 /// \brief Get a lazy one-at-time loading module from bitcode.
3702 /// This isn't always used in a lazy context. In particular, it's also used by
3703 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3704 /// in forward-referenced functions from block address references.
3706 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3707 /// materialize everything -- in particular, if this isn't truly lazy.
3708 static ErrorOr<Module *>
3709 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3710 LLVMContext &Context, bool WillMaterializeAll,
3711 DiagnosticHandlerFunction DiagnosticHandler) {
3712 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3714 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3715 M->setMaterializer(R);
3717 auto cleanupOnError = [&](std::error_code EC) {
3718 R->releaseBuffer(); // Never take ownership on error.
3719 delete M; // Also deletes R.
3723 if (std::error_code EC = R->ParseBitcodeInto(M))
3724 return cleanupOnError(EC);
3726 if (!WillMaterializeAll)
3727 // Resolve forward references from blockaddresses.
3728 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3729 return cleanupOnError(EC);
3731 Buffer.release(); // The BitcodeReader owns it now.
3736 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3737 LLVMContext &Context,
3738 DiagnosticHandlerFunction DiagnosticHandler) {
3739 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3743 ErrorOr<std::unique_ptr<Module>>
3744 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3745 LLVMContext &Context,
3746 DiagnosticHandlerFunction DiagnosticHandler) {
3747 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3748 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
3749 M->setMaterializer(R);
3750 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3752 return std::move(M);
3756 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3757 DiagnosticHandlerFunction DiagnosticHandler) {
3758 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3759 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3760 std::move(Buf), Context, true, DiagnosticHandler);
3763 Module *M = ModuleOrErr.get();
3764 // Read in the entire module, and destroy the BitcodeReader.
3765 if (std::error_code EC = M->materializeAllPermanently()) {
3770 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3771 // written. We must defer until the Module has been fully materialized.
3777 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3778 DiagnosticHandlerFunction DiagnosticHandler) {
3779 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3780 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3782 ErrorOr<std::string> Triple = R->parseTriple();
3783 if (Triple.getError())
3785 return Triple.get();