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/DebugInfoMetadata.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/OperandTraits.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Support/DataStream.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
36 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
39 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
40 DiagnosticSeverity Severity,
42 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
44 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
46 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
47 std::error_code EC, const Twine &Message) {
48 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
49 DiagnosticHandler(DI);
53 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
55 return Error(DiagnosticHandler, EC, EC.message());
58 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
59 return ::Error(DiagnosticHandler, make_error_code(E), Message);
62 std::error_code BitcodeReader::Error(const Twine &Message) {
63 return ::Error(DiagnosticHandler,
64 make_error_code(BitcodeError::CorruptedBitcode), Message);
67 std::error_code BitcodeReader::Error(BitcodeError E) {
68 return ::Error(DiagnosticHandler, make_error_code(E));
71 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
75 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
78 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
79 DiagnosticHandlerFunction DiagnosticHandler)
80 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
81 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
82 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
83 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
84 WillMaterializeAllForwardRefs(false) {}
86 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
87 DiagnosticHandlerFunction DiagnosticHandler)
88 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
89 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
90 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
91 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
92 WillMaterializeAllForwardRefs(false) {}
94 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
95 if (WillMaterializeAllForwardRefs)
96 return std::error_code();
99 WillMaterializeAllForwardRefs = true;
101 while (!BasicBlockFwdRefQueue.empty()) {
102 Function *F = BasicBlockFwdRefQueue.front();
103 BasicBlockFwdRefQueue.pop_front();
104 assert(F && "Expected valid function");
105 if (!BasicBlockFwdRefs.count(F))
106 // Already materialized.
109 // Check for a function that isn't materializable to prevent an infinite
110 // loop. When parsing a blockaddress stored in a global variable, there
111 // isn't a trivial way to check if a function will have a body without a
112 // linear search through FunctionsWithBodies, so just check it here.
113 if (!F->isMaterializable())
114 return Error("Never resolved function from blockaddress");
116 // Try to materialize F.
117 if (std::error_code EC = materialize(F))
120 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
123 WillMaterializeAllForwardRefs = false;
124 return std::error_code();
127 void BitcodeReader::FreeState() {
129 std::vector<Type*>().swap(TypeList);
132 std::vector<Comdat *>().swap(ComdatList);
134 std::vector<AttributeSet>().swap(MAttributes);
135 std::vector<BasicBlock*>().swap(FunctionBBs);
136 std::vector<Function*>().swap(FunctionsWithBodies);
137 DeferredFunctionInfo.clear();
140 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
141 BasicBlockFwdRefQueue.clear();
144 //===----------------------------------------------------------------------===//
145 // Helper functions to implement forward reference resolution, etc.
146 //===----------------------------------------------------------------------===//
148 /// ConvertToString - Convert a string from a record into an std::string, return
150 template<typename StrTy>
151 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
153 if (Idx > Record.size())
156 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
157 Result += (char)Record[i];
161 static bool hasImplicitComdat(size_t Val) {
165 case 1: // Old WeakAnyLinkage
166 case 4: // Old LinkOnceAnyLinkage
167 case 10: // Old WeakODRLinkage
168 case 11: // Old LinkOnceODRLinkage
173 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
175 default: // Map unknown/new linkages to external
177 return GlobalValue::ExternalLinkage;
179 return GlobalValue::AppendingLinkage;
181 return GlobalValue::InternalLinkage;
183 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
185 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
187 return GlobalValue::ExternalWeakLinkage;
189 return GlobalValue::CommonLinkage;
191 return GlobalValue::PrivateLinkage;
193 return GlobalValue::AvailableExternallyLinkage;
195 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
197 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
199 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
200 case 1: // Old value with implicit comdat.
202 return GlobalValue::WeakAnyLinkage;
203 case 10: // Old value with implicit comdat.
205 return GlobalValue::WeakODRLinkage;
206 case 4: // Old value with implicit comdat.
208 return GlobalValue::LinkOnceAnyLinkage;
209 case 11: // Old value with implicit comdat.
211 return GlobalValue::LinkOnceODRLinkage;
215 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
217 default: // Map unknown visibilities to default.
218 case 0: return GlobalValue::DefaultVisibility;
219 case 1: return GlobalValue::HiddenVisibility;
220 case 2: return GlobalValue::ProtectedVisibility;
224 static GlobalValue::DLLStorageClassTypes
225 GetDecodedDLLStorageClass(unsigned Val) {
227 default: // Map unknown values to default.
228 case 0: return GlobalValue::DefaultStorageClass;
229 case 1: return GlobalValue::DLLImportStorageClass;
230 case 2: return GlobalValue::DLLExportStorageClass;
234 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
236 case 0: return GlobalVariable::NotThreadLocal;
237 default: // Map unknown non-zero value to general dynamic.
238 case 1: return GlobalVariable::GeneralDynamicTLSModel;
239 case 2: return GlobalVariable::LocalDynamicTLSModel;
240 case 3: return GlobalVariable::InitialExecTLSModel;
241 case 4: return GlobalVariable::LocalExecTLSModel;
245 static int GetDecodedCastOpcode(unsigned Val) {
248 case bitc::CAST_TRUNC : return Instruction::Trunc;
249 case bitc::CAST_ZEXT : return Instruction::ZExt;
250 case bitc::CAST_SEXT : return Instruction::SExt;
251 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
252 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
253 case bitc::CAST_UITOFP : return Instruction::UIToFP;
254 case bitc::CAST_SITOFP : return Instruction::SIToFP;
255 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
256 case bitc::CAST_FPEXT : return Instruction::FPExt;
257 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
258 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
259 case bitc::CAST_BITCAST : return Instruction::BitCast;
260 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
263 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
266 case bitc::BINOP_ADD:
267 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
268 case bitc::BINOP_SUB:
269 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
270 case bitc::BINOP_MUL:
271 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
272 case bitc::BINOP_UDIV: return Instruction::UDiv;
273 case bitc::BINOP_SDIV:
274 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
275 case bitc::BINOP_UREM: return Instruction::URem;
276 case bitc::BINOP_SREM:
277 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
278 case bitc::BINOP_SHL: return Instruction::Shl;
279 case bitc::BINOP_LSHR: return Instruction::LShr;
280 case bitc::BINOP_ASHR: return Instruction::AShr;
281 case bitc::BINOP_AND: return Instruction::And;
282 case bitc::BINOP_OR: return Instruction::Or;
283 case bitc::BINOP_XOR: return Instruction::Xor;
287 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
289 default: return AtomicRMWInst::BAD_BINOP;
290 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
291 case bitc::RMW_ADD: return AtomicRMWInst::Add;
292 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
293 case bitc::RMW_AND: return AtomicRMWInst::And;
294 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
295 case bitc::RMW_OR: return AtomicRMWInst::Or;
296 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
297 case bitc::RMW_MAX: return AtomicRMWInst::Max;
298 case bitc::RMW_MIN: return AtomicRMWInst::Min;
299 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
300 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
304 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
306 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
307 case bitc::ORDERING_UNORDERED: return Unordered;
308 case bitc::ORDERING_MONOTONIC: return Monotonic;
309 case bitc::ORDERING_ACQUIRE: return Acquire;
310 case bitc::ORDERING_RELEASE: return Release;
311 case bitc::ORDERING_ACQREL: return AcquireRelease;
312 default: // Map unknown orderings to sequentially-consistent.
313 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
317 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
319 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
320 default: // Map unknown scopes to cross-thread.
321 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
325 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
327 default: // Map unknown selection kinds to any.
328 case bitc::COMDAT_SELECTION_KIND_ANY:
330 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
331 return Comdat::ExactMatch;
332 case bitc::COMDAT_SELECTION_KIND_LARGEST:
333 return Comdat::Largest;
334 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
335 return Comdat::NoDuplicates;
336 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
337 return Comdat::SameSize;
341 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
343 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
344 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
350 /// @brief A class for maintaining the slot number definition
351 /// as a placeholder for the actual definition for forward constants defs.
352 class ConstantPlaceHolder : public ConstantExpr {
353 void operator=(const ConstantPlaceHolder &) = delete;
355 // allocate space for exactly one operand
356 void *operator new(size_t s) {
357 return User::operator new(s, 1);
359 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
360 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
361 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
364 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
365 static bool classof(const Value *V) {
366 return isa<ConstantExpr>(V) &&
367 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
371 /// Provide fast operand accessors
372 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
376 // FIXME: can we inherit this from ConstantExpr?
378 struct OperandTraits<ConstantPlaceHolder> :
379 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
381 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
385 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
394 WeakVH &OldV = ValuePtrs[Idx];
400 // Handle constants and non-constants (e.g. instrs) differently for
402 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
403 ResolveConstants.push_back(std::make_pair(PHC, Idx));
406 // If there was a forward reference to this value, replace it.
407 Value *PrevVal = OldV;
408 OldV->replaceAllUsesWith(V);
414 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
419 if (Value *V = ValuePtrs[Idx]) {
420 assert(Ty == V->getType() && "Type mismatch in constant table!");
421 return cast<Constant>(V);
424 // Create and return a placeholder, which will later be RAUW'd.
425 Constant *C = new ConstantPlaceHolder(Ty, Context);
430 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
434 if (Value *V = ValuePtrs[Idx]) {
435 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
439 // No type specified, must be invalid reference.
440 if (!Ty) return nullptr;
442 // Create and return a placeholder, which will later be RAUW'd.
443 Value *V = new Argument(Ty);
448 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
449 /// resolves any forward references. The idea behind this is that we sometimes
450 /// get constants (such as large arrays) which reference *many* forward ref
451 /// constants. Replacing each of these causes a lot of thrashing when
452 /// building/reuniquing the constant. Instead of doing this, we look at all the
453 /// uses and rewrite all the place holders at once for any constant that uses
455 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
456 // Sort the values by-pointer so that they are efficient to look up with a
458 std::sort(ResolveConstants.begin(), ResolveConstants.end());
460 SmallVector<Constant*, 64> NewOps;
462 while (!ResolveConstants.empty()) {
463 Value *RealVal = operator[](ResolveConstants.back().second);
464 Constant *Placeholder = ResolveConstants.back().first;
465 ResolveConstants.pop_back();
467 // Loop over all users of the placeholder, updating them to reference the
468 // new value. If they reference more than one placeholder, update them all
470 while (!Placeholder->use_empty()) {
471 auto UI = Placeholder->user_begin();
474 // If the using object isn't uniqued, just update the operands. This
475 // handles instructions and initializers for global variables.
476 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
477 UI.getUse().set(RealVal);
481 // Otherwise, we have a constant that uses the placeholder. Replace that
482 // constant with a new constant that has *all* placeholder uses updated.
483 Constant *UserC = cast<Constant>(U);
484 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
487 if (!isa<ConstantPlaceHolder>(*I)) {
488 // Not a placeholder reference.
490 } else if (*I == Placeholder) {
491 // Common case is that it just references this one placeholder.
494 // Otherwise, look up the placeholder in ResolveConstants.
495 ResolveConstantsTy::iterator It =
496 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
497 std::pair<Constant*, unsigned>(cast<Constant>(*I),
499 assert(It != ResolveConstants.end() && It->first == *I);
500 NewOp = operator[](It->second);
503 NewOps.push_back(cast<Constant>(NewOp));
506 // Make the new constant.
508 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
509 NewC = ConstantArray::get(UserCA->getType(), NewOps);
510 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
511 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
512 } else if (isa<ConstantVector>(UserC)) {
513 NewC = ConstantVector::get(NewOps);
515 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
516 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
519 UserC->replaceAllUsesWith(NewC);
520 UserC->destroyConstant();
524 // Update all ValueHandles, they should be the only users at this point.
525 Placeholder->replaceAllUsesWith(RealVal);
530 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
539 TrackingMDRef &OldMD = MDValuePtrs[Idx];
545 // If there was a forward reference to this value, replace it.
546 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
547 PrevMD->replaceAllUsesWith(MD);
551 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
555 if (Metadata *MD = MDValuePtrs[Idx])
558 // Track forward refs to be resolved later.
560 MinFwdRef = std::min(MinFwdRef, Idx);
561 MaxFwdRef = std::max(MaxFwdRef, Idx);
564 MinFwdRef = MaxFwdRef = Idx;
568 // Create and return a placeholder, which will later be RAUW'd.
569 Metadata *MD = MDNode::getTemporary(Context, None).release();
570 MDValuePtrs[Idx].reset(MD);
574 void BitcodeReaderMDValueList::tryToResolveCycles() {
580 // Still forward references... can't resolve cycles.
583 // Resolve any cycles.
584 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
585 auto &MD = MDValuePtrs[I];
586 auto *N = dyn_cast_or_null<MDNode>(MD);
590 assert(!N->isTemporary() && "Unexpected forward reference");
594 // Make sure we return early again until there's another forward ref.
598 Type *BitcodeReader::getTypeByID(unsigned ID) {
599 // The type table size is always specified correctly.
600 if (ID >= TypeList.size())
603 if (Type *Ty = TypeList[ID])
606 // If we have a forward reference, the only possible case is when it is to a
607 // named struct. Just create a placeholder for now.
608 return TypeList[ID] = createIdentifiedStructType(Context);
611 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
613 auto *Ret = StructType::create(Context, Name);
614 IdentifiedStructTypes.push_back(Ret);
618 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
619 auto *Ret = StructType::create(Context);
620 IdentifiedStructTypes.push_back(Ret);
625 //===----------------------------------------------------------------------===//
626 // Functions for parsing blocks from the bitcode file
627 //===----------------------------------------------------------------------===//
630 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
631 /// been decoded from the given integer. This function must stay in sync with
632 /// 'encodeLLVMAttributesForBitcode'.
633 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
634 uint64_t EncodedAttrs) {
635 // FIXME: Remove in 4.0.
637 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
638 // the bits above 31 down by 11 bits.
639 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
640 assert((!Alignment || isPowerOf2_32(Alignment)) &&
641 "Alignment must be a power of two.");
644 B.addAlignmentAttr(Alignment);
645 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
646 (EncodedAttrs & 0xffff));
649 std::error_code BitcodeReader::ParseAttributeBlock() {
650 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
651 return Error("Invalid record");
653 if (!MAttributes.empty())
654 return Error("Invalid multiple blocks");
656 SmallVector<uint64_t, 64> Record;
658 SmallVector<AttributeSet, 8> Attrs;
660 // Read all the records.
662 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
664 switch (Entry.Kind) {
665 case BitstreamEntry::SubBlock: // Handled for us already.
666 case BitstreamEntry::Error:
667 return Error("Malformed block");
668 case BitstreamEntry::EndBlock:
669 return std::error_code();
670 case BitstreamEntry::Record:
671 // The interesting case.
677 switch (Stream.readRecord(Entry.ID, Record)) {
678 default: // Default behavior: ignore.
680 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
681 // FIXME: Remove in 4.0.
682 if (Record.size() & 1)
683 return Error("Invalid record");
685 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
687 decodeLLVMAttributesForBitcode(B, Record[i+1]);
688 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
691 MAttributes.push_back(AttributeSet::get(Context, Attrs));
695 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
696 for (unsigned i = 0, e = Record.size(); i != e; ++i)
697 Attrs.push_back(MAttributeGroups[Record[i]]);
699 MAttributes.push_back(AttributeSet::get(Context, Attrs));
707 // Returns Attribute::None on unrecognized codes.
708 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
711 return Attribute::None;
712 case bitc::ATTR_KIND_ALIGNMENT:
713 return Attribute::Alignment;
714 case bitc::ATTR_KIND_ALWAYS_INLINE:
715 return Attribute::AlwaysInline;
716 case bitc::ATTR_KIND_BUILTIN:
717 return Attribute::Builtin;
718 case bitc::ATTR_KIND_BY_VAL:
719 return Attribute::ByVal;
720 case bitc::ATTR_KIND_IN_ALLOCA:
721 return Attribute::InAlloca;
722 case bitc::ATTR_KIND_COLD:
723 return Attribute::Cold;
724 case bitc::ATTR_KIND_INLINE_HINT:
725 return Attribute::InlineHint;
726 case bitc::ATTR_KIND_IN_REG:
727 return Attribute::InReg;
728 case bitc::ATTR_KIND_JUMP_TABLE:
729 return Attribute::JumpTable;
730 case bitc::ATTR_KIND_MIN_SIZE:
731 return Attribute::MinSize;
732 case bitc::ATTR_KIND_NAKED:
733 return Attribute::Naked;
734 case bitc::ATTR_KIND_NEST:
735 return Attribute::Nest;
736 case bitc::ATTR_KIND_NO_ALIAS:
737 return Attribute::NoAlias;
738 case bitc::ATTR_KIND_NO_BUILTIN:
739 return Attribute::NoBuiltin;
740 case bitc::ATTR_KIND_NO_CAPTURE:
741 return Attribute::NoCapture;
742 case bitc::ATTR_KIND_NO_DUPLICATE:
743 return Attribute::NoDuplicate;
744 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
745 return Attribute::NoImplicitFloat;
746 case bitc::ATTR_KIND_NO_INLINE:
747 return Attribute::NoInline;
748 case bitc::ATTR_KIND_NON_LAZY_BIND:
749 return Attribute::NonLazyBind;
750 case bitc::ATTR_KIND_NON_NULL:
751 return Attribute::NonNull;
752 case bitc::ATTR_KIND_DEREFERENCEABLE:
753 return Attribute::Dereferenceable;
754 case bitc::ATTR_KIND_NO_RED_ZONE:
755 return Attribute::NoRedZone;
756 case bitc::ATTR_KIND_NO_RETURN:
757 return Attribute::NoReturn;
758 case bitc::ATTR_KIND_NO_UNWIND:
759 return Attribute::NoUnwind;
760 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
761 return Attribute::OptimizeForSize;
762 case bitc::ATTR_KIND_OPTIMIZE_NONE:
763 return Attribute::OptimizeNone;
764 case bitc::ATTR_KIND_READ_NONE:
765 return Attribute::ReadNone;
766 case bitc::ATTR_KIND_READ_ONLY:
767 return Attribute::ReadOnly;
768 case bitc::ATTR_KIND_RETURNED:
769 return Attribute::Returned;
770 case bitc::ATTR_KIND_RETURNS_TWICE:
771 return Attribute::ReturnsTwice;
772 case bitc::ATTR_KIND_S_EXT:
773 return Attribute::SExt;
774 case bitc::ATTR_KIND_STACK_ALIGNMENT:
775 return Attribute::StackAlignment;
776 case bitc::ATTR_KIND_STACK_PROTECT:
777 return Attribute::StackProtect;
778 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
779 return Attribute::StackProtectReq;
780 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
781 return Attribute::StackProtectStrong;
782 case bitc::ATTR_KIND_STRUCT_RET:
783 return Attribute::StructRet;
784 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
785 return Attribute::SanitizeAddress;
786 case bitc::ATTR_KIND_SANITIZE_THREAD:
787 return Attribute::SanitizeThread;
788 case bitc::ATTR_KIND_SANITIZE_MEMORY:
789 return Attribute::SanitizeMemory;
790 case bitc::ATTR_KIND_UW_TABLE:
791 return Attribute::UWTable;
792 case bitc::ATTR_KIND_Z_EXT:
793 return Attribute::ZExt;
797 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
798 unsigned &Alignment) {
799 // Note: Alignment in bitcode files is incremented by 1, so that zero
800 // can be used for default alignment.
801 if (Exponent > Value::MaxAlignmentExponent + 1)
802 return Error("Invalid alignment value");
803 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
804 return std::error_code();
807 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
808 Attribute::AttrKind *Kind) {
809 *Kind = GetAttrFromCode(Code);
810 if (*Kind == Attribute::None)
811 return Error(BitcodeError::CorruptedBitcode,
812 "Unknown attribute kind (" + Twine(Code) + ")");
813 return std::error_code();
816 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
817 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
818 return Error("Invalid record");
820 if (!MAttributeGroups.empty())
821 return Error("Invalid multiple blocks");
823 SmallVector<uint64_t, 64> Record;
825 // Read all the records.
827 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
829 switch (Entry.Kind) {
830 case BitstreamEntry::SubBlock: // Handled for us already.
831 case BitstreamEntry::Error:
832 return Error("Malformed block");
833 case BitstreamEntry::EndBlock:
834 return std::error_code();
835 case BitstreamEntry::Record:
836 // The interesting case.
842 switch (Stream.readRecord(Entry.ID, Record)) {
843 default: // Default behavior: ignore.
845 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
846 if (Record.size() < 3)
847 return Error("Invalid record");
849 uint64_t GrpID = Record[0];
850 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
853 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
854 if (Record[i] == 0) { // Enum attribute
855 Attribute::AttrKind Kind;
856 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
859 B.addAttribute(Kind);
860 } else if (Record[i] == 1) { // Integer attribute
861 Attribute::AttrKind Kind;
862 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
864 if (Kind == Attribute::Alignment)
865 B.addAlignmentAttr(Record[++i]);
866 else if (Kind == Attribute::StackAlignment)
867 B.addStackAlignmentAttr(Record[++i]);
868 else if (Kind == Attribute::Dereferenceable)
869 B.addDereferenceableAttr(Record[++i]);
870 } else { // String attribute
871 assert((Record[i] == 3 || Record[i] == 4) &&
872 "Invalid attribute group entry");
873 bool HasValue = (Record[i++] == 4);
874 SmallString<64> KindStr;
875 SmallString<64> ValStr;
877 while (Record[i] != 0 && i != e)
878 KindStr += Record[i++];
879 assert(Record[i] == 0 && "Kind string not null terminated");
882 // Has a value associated with it.
883 ++i; // Skip the '0' that terminates the "kind" string.
884 while (Record[i] != 0 && i != e)
885 ValStr += Record[i++];
886 assert(Record[i] == 0 && "Value string not null terminated");
889 B.addAttribute(KindStr.str(), ValStr.str());
893 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
900 std::error_code BitcodeReader::ParseTypeTable() {
901 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
902 return Error("Invalid record");
904 return ParseTypeTableBody();
907 std::error_code BitcodeReader::ParseTypeTableBody() {
908 if (!TypeList.empty())
909 return Error("Invalid multiple blocks");
911 SmallVector<uint64_t, 64> Record;
912 unsigned NumRecords = 0;
914 SmallString<64> TypeName;
916 // Read all the records for this type table.
918 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
920 switch (Entry.Kind) {
921 case BitstreamEntry::SubBlock: // Handled for us already.
922 case BitstreamEntry::Error:
923 return Error("Malformed block");
924 case BitstreamEntry::EndBlock:
925 if (NumRecords != TypeList.size())
926 return Error("Malformed block");
927 return std::error_code();
928 case BitstreamEntry::Record:
929 // The interesting case.
935 Type *ResultTy = nullptr;
936 switch (Stream.readRecord(Entry.ID, Record)) {
938 return Error("Invalid value");
939 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
940 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
941 // type list. This allows us to reserve space.
942 if (Record.size() < 1)
943 return Error("Invalid record");
944 TypeList.resize(Record[0]);
946 case bitc::TYPE_CODE_VOID: // VOID
947 ResultTy = Type::getVoidTy(Context);
949 case bitc::TYPE_CODE_HALF: // HALF
950 ResultTy = Type::getHalfTy(Context);
952 case bitc::TYPE_CODE_FLOAT: // FLOAT
953 ResultTy = Type::getFloatTy(Context);
955 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
956 ResultTy = Type::getDoubleTy(Context);
958 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
959 ResultTy = Type::getX86_FP80Ty(Context);
961 case bitc::TYPE_CODE_FP128: // FP128
962 ResultTy = Type::getFP128Ty(Context);
964 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
965 ResultTy = Type::getPPC_FP128Ty(Context);
967 case bitc::TYPE_CODE_LABEL: // LABEL
968 ResultTy = Type::getLabelTy(Context);
970 case bitc::TYPE_CODE_METADATA: // METADATA
971 ResultTy = Type::getMetadataTy(Context);
973 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
974 ResultTy = Type::getX86_MMXTy(Context);
976 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
977 if (Record.size() < 1)
978 return Error("Invalid record");
980 uint64_t NumBits = Record[0];
981 if (NumBits < IntegerType::MIN_INT_BITS ||
982 NumBits > IntegerType::MAX_INT_BITS)
983 return Error("Bitwidth for integer type out of range");
984 ResultTy = IntegerType::get(Context, NumBits);
987 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
988 // [pointee type, address space]
989 if (Record.size() < 1)
990 return Error("Invalid record");
991 unsigned AddressSpace = 0;
992 if (Record.size() == 2)
993 AddressSpace = Record[1];
994 ResultTy = getTypeByID(Record[0]);
996 return Error("Invalid type");
997 ResultTy = PointerType::get(ResultTy, AddressSpace);
1000 case bitc::TYPE_CODE_FUNCTION_OLD: {
1001 // FIXME: attrid is dead, remove it in LLVM 4.0
1002 // FUNCTION: [vararg, attrid, retty, paramty x N]
1003 if (Record.size() < 3)
1004 return Error("Invalid record");
1005 SmallVector<Type*, 8> ArgTys;
1006 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1007 if (Type *T = getTypeByID(Record[i]))
1008 ArgTys.push_back(T);
1013 ResultTy = getTypeByID(Record[2]);
1014 if (!ResultTy || ArgTys.size() < Record.size()-3)
1015 return Error("Invalid type");
1017 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1020 case bitc::TYPE_CODE_FUNCTION: {
1021 // FUNCTION: [vararg, retty, paramty x N]
1022 if (Record.size() < 2)
1023 return Error("Invalid record");
1024 SmallVector<Type*, 8> ArgTys;
1025 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1026 if (Type *T = getTypeByID(Record[i]))
1027 ArgTys.push_back(T);
1032 ResultTy = getTypeByID(Record[1]);
1033 if (!ResultTy || ArgTys.size() < Record.size()-2)
1034 return Error("Invalid type");
1036 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1039 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1040 if (Record.size() < 1)
1041 return Error("Invalid record");
1042 SmallVector<Type*, 8> EltTys;
1043 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1044 if (Type *T = getTypeByID(Record[i]))
1045 EltTys.push_back(T);
1049 if (EltTys.size() != Record.size()-1)
1050 return Error("Invalid type");
1051 ResultTy = StructType::get(Context, EltTys, Record[0]);
1054 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1055 if (ConvertToString(Record, 0, TypeName))
1056 return Error("Invalid record");
1059 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1060 if (Record.size() < 1)
1061 return Error("Invalid record");
1063 if (NumRecords >= TypeList.size())
1064 return Error("Invalid TYPE table");
1066 // Check to see if this was forward referenced, if so fill in the temp.
1067 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1069 Res->setName(TypeName);
1070 TypeList[NumRecords] = nullptr;
1071 } else // Otherwise, create a new struct.
1072 Res = createIdentifiedStructType(Context, TypeName);
1075 SmallVector<Type*, 8> EltTys;
1076 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1077 if (Type *T = getTypeByID(Record[i]))
1078 EltTys.push_back(T);
1082 if (EltTys.size() != Record.size()-1)
1083 return Error("Invalid record");
1084 Res->setBody(EltTys, Record[0]);
1088 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1089 if (Record.size() != 1)
1090 return Error("Invalid record");
1092 if (NumRecords >= TypeList.size())
1093 return Error("Invalid TYPE table");
1095 // Check to see if this was forward referenced, if so fill in the temp.
1096 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1098 Res->setName(TypeName);
1099 TypeList[NumRecords] = nullptr;
1100 } else // Otherwise, create a new struct with no body.
1101 Res = createIdentifiedStructType(Context, TypeName);
1106 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1107 if (Record.size() < 2)
1108 return Error("Invalid record");
1109 if ((ResultTy = getTypeByID(Record[1])))
1110 ResultTy = ArrayType::get(ResultTy, Record[0]);
1112 return Error("Invalid type");
1114 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1115 if (Record.size() < 2)
1116 return Error("Invalid record");
1117 if ((ResultTy = getTypeByID(Record[1])))
1118 ResultTy = VectorType::get(ResultTy, Record[0]);
1120 return Error("Invalid type");
1124 if (NumRecords >= TypeList.size())
1125 return Error("Invalid TYPE table");
1126 if (TypeList[NumRecords])
1128 "Invalid TYPE table: Only named structs can be forward referenced");
1129 assert(ResultTy && "Didn't read a type?");
1130 TypeList[NumRecords++] = ResultTy;
1134 std::error_code BitcodeReader::ParseValueSymbolTable() {
1135 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1136 return Error("Invalid record");
1138 SmallVector<uint64_t, 64> Record;
1140 Triple TT(TheModule->getTargetTriple());
1142 // Read all the records for this value table.
1143 SmallString<128> ValueName;
1145 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1147 switch (Entry.Kind) {
1148 case BitstreamEntry::SubBlock: // Handled for us already.
1149 case BitstreamEntry::Error:
1150 return Error("Malformed block");
1151 case BitstreamEntry::EndBlock:
1152 return std::error_code();
1153 case BitstreamEntry::Record:
1154 // The interesting case.
1160 switch (Stream.readRecord(Entry.ID, Record)) {
1161 default: // Default behavior: unknown type.
1163 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1164 if (ConvertToString(Record, 1, ValueName))
1165 return Error("Invalid record");
1166 unsigned ValueID = Record[0];
1167 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1168 return Error("Invalid record");
1169 Value *V = ValueList[ValueID];
1171 V->setName(StringRef(ValueName.data(), ValueName.size()));
1172 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1173 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1174 if (TT.isOSBinFormatMachO())
1175 GO->setComdat(nullptr);
1177 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1183 case bitc::VST_CODE_BBENTRY: {
1184 if (ConvertToString(Record, 1, ValueName))
1185 return Error("Invalid record");
1186 BasicBlock *BB = getBasicBlock(Record[0]);
1188 return Error("Invalid record");
1190 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1198 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1200 std::error_code BitcodeReader::ParseMetadata() {
1201 unsigned NextMDValueNo = MDValueList.size();
1203 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1204 return Error("Invalid record");
1206 SmallVector<uint64_t, 64> Record;
1209 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1210 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1212 return getMD(ID - 1);
1215 auto getMDString = [&](unsigned ID) -> MDString *{
1216 // This requires that the ID is not really a forward reference. In
1217 // particular, the MDString must already have been resolved.
1218 return cast_or_null<MDString>(getMDOrNull(ID));
1221 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1222 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1224 // Read all the records.
1226 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1228 switch (Entry.Kind) {
1229 case BitstreamEntry::SubBlock: // Handled for us already.
1230 case BitstreamEntry::Error:
1231 return Error("Malformed block");
1232 case BitstreamEntry::EndBlock:
1233 MDValueList.tryToResolveCycles();
1234 return std::error_code();
1235 case BitstreamEntry::Record:
1236 // The interesting case.
1242 unsigned Code = Stream.readRecord(Entry.ID, Record);
1243 bool IsDistinct = false;
1245 default: // Default behavior: ignore.
1247 case bitc::METADATA_NAME: {
1248 // Read name of the named metadata.
1249 SmallString<8> Name(Record.begin(), Record.end());
1251 Code = Stream.ReadCode();
1253 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1254 unsigned NextBitCode = Stream.readRecord(Code, Record);
1255 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1257 // Read named metadata elements.
1258 unsigned Size = Record.size();
1259 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1260 for (unsigned i = 0; i != Size; ++i) {
1261 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1263 return Error("Invalid record");
1264 NMD->addOperand(MD);
1268 case bitc::METADATA_OLD_FN_NODE: {
1269 // FIXME: Remove in 4.0.
1270 // This is a LocalAsMetadata record, the only type of function-local
1272 if (Record.size() % 2 == 1)
1273 return Error("Invalid record");
1275 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1276 // to be legal, but there's no upgrade path.
1277 auto dropRecord = [&] {
1278 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1280 if (Record.size() != 2) {
1285 Type *Ty = getTypeByID(Record[0]);
1286 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1291 MDValueList.AssignValue(
1292 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1296 case bitc::METADATA_OLD_NODE: {
1297 // FIXME: Remove in 4.0.
1298 if (Record.size() % 2 == 1)
1299 return Error("Invalid record");
1301 unsigned Size = Record.size();
1302 SmallVector<Metadata *, 8> Elts;
1303 for (unsigned i = 0; i != Size; i += 2) {
1304 Type *Ty = getTypeByID(Record[i]);
1306 return Error("Invalid record");
1307 if (Ty->isMetadataTy())
1308 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1309 else if (!Ty->isVoidTy()) {
1311 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1312 assert(isa<ConstantAsMetadata>(MD) &&
1313 "Expected non-function-local metadata");
1316 Elts.push_back(nullptr);
1318 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1321 case bitc::METADATA_VALUE: {
1322 if (Record.size() != 2)
1323 return Error("Invalid record");
1325 Type *Ty = getTypeByID(Record[0]);
1326 if (Ty->isMetadataTy() || Ty->isVoidTy())
1327 return Error("Invalid record");
1329 MDValueList.AssignValue(
1330 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1334 case bitc::METADATA_DISTINCT_NODE:
1337 case bitc::METADATA_NODE: {
1338 SmallVector<Metadata *, 8> Elts;
1339 Elts.reserve(Record.size());
1340 for (unsigned ID : Record)
1341 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1342 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1343 : MDNode::get(Context, Elts),
1347 case bitc::METADATA_LOCATION: {
1348 if (Record.size() != 5)
1349 return Error("Invalid record");
1351 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1352 unsigned Line = Record[1];
1353 unsigned Column = Record[2];
1354 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1355 Metadata *InlinedAt =
1356 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1357 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1361 case bitc::METADATA_GENERIC_DEBUG: {
1362 if (Record.size() < 4)
1363 return Error("Invalid record");
1365 unsigned Tag = Record[1];
1366 unsigned Version = Record[2];
1368 if (Tag >= 1u << 16 || Version != 0)
1369 return Error("Invalid record");
1371 auto *Header = getMDString(Record[3]);
1372 SmallVector<Metadata *, 8> DwarfOps;
1373 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1374 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1376 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1377 (Context, Tag, Header, DwarfOps)),
1381 case bitc::METADATA_SUBRANGE: {
1382 if (Record.size() != 3)
1383 return Error("Invalid record");
1385 MDValueList.AssignValue(
1386 GET_OR_DISTINCT(MDSubrange, Record[0],
1387 (Context, Record[1], unrotateSign(Record[2]))),
1391 case bitc::METADATA_ENUMERATOR: {
1392 if (Record.size() != 3)
1393 return Error("Invalid record");
1395 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1396 (Context, unrotateSign(Record[1]),
1397 getMDString(Record[2]))),
1401 case bitc::METADATA_BASIC_TYPE: {
1402 if (Record.size() != 6)
1403 return Error("Invalid record");
1405 MDValueList.AssignValue(
1406 GET_OR_DISTINCT(MDBasicType, Record[0],
1407 (Context, Record[1], getMDString(Record[2]),
1408 Record[3], Record[4], Record[5])),
1412 case bitc::METADATA_DERIVED_TYPE: {
1413 if (Record.size() != 12)
1414 return Error("Invalid record");
1416 MDValueList.AssignValue(
1417 GET_OR_DISTINCT(MDDerivedType, Record[0],
1418 (Context, Record[1], getMDString(Record[2]),
1419 getMDOrNull(Record[3]), Record[4],
1420 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1421 Record[7], Record[8], Record[9], Record[10],
1422 getMDOrNull(Record[11]))),
1426 case bitc::METADATA_COMPOSITE_TYPE: {
1427 if (Record.size() != 16)
1428 return Error("Invalid record");
1430 MDValueList.AssignValue(
1431 GET_OR_DISTINCT(MDCompositeType, Record[0],
1432 (Context, Record[1], getMDString(Record[2]),
1433 getMDOrNull(Record[3]), Record[4],
1434 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1435 Record[7], Record[8], Record[9], Record[10],
1436 getMDOrNull(Record[11]), Record[12],
1437 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1438 getMDString(Record[15]))),
1442 case bitc::METADATA_SUBROUTINE_TYPE: {
1443 if (Record.size() != 3)
1444 return Error("Invalid record");
1446 MDValueList.AssignValue(
1447 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1448 (Context, Record[1], getMDOrNull(Record[2]))),
1452 case bitc::METADATA_FILE: {
1453 if (Record.size() != 3)
1454 return Error("Invalid record");
1456 MDValueList.AssignValue(
1457 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1458 getMDString(Record[2]))),
1462 case bitc::METADATA_COMPILE_UNIT: {
1463 if (Record.size() != 14)
1464 return Error("Invalid record");
1466 MDValueList.AssignValue(
1467 GET_OR_DISTINCT(MDCompileUnit, Record[0],
1468 (Context, Record[1], getMDOrNull(Record[2]),
1469 getMDString(Record[3]), Record[4],
1470 getMDString(Record[5]), Record[6],
1471 getMDString(Record[7]), Record[8],
1472 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1473 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1474 getMDOrNull(Record[13]))),
1478 case bitc::METADATA_SUBPROGRAM: {
1479 if (Record.size() != 19)
1480 return Error("Invalid record");
1482 MDValueList.AssignValue(
1484 MDSubprogram, Record[0],
1485 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1486 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1487 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1488 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1489 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1490 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1494 case bitc::METADATA_LEXICAL_BLOCK: {
1495 if (Record.size() != 5)
1496 return Error("Invalid record");
1498 MDValueList.AssignValue(
1499 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1500 (Context, getMDOrNull(Record[1]),
1501 getMDOrNull(Record[2]), Record[3], Record[4])),
1505 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1506 if (Record.size() != 4)
1507 return Error("Invalid record");
1509 MDValueList.AssignValue(
1510 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1511 (Context, getMDOrNull(Record[1]),
1512 getMDOrNull(Record[2]), Record[3])),
1516 case bitc::METADATA_NAMESPACE: {
1517 if (Record.size() != 5)
1518 return Error("Invalid record");
1520 MDValueList.AssignValue(
1521 GET_OR_DISTINCT(MDNamespace, Record[0],
1522 (Context, getMDOrNull(Record[1]),
1523 getMDOrNull(Record[2]), getMDString(Record[3]),
1528 case bitc::METADATA_TEMPLATE_TYPE: {
1529 if (Record.size() != 3)
1530 return Error("Invalid record");
1532 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1534 (Context, getMDString(Record[1]),
1535 getMDOrNull(Record[2]))),
1539 case bitc::METADATA_TEMPLATE_VALUE: {
1540 if (Record.size() != 5)
1541 return Error("Invalid record");
1543 MDValueList.AssignValue(
1544 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1545 (Context, Record[1], getMDString(Record[2]),
1546 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1550 case bitc::METADATA_GLOBAL_VAR: {
1551 if (Record.size() != 11)
1552 return Error("Invalid record");
1554 MDValueList.AssignValue(
1555 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1556 (Context, getMDOrNull(Record[1]),
1557 getMDString(Record[2]), getMDString(Record[3]),
1558 getMDOrNull(Record[4]), Record[5],
1559 getMDOrNull(Record[6]), Record[7], Record[8],
1560 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1564 case bitc::METADATA_LOCAL_VAR: {
1565 if (Record.size() != 10)
1566 return Error("Invalid record");
1568 MDValueList.AssignValue(
1569 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1570 (Context, Record[1], getMDOrNull(Record[2]),
1571 getMDString(Record[3]), getMDOrNull(Record[4]),
1572 Record[5], getMDOrNull(Record[6]), Record[7],
1573 Record[8], getMDOrNull(Record[9]))),
1577 case bitc::METADATA_EXPRESSION: {
1578 if (Record.size() < 1)
1579 return Error("Invalid record");
1581 MDValueList.AssignValue(
1582 GET_OR_DISTINCT(MDExpression, Record[0],
1583 (Context, makeArrayRef(Record).slice(1))),
1587 case bitc::METADATA_OBJC_PROPERTY: {
1588 if (Record.size() != 8)
1589 return Error("Invalid record");
1591 MDValueList.AssignValue(
1592 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1593 (Context, getMDString(Record[1]),
1594 getMDOrNull(Record[2]), Record[3],
1595 getMDString(Record[4]), getMDString(Record[5]),
1596 Record[6], getMDOrNull(Record[7]))),
1600 case bitc::METADATA_IMPORTED_ENTITY: {
1601 if (Record.size() != 6)
1602 return Error("Invalid record");
1604 MDValueList.AssignValue(
1605 GET_OR_DISTINCT(MDImportedEntity, Record[0],
1606 (Context, Record[1], getMDOrNull(Record[2]),
1607 getMDOrNull(Record[3]), Record[4],
1608 getMDString(Record[5]))),
1612 case bitc::METADATA_STRING: {
1613 std::string String(Record.begin(), Record.end());
1614 llvm::UpgradeMDStringConstant(String);
1615 Metadata *MD = MDString::get(Context, String);
1616 MDValueList.AssignValue(MD, NextMDValueNo++);
1619 case bitc::METADATA_KIND: {
1620 if (Record.size() < 2)
1621 return Error("Invalid record");
1623 unsigned Kind = Record[0];
1624 SmallString<8> Name(Record.begin()+1, Record.end());
1626 unsigned NewKind = TheModule->getMDKindID(Name.str());
1627 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1628 return Error("Conflicting METADATA_KIND records");
1633 #undef GET_OR_DISTINCT
1636 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1637 /// the LSB for dense VBR encoding.
1638 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1643 // There is no such thing as -0 with integers. "-0" really means MININT.
1647 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1648 /// values and aliases that we can.
1649 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1650 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1651 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1652 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1653 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1655 GlobalInitWorklist.swap(GlobalInits);
1656 AliasInitWorklist.swap(AliasInits);
1657 FunctionPrefixWorklist.swap(FunctionPrefixes);
1658 FunctionPrologueWorklist.swap(FunctionPrologues);
1660 while (!GlobalInitWorklist.empty()) {
1661 unsigned ValID = GlobalInitWorklist.back().second;
1662 if (ValID >= ValueList.size()) {
1663 // Not ready to resolve this yet, it requires something later in the file.
1664 GlobalInits.push_back(GlobalInitWorklist.back());
1666 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1667 GlobalInitWorklist.back().first->setInitializer(C);
1669 return Error("Expected a constant");
1671 GlobalInitWorklist.pop_back();
1674 while (!AliasInitWorklist.empty()) {
1675 unsigned ValID = AliasInitWorklist.back().second;
1676 if (ValID >= ValueList.size()) {
1677 AliasInits.push_back(AliasInitWorklist.back());
1679 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1680 AliasInitWorklist.back().first->setAliasee(C);
1682 return Error("Expected a constant");
1684 AliasInitWorklist.pop_back();
1687 while (!FunctionPrefixWorklist.empty()) {
1688 unsigned ValID = FunctionPrefixWorklist.back().second;
1689 if (ValID >= ValueList.size()) {
1690 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1692 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1693 FunctionPrefixWorklist.back().first->setPrefixData(C);
1695 return Error("Expected a constant");
1697 FunctionPrefixWorklist.pop_back();
1700 while (!FunctionPrologueWorklist.empty()) {
1701 unsigned ValID = FunctionPrologueWorklist.back().second;
1702 if (ValID >= ValueList.size()) {
1703 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1705 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1706 FunctionPrologueWorklist.back().first->setPrologueData(C);
1708 return Error("Expected a constant");
1710 FunctionPrologueWorklist.pop_back();
1713 return std::error_code();
1716 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1717 SmallVector<uint64_t, 8> Words(Vals.size());
1718 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1719 BitcodeReader::decodeSignRotatedValue);
1721 return APInt(TypeBits, Words);
1724 std::error_code BitcodeReader::ParseConstants() {
1725 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1726 return Error("Invalid record");
1728 SmallVector<uint64_t, 64> Record;
1730 // Read all the records for this value table.
1731 Type *CurTy = Type::getInt32Ty(Context);
1732 unsigned NextCstNo = ValueList.size();
1734 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1736 switch (Entry.Kind) {
1737 case BitstreamEntry::SubBlock: // Handled for us already.
1738 case BitstreamEntry::Error:
1739 return Error("Malformed block");
1740 case BitstreamEntry::EndBlock:
1741 if (NextCstNo != ValueList.size())
1742 return Error("Invalid ronstant reference");
1744 // Once all the constants have been read, go through and resolve forward
1746 ValueList.ResolveConstantForwardRefs();
1747 return std::error_code();
1748 case BitstreamEntry::Record:
1749 // The interesting case.
1756 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1758 default: // Default behavior: unknown constant
1759 case bitc::CST_CODE_UNDEF: // UNDEF
1760 V = UndefValue::get(CurTy);
1762 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1764 return Error("Invalid record");
1765 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1766 return Error("Invalid record");
1767 CurTy = TypeList[Record[0]];
1768 continue; // Skip the ValueList manipulation.
1769 case bitc::CST_CODE_NULL: // NULL
1770 V = Constant::getNullValue(CurTy);
1772 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1773 if (!CurTy->isIntegerTy() || Record.empty())
1774 return Error("Invalid record");
1775 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1777 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1778 if (!CurTy->isIntegerTy() || Record.empty())
1779 return Error("Invalid record");
1781 APInt VInt = ReadWideAPInt(Record,
1782 cast<IntegerType>(CurTy)->getBitWidth());
1783 V = ConstantInt::get(Context, VInt);
1787 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1789 return Error("Invalid record");
1790 if (CurTy->isHalfTy())
1791 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1792 APInt(16, (uint16_t)Record[0])));
1793 else if (CurTy->isFloatTy())
1794 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1795 APInt(32, (uint32_t)Record[0])));
1796 else if (CurTy->isDoubleTy())
1797 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1798 APInt(64, Record[0])));
1799 else if (CurTy->isX86_FP80Ty()) {
1800 // Bits are not stored the same way as a normal i80 APInt, compensate.
1801 uint64_t Rearrange[2];
1802 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1803 Rearrange[1] = Record[0] >> 48;
1804 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1805 APInt(80, Rearrange)));
1806 } else if (CurTy->isFP128Ty())
1807 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1808 APInt(128, Record)));
1809 else if (CurTy->isPPC_FP128Ty())
1810 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1811 APInt(128, Record)));
1813 V = UndefValue::get(CurTy);
1817 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1819 return Error("Invalid record");
1821 unsigned Size = Record.size();
1822 SmallVector<Constant*, 16> Elts;
1824 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1825 for (unsigned i = 0; i != Size; ++i)
1826 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1827 STy->getElementType(i)));
1828 V = ConstantStruct::get(STy, Elts);
1829 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1830 Type *EltTy = ATy->getElementType();
1831 for (unsigned i = 0; i != Size; ++i)
1832 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1833 V = ConstantArray::get(ATy, Elts);
1834 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1835 Type *EltTy = VTy->getElementType();
1836 for (unsigned i = 0; i != Size; ++i)
1837 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1838 V = ConstantVector::get(Elts);
1840 V = UndefValue::get(CurTy);
1844 case bitc::CST_CODE_STRING: // STRING: [values]
1845 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1847 return Error("Invalid record");
1849 SmallString<16> Elts(Record.begin(), Record.end());
1850 V = ConstantDataArray::getString(Context, Elts,
1851 BitCode == bitc::CST_CODE_CSTRING);
1854 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1856 return Error("Invalid record");
1858 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1859 unsigned Size = Record.size();
1861 if (EltTy->isIntegerTy(8)) {
1862 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1863 if (isa<VectorType>(CurTy))
1864 V = ConstantDataVector::get(Context, Elts);
1866 V = ConstantDataArray::get(Context, Elts);
1867 } else if (EltTy->isIntegerTy(16)) {
1868 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1869 if (isa<VectorType>(CurTy))
1870 V = ConstantDataVector::get(Context, Elts);
1872 V = ConstantDataArray::get(Context, Elts);
1873 } else if (EltTy->isIntegerTy(32)) {
1874 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1875 if (isa<VectorType>(CurTy))
1876 V = ConstantDataVector::get(Context, Elts);
1878 V = ConstantDataArray::get(Context, Elts);
1879 } else if (EltTy->isIntegerTy(64)) {
1880 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1881 if (isa<VectorType>(CurTy))
1882 V = ConstantDataVector::get(Context, Elts);
1884 V = ConstantDataArray::get(Context, Elts);
1885 } else if (EltTy->isFloatTy()) {
1886 SmallVector<float, 16> Elts(Size);
1887 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1888 if (isa<VectorType>(CurTy))
1889 V = ConstantDataVector::get(Context, Elts);
1891 V = ConstantDataArray::get(Context, Elts);
1892 } else if (EltTy->isDoubleTy()) {
1893 SmallVector<double, 16> Elts(Size);
1894 std::transform(Record.begin(), Record.end(), Elts.begin(),
1896 if (isa<VectorType>(CurTy))
1897 V = ConstantDataVector::get(Context, Elts);
1899 V = ConstantDataArray::get(Context, Elts);
1901 return Error("Invalid type for value");
1906 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1907 if (Record.size() < 3)
1908 return Error("Invalid record");
1909 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1911 V = UndefValue::get(CurTy); // Unknown binop.
1913 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1914 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1916 if (Record.size() >= 4) {
1917 if (Opc == Instruction::Add ||
1918 Opc == Instruction::Sub ||
1919 Opc == Instruction::Mul ||
1920 Opc == Instruction::Shl) {
1921 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1922 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1923 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1924 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1925 } else if (Opc == Instruction::SDiv ||
1926 Opc == Instruction::UDiv ||
1927 Opc == Instruction::LShr ||
1928 Opc == Instruction::AShr) {
1929 if (Record[3] & (1 << bitc::PEO_EXACT))
1930 Flags |= SDivOperator::IsExact;
1933 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1937 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1938 if (Record.size() < 3)
1939 return Error("Invalid record");
1940 int Opc = GetDecodedCastOpcode(Record[0]);
1942 V = UndefValue::get(CurTy); // Unknown cast.
1944 Type *OpTy = getTypeByID(Record[1]);
1946 return Error("Invalid record");
1947 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1948 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1949 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1953 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1954 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1955 if (Record.size() & 1)
1956 return Error("Invalid record");
1957 SmallVector<Constant*, 16> Elts;
1958 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1959 Type *ElTy = getTypeByID(Record[i]);
1961 return Error("Invalid record");
1962 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1964 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1965 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1967 bitc::CST_CODE_CE_INBOUNDS_GEP);
1970 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1971 if (Record.size() < 3)
1972 return Error("Invalid record");
1974 Type *SelectorTy = Type::getInt1Ty(Context);
1976 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1977 // vector. Otherwise, it must be a single bit.
1978 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1979 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1980 VTy->getNumElements());
1982 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1984 ValueList.getConstantFwdRef(Record[1],CurTy),
1985 ValueList.getConstantFwdRef(Record[2],CurTy));
1988 case bitc::CST_CODE_CE_EXTRACTELT
1989 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1990 if (Record.size() < 3)
1991 return Error("Invalid record");
1993 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1995 return Error("Invalid record");
1996 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1997 Constant *Op1 = nullptr;
1998 if (Record.size() == 4) {
1999 Type *IdxTy = getTypeByID(Record[2]);
2001 return Error("Invalid record");
2002 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2003 } else // TODO: Remove with llvm 4.0
2004 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2006 return Error("Invalid record");
2007 V = ConstantExpr::getExtractElement(Op0, Op1);
2010 case bitc::CST_CODE_CE_INSERTELT
2011 : { // CE_INSERTELT: [opval, opval, opty, opval]
2012 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2013 if (Record.size() < 3 || !OpTy)
2014 return Error("Invalid record");
2015 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2016 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2017 OpTy->getElementType());
2018 Constant *Op2 = nullptr;
2019 if (Record.size() == 4) {
2020 Type *IdxTy = getTypeByID(Record[2]);
2022 return Error("Invalid record");
2023 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2024 } else // TODO: Remove with llvm 4.0
2025 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2027 return Error("Invalid record");
2028 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2031 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2032 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2033 if (Record.size() < 3 || !OpTy)
2034 return Error("Invalid record");
2035 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2036 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2037 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2038 OpTy->getNumElements());
2039 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2040 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2043 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2044 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2046 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2047 if (Record.size() < 4 || !RTy || !OpTy)
2048 return Error("Invalid record");
2049 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2050 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2051 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2052 RTy->getNumElements());
2053 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2054 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2057 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2058 if (Record.size() < 4)
2059 return Error("Invalid record");
2060 Type *OpTy = getTypeByID(Record[0]);
2062 return Error("Invalid record");
2063 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2064 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2066 if (OpTy->isFPOrFPVectorTy())
2067 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2069 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2072 // This maintains backward compatibility, pre-asm dialect keywords.
2073 // FIXME: Remove with the 4.0 release.
2074 case bitc::CST_CODE_INLINEASM_OLD: {
2075 if (Record.size() < 2)
2076 return Error("Invalid record");
2077 std::string AsmStr, ConstrStr;
2078 bool HasSideEffects = Record[0] & 1;
2079 bool IsAlignStack = Record[0] >> 1;
2080 unsigned AsmStrSize = Record[1];
2081 if (2+AsmStrSize >= Record.size())
2082 return Error("Invalid record");
2083 unsigned ConstStrSize = Record[2+AsmStrSize];
2084 if (3+AsmStrSize+ConstStrSize > Record.size())
2085 return Error("Invalid record");
2087 for (unsigned i = 0; i != AsmStrSize; ++i)
2088 AsmStr += (char)Record[2+i];
2089 for (unsigned i = 0; i != ConstStrSize; ++i)
2090 ConstrStr += (char)Record[3+AsmStrSize+i];
2091 PointerType *PTy = cast<PointerType>(CurTy);
2092 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2093 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2096 // This version adds support for the asm dialect keywords (e.g.,
2098 case bitc::CST_CODE_INLINEASM: {
2099 if (Record.size() < 2)
2100 return Error("Invalid record");
2101 std::string AsmStr, ConstrStr;
2102 bool HasSideEffects = Record[0] & 1;
2103 bool IsAlignStack = (Record[0] >> 1) & 1;
2104 unsigned AsmDialect = Record[0] >> 2;
2105 unsigned AsmStrSize = Record[1];
2106 if (2+AsmStrSize >= Record.size())
2107 return Error("Invalid record");
2108 unsigned ConstStrSize = Record[2+AsmStrSize];
2109 if (3+AsmStrSize+ConstStrSize > Record.size())
2110 return Error("Invalid record");
2112 for (unsigned i = 0; i != AsmStrSize; ++i)
2113 AsmStr += (char)Record[2+i];
2114 for (unsigned i = 0; i != ConstStrSize; ++i)
2115 ConstrStr += (char)Record[3+AsmStrSize+i];
2116 PointerType *PTy = cast<PointerType>(CurTy);
2117 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2118 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2119 InlineAsm::AsmDialect(AsmDialect));
2122 case bitc::CST_CODE_BLOCKADDRESS:{
2123 if (Record.size() < 3)
2124 return Error("Invalid record");
2125 Type *FnTy = getTypeByID(Record[0]);
2127 return Error("Invalid record");
2129 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2131 return Error("Invalid record");
2133 // Don't let Fn get dematerialized.
2134 BlockAddressesTaken.insert(Fn);
2136 // If the function is already parsed we can insert the block address right
2139 unsigned BBID = Record[2];
2141 // Invalid reference to entry block.
2142 return Error("Invalid ID");
2144 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2145 for (size_t I = 0, E = BBID; I != E; ++I) {
2147 return Error("Invalid ID");
2152 // Otherwise insert a placeholder and remember it so it can be inserted
2153 // when the function is parsed.
2154 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2156 BasicBlockFwdRefQueue.push_back(Fn);
2157 if (FwdBBs.size() < BBID + 1)
2158 FwdBBs.resize(BBID + 1);
2160 FwdBBs[BBID] = BasicBlock::Create(Context);
2163 V = BlockAddress::get(Fn, BB);
2168 ValueList.AssignValue(V, NextCstNo);
2173 std::error_code BitcodeReader::ParseUseLists() {
2174 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2175 return Error("Invalid record");
2177 // Read all the records.
2178 SmallVector<uint64_t, 64> Record;
2180 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2182 switch (Entry.Kind) {
2183 case BitstreamEntry::SubBlock: // Handled for us already.
2184 case BitstreamEntry::Error:
2185 return Error("Malformed block");
2186 case BitstreamEntry::EndBlock:
2187 return std::error_code();
2188 case BitstreamEntry::Record:
2189 // The interesting case.
2193 // Read a use list record.
2196 switch (Stream.readRecord(Entry.ID, Record)) {
2197 default: // Default behavior: unknown type.
2199 case bitc::USELIST_CODE_BB:
2202 case bitc::USELIST_CODE_DEFAULT: {
2203 unsigned RecordLength = Record.size();
2204 if (RecordLength < 3)
2205 // Records should have at least an ID and two indexes.
2206 return Error("Invalid record");
2207 unsigned ID = Record.back();
2212 assert(ID < FunctionBBs.size() && "Basic block not found");
2213 V = FunctionBBs[ID];
2216 unsigned NumUses = 0;
2217 SmallDenseMap<const Use *, unsigned, 16> Order;
2218 for (const Use &U : V->uses()) {
2219 if (++NumUses > Record.size())
2221 Order[&U] = Record[NumUses - 1];
2223 if (Order.size() != Record.size() || NumUses > Record.size())
2224 // Mismatches can happen if the functions are being materialized lazily
2225 // (out-of-order), or a value has been upgraded.
2228 V->sortUseList([&](const Use &L, const Use &R) {
2229 return Order.lookup(&L) < Order.lookup(&R);
2237 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2238 /// remember where it is and then skip it. This lets us lazily deserialize the
2240 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2241 // Get the function we are talking about.
2242 if (FunctionsWithBodies.empty())
2243 return Error("Insufficient function protos");
2245 Function *Fn = FunctionsWithBodies.back();
2246 FunctionsWithBodies.pop_back();
2248 // Save the current stream state.
2249 uint64_t CurBit = Stream.GetCurrentBitNo();
2250 DeferredFunctionInfo[Fn] = CurBit;
2252 // Skip over the function block for now.
2253 if (Stream.SkipBlock())
2254 return Error("Invalid record");
2255 return std::error_code();
2258 std::error_code BitcodeReader::GlobalCleanup() {
2259 // Patch the initializers for globals and aliases up.
2260 ResolveGlobalAndAliasInits();
2261 if (!GlobalInits.empty() || !AliasInits.empty())
2262 return Error("Malformed global initializer set");
2264 // Look for intrinsic functions which need to be upgraded at some point
2265 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2268 if (UpgradeIntrinsicFunction(FI, NewFn))
2269 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2272 // Look for global variables which need to be renamed.
2273 for (Module::global_iterator
2274 GI = TheModule->global_begin(), GE = TheModule->global_end();
2276 GlobalVariable *GV = GI++;
2277 UpgradeGlobalVariable(GV);
2280 // Force deallocation of memory for these vectors to favor the client that
2281 // want lazy deserialization.
2282 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2283 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2284 return std::error_code();
2287 std::error_code BitcodeReader::ParseModule(bool Resume) {
2289 Stream.JumpToBit(NextUnreadBit);
2290 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2291 return Error("Invalid record");
2293 SmallVector<uint64_t, 64> Record;
2294 std::vector<std::string> SectionTable;
2295 std::vector<std::string> GCTable;
2297 // Read all the records for this module.
2299 BitstreamEntry Entry = Stream.advance();
2301 switch (Entry.Kind) {
2302 case BitstreamEntry::Error:
2303 return Error("Malformed block");
2304 case BitstreamEntry::EndBlock:
2305 return GlobalCleanup();
2307 case BitstreamEntry::SubBlock:
2309 default: // Skip unknown content.
2310 if (Stream.SkipBlock())
2311 return Error("Invalid record");
2313 case bitc::BLOCKINFO_BLOCK_ID:
2314 if (Stream.ReadBlockInfoBlock())
2315 return Error("Malformed block");
2317 case bitc::PARAMATTR_BLOCK_ID:
2318 if (std::error_code EC = ParseAttributeBlock())
2321 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2322 if (std::error_code EC = ParseAttributeGroupBlock())
2325 case bitc::TYPE_BLOCK_ID_NEW:
2326 if (std::error_code EC = ParseTypeTable())
2329 case bitc::VALUE_SYMTAB_BLOCK_ID:
2330 if (std::error_code EC = ParseValueSymbolTable())
2332 SeenValueSymbolTable = true;
2334 case bitc::CONSTANTS_BLOCK_ID:
2335 if (std::error_code EC = ParseConstants())
2337 if (std::error_code EC = ResolveGlobalAndAliasInits())
2340 case bitc::METADATA_BLOCK_ID:
2341 if (std::error_code EC = ParseMetadata())
2344 case bitc::FUNCTION_BLOCK_ID:
2345 // If this is the first function body we've seen, reverse the
2346 // FunctionsWithBodies list.
2347 if (!SeenFirstFunctionBody) {
2348 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2349 if (std::error_code EC = GlobalCleanup())
2351 SeenFirstFunctionBody = true;
2354 if (std::error_code EC = RememberAndSkipFunctionBody())
2356 // For streaming bitcode, suspend parsing when we reach the function
2357 // bodies. Subsequent materialization calls will resume it when
2358 // necessary. For streaming, the function bodies must be at the end of
2359 // the bitcode. If the bitcode file is old, the symbol table will be
2360 // at the end instead and will not have been seen yet. In this case,
2361 // just finish the parse now.
2362 if (LazyStreamer && SeenValueSymbolTable) {
2363 NextUnreadBit = Stream.GetCurrentBitNo();
2364 return std::error_code();
2367 case bitc::USELIST_BLOCK_ID:
2368 if (std::error_code EC = ParseUseLists())
2374 case BitstreamEntry::Record:
2375 // The interesting case.
2381 switch (Stream.readRecord(Entry.ID, Record)) {
2382 default: break; // Default behavior, ignore unknown content.
2383 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2384 if (Record.size() < 1)
2385 return Error("Invalid record");
2386 // Only version #0 and #1 are supported so far.
2387 unsigned module_version = Record[0];
2388 switch (module_version) {
2390 return Error("Invalid value");
2392 UseRelativeIDs = false;
2395 UseRelativeIDs = true;
2400 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2402 if (ConvertToString(Record, 0, S))
2403 return Error("Invalid record");
2404 TheModule->setTargetTriple(S);
2407 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2409 if (ConvertToString(Record, 0, S))
2410 return Error("Invalid record");
2411 TheModule->setDataLayout(S);
2414 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2416 if (ConvertToString(Record, 0, S))
2417 return Error("Invalid record");
2418 TheModule->setModuleInlineAsm(S);
2421 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2422 // FIXME: Remove in 4.0.
2424 if (ConvertToString(Record, 0, S))
2425 return Error("Invalid record");
2429 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2431 if (ConvertToString(Record, 0, S))
2432 return Error("Invalid record");
2433 SectionTable.push_back(S);
2436 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2438 if (ConvertToString(Record, 0, S))
2439 return Error("Invalid record");
2440 GCTable.push_back(S);
2443 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2444 if (Record.size() < 2)
2445 return Error("Invalid record");
2446 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2447 unsigned ComdatNameSize = Record[1];
2448 std::string ComdatName;
2449 ComdatName.reserve(ComdatNameSize);
2450 for (unsigned i = 0; i != ComdatNameSize; ++i)
2451 ComdatName += (char)Record[2 + i];
2452 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2453 C->setSelectionKind(SK);
2454 ComdatList.push_back(C);
2457 // GLOBALVAR: [pointer type, isconst, initid,
2458 // linkage, alignment, section, visibility, threadlocal,
2459 // unnamed_addr, externally_initialized, dllstorageclass,
2461 case bitc::MODULE_CODE_GLOBALVAR: {
2462 if (Record.size() < 6)
2463 return Error("Invalid record");
2464 Type *Ty = getTypeByID(Record[0]);
2466 return Error("Invalid record");
2467 if (!Ty->isPointerTy())
2468 return Error("Invalid type for value");
2469 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2470 Ty = cast<PointerType>(Ty)->getElementType();
2472 bool isConstant = Record[1];
2473 uint64_t RawLinkage = Record[3];
2474 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2476 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2478 std::string Section;
2480 if (Record[5]-1 >= SectionTable.size())
2481 return Error("Invalid ID");
2482 Section = SectionTable[Record[5]-1];
2484 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2485 // Local linkage must have default visibility.
2486 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2487 // FIXME: Change to an error if non-default in 4.0.
2488 Visibility = GetDecodedVisibility(Record[6]);
2490 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2491 if (Record.size() > 7)
2492 TLM = GetDecodedThreadLocalMode(Record[7]);
2494 bool UnnamedAddr = false;
2495 if (Record.size() > 8)
2496 UnnamedAddr = Record[8];
2498 bool ExternallyInitialized = false;
2499 if (Record.size() > 9)
2500 ExternallyInitialized = Record[9];
2502 GlobalVariable *NewGV =
2503 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2504 TLM, AddressSpace, ExternallyInitialized);
2505 NewGV->setAlignment(Alignment);
2506 if (!Section.empty())
2507 NewGV->setSection(Section);
2508 NewGV->setVisibility(Visibility);
2509 NewGV->setUnnamedAddr(UnnamedAddr);
2511 if (Record.size() > 10)
2512 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2514 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2516 ValueList.push_back(NewGV);
2518 // Remember which value to use for the global initializer.
2519 if (unsigned InitID = Record[2])
2520 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2522 if (Record.size() > 11) {
2523 if (unsigned ComdatID = Record[11]) {
2524 assert(ComdatID <= ComdatList.size());
2525 NewGV->setComdat(ComdatList[ComdatID - 1]);
2527 } else if (hasImplicitComdat(RawLinkage)) {
2528 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2532 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2533 // alignment, section, visibility, gc, unnamed_addr,
2534 // prologuedata, dllstorageclass, comdat, prefixdata]
2535 case bitc::MODULE_CODE_FUNCTION: {
2536 if (Record.size() < 8)
2537 return Error("Invalid record");
2538 Type *Ty = getTypeByID(Record[0]);
2540 return Error("Invalid record");
2541 if (!Ty->isPointerTy())
2542 return Error("Invalid type for value");
2544 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2546 return Error("Invalid type for value");
2548 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2551 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2552 bool isProto = Record[2];
2553 uint64_t RawLinkage = Record[3];
2554 Func->setLinkage(getDecodedLinkage(RawLinkage));
2555 Func->setAttributes(getAttributes(Record[4]));
2558 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2560 Func->setAlignment(Alignment);
2562 if (Record[6]-1 >= SectionTable.size())
2563 return Error("Invalid ID");
2564 Func->setSection(SectionTable[Record[6]-1]);
2566 // Local linkage must have default visibility.
2567 if (!Func->hasLocalLinkage())
2568 // FIXME: Change to an error if non-default in 4.0.
2569 Func->setVisibility(GetDecodedVisibility(Record[7]));
2570 if (Record.size() > 8 && Record[8]) {
2571 if (Record[8]-1 > GCTable.size())
2572 return Error("Invalid ID");
2573 Func->setGC(GCTable[Record[8]-1].c_str());
2575 bool UnnamedAddr = false;
2576 if (Record.size() > 9)
2577 UnnamedAddr = Record[9];
2578 Func->setUnnamedAddr(UnnamedAddr);
2579 if (Record.size() > 10 && Record[10] != 0)
2580 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2582 if (Record.size() > 11)
2583 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2585 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2587 if (Record.size() > 12) {
2588 if (unsigned ComdatID = Record[12]) {
2589 assert(ComdatID <= ComdatList.size());
2590 Func->setComdat(ComdatList[ComdatID - 1]);
2592 } else if (hasImplicitComdat(RawLinkage)) {
2593 Func->setComdat(reinterpret_cast<Comdat *>(1));
2596 if (Record.size() > 13 && Record[13] != 0)
2597 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2599 ValueList.push_back(Func);
2601 // If this is a function with a body, remember the prototype we are
2602 // creating now, so that we can match up the body with them later.
2604 Func->setIsMaterializable(true);
2605 FunctionsWithBodies.push_back(Func);
2607 DeferredFunctionInfo[Func] = 0;
2611 // ALIAS: [alias type, aliasee val#, linkage]
2612 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2613 case bitc::MODULE_CODE_ALIAS: {
2614 if (Record.size() < 3)
2615 return Error("Invalid record");
2616 Type *Ty = getTypeByID(Record[0]);
2618 return Error("Invalid record");
2619 auto *PTy = dyn_cast<PointerType>(Ty);
2621 return Error("Invalid type for value");
2624 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2625 getDecodedLinkage(Record[2]), "", TheModule);
2626 // Old bitcode files didn't have visibility field.
2627 // Local linkage must have default visibility.
2628 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2629 // FIXME: Change to an error if non-default in 4.0.
2630 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2631 if (Record.size() > 4)
2632 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2634 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2635 if (Record.size() > 5)
2636 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2637 if (Record.size() > 6)
2638 NewGA->setUnnamedAddr(Record[6]);
2639 ValueList.push_back(NewGA);
2640 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2643 /// MODULE_CODE_PURGEVALS: [numvals]
2644 case bitc::MODULE_CODE_PURGEVALS:
2645 // Trim down the value list to the specified size.
2646 if (Record.size() < 1 || Record[0] > ValueList.size())
2647 return Error("Invalid record");
2648 ValueList.shrinkTo(Record[0]);
2655 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2656 TheModule = nullptr;
2658 if (std::error_code EC = InitStream())
2661 // Sniff for the signature.
2662 if (Stream.Read(8) != 'B' ||
2663 Stream.Read(8) != 'C' ||
2664 Stream.Read(4) != 0x0 ||
2665 Stream.Read(4) != 0xC ||
2666 Stream.Read(4) != 0xE ||
2667 Stream.Read(4) != 0xD)
2668 return Error("Invalid bitcode signature");
2670 // We expect a number of well-defined blocks, though we don't necessarily
2671 // need to understand them all.
2673 if (Stream.AtEndOfStream())
2674 return std::error_code();
2676 BitstreamEntry Entry =
2677 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2679 switch (Entry.Kind) {
2680 case BitstreamEntry::Error:
2681 return Error("Malformed block");
2682 case BitstreamEntry::EndBlock:
2683 return std::error_code();
2685 case BitstreamEntry::SubBlock:
2687 case bitc::BLOCKINFO_BLOCK_ID:
2688 if (Stream.ReadBlockInfoBlock())
2689 return Error("Malformed block");
2691 case bitc::MODULE_BLOCK_ID:
2692 // Reject multiple MODULE_BLOCK's in a single bitstream.
2694 return Error("Invalid multiple blocks");
2696 if (std::error_code EC = ParseModule(false))
2699 return std::error_code();
2702 if (Stream.SkipBlock())
2703 return Error("Invalid record");
2707 case BitstreamEntry::Record:
2708 // There should be no records in the top-level of blocks.
2710 // The ranlib in Xcode 4 will align archive members by appending newlines
2711 // to the end of them. If this file size is a multiple of 4 but not 8, we
2712 // have to read and ignore these final 4 bytes :-(
2713 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2714 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2715 Stream.AtEndOfStream())
2716 return std::error_code();
2718 return Error("Invalid record");
2723 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2724 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2725 return Error("Invalid record");
2727 SmallVector<uint64_t, 64> Record;
2730 // Read all the records for this module.
2732 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2734 switch (Entry.Kind) {
2735 case BitstreamEntry::SubBlock: // Handled for us already.
2736 case BitstreamEntry::Error:
2737 return Error("Malformed block");
2738 case BitstreamEntry::EndBlock:
2740 case BitstreamEntry::Record:
2741 // The interesting case.
2746 switch (Stream.readRecord(Entry.ID, Record)) {
2747 default: break; // Default behavior, ignore unknown content.
2748 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2750 if (ConvertToString(Record, 0, S))
2751 return Error("Invalid record");
2758 llvm_unreachable("Exit infinite loop");
2761 ErrorOr<std::string> BitcodeReader::parseTriple() {
2762 if (std::error_code EC = InitStream())
2765 // Sniff for the signature.
2766 if (Stream.Read(8) != 'B' ||
2767 Stream.Read(8) != 'C' ||
2768 Stream.Read(4) != 0x0 ||
2769 Stream.Read(4) != 0xC ||
2770 Stream.Read(4) != 0xE ||
2771 Stream.Read(4) != 0xD)
2772 return Error("Invalid bitcode signature");
2774 // We expect a number of well-defined blocks, though we don't necessarily
2775 // need to understand them all.
2777 BitstreamEntry Entry = Stream.advance();
2779 switch (Entry.Kind) {
2780 case BitstreamEntry::Error:
2781 return Error("Malformed block");
2782 case BitstreamEntry::EndBlock:
2783 return std::error_code();
2785 case BitstreamEntry::SubBlock:
2786 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2787 return parseModuleTriple();
2789 // Ignore other sub-blocks.
2790 if (Stream.SkipBlock())
2791 return Error("Malformed block");
2794 case BitstreamEntry::Record:
2795 Stream.skipRecord(Entry.ID);
2801 /// ParseMetadataAttachment - Parse metadata attachments.
2802 std::error_code BitcodeReader::ParseMetadataAttachment() {
2803 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2804 return Error("Invalid record");
2806 SmallVector<uint64_t, 64> Record;
2808 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2810 switch (Entry.Kind) {
2811 case BitstreamEntry::SubBlock: // Handled for us already.
2812 case BitstreamEntry::Error:
2813 return Error("Malformed block");
2814 case BitstreamEntry::EndBlock:
2815 return std::error_code();
2816 case BitstreamEntry::Record:
2817 // The interesting case.
2821 // Read a metadata attachment record.
2823 switch (Stream.readRecord(Entry.ID, Record)) {
2824 default: // Default behavior: ignore.
2826 case bitc::METADATA_ATTACHMENT: {
2827 unsigned RecordLength = Record.size();
2828 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2829 return Error("Invalid record");
2830 Instruction *Inst = InstructionList[Record[0]];
2831 for (unsigned i = 1; i != RecordLength; i = i+2) {
2832 unsigned Kind = Record[i];
2833 DenseMap<unsigned, unsigned>::iterator I =
2834 MDKindMap.find(Kind);
2835 if (I == MDKindMap.end())
2836 return Error("Invalid ID");
2837 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2838 if (isa<LocalAsMetadata>(Node))
2839 // Drop the attachment. This used to be legal, but there's no
2842 Inst->setMetadata(I->second, cast<MDNode>(Node));
2843 if (I->second == LLVMContext::MD_tbaa)
2844 InstsWithTBAATag.push_back(Inst);
2852 /// ParseFunctionBody - Lazily parse the specified function body block.
2853 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2854 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2855 return Error("Invalid record");
2857 InstructionList.clear();
2858 unsigned ModuleValueListSize = ValueList.size();
2859 unsigned ModuleMDValueListSize = MDValueList.size();
2861 // Add all the function arguments to the value table.
2862 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2863 ValueList.push_back(I);
2865 unsigned NextValueNo = ValueList.size();
2866 BasicBlock *CurBB = nullptr;
2867 unsigned CurBBNo = 0;
2870 auto getLastInstruction = [&]() -> Instruction * {
2871 if (CurBB && !CurBB->empty())
2872 return &CurBB->back();
2873 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2874 !FunctionBBs[CurBBNo - 1]->empty())
2875 return &FunctionBBs[CurBBNo - 1]->back();
2879 // Read all the records.
2880 SmallVector<uint64_t, 64> Record;
2882 BitstreamEntry Entry = Stream.advance();
2884 switch (Entry.Kind) {
2885 case BitstreamEntry::Error:
2886 return Error("Malformed block");
2887 case BitstreamEntry::EndBlock:
2888 goto OutOfRecordLoop;
2890 case BitstreamEntry::SubBlock:
2892 default: // Skip unknown content.
2893 if (Stream.SkipBlock())
2894 return Error("Invalid record");
2896 case bitc::CONSTANTS_BLOCK_ID:
2897 if (std::error_code EC = ParseConstants())
2899 NextValueNo = ValueList.size();
2901 case bitc::VALUE_SYMTAB_BLOCK_ID:
2902 if (std::error_code EC = ParseValueSymbolTable())
2905 case bitc::METADATA_ATTACHMENT_ID:
2906 if (std::error_code EC = ParseMetadataAttachment())
2909 case bitc::METADATA_BLOCK_ID:
2910 if (std::error_code EC = ParseMetadata())
2913 case bitc::USELIST_BLOCK_ID:
2914 if (std::error_code EC = ParseUseLists())
2920 case BitstreamEntry::Record:
2921 // The interesting case.
2927 Instruction *I = nullptr;
2928 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2930 default: // Default behavior: reject
2931 return Error("Invalid value");
2932 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2933 if (Record.size() < 1 || Record[0] == 0)
2934 return Error("Invalid record");
2935 // Create all the basic blocks for the function.
2936 FunctionBBs.resize(Record[0]);
2938 // See if anything took the address of blocks in this function.
2939 auto BBFRI = BasicBlockFwdRefs.find(F);
2940 if (BBFRI == BasicBlockFwdRefs.end()) {
2941 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2942 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2944 auto &BBRefs = BBFRI->second;
2945 // Check for invalid basic block references.
2946 if (BBRefs.size() > FunctionBBs.size())
2947 return Error("Invalid ID");
2948 assert(!BBRefs.empty() && "Unexpected empty array");
2949 assert(!BBRefs.front() && "Invalid reference to entry block");
2950 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2952 if (I < RE && BBRefs[I]) {
2953 BBRefs[I]->insertInto(F);
2954 FunctionBBs[I] = BBRefs[I];
2956 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2959 // Erase from the table.
2960 BasicBlockFwdRefs.erase(BBFRI);
2963 CurBB = FunctionBBs[0];
2967 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2968 // This record indicates that the last instruction is at the same
2969 // location as the previous instruction with a location.
2970 I = getLastInstruction();
2973 return Error("Invalid record");
2974 I->setDebugLoc(LastLoc);
2978 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2979 I = getLastInstruction();
2980 if (!I || Record.size() < 4)
2981 return Error("Invalid record");
2983 unsigned Line = Record[0], Col = Record[1];
2984 unsigned ScopeID = Record[2], IAID = Record[3];
2986 MDNode *Scope = nullptr, *IA = nullptr;
2987 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2988 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2989 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2990 I->setDebugLoc(LastLoc);
2995 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2998 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2999 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3000 OpNum+1 > Record.size())
3001 return Error("Invalid record");
3003 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3005 return Error("Invalid record");
3006 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3007 InstructionList.push_back(I);
3008 if (OpNum < Record.size()) {
3009 if (Opc == Instruction::Add ||
3010 Opc == Instruction::Sub ||
3011 Opc == Instruction::Mul ||
3012 Opc == Instruction::Shl) {
3013 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3014 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3015 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3016 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3017 } else if (Opc == Instruction::SDiv ||
3018 Opc == Instruction::UDiv ||
3019 Opc == Instruction::LShr ||
3020 Opc == Instruction::AShr) {
3021 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3022 cast<BinaryOperator>(I)->setIsExact(true);
3023 } else if (isa<FPMathOperator>(I)) {
3025 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3026 FMF.setUnsafeAlgebra();
3027 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3029 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3031 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3032 FMF.setNoSignedZeros();
3033 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3034 FMF.setAllowReciprocal();
3036 I->setFastMathFlags(FMF);
3042 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3045 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3046 OpNum+2 != Record.size())
3047 return Error("Invalid record");
3049 Type *ResTy = getTypeByID(Record[OpNum]);
3050 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3051 if (Opc == -1 || !ResTy)
3052 return Error("Invalid record");
3053 Instruction *Temp = nullptr;
3054 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3056 InstructionList.push_back(Temp);
3057 CurBB->getInstList().push_back(Temp);
3060 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3062 InstructionList.push_back(I);
3065 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3066 case bitc::FUNC_CODE_INST_GEP_OLD:
3067 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3073 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3074 InBounds = Record[OpNum++];
3075 Ty = getTypeByID(Record[OpNum++]);
3077 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3082 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3083 return Error("Invalid record");
3085 SmallVector<Value*, 16> GEPIdx;
3086 while (OpNum != Record.size()) {
3088 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3089 return Error("Invalid record");
3090 GEPIdx.push_back(Op);
3093 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
3094 assert(!Ty || Ty == cast<GetElementPtrInst>(I)->getSourceElementType());
3095 InstructionList.push_back(I);
3097 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3101 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3102 // EXTRACTVAL: [opty, opval, n x indices]
3105 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3106 return Error("Invalid record");
3108 SmallVector<unsigned, 4> EXTRACTVALIdx;
3109 Type *CurTy = Agg->getType();
3110 for (unsigned RecSize = Record.size();
3111 OpNum != RecSize; ++OpNum) {
3112 bool IsArray = CurTy->isArrayTy();
3113 bool IsStruct = CurTy->isStructTy();
3114 uint64_t Index = Record[OpNum];
3116 if (!IsStruct && !IsArray)
3117 return Error("EXTRACTVAL: Invalid type");
3118 if ((unsigned)Index != Index)
3119 return Error("Invalid value");
3120 if (IsStruct && Index >= CurTy->subtypes().size())
3121 return Error("EXTRACTVAL: Invalid struct index");
3122 if (IsArray && Index >= CurTy->getArrayNumElements())
3123 return Error("EXTRACTVAL: Invalid array index");
3124 EXTRACTVALIdx.push_back((unsigned)Index);
3127 CurTy = CurTy->subtypes()[Index];
3129 CurTy = CurTy->subtypes()[0];
3132 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3133 InstructionList.push_back(I);
3137 case bitc::FUNC_CODE_INST_INSERTVAL: {
3138 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3141 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3142 return Error("Invalid record");
3144 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3145 return Error("Invalid record");
3147 SmallVector<unsigned, 4> INSERTVALIdx;
3148 Type *CurTy = Agg->getType();
3149 for (unsigned RecSize = Record.size();
3150 OpNum != RecSize; ++OpNum) {
3151 bool IsArray = CurTy->isArrayTy();
3152 bool IsStruct = CurTy->isStructTy();
3153 uint64_t Index = Record[OpNum];
3155 if (!IsStruct && !IsArray)
3156 return Error("INSERTVAL: Invalid type");
3157 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3158 return Error("Invalid type");
3159 if ((unsigned)Index != Index)
3160 return Error("Invalid value");
3161 if (IsStruct && Index >= CurTy->subtypes().size())
3162 return Error("INSERTVAL: Invalid struct index");
3163 if (IsArray && Index >= CurTy->getArrayNumElements())
3164 return Error("INSERTVAL: Invalid array index");
3166 INSERTVALIdx.push_back((unsigned)Index);
3168 CurTy = CurTy->subtypes()[Index];
3170 CurTy = CurTy->subtypes()[0];
3173 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3174 InstructionList.push_back(I);
3178 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3179 // obsolete form of select
3180 // handles select i1 ... in old bitcode
3182 Value *TrueVal, *FalseVal, *Cond;
3183 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3184 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3185 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3186 return Error("Invalid record");
3188 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3189 InstructionList.push_back(I);
3193 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3194 // new form of select
3195 // handles select i1 or select [N x i1]
3197 Value *TrueVal, *FalseVal, *Cond;
3198 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3199 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3200 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3201 return Error("Invalid record");
3203 // select condition can be either i1 or [N x i1]
3204 if (VectorType* vector_type =
3205 dyn_cast<VectorType>(Cond->getType())) {
3207 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3208 return Error("Invalid type for value");
3211 if (Cond->getType() != Type::getInt1Ty(Context))
3212 return Error("Invalid type for value");
3215 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3216 InstructionList.push_back(I);
3220 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3223 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3224 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3225 return Error("Invalid record");
3226 I = ExtractElementInst::Create(Vec, Idx);
3227 InstructionList.push_back(I);
3231 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3233 Value *Vec, *Elt, *Idx;
3234 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3235 popValue(Record, OpNum, NextValueNo,
3236 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3237 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3238 return Error("Invalid record");
3239 I = InsertElementInst::Create(Vec, Elt, Idx);
3240 InstructionList.push_back(I);
3244 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3246 Value *Vec1, *Vec2, *Mask;
3247 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3248 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3249 return Error("Invalid record");
3251 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3252 return Error("Invalid record");
3253 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3254 InstructionList.push_back(I);
3258 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3259 // Old form of ICmp/FCmp returning bool
3260 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3261 // both legal on vectors but had different behaviour.
3262 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3263 // FCmp/ICmp returning bool or vector of bool
3267 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3268 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3269 OpNum+1 != Record.size())
3270 return Error("Invalid record");
3272 if (LHS->getType()->isFPOrFPVectorTy())
3273 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3275 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3276 InstructionList.push_back(I);
3280 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3282 unsigned Size = Record.size();
3284 I = ReturnInst::Create(Context);
3285 InstructionList.push_back(I);
3290 Value *Op = nullptr;
3291 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3292 return Error("Invalid record");
3293 if (OpNum != Record.size())
3294 return Error("Invalid record");
3296 I = ReturnInst::Create(Context, Op);
3297 InstructionList.push_back(I);
3300 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3301 if (Record.size() != 1 && Record.size() != 3)
3302 return Error("Invalid record");
3303 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3305 return Error("Invalid record");
3307 if (Record.size() == 1) {
3308 I = BranchInst::Create(TrueDest);
3309 InstructionList.push_back(I);
3312 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3313 Value *Cond = getValue(Record, 2, NextValueNo,
3314 Type::getInt1Ty(Context));
3315 if (!FalseDest || !Cond)
3316 return Error("Invalid record");
3317 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3318 InstructionList.push_back(I);
3322 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3324 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3325 // "New" SwitchInst format with case ranges. The changes to write this
3326 // format were reverted but we still recognize bitcode that uses it.
3327 // Hopefully someday we will have support for case ranges and can use
3328 // this format again.
3330 Type *OpTy = getTypeByID(Record[1]);
3331 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3333 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3334 BasicBlock *Default = getBasicBlock(Record[3]);
3335 if (!OpTy || !Cond || !Default)
3336 return Error("Invalid record");
3338 unsigned NumCases = Record[4];
3340 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3341 InstructionList.push_back(SI);
3343 unsigned CurIdx = 5;
3344 for (unsigned i = 0; i != NumCases; ++i) {
3345 SmallVector<ConstantInt*, 1> CaseVals;
3346 unsigned NumItems = Record[CurIdx++];
3347 for (unsigned ci = 0; ci != NumItems; ++ci) {
3348 bool isSingleNumber = Record[CurIdx++];
3351 unsigned ActiveWords = 1;
3352 if (ValueBitWidth > 64)
3353 ActiveWords = Record[CurIdx++];
3354 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3356 CurIdx += ActiveWords;
3358 if (!isSingleNumber) {
3360 if (ValueBitWidth > 64)
3361 ActiveWords = Record[CurIdx++];
3363 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3365 CurIdx += ActiveWords;
3367 // FIXME: It is not clear whether values in the range should be
3368 // compared as signed or unsigned values. The partially
3369 // implemented changes that used this format in the past used
3370 // unsigned comparisons.
3371 for ( ; Low.ule(High); ++Low)
3372 CaseVals.push_back(ConstantInt::get(Context, Low));
3374 CaseVals.push_back(ConstantInt::get(Context, Low));
3376 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3377 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3378 cve = CaseVals.end(); cvi != cve; ++cvi)
3379 SI->addCase(*cvi, DestBB);
3385 // Old SwitchInst format without case ranges.
3387 if (Record.size() < 3 || (Record.size() & 1) == 0)
3388 return Error("Invalid record");
3389 Type *OpTy = getTypeByID(Record[0]);
3390 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3391 BasicBlock *Default = getBasicBlock(Record[2]);
3392 if (!OpTy || !Cond || !Default)
3393 return Error("Invalid record");
3394 unsigned NumCases = (Record.size()-3)/2;
3395 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3396 InstructionList.push_back(SI);
3397 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3398 ConstantInt *CaseVal =
3399 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3400 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3401 if (!CaseVal || !DestBB) {
3403 return Error("Invalid record");
3405 SI->addCase(CaseVal, DestBB);
3410 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3411 if (Record.size() < 2)
3412 return Error("Invalid record");
3413 Type *OpTy = getTypeByID(Record[0]);
3414 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3415 if (!OpTy || !Address)
3416 return Error("Invalid record");
3417 unsigned NumDests = Record.size()-2;
3418 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3419 InstructionList.push_back(IBI);
3420 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3421 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3422 IBI->addDestination(DestBB);
3425 return Error("Invalid record");
3432 case bitc::FUNC_CODE_INST_INVOKE: {
3433 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3434 if (Record.size() < 4)
3435 return Error("Invalid record");
3436 AttributeSet PAL = getAttributes(Record[0]);
3437 unsigned CCInfo = Record[1];
3438 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3439 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3443 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3444 return Error("Invalid record");
3446 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3447 FunctionType *FTy = !CalleeTy ? nullptr :
3448 dyn_cast<FunctionType>(CalleeTy->getElementType());
3450 // Check that the right number of fixed parameters are here.
3451 if (!FTy || !NormalBB || !UnwindBB ||
3452 Record.size() < OpNum+FTy->getNumParams())
3453 return Error("Invalid record");
3455 SmallVector<Value*, 16> Ops;
3456 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3457 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3458 FTy->getParamType(i)));
3460 return Error("Invalid record");
3463 if (!FTy->isVarArg()) {
3464 if (Record.size() != OpNum)
3465 return Error("Invalid record");
3467 // Read type/value pairs for varargs params.
3468 while (OpNum != Record.size()) {
3470 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3471 return Error("Invalid record");
3476 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3477 InstructionList.push_back(I);
3478 cast<InvokeInst>(I)->setCallingConv(
3479 static_cast<CallingConv::ID>(CCInfo));
3480 cast<InvokeInst>(I)->setAttributes(PAL);
3483 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3485 Value *Val = nullptr;
3486 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3487 return Error("Invalid record");
3488 I = ResumeInst::Create(Val);
3489 InstructionList.push_back(I);
3492 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3493 I = new UnreachableInst(Context);
3494 InstructionList.push_back(I);
3496 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3497 if (Record.size() < 1 || ((Record.size()-1)&1))
3498 return Error("Invalid record");
3499 Type *Ty = getTypeByID(Record[0]);
3501 return Error("Invalid record");
3503 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3504 InstructionList.push_back(PN);
3506 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3508 // With the new function encoding, it is possible that operands have
3509 // negative IDs (for forward references). Use a signed VBR
3510 // representation to keep the encoding small.
3512 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3514 V = getValue(Record, 1+i, NextValueNo, Ty);
3515 BasicBlock *BB = getBasicBlock(Record[2+i]);
3517 return Error("Invalid record");
3518 PN->addIncoming(V, BB);
3524 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3525 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3527 if (Record.size() < 4)
3528 return Error("Invalid record");
3529 Type *Ty = getTypeByID(Record[Idx++]);
3531 return Error("Invalid record");
3532 Value *PersFn = nullptr;
3533 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3534 return Error("Invalid record");
3536 bool IsCleanup = !!Record[Idx++];
3537 unsigned NumClauses = Record[Idx++];
3538 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3539 LP->setCleanup(IsCleanup);
3540 for (unsigned J = 0; J != NumClauses; ++J) {
3541 LandingPadInst::ClauseType CT =
3542 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3545 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3547 return Error("Invalid record");
3550 assert((CT != LandingPadInst::Catch ||
3551 !isa<ArrayType>(Val->getType())) &&
3552 "Catch clause has a invalid type!");
3553 assert((CT != LandingPadInst::Filter ||
3554 isa<ArrayType>(Val->getType())) &&
3555 "Filter clause has invalid type!");
3556 LP->addClause(cast<Constant>(Val));
3560 InstructionList.push_back(I);
3564 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3565 if (Record.size() != 4)
3566 return Error("Invalid record");
3568 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3569 Type *OpTy = getTypeByID(Record[1]);
3570 Value *Size = getFnValueByID(Record[2], OpTy);
3571 uint64_t AlignRecord = Record[3];
3572 const uint64_t InAllocaMask = uint64_t(1) << 5;
3573 bool InAlloca = AlignRecord & InAllocaMask;
3575 if (std::error_code EC =
3576 parseAlignmentValue(AlignRecord & ~InAllocaMask, Align)) {
3580 return Error("Invalid record");
3581 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, Align);
3582 AI->setUsedWithInAlloca(InAlloca);
3584 InstructionList.push_back(I);
3587 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3590 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3591 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
3592 return Error("Invalid record");
3595 if (OpNum + 3 == Record.size())
3596 Ty = getTypeByID(Record[OpNum++]);
3599 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3601 I = new LoadInst(Op, "", Record[OpNum+1], Align);
3603 assert((!Ty || Ty == I->getType()) &&
3604 "Explicit type doesn't match pointee type of the first operand");
3606 InstructionList.push_back(I);
3609 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3610 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3613 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3614 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
3615 return Error("Invalid record");
3618 if (OpNum + 5 == Record.size())
3619 Ty = getTypeByID(Record[OpNum++]);
3621 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3622 if (Ordering == NotAtomic || Ordering == Release ||
3623 Ordering == AcquireRelease)
3624 return Error("Invalid record");
3625 if (Ordering != NotAtomic && Record[OpNum] == 0)
3626 return Error("Invalid record");
3627 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3630 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3632 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
3634 assert((!Ty || Ty == I->getType()) &&
3635 "Explicit type doesn't match pointee type of the first operand");
3637 InstructionList.push_back(I);
3640 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3643 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3644 popValue(Record, OpNum, NextValueNo,
3645 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3646 OpNum+2 != Record.size())
3647 return Error("Invalid record");
3649 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3651 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
3652 InstructionList.push_back(I);
3655 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3656 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3659 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3660 popValue(Record, OpNum, NextValueNo,
3661 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3662 OpNum+4 != Record.size())
3663 return Error("Invalid record");
3665 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3666 if (Ordering == NotAtomic || Ordering == Acquire ||
3667 Ordering == AcquireRelease)
3668 return Error("Invalid record");
3669 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3670 if (Ordering != NotAtomic && Record[OpNum] == 0)
3671 return Error("Invalid record");
3674 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3676 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
3677 InstructionList.push_back(I);
3680 case bitc::FUNC_CODE_INST_CMPXCHG: {
3681 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3682 // failureordering?, isweak?]
3684 Value *Ptr, *Cmp, *New;
3685 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3686 popValue(Record, OpNum, NextValueNo,
3687 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3688 popValue(Record, OpNum, NextValueNo,
3689 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3690 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3691 return Error("Invalid record");
3692 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3693 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3694 return Error("Invalid record");
3695 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3697 AtomicOrdering FailureOrdering;
3698 if (Record.size() < 7)
3700 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3702 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3704 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3706 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3708 if (Record.size() < 8) {
3709 // Before weak cmpxchgs existed, the instruction simply returned the
3710 // value loaded from memory, so bitcode files from that era will be
3711 // expecting the first component of a modern cmpxchg.
3712 CurBB->getInstList().push_back(I);
3713 I = ExtractValueInst::Create(I, 0);
3715 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3718 InstructionList.push_back(I);
3721 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3722 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3725 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3726 popValue(Record, OpNum, NextValueNo,
3727 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3728 OpNum+4 != Record.size())
3729 return Error("Invalid record");
3730 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3731 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3732 Operation > AtomicRMWInst::LAST_BINOP)
3733 return Error("Invalid record");
3734 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3735 if (Ordering == NotAtomic || Ordering == Unordered)
3736 return Error("Invalid record");
3737 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3738 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3739 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3740 InstructionList.push_back(I);
3743 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3744 if (2 != Record.size())
3745 return Error("Invalid record");
3746 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3747 if (Ordering == NotAtomic || Ordering == Unordered ||
3748 Ordering == Monotonic)
3749 return Error("Invalid record");
3750 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3751 I = new FenceInst(Context, Ordering, SynchScope);
3752 InstructionList.push_back(I);
3755 case bitc::FUNC_CODE_INST_CALL: {
3756 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3757 if (Record.size() < 3)
3758 return Error("Invalid record");
3760 AttributeSet PAL = getAttributes(Record[0]);
3761 unsigned CCInfo = Record[1];
3765 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3766 return Error("Invalid record");
3768 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3769 FunctionType *FTy = nullptr;
3770 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3771 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3772 return Error("Invalid record");
3774 SmallVector<Value*, 16> Args;
3775 // Read the fixed params.
3776 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3777 if (FTy->getParamType(i)->isLabelTy())
3778 Args.push_back(getBasicBlock(Record[OpNum]));
3780 Args.push_back(getValue(Record, OpNum, NextValueNo,
3781 FTy->getParamType(i)));
3783 return Error("Invalid record");
3786 // Read type/value pairs for varargs params.
3787 if (!FTy->isVarArg()) {
3788 if (OpNum != Record.size())
3789 return Error("Invalid record");
3791 while (OpNum != Record.size()) {
3793 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3794 return Error("Invalid record");
3799 I = CallInst::Create(Callee, Args);
3800 InstructionList.push_back(I);
3801 cast<CallInst>(I)->setCallingConv(
3802 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3803 CallInst::TailCallKind TCK = CallInst::TCK_None;
3805 TCK = CallInst::TCK_Tail;
3806 if (CCInfo & (1 << 14))
3807 TCK = CallInst::TCK_MustTail;
3808 cast<CallInst>(I)->setTailCallKind(TCK);
3809 cast<CallInst>(I)->setAttributes(PAL);
3812 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3813 if (Record.size() < 3)
3814 return Error("Invalid record");
3815 Type *OpTy = getTypeByID(Record[0]);
3816 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3817 Type *ResTy = getTypeByID(Record[2]);
3818 if (!OpTy || !Op || !ResTy)
3819 return Error("Invalid record");
3820 I = new VAArgInst(Op, ResTy);
3821 InstructionList.push_back(I);
3826 // Add instruction to end of current BB. If there is no current BB, reject
3830 return Error("Invalid instruction with no BB");
3832 CurBB->getInstList().push_back(I);
3834 // If this was a terminator instruction, move to the next block.
3835 if (isa<TerminatorInst>(I)) {
3837 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3840 // Non-void values get registered in the value table for future use.
3841 if (I && !I->getType()->isVoidTy())
3842 ValueList.AssignValue(I, NextValueNo++);
3847 // Check the function list for unresolved values.
3848 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3849 if (!A->getParent()) {
3850 // We found at least one unresolved value. Nuke them all to avoid leaks.
3851 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3852 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3853 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3857 return Error("Never resolved value found in function");
3861 // FIXME: Check for unresolved forward-declared metadata references
3862 // and clean up leaks.
3864 // Trim the value list down to the size it was before we parsed this function.
3865 ValueList.shrinkTo(ModuleValueListSize);
3866 MDValueList.shrinkTo(ModuleMDValueListSize);
3867 std::vector<BasicBlock*>().swap(FunctionBBs);
3868 return std::error_code();
3871 /// Find the function body in the bitcode stream
3872 std::error_code BitcodeReader::FindFunctionInStream(
3874 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3875 while (DeferredFunctionInfoIterator->second == 0) {
3876 if (Stream.AtEndOfStream())
3877 return Error("Could not find function in stream");
3878 // ParseModule will parse the next body in the stream and set its
3879 // position in the DeferredFunctionInfo map.
3880 if (std::error_code EC = ParseModule(true))
3883 return std::error_code();
3886 //===----------------------------------------------------------------------===//
3887 // GVMaterializer implementation
3888 //===----------------------------------------------------------------------===//
3890 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3892 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3893 Function *F = dyn_cast<Function>(GV);
3894 // If it's not a function or is already material, ignore the request.
3895 if (!F || !F->isMaterializable())
3896 return std::error_code();
3898 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3899 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3900 // If its position is recorded as 0, its body is somewhere in the stream
3901 // but we haven't seen it yet.
3902 if (DFII->second == 0 && LazyStreamer)
3903 if (std::error_code EC = FindFunctionInStream(F, DFII))
3906 // Move the bit stream to the saved position of the deferred function body.
3907 Stream.JumpToBit(DFII->second);
3909 if (std::error_code EC = ParseFunctionBody(F))
3911 F->setIsMaterializable(false);
3913 // Upgrade any old intrinsic calls in the function.
3914 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3915 E = UpgradedIntrinsics.end(); I != E; ++I) {
3916 if (I->first != I->second) {
3917 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3919 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3920 UpgradeIntrinsicCall(CI, I->second);
3925 // Bring in any functions that this function forward-referenced via
3927 return materializeForwardReferencedFunctions();
3930 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3931 const Function *F = dyn_cast<Function>(GV);
3932 if (!F || F->isDeclaration())
3935 // Dematerializing F would leave dangling references that wouldn't be
3936 // reconnected on re-materialization.
3937 if (BlockAddressesTaken.count(F))
3940 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3943 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3944 Function *F = dyn_cast<Function>(GV);
3945 // If this function isn't dematerializable, this is a noop.
3946 if (!F || !isDematerializable(F))
3949 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3951 // Just forget the function body, we can remat it later.
3952 F->dropAllReferences();
3953 F->setIsMaterializable(true);
3956 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3957 assert(M == TheModule &&
3958 "Can only Materialize the Module this BitcodeReader is attached to.");
3960 // Promise to materialize all forward references.
3961 WillMaterializeAllForwardRefs = true;
3963 // Iterate over the module, deserializing any functions that are still on
3965 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3967 if (std::error_code EC = materialize(F))
3970 // At this point, if there are any function bodies, the current bit is
3971 // pointing to the END_BLOCK record after them. Now make sure the rest
3972 // of the bits in the module have been read.
3976 // Check that all block address forward references got resolved (as we
3978 if (!BasicBlockFwdRefs.empty())
3979 return Error("Never resolved function from blockaddress");
3981 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3982 // delete the old functions to clean up. We can't do this unless the entire
3983 // module is materialized because there could always be another function body
3984 // with calls to the old function.
3985 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3986 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3987 if (I->first != I->second) {
3988 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3990 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3991 UpgradeIntrinsicCall(CI, I->second);
3993 if (!I->first->use_empty())
3994 I->first->replaceAllUsesWith(I->second);
3995 I->first->eraseFromParent();
3998 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4000 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4001 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4003 UpgradeDebugInfo(*M);
4004 return std::error_code();
4007 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4008 return IdentifiedStructTypes;
4011 std::error_code BitcodeReader::InitStream() {
4013 return InitLazyStream();
4014 return InitStreamFromBuffer();
4017 std::error_code BitcodeReader::InitStreamFromBuffer() {
4018 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4019 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4021 if (Buffer->getBufferSize() & 3)
4022 return Error("Invalid bitcode signature");
4024 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4025 // The magic number is 0x0B17C0DE stored in little endian.
4026 if (isBitcodeWrapper(BufPtr, BufEnd))
4027 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4028 return Error("Invalid bitcode wrapper header");
4030 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4031 Stream.init(&*StreamFile);
4033 return std::error_code();
4036 std::error_code BitcodeReader::InitLazyStream() {
4037 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4039 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4040 StreamingMemoryObject &Bytes = *OwnedBytes;
4041 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4042 Stream.init(&*StreamFile);
4044 unsigned char buf[16];
4045 if (Bytes.readBytes(buf, 16, 0) != 16)
4046 return Error("Invalid bitcode signature");
4048 if (!isBitcode(buf, buf + 16))
4049 return Error("Invalid bitcode signature");
4051 if (isBitcodeWrapper(buf, buf + 4)) {
4052 const unsigned char *bitcodeStart = buf;
4053 const unsigned char *bitcodeEnd = buf + 16;
4054 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4055 Bytes.dropLeadingBytes(bitcodeStart - buf);
4056 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4058 return std::error_code();
4062 class BitcodeErrorCategoryType : public std::error_category {
4063 const char *name() const LLVM_NOEXCEPT override {
4064 return "llvm.bitcode";
4066 std::string message(int IE) const override {
4067 BitcodeError E = static_cast<BitcodeError>(IE);
4069 case BitcodeError::InvalidBitcodeSignature:
4070 return "Invalid bitcode signature";
4071 case BitcodeError::CorruptedBitcode:
4072 return "Corrupted bitcode";
4074 llvm_unreachable("Unknown error type!");
4079 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4081 const std::error_category &llvm::BitcodeErrorCategory() {
4082 return *ErrorCategory;
4085 //===----------------------------------------------------------------------===//
4086 // External interface
4087 //===----------------------------------------------------------------------===//
4089 /// \brief Get a lazy one-at-time loading module from bitcode.
4091 /// This isn't always used in a lazy context. In particular, it's also used by
4092 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4093 /// in forward-referenced functions from block address references.
4095 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4096 /// materialize everything -- in particular, if this isn't truly lazy.
4097 static ErrorOr<Module *>
4098 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4099 LLVMContext &Context, bool WillMaterializeAll,
4100 DiagnosticHandlerFunction DiagnosticHandler) {
4101 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4103 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4104 M->setMaterializer(R);
4106 auto cleanupOnError = [&](std::error_code EC) {
4107 R->releaseBuffer(); // Never take ownership on error.
4108 delete M; // Also deletes R.
4112 if (std::error_code EC = R->ParseBitcodeInto(M))
4113 return cleanupOnError(EC);
4115 if (!WillMaterializeAll)
4116 // Resolve forward references from blockaddresses.
4117 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4118 return cleanupOnError(EC);
4120 Buffer.release(); // The BitcodeReader owns it now.
4125 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4126 LLVMContext &Context,
4127 DiagnosticHandlerFunction DiagnosticHandler) {
4128 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4132 ErrorOr<std::unique_ptr<Module>>
4133 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4134 LLVMContext &Context,
4135 DiagnosticHandlerFunction DiagnosticHandler) {
4136 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4137 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4138 M->setMaterializer(R);
4139 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4141 return std::move(M);
4145 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4146 DiagnosticHandlerFunction DiagnosticHandler) {
4147 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4148 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4149 std::move(Buf), Context, true, DiagnosticHandler);
4152 Module *M = ModuleOrErr.get();
4153 // Read in the entire module, and destroy the BitcodeReader.
4154 if (std::error_code EC = M->materializeAllPermanently()) {
4159 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4160 // written. We must defer until the Module has been fully materialized.
4166 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4167 DiagnosticHandlerFunction DiagnosticHandler) {
4168 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4169 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4171 ErrorOr<std::string> Triple = R->parseTriple();
4172 if (Triple.getError())
4174 return Triple.get();