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/ADT/Triple.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/DiagnosticPrinter.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/OperandTraits.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/Support/DataStream.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
35 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
38 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
39 DiagnosticSeverity Severity,
41 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
43 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
45 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
46 std::error_code EC, const Twine &Message) {
47 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
48 DiagnosticHandler(DI);
52 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
54 return Error(DiagnosticHandler, EC, EC.message());
57 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
58 return ::Error(DiagnosticHandler, make_error_code(E), Message);
61 std::error_code BitcodeReader::Error(const Twine &Message) {
62 return ::Error(DiagnosticHandler,
63 make_error_code(BitcodeError::CorruptedBitcode), Message);
66 std::error_code BitcodeReader::Error(BitcodeError E) {
67 return ::Error(DiagnosticHandler, make_error_code(E));
70 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
74 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
77 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
78 DiagnosticHandlerFunction DiagnosticHandler)
79 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
80 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
81 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
82 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
83 WillMaterializeAllForwardRefs(false) {}
85 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
86 DiagnosticHandlerFunction DiagnosticHandler)
87 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
88 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
89 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
90 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
91 WillMaterializeAllForwardRefs(false) {}
93 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
94 if (WillMaterializeAllForwardRefs)
95 return std::error_code();
98 WillMaterializeAllForwardRefs = true;
100 while (!BasicBlockFwdRefQueue.empty()) {
101 Function *F = BasicBlockFwdRefQueue.front();
102 BasicBlockFwdRefQueue.pop_front();
103 assert(F && "Expected valid function");
104 if (!BasicBlockFwdRefs.count(F))
105 // Already materialized.
108 // Check for a function that isn't materializable to prevent an infinite
109 // loop. When parsing a blockaddress stored in a global variable, there
110 // isn't a trivial way to check if a function will have a body without a
111 // linear search through FunctionsWithBodies, so just check it here.
112 if (!F->isMaterializable())
113 return Error("Never resolved function from blockaddress");
115 // Try to materialize F.
116 if (std::error_code EC = materialize(F))
119 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
122 WillMaterializeAllForwardRefs = false;
123 return std::error_code();
126 void BitcodeReader::FreeState() {
128 std::vector<Type*>().swap(TypeList);
131 std::vector<Comdat *>().swap(ComdatList);
133 std::vector<AttributeSet>().swap(MAttributes);
134 std::vector<BasicBlock*>().swap(FunctionBBs);
135 std::vector<Function*>().swap(FunctionsWithBodies);
136 DeferredFunctionInfo.clear();
139 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
140 BasicBlockFwdRefQueue.clear();
143 //===----------------------------------------------------------------------===//
144 // Helper functions to implement forward reference resolution, etc.
145 //===----------------------------------------------------------------------===//
147 /// ConvertToString - Convert a string from a record into an std::string, return
149 template<typename StrTy>
150 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
152 if (Idx > Record.size())
155 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
156 Result += (char)Record[i];
160 static bool hasImplicitComdat(size_t Val) {
164 case 1: // Old WeakAnyLinkage
165 case 4: // Old LinkOnceAnyLinkage
166 case 10: // Old WeakODRLinkage
167 case 11: // Old LinkOnceODRLinkage
172 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
174 default: // Map unknown/new linkages to external
176 return GlobalValue::ExternalLinkage;
178 return GlobalValue::AppendingLinkage;
180 return GlobalValue::InternalLinkage;
182 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
184 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
186 return GlobalValue::ExternalWeakLinkage;
188 return GlobalValue::CommonLinkage;
190 return GlobalValue::PrivateLinkage;
192 return GlobalValue::AvailableExternallyLinkage;
194 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
196 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
198 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
199 case 1: // Old value with implicit comdat.
201 return GlobalValue::WeakAnyLinkage;
202 case 10: // Old value with implicit comdat.
204 return GlobalValue::WeakODRLinkage;
205 case 4: // Old value with implicit comdat.
207 return GlobalValue::LinkOnceAnyLinkage;
208 case 11: // Old value with implicit comdat.
210 return GlobalValue::LinkOnceODRLinkage;
214 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
216 default: // Map unknown visibilities to default.
217 case 0: return GlobalValue::DefaultVisibility;
218 case 1: return GlobalValue::HiddenVisibility;
219 case 2: return GlobalValue::ProtectedVisibility;
223 static GlobalValue::DLLStorageClassTypes
224 GetDecodedDLLStorageClass(unsigned Val) {
226 default: // Map unknown values to default.
227 case 0: return GlobalValue::DefaultStorageClass;
228 case 1: return GlobalValue::DLLImportStorageClass;
229 case 2: return GlobalValue::DLLExportStorageClass;
233 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
235 case 0: return GlobalVariable::NotThreadLocal;
236 default: // Map unknown non-zero value to general dynamic.
237 case 1: return GlobalVariable::GeneralDynamicTLSModel;
238 case 2: return GlobalVariable::LocalDynamicTLSModel;
239 case 3: return GlobalVariable::InitialExecTLSModel;
240 case 4: return GlobalVariable::LocalExecTLSModel;
244 static int GetDecodedCastOpcode(unsigned Val) {
247 case bitc::CAST_TRUNC : return Instruction::Trunc;
248 case bitc::CAST_ZEXT : return Instruction::ZExt;
249 case bitc::CAST_SEXT : return Instruction::SExt;
250 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
251 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
252 case bitc::CAST_UITOFP : return Instruction::UIToFP;
253 case bitc::CAST_SITOFP : return Instruction::SIToFP;
254 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
255 case bitc::CAST_FPEXT : return Instruction::FPExt;
256 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
257 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
258 case bitc::CAST_BITCAST : return Instruction::BitCast;
259 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
262 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
265 case bitc::BINOP_ADD:
266 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
267 case bitc::BINOP_SUB:
268 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
269 case bitc::BINOP_MUL:
270 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
271 case bitc::BINOP_UDIV: return Instruction::UDiv;
272 case bitc::BINOP_SDIV:
273 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
274 case bitc::BINOP_UREM: return Instruction::URem;
275 case bitc::BINOP_SREM:
276 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
277 case bitc::BINOP_SHL: return Instruction::Shl;
278 case bitc::BINOP_LSHR: return Instruction::LShr;
279 case bitc::BINOP_ASHR: return Instruction::AShr;
280 case bitc::BINOP_AND: return Instruction::And;
281 case bitc::BINOP_OR: return Instruction::Or;
282 case bitc::BINOP_XOR: return Instruction::Xor;
286 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
288 default: return AtomicRMWInst::BAD_BINOP;
289 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
290 case bitc::RMW_ADD: return AtomicRMWInst::Add;
291 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
292 case bitc::RMW_AND: return AtomicRMWInst::And;
293 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
294 case bitc::RMW_OR: return AtomicRMWInst::Or;
295 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
296 case bitc::RMW_MAX: return AtomicRMWInst::Max;
297 case bitc::RMW_MIN: return AtomicRMWInst::Min;
298 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
299 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
303 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
305 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
306 case bitc::ORDERING_UNORDERED: return Unordered;
307 case bitc::ORDERING_MONOTONIC: return Monotonic;
308 case bitc::ORDERING_ACQUIRE: return Acquire;
309 case bitc::ORDERING_RELEASE: return Release;
310 case bitc::ORDERING_ACQREL: return AcquireRelease;
311 default: // Map unknown orderings to sequentially-consistent.
312 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
316 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
318 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
319 default: // Map unknown scopes to cross-thread.
320 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
324 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
326 default: // Map unknown selection kinds to any.
327 case bitc::COMDAT_SELECTION_KIND_ANY:
329 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
330 return Comdat::ExactMatch;
331 case bitc::COMDAT_SELECTION_KIND_LARGEST:
332 return Comdat::Largest;
333 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
334 return Comdat::NoDuplicates;
335 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
336 return Comdat::SameSize;
340 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
342 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
343 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
349 /// @brief A class for maintaining the slot number definition
350 /// as a placeholder for the actual definition for forward constants defs.
351 class ConstantPlaceHolder : public ConstantExpr {
352 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
354 // allocate space for exactly one operand
355 void *operator new(size_t s) {
356 return User::operator new(s, 1);
358 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
359 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
360 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
363 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
364 static bool classof(const Value *V) {
365 return isa<ConstantExpr>(V) &&
366 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
370 /// Provide fast operand accessors
371 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
375 // FIXME: can we inherit this from ConstantExpr?
377 struct OperandTraits<ConstantPlaceHolder> :
378 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
380 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
384 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
393 WeakVH &OldV = ValuePtrs[Idx];
399 // Handle constants and non-constants (e.g. instrs) differently for
401 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
402 ResolveConstants.push_back(std::make_pair(PHC, Idx));
405 // If there was a forward reference to this value, replace it.
406 Value *PrevVal = OldV;
407 OldV->replaceAllUsesWith(V);
413 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
418 if (Value *V = ValuePtrs[Idx]) {
419 assert(Ty == V->getType() && "Type mismatch in constant table!");
420 return cast<Constant>(V);
423 // Create and return a placeholder, which will later be RAUW'd.
424 Constant *C = new ConstantPlaceHolder(Ty, Context);
429 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
433 if (Value *V = ValuePtrs[Idx]) {
434 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
438 // No type specified, must be invalid reference.
439 if (!Ty) return nullptr;
441 // Create and return a placeholder, which will later be RAUW'd.
442 Value *V = new Argument(Ty);
447 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
448 /// resolves any forward references. The idea behind this is that we sometimes
449 /// get constants (such as large arrays) which reference *many* forward ref
450 /// constants. Replacing each of these causes a lot of thrashing when
451 /// building/reuniquing the constant. Instead of doing this, we look at all the
452 /// uses and rewrite all the place holders at once for any constant that uses
454 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
455 // Sort the values by-pointer so that they are efficient to look up with a
457 std::sort(ResolveConstants.begin(), ResolveConstants.end());
459 SmallVector<Constant*, 64> NewOps;
461 while (!ResolveConstants.empty()) {
462 Value *RealVal = operator[](ResolveConstants.back().second);
463 Constant *Placeholder = ResolveConstants.back().first;
464 ResolveConstants.pop_back();
466 // Loop over all users of the placeholder, updating them to reference the
467 // new value. If they reference more than one placeholder, update them all
469 while (!Placeholder->use_empty()) {
470 auto UI = Placeholder->user_begin();
473 // If the using object isn't uniqued, just update the operands. This
474 // handles instructions and initializers for global variables.
475 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
476 UI.getUse().set(RealVal);
480 // Otherwise, we have a constant that uses the placeholder. Replace that
481 // constant with a new constant that has *all* placeholder uses updated.
482 Constant *UserC = cast<Constant>(U);
483 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
486 if (!isa<ConstantPlaceHolder>(*I)) {
487 // Not a placeholder reference.
489 } else if (*I == Placeholder) {
490 // Common case is that it just references this one placeholder.
493 // Otherwise, look up the placeholder in ResolveConstants.
494 ResolveConstantsTy::iterator It =
495 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
496 std::pair<Constant*, unsigned>(cast<Constant>(*I),
498 assert(It != ResolveConstants.end() && It->first == *I);
499 NewOp = operator[](It->second);
502 NewOps.push_back(cast<Constant>(NewOp));
505 // Make the new constant.
507 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
508 NewC = ConstantArray::get(UserCA->getType(), NewOps);
509 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
510 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
511 } else if (isa<ConstantVector>(UserC)) {
512 NewC = ConstantVector::get(NewOps);
514 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
515 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
518 UserC->replaceAllUsesWith(NewC);
519 UserC->destroyConstant();
523 // Update all ValueHandles, they should be the only users at this point.
524 Placeholder->replaceAllUsesWith(RealVal);
529 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
538 TrackingMDRef &OldMD = MDValuePtrs[Idx];
544 // If there was a forward reference to this value, replace it.
545 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
546 PrevMD->replaceAllUsesWith(MD);
550 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
554 if (Metadata *MD = MDValuePtrs[Idx])
557 // Create and return a placeholder, which will later be RAUW'd.
560 Metadata *MD = MDNode::getTemporary(Context, None).release();
561 MDValuePtrs[Idx].reset(MD);
565 void BitcodeReaderMDValueList::tryToResolveCycles() {
571 // Still forward references... can't resolve cycles.
574 // Resolve any cycles.
575 for (auto &MD : MDValuePtrs) {
576 auto *N = dyn_cast_or_null<MDNode>(MD);
580 assert(!N->isTemporary() && "Unexpected forward reference");
585 Type *BitcodeReader::getTypeByID(unsigned ID) {
586 // The type table size is always specified correctly.
587 if (ID >= TypeList.size())
590 if (Type *Ty = TypeList[ID])
593 // If we have a forward reference, the only possible case is when it is to a
594 // named struct. Just create a placeholder for now.
595 return TypeList[ID] = createIdentifiedStructType(Context);
598 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
600 auto *Ret = StructType::create(Context, Name);
601 IdentifiedStructTypes.push_back(Ret);
605 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
606 auto *Ret = StructType::create(Context);
607 IdentifiedStructTypes.push_back(Ret);
612 //===----------------------------------------------------------------------===//
613 // Functions for parsing blocks from the bitcode file
614 //===----------------------------------------------------------------------===//
617 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
618 /// been decoded from the given integer. This function must stay in sync with
619 /// 'encodeLLVMAttributesForBitcode'.
620 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
621 uint64_t EncodedAttrs) {
622 // FIXME: Remove in 4.0.
624 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
625 // the bits above 31 down by 11 bits.
626 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
627 assert((!Alignment || isPowerOf2_32(Alignment)) &&
628 "Alignment must be a power of two.");
631 B.addAlignmentAttr(Alignment);
632 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
633 (EncodedAttrs & 0xffff));
636 std::error_code BitcodeReader::ParseAttributeBlock() {
637 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
638 return Error("Invalid record");
640 if (!MAttributes.empty())
641 return Error("Invalid multiple blocks");
643 SmallVector<uint64_t, 64> Record;
645 SmallVector<AttributeSet, 8> Attrs;
647 // Read all the records.
649 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
651 switch (Entry.Kind) {
652 case BitstreamEntry::SubBlock: // Handled for us already.
653 case BitstreamEntry::Error:
654 return Error("Malformed block");
655 case BitstreamEntry::EndBlock:
656 return std::error_code();
657 case BitstreamEntry::Record:
658 // The interesting case.
664 switch (Stream.readRecord(Entry.ID, Record)) {
665 default: // Default behavior: ignore.
667 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
668 // FIXME: Remove in 4.0.
669 if (Record.size() & 1)
670 return Error("Invalid record");
672 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
674 decodeLLVMAttributesForBitcode(B, Record[i+1]);
675 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
678 MAttributes.push_back(AttributeSet::get(Context, Attrs));
682 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
683 for (unsigned i = 0, e = Record.size(); i != e; ++i)
684 Attrs.push_back(MAttributeGroups[Record[i]]);
686 MAttributes.push_back(AttributeSet::get(Context, Attrs));
694 // Returns Attribute::None on unrecognized codes.
695 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
698 return Attribute::None;
699 case bitc::ATTR_KIND_ALIGNMENT:
700 return Attribute::Alignment;
701 case bitc::ATTR_KIND_ALWAYS_INLINE:
702 return Attribute::AlwaysInline;
703 case bitc::ATTR_KIND_BUILTIN:
704 return Attribute::Builtin;
705 case bitc::ATTR_KIND_BY_VAL:
706 return Attribute::ByVal;
707 case bitc::ATTR_KIND_IN_ALLOCA:
708 return Attribute::InAlloca;
709 case bitc::ATTR_KIND_COLD:
710 return Attribute::Cold;
711 case bitc::ATTR_KIND_INLINE_HINT:
712 return Attribute::InlineHint;
713 case bitc::ATTR_KIND_IN_REG:
714 return Attribute::InReg;
715 case bitc::ATTR_KIND_JUMP_TABLE:
716 return Attribute::JumpTable;
717 case bitc::ATTR_KIND_MIN_SIZE:
718 return Attribute::MinSize;
719 case bitc::ATTR_KIND_NAKED:
720 return Attribute::Naked;
721 case bitc::ATTR_KIND_NEST:
722 return Attribute::Nest;
723 case bitc::ATTR_KIND_NO_ALIAS:
724 return Attribute::NoAlias;
725 case bitc::ATTR_KIND_NO_BUILTIN:
726 return Attribute::NoBuiltin;
727 case bitc::ATTR_KIND_NO_CAPTURE:
728 return Attribute::NoCapture;
729 case bitc::ATTR_KIND_NO_DUPLICATE:
730 return Attribute::NoDuplicate;
731 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
732 return Attribute::NoImplicitFloat;
733 case bitc::ATTR_KIND_NO_INLINE:
734 return Attribute::NoInline;
735 case bitc::ATTR_KIND_NON_LAZY_BIND:
736 return Attribute::NonLazyBind;
737 case bitc::ATTR_KIND_NON_NULL:
738 return Attribute::NonNull;
739 case bitc::ATTR_KIND_DEREFERENCEABLE:
740 return Attribute::Dereferenceable;
741 case bitc::ATTR_KIND_NO_RED_ZONE:
742 return Attribute::NoRedZone;
743 case bitc::ATTR_KIND_NO_RETURN:
744 return Attribute::NoReturn;
745 case bitc::ATTR_KIND_NO_UNWIND:
746 return Attribute::NoUnwind;
747 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
748 return Attribute::OptimizeForSize;
749 case bitc::ATTR_KIND_OPTIMIZE_NONE:
750 return Attribute::OptimizeNone;
751 case bitc::ATTR_KIND_READ_NONE:
752 return Attribute::ReadNone;
753 case bitc::ATTR_KIND_READ_ONLY:
754 return Attribute::ReadOnly;
755 case bitc::ATTR_KIND_RETURNED:
756 return Attribute::Returned;
757 case bitc::ATTR_KIND_RETURNS_TWICE:
758 return Attribute::ReturnsTwice;
759 case bitc::ATTR_KIND_S_EXT:
760 return Attribute::SExt;
761 case bitc::ATTR_KIND_STACK_ALIGNMENT:
762 return Attribute::StackAlignment;
763 case bitc::ATTR_KIND_STACK_PROTECT:
764 return Attribute::StackProtect;
765 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
766 return Attribute::StackProtectReq;
767 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
768 return Attribute::StackProtectStrong;
769 case bitc::ATTR_KIND_STRUCT_RET:
770 return Attribute::StructRet;
771 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
772 return Attribute::SanitizeAddress;
773 case bitc::ATTR_KIND_SANITIZE_THREAD:
774 return Attribute::SanitizeThread;
775 case bitc::ATTR_KIND_SANITIZE_MEMORY:
776 return Attribute::SanitizeMemory;
777 case bitc::ATTR_KIND_UW_TABLE:
778 return Attribute::UWTable;
779 case bitc::ATTR_KIND_Z_EXT:
780 return Attribute::ZExt;
784 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
785 Attribute::AttrKind *Kind) {
786 *Kind = GetAttrFromCode(Code);
787 if (*Kind == Attribute::None)
788 return Error(BitcodeError::CorruptedBitcode,
789 "Unknown attribute kind (" + Twine(Code) + ")");
790 return std::error_code();
793 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
794 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
795 return Error("Invalid record");
797 if (!MAttributeGroups.empty())
798 return Error("Invalid multiple blocks");
800 SmallVector<uint64_t, 64> Record;
802 // Read all the records.
804 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
806 switch (Entry.Kind) {
807 case BitstreamEntry::SubBlock: // Handled for us already.
808 case BitstreamEntry::Error:
809 return Error("Malformed block");
810 case BitstreamEntry::EndBlock:
811 return std::error_code();
812 case BitstreamEntry::Record:
813 // The interesting case.
819 switch (Stream.readRecord(Entry.ID, Record)) {
820 default: // Default behavior: ignore.
822 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
823 if (Record.size() < 3)
824 return Error("Invalid record");
826 uint64_t GrpID = Record[0];
827 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
830 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
831 if (Record[i] == 0) { // Enum attribute
832 Attribute::AttrKind Kind;
833 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
836 B.addAttribute(Kind);
837 } else if (Record[i] == 1) { // Integer attribute
838 Attribute::AttrKind Kind;
839 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
841 if (Kind == Attribute::Alignment)
842 B.addAlignmentAttr(Record[++i]);
843 else if (Kind == Attribute::StackAlignment)
844 B.addStackAlignmentAttr(Record[++i]);
845 else if (Kind == Attribute::Dereferenceable)
846 B.addDereferenceableAttr(Record[++i]);
847 } else { // String attribute
848 assert((Record[i] == 3 || Record[i] == 4) &&
849 "Invalid attribute group entry");
850 bool HasValue = (Record[i++] == 4);
851 SmallString<64> KindStr;
852 SmallString<64> ValStr;
854 while (Record[i] != 0 && i != e)
855 KindStr += Record[i++];
856 assert(Record[i] == 0 && "Kind string not null terminated");
859 // Has a value associated with it.
860 ++i; // Skip the '0' that terminates the "kind" string.
861 while (Record[i] != 0 && i != e)
862 ValStr += Record[i++];
863 assert(Record[i] == 0 && "Value string not null terminated");
866 B.addAttribute(KindStr.str(), ValStr.str());
870 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
877 std::error_code BitcodeReader::ParseTypeTable() {
878 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
879 return Error("Invalid record");
881 return ParseTypeTableBody();
884 std::error_code BitcodeReader::ParseTypeTableBody() {
885 if (!TypeList.empty())
886 return Error("Invalid multiple blocks");
888 SmallVector<uint64_t, 64> Record;
889 unsigned NumRecords = 0;
891 SmallString<64> TypeName;
893 // Read all the records for this type table.
895 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
897 switch (Entry.Kind) {
898 case BitstreamEntry::SubBlock: // Handled for us already.
899 case BitstreamEntry::Error:
900 return Error("Malformed block");
901 case BitstreamEntry::EndBlock:
902 if (NumRecords != TypeList.size())
903 return Error("Malformed block");
904 return std::error_code();
905 case BitstreamEntry::Record:
906 // The interesting case.
912 Type *ResultTy = nullptr;
913 switch (Stream.readRecord(Entry.ID, Record)) {
915 return Error("Invalid value");
916 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
917 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
918 // type list. This allows us to reserve space.
919 if (Record.size() < 1)
920 return Error("Invalid record");
921 TypeList.resize(Record[0]);
923 case bitc::TYPE_CODE_VOID: // VOID
924 ResultTy = Type::getVoidTy(Context);
926 case bitc::TYPE_CODE_HALF: // HALF
927 ResultTy = Type::getHalfTy(Context);
929 case bitc::TYPE_CODE_FLOAT: // FLOAT
930 ResultTy = Type::getFloatTy(Context);
932 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
933 ResultTy = Type::getDoubleTy(Context);
935 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
936 ResultTy = Type::getX86_FP80Ty(Context);
938 case bitc::TYPE_CODE_FP128: // FP128
939 ResultTy = Type::getFP128Ty(Context);
941 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
942 ResultTy = Type::getPPC_FP128Ty(Context);
944 case bitc::TYPE_CODE_LABEL: // LABEL
945 ResultTy = Type::getLabelTy(Context);
947 case bitc::TYPE_CODE_METADATA: // METADATA
948 ResultTy = Type::getMetadataTy(Context);
950 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
951 ResultTy = Type::getX86_MMXTy(Context);
953 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
954 if (Record.size() < 1)
955 return Error("Invalid record");
957 ResultTy = IntegerType::get(Context, Record[0]);
959 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
960 // [pointee type, address space]
961 if (Record.size() < 1)
962 return Error("Invalid record");
963 unsigned AddressSpace = 0;
964 if (Record.size() == 2)
965 AddressSpace = Record[1];
966 ResultTy = getTypeByID(Record[0]);
968 return Error("Invalid type");
969 ResultTy = PointerType::get(ResultTy, AddressSpace);
972 case bitc::TYPE_CODE_FUNCTION_OLD: {
973 // FIXME: attrid is dead, remove it in LLVM 4.0
974 // FUNCTION: [vararg, attrid, retty, paramty x N]
975 if (Record.size() < 3)
976 return Error("Invalid record");
977 SmallVector<Type*, 8> ArgTys;
978 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
979 if (Type *T = getTypeByID(Record[i]))
985 ResultTy = getTypeByID(Record[2]);
986 if (!ResultTy || ArgTys.size() < Record.size()-3)
987 return Error("Invalid type");
989 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
992 case bitc::TYPE_CODE_FUNCTION: {
993 // FUNCTION: [vararg, retty, paramty x N]
994 if (Record.size() < 2)
995 return Error("Invalid record");
996 SmallVector<Type*, 8> ArgTys;
997 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
998 if (Type *T = getTypeByID(Record[i]))
1004 ResultTy = getTypeByID(Record[1]);
1005 if (!ResultTy || ArgTys.size() < Record.size()-2)
1006 return Error("Invalid type");
1008 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1011 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1012 if (Record.size() < 1)
1013 return Error("Invalid record");
1014 SmallVector<Type*, 8> EltTys;
1015 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1016 if (Type *T = getTypeByID(Record[i]))
1017 EltTys.push_back(T);
1021 if (EltTys.size() != Record.size()-1)
1022 return Error("Invalid type");
1023 ResultTy = StructType::get(Context, EltTys, Record[0]);
1026 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1027 if (ConvertToString(Record, 0, TypeName))
1028 return Error("Invalid record");
1031 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1032 if (Record.size() < 1)
1033 return Error("Invalid record");
1035 if (NumRecords >= TypeList.size())
1036 return Error("Invalid TYPE table");
1038 // Check to see if this was forward referenced, if so fill in the temp.
1039 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1041 Res->setName(TypeName);
1042 TypeList[NumRecords] = nullptr;
1043 } else // Otherwise, create a new struct.
1044 Res = createIdentifiedStructType(Context, TypeName);
1047 SmallVector<Type*, 8> EltTys;
1048 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1049 if (Type *T = getTypeByID(Record[i]))
1050 EltTys.push_back(T);
1054 if (EltTys.size() != Record.size()-1)
1055 return Error("Invalid record");
1056 Res->setBody(EltTys, Record[0]);
1060 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1061 if (Record.size() != 1)
1062 return Error("Invalid record");
1064 if (NumRecords >= TypeList.size())
1065 return Error("Invalid TYPE table");
1067 // Check to see if this was forward referenced, if so fill in the temp.
1068 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1070 Res->setName(TypeName);
1071 TypeList[NumRecords] = nullptr;
1072 } else // Otherwise, create a new struct with no body.
1073 Res = createIdentifiedStructType(Context, TypeName);
1078 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1079 if (Record.size() < 2)
1080 return Error("Invalid record");
1081 if ((ResultTy = getTypeByID(Record[1])))
1082 ResultTy = ArrayType::get(ResultTy, Record[0]);
1084 return Error("Invalid type");
1086 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1087 if (Record.size() < 2)
1088 return Error("Invalid record");
1089 if ((ResultTy = getTypeByID(Record[1])))
1090 ResultTy = VectorType::get(ResultTy, Record[0]);
1092 return Error("Invalid type");
1096 if (NumRecords >= TypeList.size())
1097 return Error("Invalid TYPE table");
1098 if (TypeList[NumRecords])
1100 "Invalid TYPE table: Only named structs can be forward referenced");
1101 assert(ResultTy && "Didn't read a type?");
1102 TypeList[NumRecords++] = ResultTy;
1106 std::error_code BitcodeReader::ParseValueSymbolTable() {
1107 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1108 return Error("Invalid record");
1110 SmallVector<uint64_t, 64> Record;
1112 Triple TT(TheModule->getTargetTriple());
1114 // Read all the records for this value table.
1115 SmallString<128> ValueName;
1117 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1119 switch (Entry.Kind) {
1120 case BitstreamEntry::SubBlock: // Handled for us already.
1121 case BitstreamEntry::Error:
1122 return Error("Malformed block");
1123 case BitstreamEntry::EndBlock:
1124 return std::error_code();
1125 case BitstreamEntry::Record:
1126 // The interesting case.
1132 switch (Stream.readRecord(Entry.ID, Record)) {
1133 default: // Default behavior: unknown type.
1135 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1136 if (ConvertToString(Record, 1, ValueName))
1137 return Error("Invalid record");
1138 unsigned ValueID = Record[0];
1139 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1140 return Error("Invalid record");
1141 Value *V = ValueList[ValueID];
1143 V->setName(StringRef(ValueName.data(), ValueName.size()));
1144 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1145 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1146 if (TT.isOSBinFormatMachO())
1147 GO->setComdat(nullptr);
1149 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1155 case bitc::VST_CODE_BBENTRY: {
1156 if (ConvertToString(Record, 1, ValueName))
1157 return Error("Invalid record");
1158 BasicBlock *BB = getBasicBlock(Record[0]);
1160 return Error("Invalid record");
1162 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1170 std::error_code BitcodeReader::ParseMetadata() {
1171 unsigned NextMDValueNo = MDValueList.size();
1173 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1174 return Error("Invalid record");
1176 SmallVector<uint64_t, 64> Record;
1178 // Read all the records.
1180 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1182 switch (Entry.Kind) {
1183 case BitstreamEntry::SubBlock: // Handled for us already.
1184 case BitstreamEntry::Error:
1185 return Error("Malformed block");
1186 case BitstreamEntry::EndBlock:
1187 MDValueList.tryToResolveCycles();
1188 return std::error_code();
1189 case BitstreamEntry::Record:
1190 // The interesting case.
1196 unsigned Code = Stream.readRecord(Entry.ID, Record);
1197 bool IsDistinct = false;
1199 default: // Default behavior: ignore.
1201 case bitc::METADATA_NAME: {
1202 // Read name of the named metadata.
1203 SmallString<8> Name(Record.begin(), Record.end());
1205 Code = Stream.ReadCode();
1207 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1208 unsigned NextBitCode = Stream.readRecord(Code, Record);
1209 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1211 // Read named metadata elements.
1212 unsigned Size = Record.size();
1213 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1214 for (unsigned i = 0; i != Size; ++i) {
1215 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1217 return Error("Invalid record");
1218 NMD->addOperand(MD);
1222 case bitc::METADATA_OLD_FN_NODE: {
1223 // FIXME: Remove in 4.0.
1224 // This is a LocalAsMetadata record, the only type of function-local
1226 if (Record.size() % 2 == 1)
1227 return Error("Invalid record");
1229 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1230 // to be legal, but there's no upgrade path.
1231 auto dropRecord = [&] {
1232 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1234 if (Record.size() != 2) {
1239 Type *Ty = getTypeByID(Record[0]);
1240 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1245 MDValueList.AssignValue(
1246 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1250 case bitc::METADATA_OLD_NODE: {
1251 // FIXME: Remove in 4.0.
1252 if (Record.size() % 2 == 1)
1253 return Error("Invalid record");
1255 unsigned Size = Record.size();
1256 SmallVector<Metadata *, 8> Elts;
1257 for (unsigned i = 0; i != Size; i += 2) {
1258 Type *Ty = getTypeByID(Record[i]);
1260 return Error("Invalid record");
1261 if (Ty->isMetadataTy())
1262 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1263 else if (!Ty->isVoidTy()) {
1265 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1266 assert(isa<ConstantAsMetadata>(MD) &&
1267 "Expected non-function-local metadata");
1270 Elts.push_back(nullptr);
1272 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1275 case bitc::METADATA_VALUE: {
1276 if (Record.size() != 2)
1277 return Error("Invalid record");
1279 Type *Ty = getTypeByID(Record[0]);
1280 if (Ty->isMetadataTy() || Ty->isVoidTy())
1281 return Error("Invalid record");
1283 MDValueList.AssignValue(
1284 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1288 case bitc::METADATA_DISTINCT_NODE:
1291 case bitc::METADATA_NODE: {
1292 SmallVector<Metadata *, 8> Elts;
1293 Elts.reserve(Record.size());
1294 for (unsigned ID : Record)
1295 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1296 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1297 : MDNode::get(Context, Elts),
1301 case bitc::METADATA_LOCATION: {
1302 if (Record.size() != 5)
1303 return Error("Invalid record");
1305 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1306 unsigned Line = Record[1];
1307 unsigned Column = Record[2];
1308 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1309 Metadata *InlinedAt =
1310 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1311 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1315 case bitc::METADATA_STRING: {
1316 std::string String(Record.begin(), Record.end());
1317 llvm::UpgradeMDStringConstant(String);
1318 Metadata *MD = MDString::get(Context, String);
1319 MDValueList.AssignValue(MD, NextMDValueNo++);
1322 case bitc::METADATA_KIND: {
1323 if (Record.size() < 2)
1324 return Error("Invalid record");
1326 unsigned Kind = Record[0];
1327 SmallString<8> Name(Record.begin()+1, Record.end());
1329 unsigned NewKind = TheModule->getMDKindID(Name.str());
1330 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1331 return Error("Conflicting METADATA_KIND records");
1338 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1339 /// the LSB for dense VBR encoding.
1340 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1345 // There is no such thing as -0 with integers. "-0" really means MININT.
1349 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1350 /// values and aliases that we can.
1351 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1352 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1353 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1354 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1355 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1357 GlobalInitWorklist.swap(GlobalInits);
1358 AliasInitWorklist.swap(AliasInits);
1359 FunctionPrefixWorklist.swap(FunctionPrefixes);
1360 FunctionPrologueWorklist.swap(FunctionPrologues);
1362 while (!GlobalInitWorklist.empty()) {
1363 unsigned ValID = GlobalInitWorklist.back().second;
1364 if (ValID >= ValueList.size()) {
1365 // Not ready to resolve this yet, it requires something later in the file.
1366 GlobalInits.push_back(GlobalInitWorklist.back());
1368 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1369 GlobalInitWorklist.back().first->setInitializer(C);
1371 return Error("Expected a constant");
1373 GlobalInitWorklist.pop_back();
1376 while (!AliasInitWorklist.empty()) {
1377 unsigned ValID = AliasInitWorklist.back().second;
1378 if (ValID >= ValueList.size()) {
1379 AliasInits.push_back(AliasInitWorklist.back());
1381 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1382 AliasInitWorklist.back().first->setAliasee(C);
1384 return Error("Expected a constant");
1386 AliasInitWorklist.pop_back();
1389 while (!FunctionPrefixWorklist.empty()) {
1390 unsigned ValID = FunctionPrefixWorklist.back().second;
1391 if (ValID >= ValueList.size()) {
1392 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1394 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1395 FunctionPrefixWorklist.back().first->setPrefixData(C);
1397 return Error("Expected a constant");
1399 FunctionPrefixWorklist.pop_back();
1402 while (!FunctionPrologueWorklist.empty()) {
1403 unsigned ValID = FunctionPrologueWorklist.back().second;
1404 if (ValID >= ValueList.size()) {
1405 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1407 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1408 FunctionPrologueWorklist.back().first->setPrologueData(C);
1410 return Error("Expected a constant");
1412 FunctionPrologueWorklist.pop_back();
1415 return std::error_code();
1418 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1419 SmallVector<uint64_t, 8> Words(Vals.size());
1420 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1421 BitcodeReader::decodeSignRotatedValue);
1423 return APInt(TypeBits, Words);
1426 std::error_code BitcodeReader::ParseConstants() {
1427 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1428 return Error("Invalid record");
1430 SmallVector<uint64_t, 64> Record;
1432 // Read all the records for this value table.
1433 Type *CurTy = Type::getInt32Ty(Context);
1434 unsigned NextCstNo = ValueList.size();
1436 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1438 switch (Entry.Kind) {
1439 case BitstreamEntry::SubBlock: // Handled for us already.
1440 case BitstreamEntry::Error:
1441 return Error("Malformed block");
1442 case BitstreamEntry::EndBlock:
1443 if (NextCstNo != ValueList.size())
1444 return Error("Invalid ronstant reference");
1446 // Once all the constants have been read, go through and resolve forward
1448 ValueList.ResolveConstantForwardRefs();
1449 return std::error_code();
1450 case BitstreamEntry::Record:
1451 // The interesting case.
1458 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1460 default: // Default behavior: unknown constant
1461 case bitc::CST_CODE_UNDEF: // UNDEF
1462 V = UndefValue::get(CurTy);
1464 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1466 return Error("Invalid record");
1467 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1468 return Error("Invalid record");
1469 CurTy = TypeList[Record[0]];
1470 continue; // Skip the ValueList manipulation.
1471 case bitc::CST_CODE_NULL: // NULL
1472 V = Constant::getNullValue(CurTy);
1474 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1475 if (!CurTy->isIntegerTy() || Record.empty())
1476 return Error("Invalid record");
1477 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1479 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1480 if (!CurTy->isIntegerTy() || Record.empty())
1481 return Error("Invalid record");
1483 APInt VInt = ReadWideAPInt(Record,
1484 cast<IntegerType>(CurTy)->getBitWidth());
1485 V = ConstantInt::get(Context, VInt);
1489 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1491 return Error("Invalid record");
1492 if (CurTy->isHalfTy())
1493 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1494 APInt(16, (uint16_t)Record[0])));
1495 else if (CurTy->isFloatTy())
1496 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1497 APInt(32, (uint32_t)Record[0])));
1498 else if (CurTy->isDoubleTy())
1499 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1500 APInt(64, Record[0])));
1501 else if (CurTy->isX86_FP80Ty()) {
1502 // Bits are not stored the same way as a normal i80 APInt, compensate.
1503 uint64_t Rearrange[2];
1504 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1505 Rearrange[1] = Record[0] >> 48;
1506 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1507 APInt(80, Rearrange)));
1508 } else if (CurTy->isFP128Ty())
1509 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1510 APInt(128, Record)));
1511 else if (CurTy->isPPC_FP128Ty())
1512 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1513 APInt(128, Record)));
1515 V = UndefValue::get(CurTy);
1519 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1521 return Error("Invalid record");
1523 unsigned Size = Record.size();
1524 SmallVector<Constant*, 16> Elts;
1526 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1527 for (unsigned i = 0; i != Size; ++i)
1528 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1529 STy->getElementType(i)));
1530 V = ConstantStruct::get(STy, Elts);
1531 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1532 Type *EltTy = ATy->getElementType();
1533 for (unsigned i = 0; i != Size; ++i)
1534 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1535 V = ConstantArray::get(ATy, Elts);
1536 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1537 Type *EltTy = VTy->getElementType();
1538 for (unsigned i = 0; i != Size; ++i)
1539 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1540 V = ConstantVector::get(Elts);
1542 V = UndefValue::get(CurTy);
1546 case bitc::CST_CODE_STRING: // STRING: [values]
1547 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1549 return Error("Invalid record");
1551 SmallString<16> Elts(Record.begin(), Record.end());
1552 V = ConstantDataArray::getString(Context, Elts,
1553 BitCode == bitc::CST_CODE_CSTRING);
1556 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1558 return Error("Invalid record");
1560 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1561 unsigned Size = Record.size();
1563 if (EltTy->isIntegerTy(8)) {
1564 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1565 if (isa<VectorType>(CurTy))
1566 V = ConstantDataVector::get(Context, Elts);
1568 V = ConstantDataArray::get(Context, Elts);
1569 } else if (EltTy->isIntegerTy(16)) {
1570 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1571 if (isa<VectorType>(CurTy))
1572 V = ConstantDataVector::get(Context, Elts);
1574 V = ConstantDataArray::get(Context, Elts);
1575 } else if (EltTy->isIntegerTy(32)) {
1576 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1577 if (isa<VectorType>(CurTy))
1578 V = ConstantDataVector::get(Context, Elts);
1580 V = ConstantDataArray::get(Context, Elts);
1581 } else if (EltTy->isIntegerTy(64)) {
1582 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1583 if (isa<VectorType>(CurTy))
1584 V = ConstantDataVector::get(Context, Elts);
1586 V = ConstantDataArray::get(Context, Elts);
1587 } else if (EltTy->isFloatTy()) {
1588 SmallVector<float, 16> Elts(Size);
1589 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1590 if (isa<VectorType>(CurTy))
1591 V = ConstantDataVector::get(Context, Elts);
1593 V = ConstantDataArray::get(Context, Elts);
1594 } else if (EltTy->isDoubleTy()) {
1595 SmallVector<double, 16> Elts(Size);
1596 std::transform(Record.begin(), Record.end(), Elts.begin(),
1598 if (isa<VectorType>(CurTy))
1599 V = ConstantDataVector::get(Context, Elts);
1601 V = ConstantDataArray::get(Context, Elts);
1603 return Error("Invalid type for value");
1608 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1609 if (Record.size() < 3)
1610 return Error("Invalid record");
1611 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1613 V = UndefValue::get(CurTy); // Unknown binop.
1615 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1616 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1618 if (Record.size() >= 4) {
1619 if (Opc == Instruction::Add ||
1620 Opc == Instruction::Sub ||
1621 Opc == Instruction::Mul ||
1622 Opc == Instruction::Shl) {
1623 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1624 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1625 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1626 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1627 } else if (Opc == Instruction::SDiv ||
1628 Opc == Instruction::UDiv ||
1629 Opc == Instruction::LShr ||
1630 Opc == Instruction::AShr) {
1631 if (Record[3] & (1 << bitc::PEO_EXACT))
1632 Flags |= SDivOperator::IsExact;
1635 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1639 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1640 if (Record.size() < 3)
1641 return Error("Invalid record");
1642 int Opc = GetDecodedCastOpcode(Record[0]);
1644 V = UndefValue::get(CurTy); // Unknown cast.
1646 Type *OpTy = getTypeByID(Record[1]);
1648 return Error("Invalid record");
1649 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1650 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1651 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1655 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1656 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1657 if (Record.size() & 1)
1658 return Error("Invalid record");
1659 SmallVector<Constant*, 16> Elts;
1660 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1661 Type *ElTy = getTypeByID(Record[i]);
1663 return Error("Invalid record");
1664 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1666 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1667 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1669 bitc::CST_CODE_CE_INBOUNDS_GEP);
1672 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1673 if (Record.size() < 3)
1674 return Error("Invalid record");
1676 Type *SelectorTy = Type::getInt1Ty(Context);
1678 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1679 // vector. Otherwise, it must be a single bit.
1680 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1681 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1682 VTy->getNumElements());
1684 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1686 ValueList.getConstantFwdRef(Record[1],CurTy),
1687 ValueList.getConstantFwdRef(Record[2],CurTy));
1690 case bitc::CST_CODE_CE_EXTRACTELT
1691 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1692 if (Record.size() < 3)
1693 return Error("Invalid record");
1695 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1697 return Error("Invalid record");
1698 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1699 Constant *Op1 = nullptr;
1700 if (Record.size() == 4) {
1701 Type *IdxTy = getTypeByID(Record[2]);
1703 return Error("Invalid record");
1704 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1705 } else // TODO: Remove with llvm 4.0
1706 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1708 return Error("Invalid record");
1709 V = ConstantExpr::getExtractElement(Op0, Op1);
1712 case bitc::CST_CODE_CE_INSERTELT
1713 : { // CE_INSERTELT: [opval, opval, opty, opval]
1714 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1715 if (Record.size() < 3 || !OpTy)
1716 return Error("Invalid record");
1717 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1718 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1719 OpTy->getElementType());
1720 Constant *Op2 = nullptr;
1721 if (Record.size() == 4) {
1722 Type *IdxTy = getTypeByID(Record[2]);
1724 return Error("Invalid record");
1725 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1726 } else // TODO: Remove with llvm 4.0
1727 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1729 return Error("Invalid record");
1730 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1733 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1734 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1735 if (Record.size() < 3 || !OpTy)
1736 return Error("Invalid record");
1737 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1738 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1739 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1740 OpTy->getNumElements());
1741 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1742 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1745 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1746 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1748 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1749 if (Record.size() < 4 || !RTy || !OpTy)
1750 return Error("Invalid record");
1751 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1752 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1753 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1754 RTy->getNumElements());
1755 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1756 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1759 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1760 if (Record.size() < 4)
1761 return Error("Invalid record");
1762 Type *OpTy = getTypeByID(Record[0]);
1764 return Error("Invalid record");
1765 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1766 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1768 if (OpTy->isFPOrFPVectorTy())
1769 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1771 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1774 // This maintains backward compatibility, pre-asm dialect keywords.
1775 // FIXME: Remove with the 4.0 release.
1776 case bitc::CST_CODE_INLINEASM_OLD: {
1777 if (Record.size() < 2)
1778 return Error("Invalid record");
1779 std::string AsmStr, ConstrStr;
1780 bool HasSideEffects = Record[0] & 1;
1781 bool IsAlignStack = Record[0] >> 1;
1782 unsigned AsmStrSize = Record[1];
1783 if (2+AsmStrSize >= Record.size())
1784 return Error("Invalid record");
1785 unsigned ConstStrSize = Record[2+AsmStrSize];
1786 if (3+AsmStrSize+ConstStrSize > Record.size())
1787 return Error("Invalid record");
1789 for (unsigned i = 0; i != AsmStrSize; ++i)
1790 AsmStr += (char)Record[2+i];
1791 for (unsigned i = 0; i != ConstStrSize; ++i)
1792 ConstrStr += (char)Record[3+AsmStrSize+i];
1793 PointerType *PTy = cast<PointerType>(CurTy);
1794 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1795 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1798 // This version adds support for the asm dialect keywords (e.g.,
1800 case bitc::CST_CODE_INLINEASM: {
1801 if (Record.size() < 2)
1802 return Error("Invalid record");
1803 std::string AsmStr, ConstrStr;
1804 bool HasSideEffects = Record[0] & 1;
1805 bool IsAlignStack = (Record[0] >> 1) & 1;
1806 unsigned AsmDialect = Record[0] >> 2;
1807 unsigned AsmStrSize = Record[1];
1808 if (2+AsmStrSize >= Record.size())
1809 return Error("Invalid record");
1810 unsigned ConstStrSize = Record[2+AsmStrSize];
1811 if (3+AsmStrSize+ConstStrSize > Record.size())
1812 return Error("Invalid record");
1814 for (unsigned i = 0; i != AsmStrSize; ++i)
1815 AsmStr += (char)Record[2+i];
1816 for (unsigned i = 0; i != ConstStrSize; ++i)
1817 ConstrStr += (char)Record[3+AsmStrSize+i];
1818 PointerType *PTy = cast<PointerType>(CurTy);
1819 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1820 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1821 InlineAsm::AsmDialect(AsmDialect));
1824 case bitc::CST_CODE_BLOCKADDRESS:{
1825 if (Record.size() < 3)
1826 return Error("Invalid record");
1827 Type *FnTy = getTypeByID(Record[0]);
1829 return Error("Invalid record");
1831 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1833 return Error("Invalid record");
1835 // Don't let Fn get dematerialized.
1836 BlockAddressesTaken.insert(Fn);
1838 // If the function is already parsed we can insert the block address right
1841 unsigned BBID = Record[2];
1843 // Invalid reference to entry block.
1844 return Error("Invalid ID");
1846 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1847 for (size_t I = 0, E = BBID; I != E; ++I) {
1849 return Error("Invalid ID");
1854 // Otherwise insert a placeholder and remember it so it can be inserted
1855 // when the function is parsed.
1856 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1858 BasicBlockFwdRefQueue.push_back(Fn);
1859 if (FwdBBs.size() < BBID + 1)
1860 FwdBBs.resize(BBID + 1);
1862 FwdBBs[BBID] = BasicBlock::Create(Context);
1865 V = BlockAddress::get(Fn, BB);
1870 ValueList.AssignValue(V, NextCstNo);
1875 std::error_code BitcodeReader::ParseUseLists() {
1876 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1877 return Error("Invalid record");
1879 // Read all the records.
1880 SmallVector<uint64_t, 64> Record;
1882 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1884 switch (Entry.Kind) {
1885 case BitstreamEntry::SubBlock: // Handled for us already.
1886 case BitstreamEntry::Error:
1887 return Error("Malformed block");
1888 case BitstreamEntry::EndBlock:
1889 return std::error_code();
1890 case BitstreamEntry::Record:
1891 // The interesting case.
1895 // Read a use list record.
1898 switch (Stream.readRecord(Entry.ID, Record)) {
1899 default: // Default behavior: unknown type.
1901 case bitc::USELIST_CODE_BB:
1904 case bitc::USELIST_CODE_DEFAULT: {
1905 unsigned RecordLength = Record.size();
1906 if (RecordLength < 3)
1907 // Records should have at least an ID and two indexes.
1908 return Error("Invalid record");
1909 unsigned ID = Record.back();
1914 assert(ID < FunctionBBs.size() && "Basic block not found");
1915 V = FunctionBBs[ID];
1918 unsigned NumUses = 0;
1919 SmallDenseMap<const Use *, unsigned, 16> Order;
1920 for (const Use &U : V->uses()) {
1921 if (++NumUses > Record.size())
1923 Order[&U] = Record[NumUses - 1];
1925 if (Order.size() != Record.size() || NumUses > Record.size())
1926 // Mismatches can happen if the functions are being materialized lazily
1927 // (out-of-order), or a value has been upgraded.
1930 V->sortUseList([&](const Use &L, const Use &R) {
1931 return Order.lookup(&L) < Order.lookup(&R);
1939 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1940 /// remember where it is and then skip it. This lets us lazily deserialize the
1942 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1943 // Get the function we are talking about.
1944 if (FunctionsWithBodies.empty())
1945 return Error("Insufficient function protos");
1947 Function *Fn = FunctionsWithBodies.back();
1948 FunctionsWithBodies.pop_back();
1950 // Save the current stream state.
1951 uint64_t CurBit = Stream.GetCurrentBitNo();
1952 DeferredFunctionInfo[Fn] = CurBit;
1954 // Skip over the function block for now.
1955 if (Stream.SkipBlock())
1956 return Error("Invalid record");
1957 return std::error_code();
1960 std::error_code BitcodeReader::GlobalCleanup() {
1961 // Patch the initializers for globals and aliases up.
1962 ResolveGlobalAndAliasInits();
1963 if (!GlobalInits.empty() || !AliasInits.empty())
1964 return Error("Malformed global initializer set");
1966 // Look for intrinsic functions which need to be upgraded at some point
1967 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1970 if (UpgradeIntrinsicFunction(FI, NewFn))
1971 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1974 // Look for global variables which need to be renamed.
1975 for (Module::global_iterator
1976 GI = TheModule->global_begin(), GE = TheModule->global_end();
1978 GlobalVariable *GV = GI++;
1979 UpgradeGlobalVariable(GV);
1982 // Force deallocation of memory for these vectors to favor the client that
1983 // want lazy deserialization.
1984 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1985 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1986 return std::error_code();
1989 std::error_code BitcodeReader::ParseModule(bool Resume) {
1991 Stream.JumpToBit(NextUnreadBit);
1992 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1993 return Error("Invalid record");
1995 SmallVector<uint64_t, 64> Record;
1996 std::vector<std::string> SectionTable;
1997 std::vector<std::string> GCTable;
1999 // Read all the records for this module.
2001 BitstreamEntry Entry = Stream.advance();
2003 switch (Entry.Kind) {
2004 case BitstreamEntry::Error:
2005 return Error("Malformed block");
2006 case BitstreamEntry::EndBlock:
2007 return GlobalCleanup();
2009 case BitstreamEntry::SubBlock:
2011 default: // Skip unknown content.
2012 if (Stream.SkipBlock())
2013 return Error("Invalid record");
2015 case bitc::BLOCKINFO_BLOCK_ID:
2016 if (Stream.ReadBlockInfoBlock())
2017 return Error("Malformed block");
2019 case bitc::PARAMATTR_BLOCK_ID:
2020 if (std::error_code EC = ParseAttributeBlock())
2023 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2024 if (std::error_code EC = ParseAttributeGroupBlock())
2027 case bitc::TYPE_BLOCK_ID_NEW:
2028 if (std::error_code EC = ParseTypeTable())
2031 case bitc::VALUE_SYMTAB_BLOCK_ID:
2032 if (std::error_code EC = ParseValueSymbolTable())
2034 SeenValueSymbolTable = true;
2036 case bitc::CONSTANTS_BLOCK_ID:
2037 if (std::error_code EC = ParseConstants())
2039 if (std::error_code EC = ResolveGlobalAndAliasInits())
2042 case bitc::METADATA_BLOCK_ID:
2043 if (std::error_code EC = ParseMetadata())
2046 case bitc::FUNCTION_BLOCK_ID:
2047 // If this is the first function body we've seen, reverse the
2048 // FunctionsWithBodies list.
2049 if (!SeenFirstFunctionBody) {
2050 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2051 if (std::error_code EC = GlobalCleanup())
2053 SeenFirstFunctionBody = true;
2056 if (std::error_code EC = RememberAndSkipFunctionBody())
2058 // For streaming bitcode, suspend parsing when we reach the function
2059 // bodies. Subsequent materialization calls will resume it when
2060 // necessary. For streaming, the function bodies must be at the end of
2061 // the bitcode. If the bitcode file is old, the symbol table will be
2062 // at the end instead and will not have been seen yet. In this case,
2063 // just finish the parse now.
2064 if (LazyStreamer && SeenValueSymbolTable) {
2065 NextUnreadBit = Stream.GetCurrentBitNo();
2066 return std::error_code();
2069 case bitc::USELIST_BLOCK_ID:
2070 if (std::error_code EC = ParseUseLists())
2076 case BitstreamEntry::Record:
2077 // The interesting case.
2083 switch (Stream.readRecord(Entry.ID, Record)) {
2084 default: break; // Default behavior, ignore unknown content.
2085 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2086 if (Record.size() < 1)
2087 return Error("Invalid record");
2088 // Only version #0 and #1 are supported so far.
2089 unsigned module_version = Record[0];
2090 switch (module_version) {
2092 return Error("Invalid value");
2094 UseRelativeIDs = false;
2097 UseRelativeIDs = true;
2102 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2104 if (ConvertToString(Record, 0, S))
2105 return Error("Invalid record");
2106 TheModule->setTargetTriple(S);
2109 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2111 if (ConvertToString(Record, 0, S))
2112 return Error("Invalid record");
2113 TheModule->setDataLayout(S);
2116 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2118 if (ConvertToString(Record, 0, S))
2119 return Error("Invalid record");
2120 TheModule->setModuleInlineAsm(S);
2123 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2124 // FIXME: Remove in 4.0.
2126 if (ConvertToString(Record, 0, S))
2127 return Error("Invalid record");
2131 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2133 if (ConvertToString(Record, 0, S))
2134 return Error("Invalid record");
2135 SectionTable.push_back(S);
2138 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2140 if (ConvertToString(Record, 0, S))
2141 return Error("Invalid record");
2142 GCTable.push_back(S);
2145 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2146 if (Record.size() < 2)
2147 return Error("Invalid record");
2148 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2149 unsigned ComdatNameSize = Record[1];
2150 std::string ComdatName;
2151 ComdatName.reserve(ComdatNameSize);
2152 for (unsigned i = 0; i != ComdatNameSize; ++i)
2153 ComdatName += (char)Record[2 + i];
2154 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2155 C->setSelectionKind(SK);
2156 ComdatList.push_back(C);
2159 // GLOBALVAR: [pointer type, isconst, initid,
2160 // linkage, alignment, section, visibility, threadlocal,
2161 // unnamed_addr, dllstorageclass]
2162 case bitc::MODULE_CODE_GLOBALVAR: {
2163 if (Record.size() < 6)
2164 return Error("Invalid record");
2165 Type *Ty = getTypeByID(Record[0]);
2167 return Error("Invalid record");
2168 if (!Ty->isPointerTy())
2169 return Error("Invalid type for value");
2170 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2171 Ty = cast<PointerType>(Ty)->getElementType();
2173 bool isConstant = Record[1];
2174 uint64_t RawLinkage = Record[3];
2175 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2176 unsigned Alignment = (1 << Record[4]) >> 1;
2177 std::string Section;
2179 if (Record[5]-1 >= SectionTable.size())
2180 return Error("Invalid ID");
2181 Section = SectionTable[Record[5]-1];
2183 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2184 // Local linkage must have default visibility.
2185 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2186 // FIXME: Change to an error if non-default in 4.0.
2187 Visibility = GetDecodedVisibility(Record[6]);
2189 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2190 if (Record.size() > 7)
2191 TLM = GetDecodedThreadLocalMode(Record[7]);
2193 bool UnnamedAddr = false;
2194 if (Record.size() > 8)
2195 UnnamedAddr = Record[8];
2197 bool ExternallyInitialized = false;
2198 if (Record.size() > 9)
2199 ExternallyInitialized = Record[9];
2201 GlobalVariable *NewGV =
2202 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2203 TLM, AddressSpace, ExternallyInitialized);
2204 NewGV->setAlignment(Alignment);
2205 if (!Section.empty())
2206 NewGV->setSection(Section);
2207 NewGV->setVisibility(Visibility);
2208 NewGV->setUnnamedAddr(UnnamedAddr);
2210 if (Record.size() > 10)
2211 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2213 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2215 ValueList.push_back(NewGV);
2217 // Remember which value to use for the global initializer.
2218 if (unsigned InitID = Record[2])
2219 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2221 if (Record.size() > 11) {
2222 if (unsigned ComdatID = Record[11]) {
2223 assert(ComdatID <= ComdatList.size());
2224 NewGV->setComdat(ComdatList[ComdatID - 1]);
2226 } else if (hasImplicitComdat(RawLinkage)) {
2227 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2231 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2232 // alignment, section, visibility, gc, unnamed_addr,
2233 // prologuedata, dllstorageclass, comdat, prefixdata]
2234 case bitc::MODULE_CODE_FUNCTION: {
2235 if (Record.size() < 8)
2236 return Error("Invalid record");
2237 Type *Ty = getTypeByID(Record[0]);
2239 return Error("Invalid record");
2240 if (!Ty->isPointerTy())
2241 return Error("Invalid type for value");
2243 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2245 return Error("Invalid type for value");
2247 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2250 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2251 bool isProto = Record[2];
2252 uint64_t RawLinkage = Record[3];
2253 Func->setLinkage(getDecodedLinkage(RawLinkage));
2254 Func->setAttributes(getAttributes(Record[4]));
2256 Func->setAlignment((1 << Record[5]) >> 1);
2258 if (Record[6]-1 >= SectionTable.size())
2259 return Error("Invalid ID");
2260 Func->setSection(SectionTable[Record[6]-1]);
2262 // Local linkage must have default visibility.
2263 if (!Func->hasLocalLinkage())
2264 // FIXME: Change to an error if non-default in 4.0.
2265 Func->setVisibility(GetDecodedVisibility(Record[7]));
2266 if (Record.size() > 8 && Record[8]) {
2267 if (Record[8]-1 > GCTable.size())
2268 return Error("Invalid ID");
2269 Func->setGC(GCTable[Record[8]-1].c_str());
2271 bool UnnamedAddr = false;
2272 if (Record.size() > 9)
2273 UnnamedAddr = Record[9];
2274 Func->setUnnamedAddr(UnnamedAddr);
2275 if (Record.size() > 10 && Record[10] != 0)
2276 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2278 if (Record.size() > 11)
2279 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2281 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2283 if (Record.size() > 12) {
2284 if (unsigned ComdatID = Record[12]) {
2285 assert(ComdatID <= ComdatList.size());
2286 Func->setComdat(ComdatList[ComdatID - 1]);
2288 } else if (hasImplicitComdat(RawLinkage)) {
2289 Func->setComdat(reinterpret_cast<Comdat *>(1));
2292 if (Record.size() > 13 && Record[13] != 0)
2293 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2295 ValueList.push_back(Func);
2297 // If this is a function with a body, remember the prototype we are
2298 // creating now, so that we can match up the body with them later.
2300 Func->setIsMaterializable(true);
2301 FunctionsWithBodies.push_back(Func);
2303 DeferredFunctionInfo[Func] = 0;
2307 // ALIAS: [alias type, aliasee val#, linkage]
2308 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2309 case bitc::MODULE_CODE_ALIAS: {
2310 if (Record.size() < 3)
2311 return Error("Invalid record");
2312 Type *Ty = getTypeByID(Record[0]);
2314 return Error("Invalid record");
2315 auto *PTy = dyn_cast<PointerType>(Ty);
2317 return Error("Invalid type for value");
2320 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2321 getDecodedLinkage(Record[2]), "", TheModule);
2322 // Old bitcode files didn't have visibility field.
2323 // Local linkage must have default visibility.
2324 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2325 // FIXME: Change to an error if non-default in 4.0.
2326 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2327 if (Record.size() > 4)
2328 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2330 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2331 if (Record.size() > 5)
2332 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2333 if (Record.size() > 6)
2334 NewGA->setUnnamedAddr(Record[6]);
2335 ValueList.push_back(NewGA);
2336 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2339 /// MODULE_CODE_PURGEVALS: [numvals]
2340 case bitc::MODULE_CODE_PURGEVALS:
2341 // Trim down the value list to the specified size.
2342 if (Record.size() < 1 || Record[0] > ValueList.size())
2343 return Error("Invalid record");
2344 ValueList.shrinkTo(Record[0]);
2351 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2352 TheModule = nullptr;
2354 if (std::error_code EC = InitStream())
2357 // Sniff for the signature.
2358 if (Stream.Read(8) != 'B' ||
2359 Stream.Read(8) != 'C' ||
2360 Stream.Read(4) != 0x0 ||
2361 Stream.Read(4) != 0xC ||
2362 Stream.Read(4) != 0xE ||
2363 Stream.Read(4) != 0xD)
2364 return Error("Invalid bitcode signature");
2366 // We expect a number of well-defined blocks, though we don't necessarily
2367 // need to understand them all.
2369 if (Stream.AtEndOfStream())
2370 return std::error_code();
2372 BitstreamEntry Entry =
2373 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2375 switch (Entry.Kind) {
2376 case BitstreamEntry::Error:
2377 return Error("Malformed block");
2378 case BitstreamEntry::EndBlock:
2379 return std::error_code();
2381 case BitstreamEntry::SubBlock:
2383 case bitc::BLOCKINFO_BLOCK_ID:
2384 if (Stream.ReadBlockInfoBlock())
2385 return Error("Malformed block");
2387 case bitc::MODULE_BLOCK_ID:
2388 // Reject multiple MODULE_BLOCK's in a single bitstream.
2390 return Error("Invalid multiple blocks");
2392 if (std::error_code EC = ParseModule(false))
2395 return std::error_code();
2398 if (Stream.SkipBlock())
2399 return Error("Invalid record");
2403 case BitstreamEntry::Record:
2404 // There should be no records in the top-level of blocks.
2406 // The ranlib in Xcode 4 will align archive members by appending newlines
2407 // to the end of them. If this file size is a multiple of 4 but not 8, we
2408 // have to read and ignore these final 4 bytes :-(
2409 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2410 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2411 Stream.AtEndOfStream())
2412 return std::error_code();
2414 return Error("Invalid record");
2419 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2420 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2421 return Error("Invalid record");
2423 SmallVector<uint64_t, 64> Record;
2426 // Read all the records for this module.
2428 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2430 switch (Entry.Kind) {
2431 case BitstreamEntry::SubBlock: // Handled for us already.
2432 case BitstreamEntry::Error:
2433 return Error("Malformed block");
2434 case BitstreamEntry::EndBlock:
2436 case BitstreamEntry::Record:
2437 // The interesting case.
2442 switch (Stream.readRecord(Entry.ID, Record)) {
2443 default: break; // Default behavior, ignore unknown content.
2444 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2446 if (ConvertToString(Record, 0, S))
2447 return Error("Invalid record");
2454 llvm_unreachable("Exit infinite loop");
2457 ErrorOr<std::string> BitcodeReader::parseTriple() {
2458 if (std::error_code EC = InitStream())
2461 // Sniff for the signature.
2462 if (Stream.Read(8) != 'B' ||
2463 Stream.Read(8) != 'C' ||
2464 Stream.Read(4) != 0x0 ||
2465 Stream.Read(4) != 0xC ||
2466 Stream.Read(4) != 0xE ||
2467 Stream.Read(4) != 0xD)
2468 return Error("Invalid bitcode signature");
2470 // We expect a number of well-defined blocks, though we don't necessarily
2471 // need to understand them all.
2473 BitstreamEntry Entry = Stream.advance();
2475 switch (Entry.Kind) {
2476 case BitstreamEntry::Error:
2477 return Error("Malformed block");
2478 case BitstreamEntry::EndBlock:
2479 return std::error_code();
2481 case BitstreamEntry::SubBlock:
2482 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2483 return parseModuleTriple();
2485 // Ignore other sub-blocks.
2486 if (Stream.SkipBlock())
2487 return Error("Malformed block");
2490 case BitstreamEntry::Record:
2491 Stream.skipRecord(Entry.ID);
2497 /// ParseMetadataAttachment - Parse metadata attachments.
2498 std::error_code BitcodeReader::ParseMetadataAttachment() {
2499 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2500 return Error("Invalid record");
2502 SmallVector<uint64_t, 64> Record;
2504 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2506 switch (Entry.Kind) {
2507 case BitstreamEntry::SubBlock: // Handled for us already.
2508 case BitstreamEntry::Error:
2509 return Error("Malformed block");
2510 case BitstreamEntry::EndBlock:
2511 return std::error_code();
2512 case BitstreamEntry::Record:
2513 // The interesting case.
2517 // Read a metadata attachment record.
2519 switch (Stream.readRecord(Entry.ID, Record)) {
2520 default: // Default behavior: ignore.
2522 case bitc::METADATA_ATTACHMENT: {
2523 unsigned RecordLength = Record.size();
2524 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2525 return Error("Invalid record");
2526 Instruction *Inst = InstructionList[Record[0]];
2527 for (unsigned i = 1; i != RecordLength; i = i+2) {
2528 unsigned Kind = Record[i];
2529 DenseMap<unsigned, unsigned>::iterator I =
2530 MDKindMap.find(Kind);
2531 if (I == MDKindMap.end())
2532 return Error("Invalid ID");
2533 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2534 if (isa<LocalAsMetadata>(Node))
2535 // Drop the attachment. This used to be legal, but there's no
2538 Inst->setMetadata(I->second, cast<MDNode>(Node));
2539 if (I->second == LLVMContext::MD_tbaa)
2540 InstsWithTBAATag.push_back(Inst);
2548 /// ParseFunctionBody - Lazily parse the specified function body block.
2549 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2550 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2551 return Error("Invalid record");
2553 InstructionList.clear();
2554 unsigned ModuleValueListSize = ValueList.size();
2555 unsigned ModuleMDValueListSize = MDValueList.size();
2557 // Add all the function arguments to the value table.
2558 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2559 ValueList.push_back(I);
2561 unsigned NextValueNo = ValueList.size();
2562 BasicBlock *CurBB = nullptr;
2563 unsigned CurBBNo = 0;
2566 auto getLastInstruction = [&]() -> Instruction * {
2567 if (CurBB && !CurBB->empty())
2568 return &CurBB->back();
2569 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2570 !FunctionBBs[CurBBNo - 1]->empty())
2571 return &FunctionBBs[CurBBNo - 1]->back();
2575 // Read all the records.
2576 SmallVector<uint64_t, 64> Record;
2578 BitstreamEntry Entry = Stream.advance();
2580 switch (Entry.Kind) {
2581 case BitstreamEntry::Error:
2582 return Error("Malformed block");
2583 case BitstreamEntry::EndBlock:
2584 goto OutOfRecordLoop;
2586 case BitstreamEntry::SubBlock:
2588 default: // Skip unknown content.
2589 if (Stream.SkipBlock())
2590 return Error("Invalid record");
2592 case bitc::CONSTANTS_BLOCK_ID:
2593 if (std::error_code EC = ParseConstants())
2595 NextValueNo = ValueList.size();
2597 case bitc::VALUE_SYMTAB_BLOCK_ID:
2598 if (std::error_code EC = ParseValueSymbolTable())
2601 case bitc::METADATA_ATTACHMENT_ID:
2602 if (std::error_code EC = ParseMetadataAttachment())
2605 case bitc::METADATA_BLOCK_ID:
2606 if (std::error_code EC = ParseMetadata())
2609 case bitc::USELIST_BLOCK_ID:
2610 if (std::error_code EC = ParseUseLists())
2616 case BitstreamEntry::Record:
2617 // The interesting case.
2623 Instruction *I = nullptr;
2624 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2626 default: // Default behavior: reject
2627 return Error("Invalid value");
2628 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2629 if (Record.size() < 1 || Record[0] == 0)
2630 return Error("Invalid record");
2631 // Create all the basic blocks for the function.
2632 FunctionBBs.resize(Record[0]);
2634 // See if anything took the address of blocks in this function.
2635 auto BBFRI = BasicBlockFwdRefs.find(F);
2636 if (BBFRI == BasicBlockFwdRefs.end()) {
2637 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2638 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2640 auto &BBRefs = BBFRI->second;
2641 // Check for invalid basic block references.
2642 if (BBRefs.size() > FunctionBBs.size())
2643 return Error("Invalid ID");
2644 assert(!BBRefs.empty() && "Unexpected empty array");
2645 assert(!BBRefs.front() && "Invalid reference to entry block");
2646 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2648 if (I < RE && BBRefs[I]) {
2649 BBRefs[I]->insertInto(F);
2650 FunctionBBs[I] = BBRefs[I];
2652 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2655 // Erase from the table.
2656 BasicBlockFwdRefs.erase(BBFRI);
2659 CurBB = FunctionBBs[0];
2663 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2664 // This record indicates that the last instruction is at the same
2665 // location as the previous instruction with a location.
2666 I = getLastInstruction();
2669 return Error("Invalid record");
2670 I->setDebugLoc(LastLoc);
2674 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2675 I = getLastInstruction();
2676 if (!I || Record.size() < 4)
2677 return Error("Invalid record");
2679 unsigned Line = Record[0], Col = Record[1];
2680 unsigned ScopeID = Record[2], IAID = Record[3];
2682 MDNode *Scope = nullptr, *IA = nullptr;
2683 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2684 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2685 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2686 I->setDebugLoc(LastLoc);
2691 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2694 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2695 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2696 OpNum+1 > Record.size())
2697 return Error("Invalid record");
2699 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2701 return Error("Invalid record");
2702 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2703 InstructionList.push_back(I);
2704 if (OpNum < Record.size()) {
2705 if (Opc == Instruction::Add ||
2706 Opc == Instruction::Sub ||
2707 Opc == Instruction::Mul ||
2708 Opc == Instruction::Shl) {
2709 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2710 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2711 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2712 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2713 } else if (Opc == Instruction::SDiv ||
2714 Opc == Instruction::UDiv ||
2715 Opc == Instruction::LShr ||
2716 Opc == Instruction::AShr) {
2717 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2718 cast<BinaryOperator>(I)->setIsExact(true);
2719 } else if (isa<FPMathOperator>(I)) {
2721 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2722 FMF.setUnsafeAlgebra();
2723 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2725 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2727 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2728 FMF.setNoSignedZeros();
2729 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2730 FMF.setAllowReciprocal();
2732 I->setFastMathFlags(FMF);
2738 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2741 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2742 OpNum+2 != Record.size())
2743 return Error("Invalid record");
2745 Type *ResTy = getTypeByID(Record[OpNum]);
2746 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2747 if (Opc == -1 || !ResTy)
2748 return Error("Invalid record");
2749 Instruction *Temp = nullptr;
2750 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2752 InstructionList.push_back(Temp);
2753 CurBB->getInstList().push_back(Temp);
2756 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2758 InstructionList.push_back(I);
2761 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2762 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2765 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2766 return Error("Invalid record");
2768 SmallVector<Value*, 16> GEPIdx;
2769 while (OpNum != Record.size()) {
2771 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2772 return Error("Invalid record");
2773 GEPIdx.push_back(Op);
2776 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2777 InstructionList.push_back(I);
2778 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2779 cast<GetElementPtrInst>(I)->setIsInBounds(true);
2783 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2784 // EXTRACTVAL: [opty, opval, n x indices]
2787 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2788 return Error("Invalid record");
2790 SmallVector<unsigned, 4> EXTRACTVALIdx;
2791 for (unsigned RecSize = Record.size();
2792 OpNum != RecSize; ++OpNum) {
2793 uint64_t Index = Record[OpNum];
2794 if ((unsigned)Index != Index)
2795 return Error("Invalid value");
2796 EXTRACTVALIdx.push_back((unsigned)Index);
2799 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2800 InstructionList.push_back(I);
2804 case bitc::FUNC_CODE_INST_INSERTVAL: {
2805 // INSERTVAL: [opty, opval, opty, opval, n x indices]
2808 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2809 return Error("Invalid record");
2811 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2812 return Error("Invalid record");
2814 SmallVector<unsigned, 4> INSERTVALIdx;
2815 for (unsigned RecSize = Record.size();
2816 OpNum != RecSize; ++OpNum) {
2817 uint64_t Index = Record[OpNum];
2818 if ((unsigned)Index != Index)
2819 return Error("Invalid value");
2820 INSERTVALIdx.push_back((unsigned)Index);
2823 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2824 InstructionList.push_back(I);
2828 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2829 // obsolete form of select
2830 // handles select i1 ... in old bitcode
2832 Value *TrueVal, *FalseVal, *Cond;
2833 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2834 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2835 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2836 return Error("Invalid record");
2838 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2839 InstructionList.push_back(I);
2843 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2844 // new form of select
2845 // handles select i1 or select [N x i1]
2847 Value *TrueVal, *FalseVal, *Cond;
2848 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2849 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2850 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2851 return Error("Invalid record");
2853 // select condition can be either i1 or [N x i1]
2854 if (VectorType* vector_type =
2855 dyn_cast<VectorType>(Cond->getType())) {
2857 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2858 return Error("Invalid type for value");
2861 if (Cond->getType() != Type::getInt1Ty(Context))
2862 return Error("Invalid type for value");
2865 I = SelectInst::Create(Cond, TrueVal, FalseVal);
2866 InstructionList.push_back(I);
2870 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2873 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2874 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2875 return Error("Invalid record");
2876 I = ExtractElementInst::Create(Vec, Idx);
2877 InstructionList.push_back(I);
2881 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2883 Value *Vec, *Elt, *Idx;
2884 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2885 popValue(Record, OpNum, NextValueNo,
2886 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2887 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2888 return Error("Invalid record");
2889 I = InsertElementInst::Create(Vec, Elt, Idx);
2890 InstructionList.push_back(I);
2894 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2896 Value *Vec1, *Vec2, *Mask;
2897 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2898 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2899 return Error("Invalid record");
2901 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2902 return Error("Invalid record");
2903 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2904 InstructionList.push_back(I);
2908 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2909 // Old form of ICmp/FCmp returning bool
2910 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2911 // both legal on vectors but had different behaviour.
2912 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2913 // FCmp/ICmp returning bool or vector of bool
2917 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2918 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2919 OpNum+1 != Record.size())
2920 return Error("Invalid record");
2922 if (LHS->getType()->isFPOrFPVectorTy())
2923 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2925 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2926 InstructionList.push_back(I);
2930 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2932 unsigned Size = Record.size();
2934 I = ReturnInst::Create(Context);
2935 InstructionList.push_back(I);
2940 Value *Op = nullptr;
2941 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2942 return Error("Invalid record");
2943 if (OpNum != Record.size())
2944 return Error("Invalid record");
2946 I = ReturnInst::Create(Context, Op);
2947 InstructionList.push_back(I);
2950 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2951 if (Record.size() != 1 && Record.size() != 3)
2952 return Error("Invalid record");
2953 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2955 return Error("Invalid record");
2957 if (Record.size() == 1) {
2958 I = BranchInst::Create(TrueDest);
2959 InstructionList.push_back(I);
2962 BasicBlock *FalseDest = getBasicBlock(Record[1]);
2963 Value *Cond = getValue(Record, 2, NextValueNo,
2964 Type::getInt1Ty(Context));
2965 if (!FalseDest || !Cond)
2966 return Error("Invalid record");
2967 I = BranchInst::Create(TrueDest, FalseDest, Cond);
2968 InstructionList.push_back(I);
2972 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2974 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2975 // "New" SwitchInst format with case ranges. The changes to write this
2976 // format were reverted but we still recognize bitcode that uses it.
2977 // Hopefully someday we will have support for case ranges and can use
2978 // this format again.
2980 Type *OpTy = getTypeByID(Record[1]);
2981 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2983 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2984 BasicBlock *Default = getBasicBlock(Record[3]);
2985 if (!OpTy || !Cond || !Default)
2986 return Error("Invalid record");
2988 unsigned NumCases = Record[4];
2990 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2991 InstructionList.push_back(SI);
2993 unsigned CurIdx = 5;
2994 for (unsigned i = 0; i != NumCases; ++i) {
2995 SmallVector<ConstantInt*, 1> CaseVals;
2996 unsigned NumItems = Record[CurIdx++];
2997 for (unsigned ci = 0; ci != NumItems; ++ci) {
2998 bool isSingleNumber = Record[CurIdx++];
3001 unsigned ActiveWords = 1;
3002 if (ValueBitWidth > 64)
3003 ActiveWords = Record[CurIdx++];
3004 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3006 CurIdx += ActiveWords;
3008 if (!isSingleNumber) {
3010 if (ValueBitWidth > 64)
3011 ActiveWords = Record[CurIdx++];
3013 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3015 CurIdx += ActiveWords;
3017 // FIXME: It is not clear whether values in the range should be
3018 // compared as signed or unsigned values. The partially
3019 // implemented changes that used this format in the past used
3020 // unsigned comparisons.
3021 for ( ; Low.ule(High); ++Low)
3022 CaseVals.push_back(ConstantInt::get(Context, Low));
3024 CaseVals.push_back(ConstantInt::get(Context, Low));
3026 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3027 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3028 cve = CaseVals.end(); cvi != cve; ++cvi)
3029 SI->addCase(*cvi, DestBB);
3035 // Old SwitchInst format without case ranges.
3037 if (Record.size() < 3 || (Record.size() & 1) == 0)
3038 return Error("Invalid record");
3039 Type *OpTy = getTypeByID(Record[0]);
3040 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3041 BasicBlock *Default = getBasicBlock(Record[2]);
3042 if (!OpTy || !Cond || !Default)
3043 return Error("Invalid record");
3044 unsigned NumCases = (Record.size()-3)/2;
3045 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3046 InstructionList.push_back(SI);
3047 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3048 ConstantInt *CaseVal =
3049 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3050 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3051 if (!CaseVal || !DestBB) {
3053 return Error("Invalid record");
3055 SI->addCase(CaseVal, DestBB);
3060 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3061 if (Record.size() < 2)
3062 return Error("Invalid record");
3063 Type *OpTy = getTypeByID(Record[0]);
3064 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3065 if (!OpTy || !Address)
3066 return Error("Invalid record");
3067 unsigned NumDests = Record.size()-2;
3068 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3069 InstructionList.push_back(IBI);
3070 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3071 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3072 IBI->addDestination(DestBB);
3075 return Error("Invalid record");
3082 case bitc::FUNC_CODE_INST_INVOKE: {
3083 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3084 if (Record.size() < 4)
3085 return Error("Invalid record");
3086 AttributeSet PAL = getAttributes(Record[0]);
3087 unsigned CCInfo = Record[1];
3088 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3089 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3093 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3094 return Error("Invalid record");
3096 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3097 FunctionType *FTy = !CalleeTy ? nullptr :
3098 dyn_cast<FunctionType>(CalleeTy->getElementType());
3100 // Check that the right number of fixed parameters are here.
3101 if (!FTy || !NormalBB || !UnwindBB ||
3102 Record.size() < OpNum+FTy->getNumParams())
3103 return Error("Invalid record");
3105 SmallVector<Value*, 16> Ops;
3106 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3107 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3108 FTy->getParamType(i)));
3110 return Error("Invalid record");
3113 if (!FTy->isVarArg()) {
3114 if (Record.size() != OpNum)
3115 return Error("Invalid record");
3117 // Read type/value pairs for varargs params.
3118 while (OpNum != Record.size()) {
3120 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3121 return Error("Invalid record");
3126 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3127 InstructionList.push_back(I);
3128 cast<InvokeInst>(I)->setCallingConv(
3129 static_cast<CallingConv::ID>(CCInfo));
3130 cast<InvokeInst>(I)->setAttributes(PAL);
3133 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3135 Value *Val = nullptr;
3136 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3137 return Error("Invalid record");
3138 I = ResumeInst::Create(Val);
3139 InstructionList.push_back(I);
3142 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3143 I = new UnreachableInst(Context);
3144 InstructionList.push_back(I);
3146 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3147 if (Record.size() < 1 || ((Record.size()-1)&1))
3148 return Error("Invalid record");
3149 Type *Ty = getTypeByID(Record[0]);
3151 return Error("Invalid record");
3153 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3154 InstructionList.push_back(PN);
3156 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3158 // With the new function encoding, it is possible that operands have
3159 // negative IDs (for forward references). Use a signed VBR
3160 // representation to keep the encoding small.
3162 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3164 V = getValue(Record, 1+i, NextValueNo, Ty);
3165 BasicBlock *BB = getBasicBlock(Record[2+i]);
3167 return Error("Invalid record");
3168 PN->addIncoming(V, BB);
3174 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3175 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3177 if (Record.size() < 4)
3178 return Error("Invalid record");
3179 Type *Ty = getTypeByID(Record[Idx++]);
3181 return Error("Invalid record");
3182 Value *PersFn = nullptr;
3183 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3184 return Error("Invalid record");
3186 bool IsCleanup = !!Record[Idx++];
3187 unsigned NumClauses = Record[Idx++];
3188 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3189 LP->setCleanup(IsCleanup);
3190 for (unsigned J = 0; J != NumClauses; ++J) {
3191 LandingPadInst::ClauseType CT =
3192 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3195 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3197 return Error("Invalid record");
3200 assert((CT != LandingPadInst::Catch ||
3201 !isa<ArrayType>(Val->getType())) &&
3202 "Catch clause has a invalid type!");
3203 assert((CT != LandingPadInst::Filter ||
3204 isa<ArrayType>(Val->getType())) &&
3205 "Filter clause has invalid type!");
3206 LP->addClause(cast<Constant>(Val));
3210 InstructionList.push_back(I);
3214 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3215 if (Record.size() != 4)
3216 return Error("Invalid record");
3218 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3219 Type *OpTy = getTypeByID(Record[1]);
3220 Value *Size = getFnValueByID(Record[2], OpTy);
3221 unsigned AlignRecord = Record[3];
3222 bool InAlloca = AlignRecord & (1 << 5);
3223 unsigned Align = AlignRecord & ((1 << 5) - 1);
3225 return Error("Invalid record");
3226 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3227 AI->setUsedWithInAlloca(InAlloca);
3229 InstructionList.push_back(I);
3232 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3235 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3236 OpNum+2 != Record.size())
3237 return Error("Invalid record");
3239 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3240 InstructionList.push_back(I);
3243 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3244 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3247 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3248 OpNum+4 != Record.size())
3249 return Error("Invalid record");
3251 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3252 if (Ordering == NotAtomic || Ordering == Release ||
3253 Ordering == AcquireRelease)
3254 return Error("Invalid record");
3255 if (Ordering != NotAtomic && Record[OpNum] == 0)
3256 return Error("Invalid record");
3257 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3259 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3260 Ordering, SynchScope);
3261 InstructionList.push_back(I);
3264 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3267 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3268 popValue(Record, OpNum, NextValueNo,
3269 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3270 OpNum+2 != Record.size())
3271 return Error("Invalid record");
3273 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3274 InstructionList.push_back(I);
3277 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3278 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3281 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3282 popValue(Record, OpNum, NextValueNo,
3283 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3284 OpNum+4 != Record.size())
3285 return Error("Invalid record");
3287 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3288 if (Ordering == NotAtomic || Ordering == Acquire ||
3289 Ordering == AcquireRelease)
3290 return Error("Invalid record");
3291 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3292 if (Ordering != NotAtomic && Record[OpNum] == 0)
3293 return Error("Invalid record");
3295 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3296 Ordering, SynchScope);
3297 InstructionList.push_back(I);
3300 case bitc::FUNC_CODE_INST_CMPXCHG: {
3301 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3302 // failureordering?, isweak?]
3304 Value *Ptr, *Cmp, *New;
3305 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3306 popValue(Record, OpNum, NextValueNo,
3307 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3308 popValue(Record, OpNum, NextValueNo,
3309 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3310 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3311 return Error("Invalid record");
3312 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3313 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3314 return Error("Invalid record");
3315 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3317 AtomicOrdering FailureOrdering;
3318 if (Record.size() < 7)
3320 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3322 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3324 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3326 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3328 if (Record.size() < 8) {
3329 // Before weak cmpxchgs existed, the instruction simply returned the
3330 // value loaded from memory, so bitcode files from that era will be
3331 // expecting the first component of a modern cmpxchg.
3332 CurBB->getInstList().push_back(I);
3333 I = ExtractValueInst::Create(I, 0);
3335 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3338 InstructionList.push_back(I);
3341 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3342 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3345 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3346 popValue(Record, OpNum, NextValueNo,
3347 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3348 OpNum+4 != Record.size())
3349 return Error("Invalid record");
3350 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3351 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3352 Operation > AtomicRMWInst::LAST_BINOP)
3353 return Error("Invalid record");
3354 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3355 if (Ordering == NotAtomic || Ordering == Unordered)
3356 return Error("Invalid record");
3357 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3358 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3359 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3360 InstructionList.push_back(I);
3363 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3364 if (2 != Record.size())
3365 return Error("Invalid record");
3366 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3367 if (Ordering == NotAtomic || Ordering == Unordered ||
3368 Ordering == Monotonic)
3369 return Error("Invalid record");
3370 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3371 I = new FenceInst(Context, Ordering, SynchScope);
3372 InstructionList.push_back(I);
3375 case bitc::FUNC_CODE_INST_CALL: {
3376 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3377 if (Record.size() < 3)
3378 return Error("Invalid record");
3380 AttributeSet PAL = getAttributes(Record[0]);
3381 unsigned CCInfo = Record[1];
3385 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3386 return Error("Invalid record");
3388 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3389 FunctionType *FTy = nullptr;
3390 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3391 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3392 return Error("Invalid record");
3394 SmallVector<Value*, 16> Args;
3395 // Read the fixed params.
3396 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3397 if (FTy->getParamType(i)->isLabelTy())
3398 Args.push_back(getBasicBlock(Record[OpNum]));
3400 Args.push_back(getValue(Record, OpNum, NextValueNo,
3401 FTy->getParamType(i)));
3403 return Error("Invalid record");
3406 // Read type/value pairs for varargs params.
3407 if (!FTy->isVarArg()) {
3408 if (OpNum != Record.size())
3409 return Error("Invalid record");
3411 while (OpNum != Record.size()) {
3413 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3414 return Error("Invalid record");
3419 I = CallInst::Create(Callee, Args);
3420 InstructionList.push_back(I);
3421 cast<CallInst>(I)->setCallingConv(
3422 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3423 CallInst::TailCallKind TCK = CallInst::TCK_None;
3425 TCK = CallInst::TCK_Tail;
3426 if (CCInfo & (1 << 14))
3427 TCK = CallInst::TCK_MustTail;
3428 cast<CallInst>(I)->setTailCallKind(TCK);
3429 cast<CallInst>(I)->setAttributes(PAL);
3432 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3433 if (Record.size() < 3)
3434 return Error("Invalid record");
3435 Type *OpTy = getTypeByID(Record[0]);
3436 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3437 Type *ResTy = getTypeByID(Record[2]);
3438 if (!OpTy || !Op || !ResTy)
3439 return Error("Invalid record");
3440 I = new VAArgInst(Op, ResTy);
3441 InstructionList.push_back(I);
3446 // Add instruction to end of current BB. If there is no current BB, reject
3450 return Error("Invalid instruction with no BB");
3452 CurBB->getInstList().push_back(I);
3454 // If this was a terminator instruction, move to the next block.
3455 if (isa<TerminatorInst>(I)) {
3457 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3460 // Non-void values get registered in the value table for future use.
3461 if (I && !I->getType()->isVoidTy())
3462 ValueList.AssignValue(I, NextValueNo++);
3467 // Check the function list for unresolved values.
3468 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3469 if (!A->getParent()) {
3470 // We found at least one unresolved value. Nuke them all to avoid leaks.
3471 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3472 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3473 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3477 return Error("Never resolved value found in function");
3481 // FIXME: Check for unresolved forward-declared metadata references
3482 // and clean up leaks.
3484 // Trim the value list down to the size it was before we parsed this function.
3485 ValueList.shrinkTo(ModuleValueListSize);
3486 MDValueList.shrinkTo(ModuleMDValueListSize);
3487 std::vector<BasicBlock*>().swap(FunctionBBs);
3488 return std::error_code();
3491 /// Find the function body in the bitcode stream
3492 std::error_code BitcodeReader::FindFunctionInStream(
3494 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3495 while (DeferredFunctionInfoIterator->second == 0) {
3496 if (Stream.AtEndOfStream())
3497 return Error("Could not find function in stream");
3498 // ParseModule will parse the next body in the stream and set its
3499 // position in the DeferredFunctionInfo map.
3500 if (std::error_code EC = ParseModule(true))
3503 return std::error_code();
3506 //===----------------------------------------------------------------------===//
3507 // GVMaterializer implementation
3508 //===----------------------------------------------------------------------===//
3510 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3512 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3513 Function *F = dyn_cast<Function>(GV);
3514 // If it's not a function or is already material, ignore the request.
3515 if (!F || !F->isMaterializable())
3516 return std::error_code();
3518 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3519 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3520 // If its position is recorded as 0, its body is somewhere in the stream
3521 // but we haven't seen it yet.
3522 if (DFII->second == 0 && LazyStreamer)
3523 if (std::error_code EC = FindFunctionInStream(F, DFII))
3526 // Move the bit stream to the saved position of the deferred function body.
3527 Stream.JumpToBit(DFII->second);
3529 if (std::error_code EC = ParseFunctionBody(F))
3531 F->setIsMaterializable(false);
3533 // Upgrade any old intrinsic calls in the function.
3534 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3535 E = UpgradedIntrinsics.end(); I != E; ++I) {
3536 if (I->first != I->second) {
3537 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3539 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3540 UpgradeIntrinsicCall(CI, I->second);
3545 // Bring in any functions that this function forward-referenced via
3547 return materializeForwardReferencedFunctions();
3550 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3551 const Function *F = dyn_cast<Function>(GV);
3552 if (!F || F->isDeclaration())
3555 // Dematerializing F would leave dangling references that wouldn't be
3556 // reconnected on re-materialization.
3557 if (BlockAddressesTaken.count(F))
3560 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3563 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3564 Function *F = dyn_cast<Function>(GV);
3565 // If this function isn't dematerializable, this is a noop.
3566 if (!F || !isDematerializable(F))
3569 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3571 // Just forget the function body, we can remat it later.
3572 F->dropAllReferences();
3573 F->setIsMaterializable(true);
3576 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3577 assert(M == TheModule &&
3578 "Can only Materialize the Module this BitcodeReader is attached to.");
3580 // Promise to materialize all forward references.
3581 WillMaterializeAllForwardRefs = true;
3583 // Iterate over the module, deserializing any functions that are still on
3585 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3587 if (std::error_code EC = materialize(F))
3590 // At this point, if there are any function bodies, the current bit is
3591 // pointing to the END_BLOCK record after them. Now make sure the rest
3592 // of the bits in the module have been read.
3596 // Check that all block address forward references got resolved (as we
3598 if (!BasicBlockFwdRefs.empty())
3599 return Error("Never resolved function from blockaddress");
3601 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3602 // delete the old functions to clean up. We can't do this unless the entire
3603 // module is materialized because there could always be another function body
3604 // with calls to the old function.
3605 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3606 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3607 if (I->first != I->second) {
3608 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3610 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3611 UpgradeIntrinsicCall(CI, I->second);
3613 if (!I->first->use_empty())
3614 I->first->replaceAllUsesWith(I->second);
3615 I->first->eraseFromParent();
3618 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3620 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3621 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3623 UpgradeDebugInfo(*M);
3624 return std::error_code();
3627 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3628 return IdentifiedStructTypes;
3631 std::error_code BitcodeReader::InitStream() {
3633 return InitLazyStream();
3634 return InitStreamFromBuffer();
3637 std::error_code BitcodeReader::InitStreamFromBuffer() {
3638 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3639 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3641 if (Buffer->getBufferSize() & 3)
3642 return Error("Invalid bitcode signature");
3644 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3645 // The magic number is 0x0B17C0DE stored in little endian.
3646 if (isBitcodeWrapper(BufPtr, BufEnd))
3647 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3648 return Error("Invalid bitcode wrapper header");
3650 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3651 Stream.init(&*StreamFile);
3653 return std::error_code();
3656 std::error_code BitcodeReader::InitLazyStream() {
3657 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3659 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3660 StreamingMemoryObject &Bytes = *OwnedBytes;
3661 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3662 Stream.init(&*StreamFile);
3664 unsigned char buf[16];
3665 if (Bytes.readBytes(buf, 16, 0) != 16)
3666 return Error("Invalid bitcode signature");
3668 if (!isBitcode(buf, buf + 16))
3669 return Error("Invalid bitcode signature");
3671 if (isBitcodeWrapper(buf, buf + 4)) {
3672 const unsigned char *bitcodeStart = buf;
3673 const unsigned char *bitcodeEnd = buf + 16;
3674 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3675 Bytes.dropLeadingBytes(bitcodeStart - buf);
3676 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3678 return std::error_code();
3682 class BitcodeErrorCategoryType : public std::error_category {
3683 const char *name() const LLVM_NOEXCEPT override {
3684 return "llvm.bitcode";
3686 std::string message(int IE) const override {
3687 BitcodeError E = static_cast<BitcodeError>(IE);
3689 case BitcodeError::InvalidBitcodeSignature:
3690 return "Invalid bitcode signature";
3691 case BitcodeError::CorruptedBitcode:
3692 return "Corrupted bitcode";
3694 llvm_unreachable("Unknown error type!");
3699 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3701 const std::error_category &llvm::BitcodeErrorCategory() {
3702 return *ErrorCategory;
3705 //===----------------------------------------------------------------------===//
3706 // External interface
3707 //===----------------------------------------------------------------------===//
3709 /// \brief Get a lazy one-at-time loading module from bitcode.
3711 /// This isn't always used in a lazy context. In particular, it's also used by
3712 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3713 /// in forward-referenced functions from block address references.
3715 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3716 /// materialize everything -- in particular, if this isn't truly lazy.
3717 static ErrorOr<Module *>
3718 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3719 LLVMContext &Context, bool WillMaterializeAll,
3720 DiagnosticHandlerFunction DiagnosticHandler) {
3721 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3723 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3724 M->setMaterializer(R);
3726 auto cleanupOnError = [&](std::error_code EC) {
3727 R->releaseBuffer(); // Never take ownership on error.
3728 delete M; // Also deletes R.
3732 if (std::error_code EC = R->ParseBitcodeInto(M))
3733 return cleanupOnError(EC);
3735 if (!WillMaterializeAll)
3736 // Resolve forward references from blockaddresses.
3737 if (std::error_code EC = R->materializeForwardReferencedFunctions())
3738 return cleanupOnError(EC);
3740 Buffer.release(); // The BitcodeReader owns it now.
3745 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3746 LLVMContext &Context,
3747 DiagnosticHandlerFunction DiagnosticHandler) {
3748 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3752 ErrorOr<std::unique_ptr<Module>>
3753 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3754 LLVMContext &Context,
3755 DiagnosticHandlerFunction DiagnosticHandler) {
3756 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
3757 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
3758 M->setMaterializer(R);
3759 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
3761 return std::move(M);
3765 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3766 DiagnosticHandlerFunction DiagnosticHandler) {
3767 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3768 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3769 std::move(Buf), Context, true, DiagnosticHandler);
3772 Module *M = ModuleOrErr.get();
3773 // Read in the entire module, and destroy the BitcodeReader.
3774 if (std::error_code EC = M->materializeAllPermanently()) {
3779 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3780 // written. We must defer until the Module has been fully materialized.
3786 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3787 DiagnosticHandlerFunction DiagnosticHandler) {
3788 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3789 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3791 ErrorOr<std::string> Triple = R->parseTriple();
3792 if (Triple.getError())
3794 return Triple.get();