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 &) LLVM_DELETED_FUNCTION;
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 // Create and return a placeholder, which will later be RAUW'd.
561 Metadata *MD = MDNode::getTemporary(Context, None).release();
562 MDValuePtrs[Idx].reset(MD);
566 void BitcodeReaderMDValueList::tryToResolveCycles() {
572 // Still forward references... can't resolve cycles.
575 // Resolve any cycles.
576 for (auto &MD : MDValuePtrs) {
577 auto *N = dyn_cast_or_null<MDNode>(MD);
581 assert(!N->isTemporary() && "Unexpected forward reference");
586 Type *BitcodeReader::getTypeByID(unsigned ID) {
587 // The type table size is always specified correctly.
588 if (ID >= TypeList.size())
591 if (Type *Ty = TypeList[ID])
594 // If we have a forward reference, the only possible case is when it is to a
595 // named struct. Just create a placeholder for now.
596 return TypeList[ID] = createIdentifiedStructType(Context);
599 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
601 auto *Ret = StructType::create(Context, Name);
602 IdentifiedStructTypes.push_back(Ret);
606 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
607 auto *Ret = StructType::create(Context);
608 IdentifiedStructTypes.push_back(Ret);
613 //===----------------------------------------------------------------------===//
614 // Functions for parsing blocks from the bitcode file
615 //===----------------------------------------------------------------------===//
618 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
619 /// been decoded from the given integer. This function must stay in sync with
620 /// 'encodeLLVMAttributesForBitcode'.
621 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
622 uint64_t EncodedAttrs) {
623 // FIXME: Remove in 4.0.
625 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
626 // the bits above 31 down by 11 bits.
627 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
628 assert((!Alignment || isPowerOf2_32(Alignment)) &&
629 "Alignment must be a power of two.");
632 B.addAlignmentAttr(Alignment);
633 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
634 (EncodedAttrs & 0xffff));
637 std::error_code BitcodeReader::ParseAttributeBlock() {
638 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
639 return Error("Invalid record");
641 if (!MAttributes.empty())
642 return Error("Invalid multiple blocks");
644 SmallVector<uint64_t, 64> Record;
646 SmallVector<AttributeSet, 8> Attrs;
648 // Read all the records.
650 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
652 switch (Entry.Kind) {
653 case BitstreamEntry::SubBlock: // Handled for us already.
654 case BitstreamEntry::Error:
655 return Error("Malformed block");
656 case BitstreamEntry::EndBlock:
657 return std::error_code();
658 case BitstreamEntry::Record:
659 // The interesting case.
665 switch (Stream.readRecord(Entry.ID, Record)) {
666 default: // Default behavior: ignore.
668 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
669 // FIXME: Remove in 4.0.
670 if (Record.size() & 1)
671 return Error("Invalid record");
673 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
675 decodeLLVMAttributesForBitcode(B, Record[i+1]);
676 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
679 MAttributes.push_back(AttributeSet::get(Context, Attrs));
683 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
684 for (unsigned i = 0, e = Record.size(); i != e; ++i)
685 Attrs.push_back(MAttributeGroups[Record[i]]);
687 MAttributes.push_back(AttributeSet::get(Context, Attrs));
695 // Returns Attribute::None on unrecognized codes.
696 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
699 return Attribute::None;
700 case bitc::ATTR_KIND_ALIGNMENT:
701 return Attribute::Alignment;
702 case bitc::ATTR_KIND_ALWAYS_INLINE:
703 return Attribute::AlwaysInline;
704 case bitc::ATTR_KIND_BUILTIN:
705 return Attribute::Builtin;
706 case bitc::ATTR_KIND_BY_VAL:
707 return Attribute::ByVal;
708 case bitc::ATTR_KIND_IN_ALLOCA:
709 return Attribute::InAlloca;
710 case bitc::ATTR_KIND_COLD:
711 return Attribute::Cold;
712 case bitc::ATTR_KIND_INLINE_HINT:
713 return Attribute::InlineHint;
714 case bitc::ATTR_KIND_IN_REG:
715 return Attribute::InReg;
716 case bitc::ATTR_KIND_JUMP_TABLE:
717 return Attribute::JumpTable;
718 case bitc::ATTR_KIND_MIN_SIZE:
719 return Attribute::MinSize;
720 case bitc::ATTR_KIND_NAKED:
721 return Attribute::Naked;
722 case bitc::ATTR_KIND_NEST:
723 return Attribute::Nest;
724 case bitc::ATTR_KIND_NO_ALIAS:
725 return Attribute::NoAlias;
726 case bitc::ATTR_KIND_NO_BUILTIN:
727 return Attribute::NoBuiltin;
728 case bitc::ATTR_KIND_NO_CAPTURE:
729 return Attribute::NoCapture;
730 case bitc::ATTR_KIND_NO_DUPLICATE:
731 return Attribute::NoDuplicate;
732 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
733 return Attribute::NoImplicitFloat;
734 case bitc::ATTR_KIND_NO_INLINE:
735 return Attribute::NoInline;
736 case bitc::ATTR_KIND_NON_LAZY_BIND:
737 return Attribute::NonLazyBind;
738 case bitc::ATTR_KIND_NON_NULL:
739 return Attribute::NonNull;
740 case bitc::ATTR_KIND_DEREFERENCEABLE:
741 return Attribute::Dereferenceable;
742 case bitc::ATTR_KIND_NO_RED_ZONE:
743 return Attribute::NoRedZone;
744 case bitc::ATTR_KIND_NO_RETURN:
745 return Attribute::NoReturn;
746 case bitc::ATTR_KIND_NO_UNWIND:
747 return Attribute::NoUnwind;
748 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
749 return Attribute::OptimizeForSize;
750 case bitc::ATTR_KIND_OPTIMIZE_NONE:
751 return Attribute::OptimizeNone;
752 case bitc::ATTR_KIND_READ_NONE:
753 return Attribute::ReadNone;
754 case bitc::ATTR_KIND_READ_ONLY:
755 return Attribute::ReadOnly;
756 case bitc::ATTR_KIND_RETURNED:
757 return Attribute::Returned;
758 case bitc::ATTR_KIND_RETURNS_TWICE:
759 return Attribute::ReturnsTwice;
760 case bitc::ATTR_KIND_S_EXT:
761 return Attribute::SExt;
762 case bitc::ATTR_KIND_STACK_ALIGNMENT:
763 return Attribute::StackAlignment;
764 case bitc::ATTR_KIND_STACK_PROTECT:
765 return Attribute::StackProtect;
766 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
767 return Attribute::StackProtectReq;
768 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
769 return Attribute::StackProtectStrong;
770 case bitc::ATTR_KIND_STRUCT_RET:
771 return Attribute::StructRet;
772 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
773 return Attribute::SanitizeAddress;
774 case bitc::ATTR_KIND_SANITIZE_THREAD:
775 return Attribute::SanitizeThread;
776 case bitc::ATTR_KIND_SANITIZE_MEMORY:
777 return Attribute::SanitizeMemory;
778 case bitc::ATTR_KIND_UW_TABLE:
779 return Attribute::UWTable;
780 case bitc::ATTR_KIND_Z_EXT:
781 return Attribute::ZExt;
785 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
786 Attribute::AttrKind *Kind) {
787 *Kind = GetAttrFromCode(Code);
788 if (*Kind == Attribute::None)
789 return Error(BitcodeError::CorruptedBitcode,
790 "Unknown attribute kind (" + Twine(Code) + ")");
791 return std::error_code();
794 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
795 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
796 return Error("Invalid record");
798 if (!MAttributeGroups.empty())
799 return Error("Invalid multiple blocks");
801 SmallVector<uint64_t, 64> Record;
803 // Read all the records.
805 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
807 switch (Entry.Kind) {
808 case BitstreamEntry::SubBlock: // Handled for us already.
809 case BitstreamEntry::Error:
810 return Error("Malformed block");
811 case BitstreamEntry::EndBlock:
812 return std::error_code();
813 case BitstreamEntry::Record:
814 // The interesting case.
820 switch (Stream.readRecord(Entry.ID, Record)) {
821 default: // Default behavior: ignore.
823 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
824 if (Record.size() < 3)
825 return Error("Invalid record");
827 uint64_t GrpID = Record[0];
828 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
831 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
832 if (Record[i] == 0) { // Enum attribute
833 Attribute::AttrKind Kind;
834 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
837 B.addAttribute(Kind);
838 } else if (Record[i] == 1) { // Integer attribute
839 Attribute::AttrKind Kind;
840 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
842 if (Kind == Attribute::Alignment)
843 B.addAlignmentAttr(Record[++i]);
844 else if (Kind == Attribute::StackAlignment)
845 B.addStackAlignmentAttr(Record[++i]);
846 else if (Kind == Attribute::Dereferenceable)
847 B.addDereferenceableAttr(Record[++i]);
848 } else { // String attribute
849 assert((Record[i] == 3 || Record[i] == 4) &&
850 "Invalid attribute group entry");
851 bool HasValue = (Record[i++] == 4);
852 SmallString<64> KindStr;
853 SmallString<64> ValStr;
855 while (Record[i] != 0 && i != e)
856 KindStr += Record[i++];
857 assert(Record[i] == 0 && "Kind string not null terminated");
860 // Has a value associated with it.
861 ++i; // Skip the '0' that terminates the "kind" string.
862 while (Record[i] != 0 && i != e)
863 ValStr += Record[i++];
864 assert(Record[i] == 0 && "Value string not null terminated");
867 B.addAttribute(KindStr.str(), ValStr.str());
871 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
878 std::error_code BitcodeReader::ParseTypeTable() {
879 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
880 return Error("Invalid record");
882 return ParseTypeTableBody();
885 std::error_code BitcodeReader::ParseTypeTableBody() {
886 if (!TypeList.empty())
887 return Error("Invalid multiple blocks");
889 SmallVector<uint64_t, 64> Record;
890 unsigned NumRecords = 0;
892 SmallString<64> TypeName;
894 // Read all the records for this type table.
896 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
898 switch (Entry.Kind) {
899 case BitstreamEntry::SubBlock: // Handled for us already.
900 case BitstreamEntry::Error:
901 return Error("Malformed block");
902 case BitstreamEntry::EndBlock:
903 if (NumRecords != TypeList.size())
904 return Error("Malformed block");
905 return std::error_code();
906 case BitstreamEntry::Record:
907 // The interesting case.
913 Type *ResultTy = nullptr;
914 switch (Stream.readRecord(Entry.ID, Record)) {
916 return Error("Invalid value");
917 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
918 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
919 // type list. This allows us to reserve space.
920 if (Record.size() < 1)
921 return Error("Invalid record");
922 TypeList.resize(Record[0]);
924 case bitc::TYPE_CODE_VOID: // VOID
925 ResultTy = Type::getVoidTy(Context);
927 case bitc::TYPE_CODE_HALF: // HALF
928 ResultTy = Type::getHalfTy(Context);
930 case bitc::TYPE_CODE_FLOAT: // FLOAT
931 ResultTy = Type::getFloatTy(Context);
933 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
934 ResultTy = Type::getDoubleTy(Context);
936 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
937 ResultTy = Type::getX86_FP80Ty(Context);
939 case bitc::TYPE_CODE_FP128: // FP128
940 ResultTy = Type::getFP128Ty(Context);
942 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
943 ResultTy = Type::getPPC_FP128Ty(Context);
945 case bitc::TYPE_CODE_LABEL: // LABEL
946 ResultTy = Type::getLabelTy(Context);
948 case bitc::TYPE_CODE_METADATA: // METADATA
949 ResultTy = Type::getMetadataTy(Context);
951 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
952 ResultTy = Type::getX86_MMXTy(Context);
954 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
955 if (Record.size() < 1)
956 return Error("Invalid record");
958 uint64_t NumBits = Record[0];
959 if (NumBits < IntegerType::MIN_INT_BITS ||
960 NumBits > IntegerType::MAX_INT_BITS)
961 return Error("Bitwidth for integer type out of range");
962 ResultTy = IntegerType::get(Context, NumBits);
965 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
966 // [pointee type, address space]
967 if (Record.size() < 1)
968 return Error("Invalid record");
969 unsigned AddressSpace = 0;
970 if (Record.size() == 2)
971 AddressSpace = Record[1];
972 ResultTy = getTypeByID(Record[0]);
974 return Error("Invalid type");
975 ResultTy = PointerType::get(ResultTy, AddressSpace);
978 case bitc::TYPE_CODE_FUNCTION_OLD: {
979 // FIXME: attrid is dead, remove it in LLVM 4.0
980 // FUNCTION: [vararg, attrid, retty, paramty x N]
981 if (Record.size() < 3)
982 return Error("Invalid record");
983 SmallVector<Type*, 8> ArgTys;
984 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
985 if (Type *T = getTypeByID(Record[i]))
991 ResultTy = getTypeByID(Record[2]);
992 if (!ResultTy || ArgTys.size() < Record.size()-3)
993 return Error("Invalid type");
995 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
998 case bitc::TYPE_CODE_FUNCTION: {
999 // FUNCTION: [vararg, retty, paramty x N]
1000 if (Record.size() < 2)
1001 return Error("Invalid record");
1002 SmallVector<Type*, 8> ArgTys;
1003 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1004 if (Type *T = getTypeByID(Record[i]))
1005 ArgTys.push_back(T);
1010 ResultTy = getTypeByID(Record[1]);
1011 if (!ResultTy || ArgTys.size() < Record.size()-2)
1012 return Error("Invalid type");
1014 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1017 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1018 if (Record.size() < 1)
1019 return Error("Invalid record");
1020 SmallVector<Type*, 8> EltTys;
1021 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1022 if (Type *T = getTypeByID(Record[i]))
1023 EltTys.push_back(T);
1027 if (EltTys.size() != Record.size()-1)
1028 return Error("Invalid type");
1029 ResultTy = StructType::get(Context, EltTys, Record[0]);
1032 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1033 if (ConvertToString(Record, 0, TypeName))
1034 return Error("Invalid record");
1037 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1038 if (Record.size() < 1)
1039 return Error("Invalid record");
1041 if (NumRecords >= TypeList.size())
1042 return Error("Invalid TYPE table");
1044 // Check to see if this was forward referenced, if so fill in the temp.
1045 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1047 Res->setName(TypeName);
1048 TypeList[NumRecords] = nullptr;
1049 } else // Otherwise, create a new struct.
1050 Res = createIdentifiedStructType(Context, TypeName);
1053 SmallVector<Type*, 8> EltTys;
1054 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1055 if (Type *T = getTypeByID(Record[i]))
1056 EltTys.push_back(T);
1060 if (EltTys.size() != Record.size()-1)
1061 return Error("Invalid record");
1062 Res->setBody(EltTys, Record[0]);
1066 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1067 if (Record.size() != 1)
1068 return Error("Invalid record");
1070 if (NumRecords >= TypeList.size())
1071 return Error("Invalid TYPE table");
1073 // Check to see if this was forward referenced, if so fill in the temp.
1074 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1076 Res->setName(TypeName);
1077 TypeList[NumRecords] = nullptr;
1078 } else // Otherwise, create a new struct with no body.
1079 Res = createIdentifiedStructType(Context, TypeName);
1084 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1085 if (Record.size() < 2)
1086 return Error("Invalid record");
1087 if ((ResultTy = getTypeByID(Record[1])))
1088 ResultTy = ArrayType::get(ResultTy, Record[0]);
1090 return Error("Invalid type");
1092 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1093 if (Record.size() < 2)
1094 return Error("Invalid record");
1095 if ((ResultTy = getTypeByID(Record[1])))
1096 ResultTy = VectorType::get(ResultTy, Record[0]);
1098 return Error("Invalid type");
1102 if (NumRecords >= TypeList.size())
1103 return Error("Invalid TYPE table");
1104 if (TypeList[NumRecords])
1106 "Invalid TYPE table: Only named structs can be forward referenced");
1107 assert(ResultTy && "Didn't read a type?");
1108 TypeList[NumRecords++] = ResultTy;
1112 std::error_code BitcodeReader::ParseValueSymbolTable() {
1113 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1114 return Error("Invalid record");
1116 SmallVector<uint64_t, 64> Record;
1118 Triple TT(TheModule->getTargetTriple());
1120 // Read all the records for this value table.
1121 SmallString<128> ValueName;
1123 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1125 switch (Entry.Kind) {
1126 case BitstreamEntry::SubBlock: // Handled for us already.
1127 case BitstreamEntry::Error:
1128 return Error("Malformed block");
1129 case BitstreamEntry::EndBlock:
1130 return std::error_code();
1131 case BitstreamEntry::Record:
1132 // The interesting case.
1138 switch (Stream.readRecord(Entry.ID, Record)) {
1139 default: // Default behavior: unknown type.
1141 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1142 if (ConvertToString(Record, 1, ValueName))
1143 return Error("Invalid record");
1144 unsigned ValueID = Record[0];
1145 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1146 return Error("Invalid record");
1147 Value *V = ValueList[ValueID];
1149 V->setName(StringRef(ValueName.data(), ValueName.size()));
1150 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1151 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1152 if (TT.isOSBinFormatMachO())
1153 GO->setComdat(nullptr);
1155 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1161 case bitc::VST_CODE_BBENTRY: {
1162 if (ConvertToString(Record, 1, ValueName))
1163 return Error("Invalid record");
1164 BasicBlock *BB = getBasicBlock(Record[0]);
1166 return Error("Invalid record");
1168 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1176 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1178 std::error_code BitcodeReader::ParseMetadata() {
1179 unsigned NextMDValueNo = MDValueList.size();
1181 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1182 return Error("Invalid record");
1184 SmallVector<uint64_t, 64> Record;
1187 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1188 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1190 return getMD(ID - 1);
1193 auto getMDString = [&](unsigned ID) -> MDString *{
1194 // This requires that the ID is not really a forward reference. In
1195 // particular, the MDString must already have been resolved.
1196 return cast_or_null<MDString>(getMDOrNull(ID));
1199 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1200 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1202 // Read all the records.
1204 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1206 switch (Entry.Kind) {
1207 case BitstreamEntry::SubBlock: // Handled for us already.
1208 case BitstreamEntry::Error:
1209 return Error("Malformed block");
1210 case BitstreamEntry::EndBlock:
1211 MDValueList.tryToResolveCycles();
1212 return std::error_code();
1213 case BitstreamEntry::Record:
1214 // The interesting case.
1220 unsigned Code = Stream.readRecord(Entry.ID, Record);
1221 bool IsDistinct = false;
1223 default: // Default behavior: ignore.
1225 case bitc::METADATA_NAME: {
1226 // Read name of the named metadata.
1227 SmallString<8> Name(Record.begin(), Record.end());
1229 Code = Stream.ReadCode();
1231 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1232 unsigned NextBitCode = Stream.readRecord(Code, Record);
1233 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1235 // Read named metadata elements.
1236 unsigned Size = Record.size();
1237 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1238 for (unsigned i = 0; i != Size; ++i) {
1239 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1241 return Error("Invalid record");
1242 NMD->addOperand(MD);
1246 case bitc::METADATA_OLD_FN_NODE: {
1247 // FIXME: Remove in 4.0.
1248 // This is a LocalAsMetadata record, the only type of function-local
1250 if (Record.size() % 2 == 1)
1251 return Error("Invalid record");
1253 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1254 // to be legal, but there's no upgrade path.
1255 auto dropRecord = [&] {
1256 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1258 if (Record.size() != 2) {
1263 Type *Ty = getTypeByID(Record[0]);
1264 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1269 MDValueList.AssignValue(
1270 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1274 case bitc::METADATA_OLD_NODE: {
1275 // FIXME: Remove in 4.0.
1276 if (Record.size() % 2 == 1)
1277 return Error("Invalid record");
1279 unsigned Size = Record.size();
1280 SmallVector<Metadata *, 8> Elts;
1281 for (unsigned i = 0; i != Size; i += 2) {
1282 Type *Ty = getTypeByID(Record[i]);
1284 return Error("Invalid record");
1285 if (Ty->isMetadataTy())
1286 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1287 else if (!Ty->isVoidTy()) {
1289 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1290 assert(isa<ConstantAsMetadata>(MD) &&
1291 "Expected non-function-local metadata");
1294 Elts.push_back(nullptr);
1296 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1299 case bitc::METADATA_VALUE: {
1300 if (Record.size() != 2)
1301 return Error("Invalid record");
1303 Type *Ty = getTypeByID(Record[0]);
1304 if (Ty->isMetadataTy() || Ty->isVoidTy())
1305 return Error("Invalid record");
1307 MDValueList.AssignValue(
1308 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1312 case bitc::METADATA_DISTINCT_NODE:
1315 case bitc::METADATA_NODE: {
1316 SmallVector<Metadata *, 8> Elts;
1317 Elts.reserve(Record.size());
1318 for (unsigned ID : Record)
1319 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1320 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1321 : MDNode::get(Context, Elts),
1325 case bitc::METADATA_LOCATION: {
1326 if (Record.size() != 5)
1327 return Error("Invalid record");
1329 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1330 unsigned Line = Record[1];
1331 unsigned Column = Record[2];
1332 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1333 Metadata *InlinedAt =
1334 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1335 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1339 case bitc::METADATA_GENERIC_DEBUG: {
1340 if (Record.size() < 4)
1341 return Error("Invalid record");
1343 unsigned Tag = Record[1];
1344 unsigned Version = Record[2];
1346 if (Tag >= 1u << 16 || Version != 0)
1347 return Error("Invalid record");
1349 auto *Header = getMDString(Record[3]);
1350 SmallVector<Metadata *, 8> DwarfOps;
1351 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1352 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1354 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1355 (Context, Tag, Header, DwarfOps)),
1359 case bitc::METADATA_SUBRANGE: {
1360 if (Record.size() != 3)
1361 return Error("Invalid record");
1363 MDValueList.AssignValue(
1364 GET_OR_DISTINCT(MDSubrange, Record[0],
1365 (Context, Record[1], unrotateSign(Record[2]))),
1369 case bitc::METADATA_ENUMERATOR: {
1370 if (Record.size() != 3)
1371 return Error("Invalid record");
1373 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1374 (Context, unrotateSign(Record[1]),
1375 getMDString(Record[2]))),
1379 case bitc::METADATA_BASIC_TYPE: {
1380 if (Record.size() != 6)
1381 return Error("Invalid record");
1383 MDValueList.AssignValue(
1384 GET_OR_DISTINCT(MDBasicType, Record[0],
1385 (Context, Record[1], getMDString(Record[2]),
1386 Record[3], Record[4], Record[5])),
1390 case bitc::METADATA_DERIVED_TYPE: {
1391 if (Record.size() != 12)
1392 return Error("Invalid record");
1394 MDValueList.AssignValue(
1395 GET_OR_DISTINCT(MDDerivedType, Record[0],
1396 (Context, Record[1], getMDString(Record[2]),
1397 getMDOrNull(Record[3]), Record[4],
1398 getMDOrNull(Record[5]), getMD(Record[6]), Record[7],
1399 Record[8], Record[9], Record[10],
1400 getMDOrNull(Record[11]))),
1404 case bitc::METADATA_COMPOSITE_TYPE: {
1405 if (Record.size() != 16)
1406 return Error("Invalid record");
1408 MDValueList.AssignValue(
1409 GET_OR_DISTINCT(MDCompositeType, Record[0],
1410 (Context, Record[1], getMDString(Record[2]),
1411 getMDOrNull(Record[3]), Record[4],
1412 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1413 Record[7], Record[8], Record[9], Record[10],
1414 getMDOrNull(Record[11]), Record[12],
1415 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1416 getMDString(Record[15]))),
1420 case bitc::METADATA_SUBROUTINE_TYPE: {
1421 if (Record.size() != 3)
1422 return Error("Invalid record");
1424 MDValueList.AssignValue(
1425 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1426 (Context, Record[1], getMDOrNull(Record[2]))),
1430 case bitc::METADATA_FILE: {
1431 if (Record.size() != 3)
1432 return Error("Invalid record");
1434 MDValueList.AssignValue(
1435 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1436 getMDString(Record[2]))),
1440 case bitc::METADATA_COMPILE_UNIT: {
1441 if (Record.size() != 14)
1442 return Error("Invalid record");
1444 MDValueList.AssignValue(
1446 MDCompileUnit, Record[0],
1447 (Context, Record[1], getMD(Record[2]), getMDString(Record[3]),
1448 Record[4], getMDString(Record[5]), Record[6],
1449 getMDString(Record[7]), Record[8], getMDOrNull(Record[9]),
1450 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1451 getMDOrNull(Record[12]), getMDOrNull(Record[13]))),
1455 case bitc::METADATA_SUBPROGRAM: {
1456 if (Record.size() != 19)
1457 return Error("Invalid record");
1459 MDValueList.AssignValue(
1461 MDSubprogram, Record[0],
1462 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1463 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1464 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1465 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1466 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1467 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1471 case bitc::METADATA_LEXICAL_BLOCK: {
1472 if (Record.size() != 5)
1473 return Error("Invalid record");
1475 MDValueList.AssignValue(
1476 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1477 (Context, getMDOrNull(Record[1]),
1478 getMDOrNull(Record[2]), Record[3], Record[4])),
1482 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1483 if (Record.size() != 4)
1484 return Error("Invalid record");
1486 MDValueList.AssignValue(
1487 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1488 (Context, getMDOrNull(Record[1]),
1489 getMDOrNull(Record[2]), Record[3])),
1493 case bitc::METADATA_NAMESPACE: {
1494 if (Record.size() != 5)
1495 return Error("Invalid record");
1497 MDValueList.AssignValue(
1498 GET_OR_DISTINCT(MDNamespace, Record[0],
1499 (Context, getMDOrNull(Record[1]),
1500 getMDOrNull(Record[2]), getMDString(Record[3]),
1505 case bitc::METADATA_TEMPLATE_TYPE: {
1506 if (Record.size() != 4)
1507 return Error("Invalid record");
1509 MDValueList.AssignValue(
1510 GET_OR_DISTINCT(MDTemplateTypeParameter, Record[0],
1511 (Context, getMDOrNull(Record[1]),
1512 getMDString(Record[2]), getMDOrNull(Record[3]))),
1516 case bitc::METADATA_TEMPLATE_VALUE: {
1517 if (Record.size() != 6)
1518 return Error("Invalid record");
1520 MDValueList.AssignValue(
1521 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1522 (Context, Record[1], getMDOrNull(Record[2]),
1523 getMDString(Record[3]), getMDOrNull(Record[4]),
1524 getMDOrNull(Record[5]))),
1528 case bitc::METADATA_GLOBAL_VAR: {
1529 if (Record.size() != 11)
1530 return Error("Invalid record");
1532 MDValueList.AssignValue(
1533 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1534 (Context, getMDOrNull(Record[1]),
1535 getMDString(Record[2]), getMDString(Record[3]),
1536 getMDOrNull(Record[4]), Record[5],
1537 getMDOrNull(Record[6]), Record[7], Record[8],
1538 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1542 case bitc::METADATA_LOCAL_VAR: {
1543 if (Record.size() != 10)
1544 return Error("Invalid record");
1546 MDValueList.AssignValue(
1547 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1548 (Context, Record[1], getMDOrNull(Record[2]),
1549 getMDString(Record[3]), getMDOrNull(Record[4]),
1550 Record[5], getMDOrNull(Record[6]), Record[7],
1551 Record[8], getMDOrNull(Record[9]))),
1555 case bitc::METADATA_EXPRESSION: {
1556 if (Record.size() < 1)
1557 return Error("Invalid record");
1559 MDValueList.AssignValue(
1560 GET_OR_DISTINCT(MDExpression, Record[0],
1561 (Context, makeArrayRef(Record).slice(1))),
1565 case bitc::METADATA_OBJC_PROPERTY: {
1566 if (Record.size() != 8)
1567 return Error("Invalid record");
1569 MDValueList.AssignValue(
1570 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1571 (Context, getMDString(Record[1]),
1572 getMDOrNull(Record[2]), Record[3],
1573 getMDString(Record[4]), getMDString(Record[5]),
1574 Record[6], getMDOrNull(Record[7]))),
1578 case bitc::METADATA_STRING: {
1579 std::string String(Record.begin(), Record.end());
1580 llvm::UpgradeMDStringConstant(String);
1581 Metadata *MD = MDString::get(Context, String);
1582 MDValueList.AssignValue(MD, NextMDValueNo++);
1585 case bitc::METADATA_KIND: {
1586 if (Record.size() < 2)
1587 return Error("Invalid record");
1589 unsigned Kind = Record[0];
1590 SmallString<8> Name(Record.begin()+1, Record.end());
1592 unsigned NewKind = TheModule->getMDKindID(Name.str());
1593 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1594 return Error("Conflicting METADATA_KIND records");
1599 #undef GET_OR_DISTINCT
1602 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1603 /// the LSB for dense VBR encoding.
1604 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1609 // There is no such thing as -0 with integers. "-0" really means MININT.
1613 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1614 /// values and aliases that we can.
1615 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1616 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1617 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1618 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1619 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1621 GlobalInitWorklist.swap(GlobalInits);
1622 AliasInitWorklist.swap(AliasInits);
1623 FunctionPrefixWorklist.swap(FunctionPrefixes);
1624 FunctionPrologueWorklist.swap(FunctionPrologues);
1626 while (!GlobalInitWorklist.empty()) {
1627 unsigned ValID = GlobalInitWorklist.back().second;
1628 if (ValID >= ValueList.size()) {
1629 // Not ready to resolve this yet, it requires something later in the file.
1630 GlobalInits.push_back(GlobalInitWorklist.back());
1632 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1633 GlobalInitWorklist.back().first->setInitializer(C);
1635 return Error("Expected a constant");
1637 GlobalInitWorklist.pop_back();
1640 while (!AliasInitWorklist.empty()) {
1641 unsigned ValID = AliasInitWorklist.back().second;
1642 if (ValID >= ValueList.size()) {
1643 AliasInits.push_back(AliasInitWorklist.back());
1645 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1646 AliasInitWorklist.back().first->setAliasee(C);
1648 return Error("Expected a constant");
1650 AliasInitWorklist.pop_back();
1653 while (!FunctionPrefixWorklist.empty()) {
1654 unsigned ValID = FunctionPrefixWorklist.back().second;
1655 if (ValID >= ValueList.size()) {
1656 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1658 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1659 FunctionPrefixWorklist.back().first->setPrefixData(C);
1661 return Error("Expected a constant");
1663 FunctionPrefixWorklist.pop_back();
1666 while (!FunctionPrologueWorklist.empty()) {
1667 unsigned ValID = FunctionPrologueWorklist.back().second;
1668 if (ValID >= ValueList.size()) {
1669 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1671 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1672 FunctionPrologueWorklist.back().first->setPrologueData(C);
1674 return Error("Expected a constant");
1676 FunctionPrologueWorklist.pop_back();
1679 return std::error_code();
1682 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1683 SmallVector<uint64_t, 8> Words(Vals.size());
1684 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1685 BitcodeReader::decodeSignRotatedValue);
1687 return APInt(TypeBits, Words);
1690 std::error_code BitcodeReader::ParseConstants() {
1691 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1692 return Error("Invalid record");
1694 SmallVector<uint64_t, 64> Record;
1696 // Read all the records for this value table.
1697 Type *CurTy = Type::getInt32Ty(Context);
1698 unsigned NextCstNo = ValueList.size();
1700 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1702 switch (Entry.Kind) {
1703 case BitstreamEntry::SubBlock: // Handled for us already.
1704 case BitstreamEntry::Error:
1705 return Error("Malformed block");
1706 case BitstreamEntry::EndBlock:
1707 if (NextCstNo != ValueList.size())
1708 return Error("Invalid ronstant reference");
1710 // Once all the constants have been read, go through and resolve forward
1712 ValueList.ResolveConstantForwardRefs();
1713 return std::error_code();
1714 case BitstreamEntry::Record:
1715 // The interesting case.
1722 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1724 default: // Default behavior: unknown constant
1725 case bitc::CST_CODE_UNDEF: // UNDEF
1726 V = UndefValue::get(CurTy);
1728 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1730 return Error("Invalid record");
1731 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1732 return Error("Invalid record");
1733 CurTy = TypeList[Record[0]];
1734 continue; // Skip the ValueList manipulation.
1735 case bitc::CST_CODE_NULL: // NULL
1736 V = Constant::getNullValue(CurTy);
1738 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1739 if (!CurTy->isIntegerTy() || Record.empty())
1740 return Error("Invalid record");
1741 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1743 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1744 if (!CurTy->isIntegerTy() || Record.empty())
1745 return Error("Invalid record");
1747 APInt VInt = ReadWideAPInt(Record,
1748 cast<IntegerType>(CurTy)->getBitWidth());
1749 V = ConstantInt::get(Context, VInt);
1753 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1755 return Error("Invalid record");
1756 if (CurTy->isHalfTy())
1757 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1758 APInt(16, (uint16_t)Record[0])));
1759 else if (CurTy->isFloatTy())
1760 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1761 APInt(32, (uint32_t)Record[0])));
1762 else if (CurTy->isDoubleTy())
1763 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1764 APInt(64, Record[0])));
1765 else if (CurTy->isX86_FP80Ty()) {
1766 // Bits are not stored the same way as a normal i80 APInt, compensate.
1767 uint64_t Rearrange[2];
1768 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1769 Rearrange[1] = Record[0] >> 48;
1770 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1771 APInt(80, Rearrange)));
1772 } else if (CurTy->isFP128Ty())
1773 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1774 APInt(128, Record)));
1775 else if (CurTy->isPPC_FP128Ty())
1776 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1777 APInt(128, Record)));
1779 V = UndefValue::get(CurTy);
1783 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1785 return Error("Invalid record");
1787 unsigned Size = Record.size();
1788 SmallVector<Constant*, 16> Elts;
1790 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1791 for (unsigned i = 0; i != Size; ++i)
1792 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1793 STy->getElementType(i)));
1794 V = ConstantStruct::get(STy, Elts);
1795 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1796 Type *EltTy = ATy->getElementType();
1797 for (unsigned i = 0; i != Size; ++i)
1798 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1799 V = ConstantArray::get(ATy, Elts);
1800 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1801 Type *EltTy = VTy->getElementType();
1802 for (unsigned i = 0; i != Size; ++i)
1803 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1804 V = ConstantVector::get(Elts);
1806 V = UndefValue::get(CurTy);
1810 case bitc::CST_CODE_STRING: // STRING: [values]
1811 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1813 return Error("Invalid record");
1815 SmallString<16> Elts(Record.begin(), Record.end());
1816 V = ConstantDataArray::getString(Context, Elts,
1817 BitCode == bitc::CST_CODE_CSTRING);
1820 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1822 return Error("Invalid record");
1824 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1825 unsigned Size = Record.size();
1827 if (EltTy->isIntegerTy(8)) {
1828 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1829 if (isa<VectorType>(CurTy))
1830 V = ConstantDataVector::get(Context, Elts);
1832 V = ConstantDataArray::get(Context, Elts);
1833 } else if (EltTy->isIntegerTy(16)) {
1834 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1835 if (isa<VectorType>(CurTy))
1836 V = ConstantDataVector::get(Context, Elts);
1838 V = ConstantDataArray::get(Context, Elts);
1839 } else if (EltTy->isIntegerTy(32)) {
1840 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1841 if (isa<VectorType>(CurTy))
1842 V = ConstantDataVector::get(Context, Elts);
1844 V = ConstantDataArray::get(Context, Elts);
1845 } else if (EltTy->isIntegerTy(64)) {
1846 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1847 if (isa<VectorType>(CurTy))
1848 V = ConstantDataVector::get(Context, Elts);
1850 V = ConstantDataArray::get(Context, Elts);
1851 } else if (EltTy->isFloatTy()) {
1852 SmallVector<float, 16> Elts(Size);
1853 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1854 if (isa<VectorType>(CurTy))
1855 V = ConstantDataVector::get(Context, Elts);
1857 V = ConstantDataArray::get(Context, Elts);
1858 } else if (EltTy->isDoubleTy()) {
1859 SmallVector<double, 16> Elts(Size);
1860 std::transform(Record.begin(), Record.end(), Elts.begin(),
1862 if (isa<VectorType>(CurTy))
1863 V = ConstantDataVector::get(Context, Elts);
1865 V = ConstantDataArray::get(Context, Elts);
1867 return Error("Invalid type for value");
1872 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1873 if (Record.size() < 3)
1874 return Error("Invalid record");
1875 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1877 V = UndefValue::get(CurTy); // Unknown binop.
1879 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1880 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1882 if (Record.size() >= 4) {
1883 if (Opc == Instruction::Add ||
1884 Opc == Instruction::Sub ||
1885 Opc == Instruction::Mul ||
1886 Opc == Instruction::Shl) {
1887 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1888 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1889 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1890 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1891 } else if (Opc == Instruction::SDiv ||
1892 Opc == Instruction::UDiv ||
1893 Opc == Instruction::LShr ||
1894 Opc == Instruction::AShr) {
1895 if (Record[3] & (1 << bitc::PEO_EXACT))
1896 Flags |= SDivOperator::IsExact;
1899 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1903 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1904 if (Record.size() < 3)
1905 return Error("Invalid record");
1906 int Opc = GetDecodedCastOpcode(Record[0]);
1908 V = UndefValue::get(CurTy); // Unknown cast.
1910 Type *OpTy = getTypeByID(Record[1]);
1912 return Error("Invalid record");
1913 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1914 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1915 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1919 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1920 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1921 if (Record.size() & 1)
1922 return Error("Invalid record");
1923 SmallVector<Constant*, 16> Elts;
1924 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1925 Type *ElTy = getTypeByID(Record[i]);
1927 return Error("Invalid record");
1928 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1930 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1931 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1933 bitc::CST_CODE_CE_INBOUNDS_GEP);
1936 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1937 if (Record.size() < 3)
1938 return Error("Invalid record");
1940 Type *SelectorTy = Type::getInt1Ty(Context);
1942 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1943 // vector. Otherwise, it must be a single bit.
1944 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1945 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1946 VTy->getNumElements());
1948 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1950 ValueList.getConstantFwdRef(Record[1],CurTy),
1951 ValueList.getConstantFwdRef(Record[2],CurTy));
1954 case bitc::CST_CODE_CE_EXTRACTELT
1955 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1956 if (Record.size() < 3)
1957 return Error("Invalid record");
1959 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1961 return Error("Invalid record");
1962 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1963 Constant *Op1 = nullptr;
1964 if (Record.size() == 4) {
1965 Type *IdxTy = getTypeByID(Record[2]);
1967 return Error("Invalid record");
1968 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1969 } else // TODO: Remove with llvm 4.0
1970 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1972 return Error("Invalid record");
1973 V = ConstantExpr::getExtractElement(Op0, Op1);
1976 case bitc::CST_CODE_CE_INSERTELT
1977 : { // CE_INSERTELT: [opval, opval, opty, opval]
1978 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1979 if (Record.size() < 3 || !OpTy)
1980 return Error("Invalid record");
1981 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1982 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1983 OpTy->getElementType());
1984 Constant *Op2 = nullptr;
1985 if (Record.size() == 4) {
1986 Type *IdxTy = getTypeByID(Record[2]);
1988 return Error("Invalid record");
1989 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1990 } else // TODO: Remove with llvm 4.0
1991 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1993 return Error("Invalid record");
1994 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1997 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1998 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1999 if (Record.size() < 3 || !OpTy)
2000 return Error("Invalid record");
2001 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2002 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2003 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2004 OpTy->getNumElements());
2005 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2006 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2009 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2010 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2012 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2013 if (Record.size() < 4 || !RTy || !OpTy)
2014 return Error("Invalid record");
2015 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2016 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2017 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2018 RTy->getNumElements());
2019 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2020 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2023 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2024 if (Record.size() < 4)
2025 return Error("Invalid record");
2026 Type *OpTy = getTypeByID(Record[0]);
2028 return Error("Invalid record");
2029 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2030 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2032 if (OpTy->isFPOrFPVectorTy())
2033 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2035 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2038 // This maintains backward compatibility, pre-asm dialect keywords.
2039 // FIXME: Remove with the 4.0 release.
2040 case bitc::CST_CODE_INLINEASM_OLD: {
2041 if (Record.size() < 2)
2042 return Error("Invalid record");
2043 std::string AsmStr, ConstrStr;
2044 bool HasSideEffects = Record[0] & 1;
2045 bool IsAlignStack = Record[0] >> 1;
2046 unsigned AsmStrSize = Record[1];
2047 if (2+AsmStrSize >= Record.size())
2048 return Error("Invalid record");
2049 unsigned ConstStrSize = Record[2+AsmStrSize];
2050 if (3+AsmStrSize+ConstStrSize > Record.size())
2051 return Error("Invalid record");
2053 for (unsigned i = 0; i != AsmStrSize; ++i)
2054 AsmStr += (char)Record[2+i];
2055 for (unsigned i = 0; i != ConstStrSize; ++i)
2056 ConstrStr += (char)Record[3+AsmStrSize+i];
2057 PointerType *PTy = cast<PointerType>(CurTy);
2058 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2059 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2062 // This version adds support for the asm dialect keywords (e.g.,
2064 case bitc::CST_CODE_INLINEASM: {
2065 if (Record.size() < 2)
2066 return Error("Invalid record");
2067 std::string AsmStr, ConstrStr;
2068 bool HasSideEffects = Record[0] & 1;
2069 bool IsAlignStack = (Record[0] >> 1) & 1;
2070 unsigned AsmDialect = Record[0] >> 2;
2071 unsigned AsmStrSize = Record[1];
2072 if (2+AsmStrSize >= Record.size())
2073 return Error("Invalid record");
2074 unsigned ConstStrSize = Record[2+AsmStrSize];
2075 if (3+AsmStrSize+ConstStrSize > Record.size())
2076 return Error("Invalid record");
2078 for (unsigned i = 0; i != AsmStrSize; ++i)
2079 AsmStr += (char)Record[2+i];
2080 for (unsigned i = 0; i != ConstStrSize; ++i)
2081 ConstrStr += (char)Record[3+AsmStrSize+i];
2082 PointerType *PTy = cast<PointerType>(CurTy);
2083 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2084 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2085 InlineAsm::AsmDialect(AsmDialect));
2088 case bitc::CST_CODE_BLOCKADDRESS:{
2089 if (Record.size() < 3)
2090 return Error("Invalid record");
2091 Type *FnTy = getTypeByID(Record[0]);
2093 return Error("Invalid record");
2095 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2097 return Error("Invalid record");
2099 // Don't let Fn get dematerialized.
2100 BlockAddressesTaken.insert(Fn);
2102 // If the function is already parsed we can insert the block address right
2105 unsigned BBID = Record[2];
2107 // Invalid reference to entry block.
2108 return Error("Invalid ID");
2110 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2111 for (size_t I = 0, E = BBID; I != E; ++I) {
2113 return Error("Invalid ID");
2118 // Otherwise insert a placeholder and remember it so it can be inserted
2119 // when the function is parsed.
2120 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2122 BasicBlockFwdRefQueue.push_back(Fn);
2123 if (FwdBBs.size() < BBID + 1)
2124 FwdBBs.resize(BBID + 1);
2126 FwdBBs[BBID] = BasicBlock::Create(Context);
2129 V = BlockAddress::get(Fn, BB);
2134 ValueList.AssignValue(V, NextCstNo);
2139 std::error_code BitcodeReader::ParseUseLists() {
2140 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2141 return Error("Invalid record");
2143 // Read all the records.
2144 SmallVector<uint64_t, 64> Record;
2146 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2148 switch (Entry.Kind) {
2149 case BitstreamEntry::SubBlock: // Handled for us already.
2150 case BitstreamEntry::Error:
2151 return Error("Malformed block");
2152 case BitstreamEntry::EndBlock:
2153 return std::error_code();
2154 case BitstreamEntry::Record:
2155 // The interesting case.
2159 // Read a use list record.
2162 switch (Stream.readRecord(Entry.ID, Record)) {
2163 default: // Default behavior: unknown type.
2165 case bitc::USELIST_CODE_BB:
2168 case bitc::USELIST_CODE_DEFAULT: {
2169 unsigned RecordLength = Record.size();
2170 if (RecordLength < 3)
2171 // Records should have at least an ID and two indexes.
2172 return Error("Invalid record");
2173 unsigned ID = Record.back();
2178 assert(ID < FunctionBBs.size() && "Basic block not found");
2179 V = FunctionBBs[ID];
2182 unsigned NumUses = 0;
2183 SmallDenseMap<const Use *, unsigned, 16> Order;
2184 for (const Use &U : V->uses()) {
2185 if (++NumUses > Record.size())
2187 Order[&U] = Record[NumUses - 1];
2189 if (Order.size() != Record.size() || NumUses > Record.size())
2190 // Mismatches can happen if the functions are being materialized lazily
2191 // (out-of-order), or a value has been upgraded.
2194 V->sortUseList([&](const Use &L, const Use &R) {
2195 return Order.lookup(&L) < Order.lookup(&R);
2203 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2204 /// remember where it is and then skip it. This lets us lazily deserialize the
2206 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2207 // Get the function we are talking about.
2208 if (FunctionsWithBodies.empty())
2209 return Error("Insufficient function protos");
2211 Function *Fn = FunctionsWithBodies.back();
2212 FunctionsWithBodies.pop_back();
2214 // Save the current stream state.
2215 uint64_t CurBit = Stream.GetCurrentBitNo();
2216 DeferredFunctionInfo[Fn] = CurBit;
2218 // Skip over the function block for now.
2219 if (Stream.SkipBlock())
2220 return Error("Invalid record");
2221 return std::error_code();
2224 std::error_code BitcodeReader::GlobalCleanup() {
2225 // Patch the initializers for globals and aliases up.
2226 ResolveGlobalAndAliasInits();
2227 if (!GlobalInits.empty() || !AliasInits.empty())
2228 return Error("Malformed global initializer set");
2230 // Look for intrinsic functions which need to be upgraded at some point
2231 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2234 if (UpgradeIntrinsicFunction(FI, NewFn))
2235 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2238 // Look for global variables which need to be renamed.
2239 for (Module::global_iterator
2240 GI = TheModule->global_begin(), GE = TheModule->global_end();
2242 GlobalVariable *GV = GI++;
2243 UpgradeGlobalVariable(GV);
2246 // Force deallocation of memory for these vectors to favor the client that
2247 // want lazy deserialization.
2248 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2249 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2250 return std::error_code();
2253 std::error_code BitcodeReader::ParseModule(bool Resume) {
2255 Stream.JumpToBit(NextUnreadBit);
2256 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2257 return Error("Invalid record");
2259 SmallVector<uint64_t, 64> Record;
2260 std::vector<std::string> SectionTable;
2261 std::vector<std::string> GCTable;
2263 // Read all the records for this module.
2265 BitstreamEntry Entry = Stream.advance();
2267 switch (Entry.Kind) {
2268 case BitstreamEntry::Error:
2269 return Error("Malformed block");
2270 case BitstreamEntry::EndBlock:
2271 return GlobalCleanup();
2273 case BitstreamEntry::SubBlock:
2275 default: // Skip unknown content.
2276 if (Stream.SkipBlock())
2277 return Error("Invalid record");
2279 case bitc::BLOCKINFO_BLOCK_ID:
2280 if (Stream.ReadBlockInfoBlock())
2281 return Error("Malformed block");
2283 case bitc::PARAMATTR_BLOCK_ID:
2284 if (std::error_code EC = ParseAttributeBlock())
2287 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2288 if (std::error_code EC = ParseAttributeGroupBlock())
2291 case bitc::TYPE_BLOCK_ID_NEW:
2292 if (std::error_code EC = ParseTypeTable())
2295 case bitc::VALUE_SYMTAB_BLOCK_ID:
2296 if (std::error_code EC = ParseValueSymbolTable())
2298 SeenValueSymbolTable = true;
2300 case bitc::CONSTANTS_BLOCK_ID:
2301 if (std::error_code EC = ParseConstants())
2303 if (std::error_code EC = ResolveGlobalAndAliasInits())
2306 case bitc::METADATA_BLOCK_ID:
2307 if (std::error_code EC = ParseMetadata())
2310 case bitc::FUNCTION_BLOCK_ID:
2311 // If this is the first function body we've seen, reverse the
2312 // FunctionsWithBodies list.
2313 if (!SeenFirstFunctionBody) {
2314 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2315 if (std::error_code EC = GlobalCleanup())
2317 SeenFirstFunctionBody = true;
2320 if (std::error_code EC = RememberAndSkipFunctionBody())
2322 // For streaming bitcode, suspend parsing when we reach the function
2323 // bodies. Subsequent materialization calls will resume it when
2324 // necessary. For streaming, the function bodies must be at the end of
2325 // the bitcode. If the bitcode file is old, the symbol table will be
2326 // at the end instead and will not have been seen yet. In this case,
2327 // just finish the parse now.
2328 if (LazyStreamer && SeenValueSymbolTable) {
2329 NextUnreadBit = Stream.GetCurrentBitNo();
2330 return std::error_code();
2333 case bitc::USELIST_BLOCK_ID:
2334 if (std::error_code EC = ParseUseLists())
2340 case BitstreamEntry::Record:
2341 // The interesting case.
2347 switch (Stream.readRecord(Entry.ID, Record)) {
2348 default: break; // Default behavior, ignore unknown content.
2349 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2350 if (Record.size() < 1)
2351 return Error("Invalid record");
2352 // Only version #0 and #1 are supported so far.
2353 unsigned module_version = Record[0];
2354 switch (module_version) {
2356 return Error("Invalid value");
2358 UseRelativeIDs = false;
2361 UseRelativeIDs = true;
2366 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2368 if (ConvertToString(Record, 0, S))
2369 return Error("Invalid record");
2370 TheModule->setTargetTriple(S);
2373 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2375 if (ConvertToString(Record, 0, S))
2376 return Error("Invalid record");
2377 TheModule->setDataLayout(S);
2380 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2382 if (ConvertToString(Record, 0, S))
2383 return Error("Invalid record");
2384 TheModule->setModuleInlineAsm(S);
2387 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2388 // FIXME: Remove in 4.0.
2390 if (ConvertToString(Record, 0, S))
2391 return Error("Invalid record");
2395 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2397 if (ConvertToString(Record, 0, S))
2398 return Error("Invalid record");
2399 SectionTable.push_back(S);
2402 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2404 if (ConvertToString(Record, 0, S))
2405 return Error("Invalid record");
2406 GCTable.push_back(S);
2409 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2410 if (Record.size() < 2)
2411 return Error("Invalid record");
2412 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2413 unsigned ComdatNameSize = Record[1];
2414 std::string ComdatName;
2415 ComdatName.reserve(ComdatNameSize);
2416 for (unsigned i = 0; i != ComdatNameSize; ++i)
2417 ComdatName += (char)Record[2 + i];
2418 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2419 C->setSelectionKind(SK);
2420 ComdatList.push_back(C);
2423 // GLOBALVAR: [pointer type, isconst, initid,
2424 // linkage, alignment, section, visibility, threadlocal,
2425 // unnamed_addr, externally_initialized, dllstorageclass,
2427 case bitc::MODULE_CODE_GLOBALVAR: {
2428 if (Record.size() < 6)
2429 return Error("Invalid record");
2430 Type *Ty = getTypeByID(Record[0]);
2432 return Error("Invalid record");
2433 if (!Ty->isPointerTy())
2434 return Error("Invalid type for value");
2435 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2436 Ty = cast<PointerType>(Ty)->getElementType();
2438 bool isConstant = Record[1];
2439 uint64_t RawLinkage = Record[3];
2440 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2441 unsigned Alignment = (1 << Record[4]) >> 1;
2442 std::string Section;
2444 if (Record[5]-1 >= SectionTable.size())
2445 return Error("Invalid ID");
2446 Section = SectionTable[Record[5]-1];
2448 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2449 // Local linkage must have default visibility.
2450 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2451 // FIXME: Change to an error if non-default in 4.0.
2452 Visibility = GetDecodedVisibility(Record[6]);
2454 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2455 if (Record.size() > 7)
2456 TLM = GetDecodedThreadLocalMode(Record[7]);
2458 bool UnnamedAddr = false;
2459 if (Record.size() > 8)
2460 UnnamedAddr = Record[8];
2462 bool ExternallyInitialized = false;
2463 if (Record.size() > 9)
2464 ExternallyInitialized = Record[9];
2466 GlobalVariable *NewGV =
2467 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2468 TLM, AddressSpace, ExternallyInitialized);
2469 NewGV->setAlignment(Alignment);
2470 if (!Section.empty())
2471 NewGV->setSection(Section);
2472 NewGV->setVisibility(Visibility);
2473 NewGV->setUnnamedAddr(UnnamedAddr);
2475 if (Record.size() > 10)
2476 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2478 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2480 ValueList.push_back(NewGV);
2482 // Remember which value to use for the global initializer.
2483 if (unsigned InitID = Record[2])
2484 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2486 if (Record.size() > 11) {
2487 if (unsigned ComdatID = Record[11]) {
2488 assert(ComdatID <= ComdatList.size());
2489 NewGV->setComdat(ComdatList[ComdatID - 1]);
2491 } else if (hasImplicitComdat(RawLinkage)) {
2492 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2496 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2497 // alignment, section, visibility, gc, unnamed_addr,
2498 // prologuedata, dllstorageclass, comdat, prefixdata]
2499 case bitc::MODULE_CODE_FUNCTION: {
2500 if (Record.size() < 8)
2501 return Error("Invalid record");
2502 Type *Ty = getTypeByID(Record[0]);
2504 return Error("Invalid record");
2505 if (!Ty->isPointerTy())
2506 return Error("Invalid type for value");
2508 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2510 return Error("Invalid type for value");
2512 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2515 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2516 bool isProto = Record[2];
2517 uint64_t RawLinkage = Record[3];
2518 Func->setLinkage(getDecodedLinkage(RawLinkage));
2519 Func->setAttributes(getAttributes(Record[4]));
2521 Func->setAlignment((1 << Record[5]) >> 1);
2523 if (Record[6]-1 >= SectionTable.size())
2524 return Error("Invalid ID");
2525 Func->setSection(SectionTable[Record[6]-1]);
2527 // Local linkage must have default visibility.
2528 if (!Func->hasLocalLinkage())
2529 // FIXME: Change to an error if non-default in 4.0.
2530 Func->setVisibility(GetDecodedVisibility(Record[7]));
2531 if (Record.size() > 8 && Record[8]) {
2532 if (Record[8]-1 > GCTable.size())
2533 return Error("Invalid ID");
2534 Func->setGC(GCTable[Record[8]-1].c_str());
2536 bool UnnamedAddr = false;
2537 if (Record.size() > 9)
2538 UnnamedAddr = Record[9];
2539 Func->setUnnamedAddr(UnnamedAddr);
2540 if (Record.size() > 10 && Record[10] != 0)
2541 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2543 if (Record.size() > 11)
2544 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2546 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2548 if (Record.size() > 12) {
2549 if (unsigned ComdatID = Record[12]) {
2550 assert(ComdatID <= ComdatList.size());
2551 Func->setComdat(ComdatList[ComdatID - 1]);
2553 } else if (hasImplicitComdat(RawLinkage)) {
2554 Func->setComdat(reinterpret_cast<Comdat *>(1));
2557 if (Record.size() > 13 && Record[13] != 0)
2558 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2560 ValueList.push_back(Func);
2562 // If this is a function with a body, remember the prototype we are
2563 // creating now, so that we can match up the body with them later.
2565 Func->setIsMaterializable(true);
2566 FunctionsWithBodies.push_back(Func);
2568 DeferredFunctionInfo[Func] = 0;
2572 // ALIAS: [alias type, aliasee val#, linkage]
2573 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2574 case bitc::MODULE_CODE_ALIAS: {
2575 if (Record.size() < 3)
2576 return Error("Invalid record");
2577 Type *Ty = getTypeByID(Record[0]);
2579 return Error("Invalid record");
2580 auto *PTy = dyn_cast<PointerType>(Ty);
2582 return Error("Invalid type for value");
2585 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2586 getDecodedLinkage(Record[2]), "", TheModule);
2587 // Old bitcode files didn't have visibility field.
2588 // Local linkage must have default visibility.
2589 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2590 // FIXME: Change to an error if non-default in 4.0.
2591 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2592 if (Record.size() > 4)
2593 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2595 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2596 if (Record.size() > 5)
2597 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2598 if (Record.size() > 6)
2599 NewGA->setUnnamedAddr(Record[6]);
2600 ValueList.push_back(NewGA);
2601 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2604 /// MODULE_CODE_PURGEVALS: [numvals]
2605 case bitc::MODULE_CODE_PURGEVALS:
2606 // Trim down the value list to the specified size.
2607 if (Record.size() < 1 || Record[0] > ValueList.size())
2608 return Error("Invalid record");
2609 ValueList.shrinkTo(Record[0]);
2616 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2617 TheModule = nullptr;
2619 if (std::error_code EC = InitStream())
2622 // Sniff for the signature.
2623 if (Stream.Read(8) != 'B' ||
2624 Stream.Read(8) != 'C' ||
2625 Stream.Read(4) != 0x0 ||
2626 Stream.Read(4) != 0xC ||
2627 Stream.Read(4) != 0xE ||
2628 Stream.Read(4) != 0xD)
2629 return Error("Invalid bitcode signature");
2631 // We expect a number of well-defined blocks, though we don't necessarily
2632 // need to understand them all.
2634 if (Stream.AtEndOfStream())
2635 return std::error_code();
2637 BitstreamEntry Entry =
2638 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2640 switch (Entry.Kind) {
2641 case BitstreamEntry::Error:
2642 return Error("Malformed block");
2643 case BitstreamEntry::EndBlock:
2644 return std::error_code();
2646 case BitstreamEntry::SubBlock:
2648 case bitc::BLOCKINFO_BLOCK_ID:
2649 if (Stream.ReadBlockInfoBlock())
2650 return Error("Malformed block");
2652 case bitc::MODULE_BLOCK_ID:
2653 // Reject multiple MODULE_BLOCK's in a single bitstream.
2655 return Error("Invalid multiple blocks");
2657 if (std::error_code EC = ParseModule(false))
2660 return std::error_code();
2663 if (Stream.SkipBlock())
2664 return Error("Invalid record");
2668 case BitstreamEntry::Record:
2669 // There should be no records in the top-level of blocks.
2671 // The ranlib in Xcode 4 will align archive members by appending newlines
2672 // to the end of them. If this file size is a multiple of 4 but not 8, we
2673 // have to read and ignore these final 4 bytes :-(
2674 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2675 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2676 Stream.AtEndOfStream())
2677 return std::error_code();
2679 return Error("Invalid record");
2684 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2685 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2686 return Error("Invalid record");
2688 SmallVector<uint64_t, 64> Record;
2691 // Read all the records for this module.
2693 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2695 switch (Entry.Kind) {
2696 case BitstreamEntry::SubBlock: // Handled for us already.
2697 case BitstreamEntry::Error:
2698 return Error("Malformed block");
2699 case BitstreamEntry::EndBlock:
2701 case BitstreamEntry::Record:
2702 // The interesting case.
2707 switch (Stream.readRecord(Entry.ID, Record)) {
2708 default: break; // Default behavior, ignore unknown content.
2709 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2711 if (ConvertToString(Record, 0, S))
2712 return Error("Invalid record");
2719 llvm_unreachable("Exit infinite loop");
2722 ErrorOr<std::string> BitcodeReader::parseTriple() {
2723 if (std::error_code EC = InitStream())
2726 // Sniff for the signature.
2727 if (Stream.Read(8) != 'B' ||
2728 Stream.Read(8) != 'C' ||
2729 Stream.Read(4) != 0x0 ||
2730 Stream.Read(4) != 0xC ||
2731 Stream.Read(4) != 0xE ||
2732 Stream.Read(4) != 0xD)
2733 return Error("Invalid bitcode signature");
2735 // We expect a number of well-defined blocks, though we don't necessarily
2736 // need to understand them all.
2738 BitstreamEntry Entry = Stream.advance();
2740 switch (Entry.Kind) {
2741 case BitstreamEntry::Error:
2742 return Error("Malformed block");
2743 case BitstreamEntry::EndBlock:
2744 return std::error_code();
2746 case BitstreamEntry::SubBlock:
2747 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2748 return parseModuleTriple();
2750 // Ignore other sub-blocks.
2751 if (Stream.SkipBlock())
2752 return Error("Malformed block");
2755 case BitstreamEntry::Record:
2756 Stream.skipRecord(Entry.ID);
2762 /// ParseMetadataAttachment - Parse metadata attachments.
2763 std::error_code BitcodeReader::ParseMetadataAttachment() {
2764 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2765 return Error("Invalid record");
2767 SmallVector<uint64_t, 64> Record;
2769 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2771 switch (Entry.Kind) {
2772 case BitstreamEntry::SubBlock: // Handled for us already.
2773 case BitstreamEntry::Error:
2774 return Error("Malformed block");
2775 case BitstreamEntry::EndBlock:
2776 return std::error_code();
2777 case BitstreamEntry::Record:
2778 // The interesting case.
2782 // Read a metadata attachment record.
2784 switch (Stream.readRecord(Entry.ID, Record)) {
2785 default: // Default behavior: ignore.
2787 case bitc::METADATA_ATTACHMENT: {
2788 unsigned RecordLength = Record.size();
2789 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2790 return Error("Invalid record");
2791 Instruction *Inst = InstructionList[Record[0]];
2792 for (unsigned i = 1; i != RecordLength; i = i+2) {
2793 unsigned Kind = Record[i];
2794 DenseMap<unsigned, unsigned>::iterator I =
2795 MDKindMap.find(Kind);
2796 if (I == MDKindMap.end())
2797 return Error("Invalid ID");
2798 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2799 if (isa<LocalAsMetadata>(Node))
2800 // Drop the attachment. This used to be legal, but there's no
2803 Inst->setMetadata(I->second, cast<MDNode>(Node));
2804 if (I->second == LLVMContext::MD_tbaa)
2805 InstsWithTBAATag.push_back(Inst);
2813 /// ParseFunctionBody - Lazily parse the specified function body block.
2814 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2815 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2816 return Error("Invalid record");
2818 InstructionList.clear();
2819 unsigned ModuleValueListSize = ValueList.size();
2820 unsigned ModuleMDValueListSize = MDValueList.size();
2822 // Add all the function arguments to the value table.
2823 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2824 ValueList.push_back(I);
2826 unsigned NextValueNo = ValueList.size();
2827 BasicBlock *CurBB = nullptr;
2828 unsigned CurBBNo = 0;
2831 auto getLastInstruction = [&]() -> Instruction * {
2832 if (CurBB && !CurBB->empty())
2833 return &CurBB->back();
2834 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2835 !FunctionBBs[CurBBNo - 1]->empty())
2836 return &FunctionBBs[CurBBNo - 1]->back();
2840 // Read all the records.
2841 SmallVector<uint64_t, 64> Record;
2843 BitstreamEntry Entry = Stream.advance();
2845 switch (Entry.Kind) {
2846 case BitstreamEntry::Error:
2847 return Error("Malformed block");
2848 case BitstreamEntry::EndBlock:
2849 goto OutOfRecordLoop;
2851 case BitstreamEntry::SubBlock:
2853 default: // Skip unknown content.
2854 if (Stream.SkipBlock())
2855 return Error("Invalid record");
2857 case bitc::CONSTANTS_BLOCK_ID:
2858 if (std::error_code EC = ParseConstants())
2860 NextValueNo = ValueList.size();
2862 case bitc::VALUE_SYMTAB_BLOCK_ID:
2863 if (std::error_code EC = ParseValueSymbolTable())
2866 case bitc::METADATA_ATTACHMENT_ID:
2867 if (std::error_code EC = ParseMetadataAttachment())
2870 case bitc::METADATA_BLOCK_ID:
2871 if (std::error_code EC = ParseMetadata())
2874 case bitc::USELIST_BLOCK_ID:
2875 if (std::error_code EC = ParseUseLists())
2881 case BitstreamEntry::Record:
2882 // The interesting case.
2888 Instruction *I = nullptr;
2889 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2891 default: // Default behavior: reject
2892 return Error("Invalid value");
2893 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2894 if (Record.size() < 1 || Record[0] == 0)
2895 return Error("Invalid record");
2896 // Create all the basic blocks for the function.
2897 FunctionBBs.resize(Record[0]);
2899 // See if anything took the address of blocks in this function.
2900 auto BBFRI = BasicBlockFwdRefs.find(F);
2901 if (BBFRI == BasicBlockFwdRefs.end()) {
2902 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2903 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2905 auto &BBRefs = BBFRI->second;
2906 // Check for invalid basic block references.
2907 if (BBRefs.size() > FunctionBBs.size())
2908 return Error("Invalid ID");
2909 assert(!BBRefs.empty() && "Unexpected empty array");
2910 assert(!BBRefs.front() && "Invalid reference to entry block");
2911 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2913 if (I < RE && BBRefs[I]) {
2914 BBRefs[I]->insertInto(F);
2915 FunctionBBs[I] = BBRefs[I];
2917 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2920 // Erase from the table.
2921 BasicBlockFwdRefs.erase(BBFRI);
2924 CurBB = FunctionBBs[0];
2928 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2929 // This record indicates that the last instruction is at the same
2930 // location as the previous instruction with a location.
2931 I = getLastInstruction();
2934 return Error("Invalid record");
2935 I->setDebugLoc(LastLoc);
2939 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2940 I = getLastInstruction();
2941 if (!I || Record.size() < 4)
2942 return Error("Invalid record");
2944 unsigned Line = Record[0], Col = Record[1];
2945 unsigned ScopeID = Record[2], IAID = Record[3];
2947 MDNode *Scope = nullptr, *IA = nullptr;
2948 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2949 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2950 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2951 I->setDebugLoc(LastLoc);
2956 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2959 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2960 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2961 OpNum+1 > Record.size())
2962 return Error("Invalid record");
2964 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2966 return Error("Invalid record");
2967 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2968 InstructionList.push_back(I);
2969 if (OpNum < Record.size()) {
2970 if (Opc == Instruction::Add ||
2971 Opc == Instruction::Sub ||
2972 Opc == Instruction::Mul ||
2973 Opc == Instruction::Shl) {
2974 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2975 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2976 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2977 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2978 } else if (Opc == Instruction::SDiv ||
2979 Opc == Instruction::UDiv ||
2980 Opc == Instruction::LShr ||
2981 Opc == Instruction::AShr) {
2982 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2983 cast<BinaryOperator>(I)->setIsExact(true);
2984 } else if (isa<FPMathOperator>(I)) {
2986 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2987 FMF.setUnsafeAlgebra();
2988 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2990 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2992 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2993 FMF.setNoSignedZeros();
2994 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2995 FMF.setAllowReciprocal();
2997 I->setFastMathFlags(FMF);
3003 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3006 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3007 OpNum+2 != Record.size())
3008 return Error("Invalid record");
3010 Type *ResTy = getTypeByID(Record[OpNum]);
3011 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3012 if (Opc == -1 || !ResTy)
3013 return Error("Invalid record");
3014 Instruction *Temp = nullptr;
3015 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3017 InstructionList.push_back(Temp);
3018 CurBB->getInstList().push_back(Temp);
3021 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3023 InstructionList.push_back(I);
3026 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
3027 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
3030 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3031 return Error("Invalid record");
3033 SmallVector<Value*, 16> GEPIdx;
3034 while (OpNum != Record.size()) {
3036 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3037 return Error("Invalid record");
3038 GEPIdx.push_back(Op);
3041 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
3042 InstructionList.push_back(I);
3043 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
3044 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3048 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3049 // EXTRACTVAL: [opty, opval, n x indices]
3052 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3053 return Error("Invalid record");
3055 SmallVector<unsigned, 4> EXTRACTVALIdx;
3056 for (unsigned RecSize = Record.size();
3057 OpNum != RecSize; ++OpNum) {
3058 uint64_t Index = Record[OpNum];
3059 if ((unsigned)Index != Index)
3060 return Error("Invalid value");
3061 EXTRACTVALIdx.push_back((unsigned)Index);
3064 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3065 InstructionList.push_back(I);
3069 case bitc::FUNC_CODE_INST_INSERTVAL: {
3070 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3073 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3074 return Error("Invalid record");
3076 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3077 return Error("Invalid record");
3079 SmallVector<unsigned, 4> INSERTVALIdx;
3080 for (unsigned RecSize = Record.size();
3081 OpNum != RecSize; ++OpNum) {
3082 uint64_t Index = Record[OpNum];
3083 if ((unsigned)Index != Index)
3084 return Error("Invalid value");
3085 INSERTVALIdx.push_back((unsigned)Index);
3088 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3089 InstructionList.push_back(I);
3093 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3094 // obsolete form of select
3095 // handles select i1 ... in old bitcode
3097 Value *TrueVal, *FalseVal, *Cond;
3098 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3099 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3100 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3101 return Error("Invalid record");
3103 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3104 InstructionList.push_back(I);
3108 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3109 // new form of select
3110 // handles select i1 or select [N x i1]
3112 Value *TrueVal, *FalseVal, *Cond;
3113 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3114 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3115 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3116 return Error("Invalid record");
3118 // select condition can be either i1 or [N x i1]
3119 if (VectorType* vector_type =
3120 dyn_cast<VectorType>(Cond->getType())) {
3122 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3123 return Error("Invalid type for value");
3126 if (Cond->getType() != Type::getInt1Ty(Context))
3127 return Error("Invalid type for value");
3130 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3131 InstructionList.push_back(I);
3135 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3138 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3139 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3140 return Error("Invalid record");
3141 I = ExtractElementInst::Create(Vec, Idx);
3142 InstructionList.push_back(I);
3146 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3148 Value *Vec, *Elt, *Idx;
3149 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3150 popValue(Record, OpNum, NextValueNo,
3151 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3152 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3153 return Error("Invalid record");
3154 I = InsertElementInst::Create(Vec, Elt, Idx);
3155 InstructionList.push_back(I);
3159 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3161 Value *Vec1, *Vec2, *Mask;
3162 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3163 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3164 return Error("Invalid record");
3166 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3167 return Error("Invalid record");
3168 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3169 InstructionList.push_back(I);
3173 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3174 // Old form of ICmp/FCmp returning bool
3175 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3176 // both legal on vectors but had different behaviour.
3177 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3178 // FCmp/ICmp returning bool or vector of bool
3182 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3183 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3184 OpNum+1 != Record.size())
3185 return Error("Invalid record");
3187 if (LHS->getType()->isFPOrFPVectorTy())
3188 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3190 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3191 InstructionList.push_back(I);
3195 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3197 unsigned Size = Record.size();
3199 I = ReturnInst::Create(Context);
3200 InstructionList.push_back(I);
3205 Value *Op = nullptr;
3206 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3207 return Error("Invalid record");
3208 if (OpNum != Record.size())
3209 return Error("Invalid record");
3211 I = ReturnInst::Create(Context, Op);
3212 InstructionList.push_back(I);
3215 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3216 if (Record.size() != 1 && Record.size() != 3)
3217 return Error("Invalid record");
3218 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3220 return Error("Invalid record");
3222 if (Record.size() == 1) {
3223 I = BranchInst::Create(TrueDest);
3224 InstructionList.push_back(I);
3227 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3228 Value *Cond = getValue(Record, 2, NextValueNo,
3229 Type::getInt1Ty(Context));
3230 if (!FalseDest || !Cond)
3231 return Error("Invalid record");
3232 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3233 InstructionList.push_back(I);
3237 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3239 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3240 // "New" SwitchInst format with case ranges. The changes to write this
3241 // format were reverted but we still recognize bitcode that uses it.
3242 // Hopefully someday we will have support for case ranges and can use
3243 // this format again.
3245 Type *OpTy = getTypeByID(Record[1]);
3246 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3248 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3249 BasicBlock *Default = getBasicBlock(Record[3]);
3250 if (!OpTy || !Cond || !Default)
3251 return Error("Invalid record");
3253 unsigned NumCases = Record[4];
3255 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3256 InstructionList.push_back(SI);
3258 unsigned CurIdx = 5;
3259 for (unsigned i = 0; i != NumCases; ++i) {
3260 SmallVector<ConstantInt*, 1> CaseVals;
3261 unsigned NumItems = Record[CurIdx++];
3262 for (unsigned ci = 0; ci != NumItems; ++ci) {
3263 bool isSingleNumber = Record[CurIdx++];
3266 unsigned ActiveWords = 1;
3267 if (ValueBitWidth > 64)
3268 ActiveWords = Record[CurIdx++];
3269 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3271 CurIdx += ActiveWords;
3273 if (!isSingleNumber) {
3275 if (ValueBitWidth > 64)
3276 ActiveWords = Record[CurIdx++];
3278 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3280 CurIdx += ActiveWords;
3282 // FIXME: It is not clear whether values in the range should be
3283 // compared as signed or unsigned values. The partially
3284 // implemented changes that used this format in the past used
3285 // unsigned comparisons.
3286 for ( ; Low.ule(High); ++Low)
3287 CaseVals.push_back(ConstantInt::get(Context, Low));
3289 CaseVals.push_back(ConstantInt::get(Context, Low));
3291 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3292 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3293 cve = CaseVals.end(); cvi != cve; ++cvi)
3294 SI->addCase(*cvi, DestBB);
3300 // Old SwitchInst format without case ranges.
3302 if (Record.size() < 3 || (Record.size() & 1) == 0)
3303 return Error("Invalid record");
3304 Type *OpTy = getTypeByID(Record[0]);
3305 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3306 BasicBlock *Default = getBasicBlock(Record[2]);
3307 if (!OpTy || !Cond || !Default)
3308 return Error("Invalid record");
3309 unsigned NumCases = (Record.size()-3)/2;
3310 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3311 InstructionList.push_back(SI);
3312 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3313 ConstantInt *CaseVal =
3314 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3315 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3316 if (!CaseVal || !DestBB) {
3318 return Error("Invalid record");
3320 SI->addCase(CaseVal, DestBB);
3325 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3326 if (Record.size() < 2)
3327 return Error("Invalid record");
3328 Type *OpTy = getTypeByID(Record[0]);
3329 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3330 if (!OpTy || !Address)
3331 return Error("Invalid record");
3332 unsigned NumDests = Record.size()-2;
3333 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3334 InstructionList.push_back(IBI);
3335 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3336 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3337 IBI->addDestination(DestBB);
3340 return Error("Invalid record");
3347 case bitc::FUNC_CODE_INST_INVOKE: {
3348 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3349 if (Record.size() < 4)
3350 return Error("Invalid record");
3351 AttributeSet PAL = getAttributes(Record[0]);
3352 unsigned CCInfo = Record[1];
3353 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3354 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3358 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3359 return Error("Invalid record");
3361 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3362 FunctionType *FTy = !CalleeTy ? nullptr :
3363 dyn_cast<FunctionType>(CalleeTy->getElementType());
3365 // Check that the right number of fixed parameters are here.
3366 if (!FTy || !NormalBB || !UnwindBB ||
3367 Record.size() < OpNum+FTy->getNumParams())
3368 return Error("Invalid record");
3370 SmallVector<Value*, 16> Ops;
3371 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3372 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3373 FTy->getParamType(i)));
3375 return Error("Invalid record");
3378 if (!FTy->isVarArg()) {
3379 if (Record.size() != OpNum)
3380 return Error("Invalid record");
3382 // Read type/value pairs for varargs params.
3383 while (OpNum != Record.size()) {
3385 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3386 return Error("Invalid record");
3391 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3392 InstructionList.push_back(I);
3393 cast<InvokeInst>(I)->setCallingConv(
3394 static_cast<CallingConv::ID>(CCInfo));
3395 cast<InvokeInst>(I)->setAttributes(PAL);
3398 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3400 Value *Val = nullptr;
3401 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3402 return Error("Invalid record");
3403 I = ResumeInst::Create(Val);
3404 InstructionList.push_back(I);
3407 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3408 I = new UnreachableInst(Context);
3409 InstructionList.push_back(I);
3411 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3412 if (Record.size() < 1 || ((Record.size()-1)&1))
3413 return Error("Invalid record");
3414 Type *Ty = getTypeByID(Record[0]);
3416 return Error("Invalid record");
3418 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3419 InstructionList.push_back(PN);
3421 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3423 // With the new function encoding, it is possible that operands have
3424 // negative IDs (for forward references). Use a signed VBR
3425 // representation to keep the encoding small.
3427 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3429 V = getValue(Record, 1+i, NextValueNo, Ty);
3430 BasicBlock *BB = getBasicBlock(Record[2+i]);
3432 return Error("Invalid record");
3433 PN->addIncoming(V, BB);
3439 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3440 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3442 if (Record.size() < 4)
3443 return Error("Invalid record");
3444 Type *Ty = getTypeByID(Record[Idx++]);
3446 return Error("Invalid record");
3447 Value *PersFn = nullptr;
3448 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3449 return Error("Invalid record");
3451 bool IsCleanup = !!Record[Idx++];
3452 unsigned NumClauses = Record[Idx++];
3453 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3454 LP->setCleanup(IsCleanup);
3455 for (unsigned J = 0; J != NumClauses; ++J) {
3456 LandingPadInst::ClauseType CT =
3457 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3460 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3462 return Error("Invalid record");
3465 assert((CT != LandingPadInst::Catch ||
3466 !isa<ArrayType>(Val->getType())) &&
3467 "Catch clause has a invalid type!");
3468 assert((CT != LandingPadInst::Filter ||
3469 isa<ArrayType>(Val->getType())) &&
3470 "Filter clause has invalid type!");
3471 LP->addClause(cast<Constant>(Val));
3475 InstructionList.push_back(I);
3479 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3480 if (Record.size() != 4)
3481 return Error("Invalid record");
3483 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3484 Type *OpTy = getTypeByID(Record[1]);
3485 Value *Size = getFnValueByID(Record[2], OpTy);
3486 unsigned AlignRecord = Record[3];
3487 bool InAlloca = AlignRecord & (1 << 5);
3488 unsigned Align = AlignRecord & ((1 << 5) - 1);
3490 return Error("Invalid record");
3491 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3492 AI->setUsedWithInAlloca(InAlloca);
3494 InstructionList.push_back(I);
3497 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3500 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3501 OpNum+2 != Record.size())
3502 return Error("Invalid record");
3504 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3505 InstructionList.push_back(I);
3508 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3509 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3512 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3513 OpNum+4 != Record.size())
3514 return Error("Invalid record");
3516 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3517 if (Ordering == NotAtomic || Ordering == Release ||
3518 Ordering == AcquireRelease)
3519 return Error("Invalid record");
3520 if (Ordering != NotAtomic && Record[OpNum] == 0)
3521 return Error("Invalid record");
3522 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3524 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3525 Ordering, SynchScope);
3526 InstructionList.push_back(I);
3529 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3532 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3533 popValue(Record, OpNum, NextValueNo,
3534 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3535 OpNum+2 != Record.size())
3536 return Error("Invalid record");
3538 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3539 InstructionList.push_back(I);
3542 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3543 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3546 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3547 popValue(Record, OpNum, NextValueNo,
3548 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3549 OpNum+4 != Record.size())
3550 return Error("Invalid record");
3552 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3553 if (Ordering == NotAtomic || Ordering == Acquire ||
3554 Ordering == AcquireRelease)
3555 return Error("Invalid record");
3556 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3557 if (Ordering != NotAtomic && Record[OpNum] == 0)
3558 return Error("Invalid record");
3560 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3561 Ordering, SynchScope);
3562 InstructionList.push_back(I);
3565 case bitc::FUNC_CODE_INST_CMPXCHG: {
3566 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3567 // failureordering?, isweak?]
3569 Value *Ptr, *Cmp, *New;
3570 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3571 popValue(Record, OpNum, NextValueNo,
3572 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3573 popValue(Record, OpNum, NextValueNo,
3574 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3575 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3576 return Error("Invalid record");
3577 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3578 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3579 return Error("Invalid record");
3580 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3582 AtomicOrdering FailureOrdering;
3583 if (Record.size() < 7)
3585 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3587 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3589 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3591 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3593 if (Record.size() < 8) {
3594 // Before weak cmpxchgs existed, the instruction simply returned the
3595 // value loaded from memory, so bitcode files from that era will be
3596 // expecting the first component of a modern cmpxchg.
3597 CurBB->getInstList().push_back(I);
3598 I = ExtractValueInst::Create(I, 0);
3600 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3603 InstructionList.push_back(I);
3606 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3607 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3610 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3611 popValue(Record, OpNum, NextValueNo,
3612 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3613 OpNum+4 != Record.size())
3614 return Error("Invalid record");
3615 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3616 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3617 Operation > AtomicRMWInst::LAST_BINOP)
3618 return Error("Invalid record");
3619 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3620 if (Ordering == NotAtomic || Ordering == Unordered)
3621 return Error("Invalid record");
3622 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3623 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3624 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3625 InstructionList.push_back(I);
3628 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3629 if (2 != Record.size())
3630 return Error("Invalid record");
3631 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3632 if (Ordering == NotAtomic || Ordering == Unordered ||
3633 Ordering == Monotonic)
3634 return Error("Invalid record");
3635 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3636 I = new FenceInst(Context, Ordering, SynchScope);
3637 InstructionList.push_back(I);
3640 case bitc::FUNC_CODE_INST_CALL: {
3641 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3642 if (Record.size() < 3)
3643 return Error("Invalid record");
3645 AttributeSet PAL = getAttributes(Record[0]);
3646 unsigned CCInfo = Record[1];
3650 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3651 return Error("Invalid record");
3653 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3654 FunctionType *FTy = nullptr;
3655 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3656 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3657 return Error("Invalid record");
3659 SmallVector<Value*, 16> Args;
3660 // Read the fixed params.
3661 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3662 if (FTy->getParamType(i)->isLabelTy())
3663 Args.push_back(getBasicBlock(Record[OpNum]));
3665 Args.push_back(getValue(Record, OpNum, NextValueNo,
3666 FTy->getParamType(i)));
3668 return Error("Invalid record");
3671 // Read type/value pairs for varargs params.
3672 if (!FTy->isVarArg()) {
3673 if (OpNum != Record.size())
3674 return Error("Invalid record");
3676 while (OpNum != Record.size()) {
3678 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3679 return Error("Invalid record");
3684 I = CallInst::Create(Callee, Args);
3685 InstructionList.push_back(I);
3686 cast<CallInst>(I)->setCallingConv(
3687 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3688 CallInst::TailCallKind TCK = CallInst::TCK_None;
3690 TCK = CallInst::TCK_Tail;
3691 if (CCInfo & (1 << 14))
3692 TCK = CallInst::TCK_MustTail;
3693 cast<CallInst>(I)->setTailCallKind(TCK);
3694 cast<CallInst>(I)->setAttributes(PAL);
3697 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3698 if (Record.size() < 3)
3699 return Error("Invalid record");
3700 Type *OpTy = getTypeByID(Record[0]);
3701 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3702 Type *ResTy = getTypeByID(Record[2]);
3703 if (!OpTy || !Op || !ResTy)
3704 return Error("Invalid record");
3705 I = new VAArgInst(Op, ResTy);
3706 InstructionList.push_back(I);
3711 // Add instruction to end of current BB. If there is no current BB, reject
3715 return Error("Invalid instruction with no BB");
3717 CurBB->getInstList().push_back(I);
3719 // If this was a terminator instruction, move to the next block.
3720 if (isa<TerminatorInst>(I)) {
3722 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3725 // Non-void values get registered in the value table for future use.
3726 if (I && !I->getType()->isVoidTy())
3727 ValueList.AssignValue(I, NextValueNo++);
3732 // Check the function list for unresolved values.
3733 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3734 if (!A->getParent()) {
3735 // We found at least one unresolved value. Nuke them all to avoid leaks.
3736 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3737 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3738 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3742 return Error("Never resolved value found in function");
3746 // FIXME: Check for unresolved forward-declared metadata references
3747 // and clean up leaks.
3749 // Trim the value list down to the size it was before we parsed this function.
3750 ValueList.shrinkTo(ModuleValueListSize);
3751 MDValueList.shrinkTo(ModuleMDValueListSize);
3752 std::vector<BasicBlock*>().swap(FunctionBBs);
3753 return std::error_code();
3756 /// Find the function body in the bitcode stream
3757 std::error_code BitcodeReader::FindFunctionInStream(
3759 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3760 while (DeferredFunctionInfoIterator->second == 0) {
3761 if (Stream.AtEndOfStream())
3762 return Error("Could not find function in stream");
3763 // ParseModule will parse the next body in the stream and set its
3764 // position in the DeferredFunctionInfo map.
3765 if (std::error_code EC = ParseModule(true))
3768 return std::error_code();
3771 //===----------------------------------------------------------------------===//
3772 // GVMaterializer implementation
3773 //===----------------------------------------------------------------------===//
3775 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3777 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3778 Function *F = dyn_cast<Function>(GV);
3779 // If it's not a function or is already material, ignore the request.
3780 if (!F || !F->isMaterializable())
3781 return std::error_code();
3783 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3784 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3785 // If its position is recorded as 0, its body is somewhere in the stream
3786 // but we haven't seen it yet.
3787 if (DFII->second == 0 && LazyStreamer)
3788 if (std::error_code EC = FindFunctionInStream(F, DFII))
3791 // Move the bit stream to the saved position of the deferred function body.
3792 Stream.JumpToBit(DFII->second);
3794 if (std::error_code EC = ParseFunctionBody(F))
3796 F->setIsMaterializable(false);
3798 // Upgrade any old intrinsic calls in the function.
3799 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3800 E = UpgradedIntrinsics.end(); I != E; ++I) {
3801 if (I->first != I->second) {
3802 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3804 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3805 UpgradeIntrinsicCall(CI, I->second);
3810 // Bring in any functions that this function forward-referenced via
3812 return materializeForwardReferencedFunctions();
3815 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3816 const Function *F = dyn_cast<Function>(GV);
3817 if (!F || F->isDeclaration())
3820 // Dematerializing F would leave dangling references that wouldn't be
3821 // reconnected on re-materialization.
3822 if (BlockAddressesTaken.count(F))
3825 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3828 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3829 Function *F = dyn_cast<Function>(GV);
3830 // If this function isn't dematerializable, this is a noop.
3831 if (!F || !isDematerializable(F))
3834 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3836 // Just forget the function body, we can remat it later.
3837 F->dropAllReferences();
3838 F->setIsMaterializable(true);
3841 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3842 assert(M == TheModule &&
3843 "Can only Materialize the Module this BitcodeReader is attached to.");
3845 // Promise to materialize all forward references.
3846 WillMaterializeAllForwardRefs = true;
3848 // Iterate over the module, deserializing any functions that are still on
3850 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3852 if (std::error_code EC = materialize(F))
3855 // At this point, if there are any function bodies, the current bit is
3856 // pointing to the END_BLOCK record after them. Now make sure the rest
3857 // of the bits in the module have been read.
3861 // Check that all block address forward references got resolved (as we
3863 if (!BasicBlockFwdRefs.empty())
3864 return Error("Never resolved function from blockaddress");
3866 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3867 // delete the old functions to clean up. We can't do this unless the entire
3868 // module is materialized because there could always be another function body
3869 // with calls to the old function.
3870 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3871 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3872 if (I->first != I->second) {
3873 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3875 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3876 UpgradeIntrinsicCall(CI, I->second);
3878 if (!I->first->use_empty())
3879 I->first->replaceAllUsesWith(I->second);
3880 I->first->eraseFromParent();
3883 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3885 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3886 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3888 UpgradeDebugInfo(*M);
3889 return std::error_code();
3892 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3893 return IdentifiedStructTypes;
3896 std::error_code BitcodeReader::InitStream() {
3898 return InitLazyStream();
3899 return InitStreamFromBuffer();
3902 std::error_code BitcodeReader::InitStreamFromBuffer() {
3903 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3904 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3906 if (Buffer->getBufferSize() & 3)
3907 return Error("Invalid bitcode signature");
3909 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3910 // The magic number is 0x0B17C0DE stored in little endian.
3911 if (isBitcodeWrapper(BufPtr, BufEnd))
3912 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3913 return Error("Invalid bitcode wrapper header");
3915 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3916 Stream.init(&*StreamFile);
3918 return std::error_code();
3921 std::error_code BitcodeReader::InitLazyStream() {
3922 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3924 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3925 StreamingMemoryObject &Bytes = *OwnedBytes;
3926 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3927 Stream.init(&*StreamFile);
3929 unsigned char buf[16];
3930 if (Bytes.readBytes(buf, 16, 0) != 16)
3931 return Error("Invalid bitcode signature");
3933 if (!isBitcode(buf, buf + 16))
3934 return Error("Invalid bitcode signature");
3936 if (isBitcodeWrapper(buf, buf + 4)) {
3937 const unsigned char *bitcodeStart = buf;
3938 const unsigned char *bitcodeEnd = buf + 16;
3939 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3940 Bytes.dropLeadingBytes(bitcodeStart - buf);
3941 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3943 return std::error_code();
3947 class BitcodeErrorCategoryType : public std::error_category {
3948 const char *name() const LLVM_NOEXCEPT override {
3949 return "llvm.bitcode";
3951 std::string message(int IE) const override {
3952 BitcodeError E = static_cast<BitcodeError>(IE);
3954 case BitcodeError::InvalidBitcodeSignature:
3955 return "Invalid bitcode signature";
3956 case BitcodeError::CorruptedBitcode:
3957 return "Corrupted bitcode";
3959 llvm_unreachable("Unknown error type!");
3964 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3966 const std::error_category &llvm::BitcodeErrorCategory() {
3967 return *ErrorCategory;
3970 //===----------------------------------------------------------------------===//
3971 // External interface
3972 //===----------------------------------------------------------------------===//
3974 /// \brief Get a lazy one-at-time loading module from bitcode.
3976 /// This isn't always used in a lazy context. In particular, it's also used by
3977 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
3978 /// in forward-referenced functions from block address references.
3980 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3981 /// materialize everything -- in particular, if this isn't truly lazy.
3982 static ErrorOr<Module *>
3983 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3984 LLVMContext &Context, bool WillMaterializeAll,
3985 DiagnosticHandlerFunction DiagnosticHandler) {
3986 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3988 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3989 M->setMaterializer(R);
3991 auto cleanupOnError = [&](std::error_code EC) {
3992 R->releaseBuffer(); // Never take ownership on error.
3993 delete M; // Also deletes R.
3997 if (std::error_code EC = R->ParseBitcodeInto(M))
3998 return cleanupOnError(EC);
4000 if (!WillMaterializeAll)
4001 // Resolve forward references from blockaddresses.
4002 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4003 return cleanupOnError(EC);
4005 Buffer.release(); // The BitcodeReader owns it now.
4010 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4011 LLVMContext &Context,
4012 DiagnosticHandlerFunction DiagnosticHandler) {
4013 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4017 ErrorOr<std::unique_ptr<Module>>
4018 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4019 LLVMContext &Context,
4020 DiagnosticHandlerFunction DiagnosticHandler) {
4021 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4022 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4023 M->setMaterializer(R);
4024 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4026 return std::move(M);
4030 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4031 DiagnosticHandlerFunction DiagnosticHandler) {
4032 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4033 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4034 std::move(Buf), Context, true, DiagnosticHandler);
4037 Module *M = ModuleOrErr.get();
4038 // Read in the entire module, and destroy the BitcodeReader.
4039 if (std::error_code EC = M->materializeAllPermanently()) {
4044 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4045 // written. We must defer until the Module has been fully materialized.
4051 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4052 DiagnosticHandlerFunction DiagnosticHandler) {
4053 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4054 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4056 ErrorOr<std::string> Triple = R->parseTriple();
4057 if (Triple.getError())
4059 return Triple.get();