1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DebugInfoMetadata.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/OperandTraits.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Support/DataStream.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
36 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
39 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
40 DiagnosticSeverity Severity,
42 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
44 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
46 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
47 std::error_code EC, const Twine &Message) {
48 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
49 DiagnosticHandler(DI);
53 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
55 return Error(DiagnosticHandler, EC, EC.message());
58 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
59 return ::Error(DiagnosticHandler, make_error_code(E), Message);
62 std::error_code BitcodeReader::Error(const Twine &Message) {
63 return ::Error(DiagnosticHandler,
64 make_error_code(BitcodeError::CorruptedBitcode), Message);
67 std::error_code BitcodeReader::Error(BitcodeError E) {
68 return ::Error(DiagnosticHandler, make_error_code(E));
71 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
75 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
78 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
79 DiagnosticHandlerFunction DiagnosticHandler)
80 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
81 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
82 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
83 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
84 WillMaterializeAllForwardRefs(false) {}
86 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
87 DiagnosticHandlerFunction DiagnosticHandler)
88 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
89 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
90 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
91 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
92 WillMaterializeAllForwardRefs(false) {}
94 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
95 if (WillMaterializeAllForwardRefs)
96 return std::error_code();
99 WillMaterializeAllForwardRefs = true;
101 while (!BasicBlockFwdRefQueue.empty()) {
102 Function *F = BasicBlockFwdRefQueue.front();
103 BasicBlockFwdRefQueue.pop_front();
104 assert(F && "Expected valid function");
105 if (!BasicBlockFwdRefs.count(F))
106 // Already materialized.
109 // Check for a function that isn't materializable to prevent an infinite
110 // loop. When parsing a blockaddress stored in a global variable, there
111 // isn't a trivial way to check if a function will have a body without a
112 // linear search through FunctionsWithBodies, so just check it here.
113 if (!F->isMaterializable())
114 return Error("Never resolved function from blockaddress");
116 // Try to materialize F.
117 if (std::error_code EC = materialize(F))
120 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
123 WillMaterializeAllForwardRefs = false;
124 return std::error_code();
127 void BitcodeReader::FreeState() {
129 std::vector<Type*>().swap(TypeList);
132 std::vector<Comdat *>().swap(ComdatList);
134 std::vector<AttributeSet>().swap(MAttributes);
135 std::vector<BasicBlock*>().swap(FunctionBBs);
136 std::vector<Function*>().swap(FunctionsWithBodies);
137 DeferredFunctionInfo.clear();
140 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
141 BasicBlockFwdRefQueue.clear();
144 //===----------------------------------------------------------------------===//
145 // Helper functions to implement forward reference resolution, etc.
146 //===----------------------------------------------------------------------===//
148 /// ConvertToString - Convert a string from a record into an std::string, return
150 template<typename StrTy>
151 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
153 if (Idx > Record.size())
156 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
157 Result += (char)Record[i];
161 static bool hasImplicitComdat(size_t Val) {
165 case 1: // Old WeakAnyLinkage
166 case 4: // Old LinkOnceAnyLinkage
167 case 10: // Old WeakODRLinkage
168 case 11: // Old LinkOnceODRLinkage
173 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
175 default: // Map unknown/new linkages to external
177 return GlobalValue::ExternalLinkage;
179 return GlobalValue::AppendingLinkage;
181 return GlobalValue::InternalLinkage;
183 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
185 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
187 return GlobalValue::ExternalWeakLinkage;
189 return GlobalValue::CommonLinkage;
191 return GlobalValue::PrivateLinkage;
193 return GlobalValue::AvailableExternallyLinkage;
195 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
197 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
199 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
200 case 1: // Old value with implicit comdat.
202 return GlobalValue::WeakAnyLinkage;
203 case 10: // Old value with implicit comdat.
205 return GlobalValue::WeakODRLinkage;
206 case 4: // Old value with implicit comdat.
208 return GlobalValue::LinkOnceAnyLinkage;
209 case 11: // Old value with implicit comdat.
211 return GlobalValue::LinkOnceODRLinkage;
215 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
217 default: // Map unknown visibilities to default.
218 case 0: return GlobalValue::DefaultVisibility;
219 case 1: return GlobalValue::HiddenVisibility;
220 case 2: return GlobalValue::ProtectedVisibility;
224 static GlobalValue::DLLStorageClassTypes
225 GetDecodedDLLStorageClass(unsigned Val) {
227 default: // Map unknown values to default.
228 case 0: return GlobalValue::DefaultStorageClass;
229 case 1: return GlobalValue::DLLImportStorageClass;
230 case 2: return GlobalValue::DLLExportStorageClass;
234 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
236 case 0: return GlobalVariable::NotThreadLocal;
237 default: // Map unknown non-zero value to general dynamic.
238 case 1: return GlobalVariable::GeneralDynamicTLSModel;
239 case 2: return GlobalVariable::LocalDynamicTLSModel;
240 case 3: return GlobalVariable::InitialExecTLSModel;
241 case 4: return GlobalVariable::LocalExecTLSModel;
245 static int GetDecodedCastOpcode(unsigned Val) {
248 case bitc::CAST_TRUNC : return Instruction::Trunc;
249 case bitc::CAST_ZEXT : return Instruction::ZExt;
250 case bitc::CAST_SEXT : return Instruction::SExt;
251 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
252 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
253 case bitc::CAST_UITOFP : return Instruction::UIToFP;
254 case bitc::CAST_SITOFP : return Instruction::SIToFP;
255 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
256 case bitc::CAST_FPEXT : return Instruction::FPExt;
257 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
258 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
259 case bitc::CAST_BITCAST : return Instruction::BitCast;
260 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
263 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
266 case bitc::BINOP_ADD:
267 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
268 case bitc::BINOP_SUB:
269 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
270 case bitc::BINOP_MUL:
271 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
272 case bitc::BINOP_UDIV: return Instruction::UDiv;
273 case bitc::BINOP_SDIV:
274 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
275 case bitc::BINOP_UREM: return Instruction::URem;
276 case bitc::BINOP_SREM:
277 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
278 case bitc::BINOP_SHL: return Instruction::Shl;
279 case bitc::BINOP_LSHR: return Instruction::LShr;
280 case bitc::BINOP_ASHR: return Instruction::AShr;
281 case bitc::BINOP_AND: return Instruction::And;
282 case bitc::BINOP_OR: return Instruction::Or;
283 case bitc::BINOP_XOR: return Instruction::Xor;
287 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
289 default: return AtomicRMWInst::BAD_BINOP;
290 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
291 case bitc::RMW_ADD: return AtomicRMWInst::Add;
292 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
293 case bitc::RMW_AND: return AtomicRMWInst::And;
294 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
295 case bitc::RMW_OR: return AtomicRMWInst::Or;
296 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
297 case bitc::RMW_MAX: return AtomicRMWInst::Max;
298 case bitc::RMW_MIN: return AtomicRMWInst::Min;
299 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
300 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
304 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
306 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
307 case bitc::ORDERING_UNORDERED: return Unordered;
308 case bitc::ORDERING_MONOTONIC: return Monotonic;
309 case bitc::ORDERING_ACQUIRE: return Acquire;
310 case bitc::ORDERING_RELEASE: return Release;
311 case bitc::ORDERING_ACQREL: return AcquireRelease;
312 default: // Map unknown orderings to sequentially-consistent.
313 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
317 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
319 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
320 default: // Map unknown scopes to cross-thread.
321 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
325 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
327 default: // Map unknown selection kinds to any.
328 case bitc::COMDAT_SELECTION_KIND_ANY:
330 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
331 return Comdat::ExactMatch;
332 case bitc::COMDAT_SELECTION_KIND_LARGEST:
333 return Comdat::Largest;
334 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
335 return Comdat::NoDuplicates;
336 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
337 return Comdat::SameSize;
341 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
343 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
344 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
350 /// @brief A class for maintaining the slot number definition
351 /// as a placeholder for the actual definition for forward constants defs.
352 class ConstantPlaceHolder : public ConstantExpr {
353 void operator=(const ConstantPlaceHolder &) = delete;
355 // allocate space for exactly one operand
356 void *operator new(size_t s) {
357 return User::operator new(s, 1);
359 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
360 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
361 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
364 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
365 static bool classof(const Value *V) {
366 return isa<ConstantExpr>(V) &&
367 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
371 /// Provide fast operand accessors
372 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
376 // FIXME: can we inherit this from ConstantExpr?
378 struct OperandTraits<ConstantPlaceHolder> :
379 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
381 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
385 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
394 WeakVH &OldV = ValuePtrs[Idx];
400 // Handle constants and non-constants (e.g. instrs) differently for
402 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
403 ResolveConstants.push_back(std::make_pair(PHC, Idx));
406 // If there was a forward reference to this value, replace it.
407 Value *PrevVal = OldV;
408 OldV->replaceAllUsesWith(V);
414 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
419 if (Value *V = ValuePtrs[Idx]) {
420 assert(Ty == V->getType() && "Type mismatch in constant table!");
421 return cast<Constant>(V);
424 // Create and return a placeholder, which will later be RAUW'd.
425 Constant *C = new ConstantPlaceHolder(Ty, Context);
430 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
434 if (Value *V = ValuePtrs[Idx]) {
435 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
439 // No type specified, must be invalid reference.
440 if (!Ty) return nullptr;
442 // Create and return a placeholder, which will later be RAUW'd.
443 Value *V = new Argument(Ty);
448 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
449 /// resolves any forward references. The idea behind this is that we sometimes
450 /// get constants (such as large arrays) which reference *many* forward ref
451 /// constants. Replacing each of these causes a lot of thrashing when
452 /// building/reuniquing the constant. Instead of doing this, we look at all the
453 /// uses and rewrite all the place holders at once for any constant that uses
455 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
456 // Sort the values by-pointer so that they are efficient to look up with a
458 std::sort(ResolveConstants.begin(), ResolveConstants.end());
460 SmallVector<Constant*, 64> NewOps;
462 while (!ResolveConstants.empty()) {
463 Value *RealVal = operator[](ResolveConstants.back().second);
464 Constant *Placeholder = ResolveConstants.back().first;
465 ResolveConstants.pop_back();
467 // Loop over all users of the placeholder, updating them to reference the
468 // new value. If they reference more than one placeholder, update them all
470 while (!Placeholder->use_empty()) {
471 auto UI = Placeholder->user_begin();
474 // If the using object isn't uniqued, just update the operands. This
475 // handles instructions and initializers for global variables.
476 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
477 UI.getUse().set(RealVal);
481 // Otherwise, we have a constant that uses the placeholder. Replace that
482 // constant with a new constant that has *all* placeholder uses updated.
483 Constant *UserC = cast<Constant>(U);
484 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
487 if (!isa<ConstantPlaceHolder>(*I)) {
488 // Not a placeholder reference.
490 } else if (*I == Placeholder) {
491 // Common case is that it just references this one placeholder.
494 // Otherwise, look up the placeholder in ResolveConstants.
495 ResolveConstantsTy::iterator It =
496 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
497 std::pair<Constant*, unsigned>(cast<Constant>(*I),
499 assert(It != ResolveConstants.end() && It->first == *I);
500 NewOp = operator[](It->second);
503 NewOps.push_back(cast<Constant>(NewOp));
506 // Make the new constant.
508 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
509 NewC = ConstantArray::get(UserCA->getType(), NewOps);
510 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
511 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
512 } else if (isa<ConstantVector>(UserC)) {
513 NewC = ConstantVector::get(NewOps);
515 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
516 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
519 UserC->replaceAllUsesWith(NewC);
520 UserC->destroyConstant();
524 // Update all ValueHandles, they should be the only users at this point.
525 Placeholder->replaceAllUsesWith(RealVal);
530 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
539 TrackingMDRef &OldMD = MDValuePtrs[Idx];
545 // If there was a forward reference to this value, replace it.
546 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
547 PrevMD->replaceAllUsesWith(MD);
551 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
555 if (Metadata *MD = MDValuePtrs[Idx])
558 // Track forward refs to be resolved later.
560 MinFwdRef = std::min(MinFwdRef, Idx);
561 MaxFwdRef = std::max(MaxFwdRef, Idx);
564 MinFwdRef = MaxFwdRef = Idx;
568 // Create and return a placeholder, which will later be RAUW'd.
569 Metadata *MD = MDNode::getTemporary(Context, None).release();
570 MDValuePtrs[Idx].reset(MD);
574 void BitcodeReaderMDValueList::tryToResolveCycles() {
580 // Still forward references... can't resolve cycles.
583 // Resolve any cycles.
584 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
585 auto &MD = MDValuePtrs[I];
586 auto *N = dyn_cast_or_null<MDNode>(MD);
590 assert(!N->isTemporary() && "Unexpected forward reference");
594 // Make sure we return early again until there's another forward ref.
598 Type *BitcodeReader::getTypeByID(unsigned ID) {
599 // The type table size is always specified correctly.
600 if (ID >= TypeList.size())
603 if (Type *Ty = TypeList[ID])
606 // If we have a forward reference, the only possible case is when it is to a
607 // named struct. Just create a placeholder for now.
608 return TypeList[ID] = createIdentifiedStructType(Context);
611 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
613 auto *Ret = StructType::create(Context, Name);
614 IdentifiedStructTypes.push_back(Ret);
618 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
619 auto *Ret = StructType::create(Context);
620 IdentifiedStructTypes.push_back(Ret);
625 //===----------------------------------------------------------------------===//
626 // Functions for parsing blocks from the bitcode file
627 //===----------------------------------------------------------------------===//
630 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
631 /// been decoded from the given integer. This function must stay in sync with
632 /// 'encodeLLVMAttributesForBitcode'.
633 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
634 uint64_t EncodedAttrs) {
635 // FIXME: Remove in 4.0.
637 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
638 // the bits above 31 down by 11 bits.
639 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
640 assert((!Alignment || isPowerOf2_32(Alignment)) &&
641 "Alignment must be a power of two.");
644 B.addAlignmentAttr(Alignment);
645 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
646 (EncodedAttrs & 0xffff));
649 std::error_code BitcodeReader::ParseAttributeBlock() {
650 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
651 return Error("Invalid record");
653 if (!MAttributes.empty())
654 return Error("Invalid multiple blocks");
656 SmallVector<uint64_t, 64> Record;
658 SmallVector<AttributeSet, 8> Attrs;
660 // Read all the records.
662 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
664 switch (Entry.Kind) {
665 case BitstreamEntry::SubBlock: // Handled for us already.
666 case BitstreamEntry::Error:
667 return Error("Malformed block");
668 case BitstreamEntry::EndBlock:
669 return std::error_code();
670 case BitstreamEntry::Record:
671 // The interesting case.
677 switch (Stream.readRecord(Entry.ID, Record)) {
678 default: // Default behavior: ignore.
680 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
681 // FIXME: Remove in 4.0.
682 if (Record.size() & 1)
683 return Error("Invalid record");
685 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
687 decodeLLVMAttributesForBitcode(B, Record[i+1]);
688 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
691 MAttributes.push_back(AttributeSet::get(Context, Attrs));
695 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
696 for (unsigned i = 0, e = Record.size(); i != e; ++i)
697 Attrs.push_back(MAttributeGroups[Record[i]]);
699 MAttributes.push_back(AttributeSet::get(Context, Attrs));
707 // Returns Attribute::None on unrecognized codes.
708 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
711 return Attribute::None;
712 case bitc::ATTR_KIND_ALIGNMENT:
713 return Attribute::Alignment;
714 case bitc::ATTR_KIND_ALWAYS_INLINE:
715 return Attribute::AlwaysInline;
716 case bitc::ATTR_KIND_BUILTIN:
717 return Attribute::Builtin;
718 case bitc::ATTR_KIND_BY_VAL:
719 return Attribute::ByVal;
720 case bitc::ATTR_KIND_IN_ALLOCA:
721 return Attribute::InAlloca;
722 case bitc::ATTR_KIND_COLD:
723 return Attribute::Cold;
724 case bitc::ATTR_KIND_INLINE_HINT:
725 return Attribute::InlineHint;
726 case bitc::ATTR_KIND_IN_REG:
727 return Attribute::InReg;
728 case bitc::ATTR_KIND_JUMP_TABLE:
729 return Attribute::JumpTable;
730 case bitc::ATTR_KIND_MIN_SIZE:
731 return Attribute::MinSize;
732 case bitc::ATTR_KIND_NAKED:
733 return Attribute::Naked;
734 case bitc::ATTR_KIND_NEST:
735 return Attribute::Nest;
736 case bitc::ATTR_KIND_NO_ALIAS:
737 return Attribute::NoAlias;
738 case bitc::ATTR_KIND_NO_BUILTIN:
739 return Attribute::NoBuiltin;
740 case bitc::ATTR_KIND_NO_CAPTURE:
741 return Attribute::NoCapture;
742 case bitc::ATTR_KIND_NO_DUPLICATE:
743 return Attribute::NoDuplicate;
744 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
745 return Attribute::NoImplicitFloat;
746 case bitc::ATTR_KIND_NO_INLINE:
747 return Attribute::NoInline;
748 case bitc::ATTR_KIND_NON_LAZY_BIND:
749 return Attribute::NonLazyBind;
750 case bitc::ATTR_KIND_NON_NULL:
751 return Attribute::NonNull;
752 case bitc::ATTR_KIND_DEREFERENCEABLE:
753 return Attribute::Dereferenceable;
754 case bitc::ATTR_KIND_NO_RED_ZONE:
755 return Attribute::NoRedZone;
756 case bitc::ATTR_KIND_NO_RETURN:
757 return Attribute::NoReturn;
758 case bitc::ATTR_KIND_NO_UNWIND:
759 return Attribute::NoUnwind;
760 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
761 return Attribute::OptimizeForSize;
762 case bitc::ATTR_KIND_OPTIMIZE_NONE:
763 return Attribute::OptimizeNone;
764 case bitc::ATTR_KIND_READ_NONE:
765 return Attribute::ReadNone;
766 case bitc::ATTR_KIND_READ_ONLY:
767 return Attribute::ReadOnly;
768 case bitc::ATTR_KIND_RETURNED:
769 return Attribute::Returned;
770 case bitc::ATTR_KIND_RETURNS_TWICE:
771 return Attribute::ReturnsTwice;
772 case bitc::ATTR_KIND_S_EXT:
773 return Attribute::SExt;
774 case bitc::ATTR_KIND_STACK_ALIGNMENT:
775 return Attribute::StackAlignment;
776 case bitc::ATTR_KIND_STACK_PROTECT:
777 return Attribute::StackProtect;
778 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
779 return Attribute::StackProtectReq;
780 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
781 return Attribute::StackProtectStrong;
782 case bitc::ATTR_KIND_STRUCT_RET:
783 return Attribute::StructRet;
784 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
785 return Attribute::SanitizeAddress;
786 case bitc::ATTR_KIND_SANITIZE_THREAD:
787 return Attribute::SanitizeThread;
788 case bitc::ATTR_KIND_SANITIZE_MEMORY:
789 return Attribute::SanitizeMemory;
790 case bitc::ATTR_KIND_UW_TABLE:
791 return Attribute::UWTable;
792 case bitc::ATTR_KIND_Z_EXT:
793 return Attribute::ZExt;
797 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
798 Attribute::AttrKind *Kind) {
799 *Kind = GetAttrFromCode(Code);
800 if (*Kind == Attribute::None)
801 return Error(BitcodeError::CorruptedBitcode,
802 "Unknown attribute kind (" + Twine(Code) + ")");
803 return std::error_code();
806 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
807 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
808 return Error("Invalid record");
810 if (!MAttributeGroups.empty())
811 return Error("Invalid multiple blocks");
813 SmallVector<uint64_t, 64> Record;
815 // Read all the records.
817 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
819 switch (Entry.Kind) {
820 case BitstreamEntry::SubBlock: // Handled for us already.
821 case BitstreamEntry::Error:
822 return Error("Malformed block");
823 case BitstreamEntry::EndBlock:
824 return std::error_code();
825 case BitstreamEntry::Record:
826 // The interesting case.
832 switch (Stream.readRecord(Entry.ID, Record)) {
833 default: // Default behavior: ignore.
835 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
836 if (Record.size() < 3)
837 return Error("Invalid record");
839 uint64_t GrpID = Record[0];
840 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
843 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
844 if (Record[i] == 0) { // Enum attribute
845 Attribute::AttrKind Kind;
846 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
849 B.addAttribute(Kind);
850 } else if (Record[i] == 1) { // Integer attribute
851 Attribute::AttrKind Kind;
852 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
854 if (Kind == Attribute::Alignment)
855 B.addAlignmentAttr(Record[++i]);
856 else if (Kind == Attribute::StackAlignment)
857 B.addStackAlignmentAttr(Record[++i]);
858 else if (Kind == Attribute::Dereferenceable)
859 B.addDereferenceableAttr(Record[++i]);
860 } else { // String attribute
861 assert((Record[i] == 3 || Record[i] == 4) &&
862 "Invalid attribute group entry");
863 bool HasValue = (Record[i++] == 4);
864 SmallString<64> KindStr;
865 SmallString<64> ValStr;
867 while (Record[i] != 0 && i != e)
868 KindStr += Record[i++];
869 assert(Record[i] == 0 && "Kind string not null terminated");
872 // Has a value associated with it.
873 ++i; // Skip the '0' that terminates the "kind" string.
874 while (Record[i] != 0 && i != e)
875 ValStr += Record[i++];
876 assert(Record[i] == 0 && "Value string not null terminated");
879 B.addAttribute(KindStr.str(), ValStr.str());
883 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
890 std::error_code BitcodeReader::ParseTypeTable() {
891 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
892 return Error("Invalid record");
894 return ParseTypeTableBody();
897 std::error_code BitcodeReader::ParseTypeTableBody() {
898 if (!TypeList.empty())
899 return Error("Invalid multiple blocks");
901 SmallVector<uint64_t, 64> Record;
902 unsigned NumRecords = 0;
904 SmallString<64> TypeName;
906 // Read all the records for this type table.
908 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
910 switch (Entry.Kind) {
911 case BitstreamEntry::SubBlock: // Handled for us already.
912 case BitstreamEntry::Error:
913 return Error("Malformed block");
914 case BitstreamEntry::EndBlock:
915 if (NumRecords != TypeList.size())
916 return Error("Malformed block");
917 return std::error_code();
918 case BitstreamEntry::Record:
919 // The interesting case.
925 Type *ResultTy = nullptr;
926 switch (Stream.readRecord(Entry.ID, Record)) {
928 return Error("Invalid value");
929 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
930 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
931 // type list. This allows us to reserve space.
932 if (Record.size() < 1)
933 return Error("Invalid record");
934 TypeList.resize(Record[0]);
936 case bitc::TYPE_CODE_VOID: // VOID
937 ResultTy = Type::getVoidTy(Context);
939 case bitc::TYPE_CODE_HALF: // HALF
940 ResultTy = Type::getHalfTy(Context);
942 case bitc::TYPE_CODE_FLOAT: // FLOAT
943 ResultTy = Type::getFloatTy(Context);
945 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
946 ResultTy = Type::getDoubleTy(Context);
948 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
949 ResultTy = Type::getX86_FP80Ty(Context);
951 case bitc::TYPE_CODE_FP128: // FP128
952 ResultTy = Type::getFP128Ty(Context);
954 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
955 ResultTy = Type::getPPC_FP128Ty(Context);
957 case bitc::TYPE_CODE_LABEL: // LABEL
958 ResultTy = Type::getLabelTy(Context);
960 case bitc::TYPE_CODE_METADATA: // METADATA
961 ResultTy = Type::getMetadataTy(Context);
963 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
964 ResultTy = Type::getX86_MMXTy(Context);
966 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
967 if (Record.size() < 1)
968 return Error("Invalid record");
970 uint64_t NumBits = Record[0];
971 if (NumBits < IntegerType::MIN_INT_BITS ||
972 NumBits > IntegerType::MAX_INT_BITS)
973 return Error("Bitwidth for integer type out of range");
974 ResultTy = IntegerType::get(Context, NumBits);
977 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
978 // [pointee type, address space]
979 if (Record.size() < 1)
980 return Error("Invalid record");
981 unsigned AddressSpace = 0;
982 if (Record.size() == 2)
983 AddressSpace = Record[1];
984 ResultTy = getTypeByID(Record[0]);
986 return Error("Invalid type");
987 ResultTy = PointerType::get(ResultTy, AddressSpace);
990 case bitc::TYPE_CODE_FUNCTION_OLD: {
991 // FIXME: attrid is dead, remove it in LLVM 4.0
992 // FUNCTION: [vararg, attrid, retty, paramty x N]
993 if (Record.size() < 3)
994 return Error("Invalid record");
995 SmallVector<Type*, 8> ArgTys;
996 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
997 if (Type *T = getTypeByID(Record[i]))
1003 ResultTy = getTypeByID(Record[2]);
1004 if (!ResultTy || ArgTys.size() < Record.size()-3)
1005 return Error("Invalid type");
1007 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1010 case bitc::TYPE_CODE_FUNCTION: {
1011 // FUNCTION: [vararg, retty, paramty x N]
1012 if (Record.size() < 2)
1013 return Error("Invalid record");
1014 SmallVector<Type*, 8> ArgTys;
1015 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1016 if (Type *T = getTypeByID(Record[i]))
1017 ArgTys.push_back(T);
1022 ResultTy = getTypeByID(Record[1]);
1023 if (!ResultTy || ArgTys.size() < Record.size()-2)
1024 return Error("Invalid type");
1026 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1029 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1030 if (Record.size() < 1)
1031 return Error("Invalid record");
1032 SmallVector<Type*, 8> EltTys;
1033 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1034 if (Type *T = getTypeByID(Record[i]))
1035 EltTys.push_back(T);
1039 if (EltTys.size() != Record.size()-1)
1040 return Error("Invalid type");
1041 ResultTy = StructType::get(Context, EltTys, Record[0]);
1044 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1045 if (ConvertToString(Record, 0, TypeName))
1046 return Error("Invalid record");
1049 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1050 if (Record.size() < 1)
1051 return Error("Invalid record");
1053 if (NumRecords >= TypeList.size())
1054 return Error("Invalid TYPE table");
1056 // Check to see if this was forward referenced, if so fill in the temp.
1057 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1059 Res->setName(TypeName);
1060 TypeList[NumRecords] = nullptr;
1061 } else // Otherwise, create a new struct.
1062 Res = createIdentifiedStructType(Context, TypeName);
1065 SmallVector<Type*, 8> EltTys;
1066 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1067 if (Type *T = getTypeByID(Record[i]))
1068 EltTys.push_back(T);
1072 if (EltTys.size() != Record.size()-1)
1073 return Error("Invalid record");
1074 Res->setBody(EltTys, Record[0]);
1078 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1079 if (Record.size() != 1)
1080 return Error("Invalid record");
1082 if (NumRecords >= TypeList.size())
1083 return Error("Invalid TYPE table");
1085 // Check to see if this was forward referenced, if so fill in the temp.
1086 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1088 Res->setName(TypeName);
1089 TypeList[NumRecords] = nullptr;
1090 } else // Otherwise, create a new struct with no body.
1091 Res = createIdentifiedStructType(Context, TypeName);
1096 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1097 if (Record.size() < 2)
1098 return Error("Invalid record");
1099 if ((ResultTy = getTypeByID(Record[1])))
1100 ResultTy = ArrayType::get(ResultTy, Record[0]);
1102 return Error("Invalid type");
1104 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1105 if (Record.size() < 2)
1106 return Error("Invalid record");
1107 if ((ResultTy = getTypeByID(Record[1])))
1108 ResultTy = VectorType::get(ResultTy, Record[0]);
1110 return Error("Invalid type");
1114 if (NumRecords >= TypeList.size())
1115 return Error("Invalid TYPE table");
1116 if (TypeList[NumRecords])
1118 "Invalid TYPE table: Only named structs can be forward referenced");
1119 assert(ResultTy && "Didn't read a type?");
1120 TypeList[NumRecords++] = ResultTy;
1124 std::error_code BitcodeReader::ParseValueSymbolTable() {
1125 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1126 return Error("Invalid record");
1128 SmallVector<uint64_t, 64> Record;
1130 Triple TT(TheModule->getTargetTriple());
1132 // Read all the records for this value table.
1133 SmallString<128> ValueName;
1135 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1137 switch (Entry.Kind) {
1138 case BitstreamEntry::SubBlock: // Handled for us already.
1139 case BitstreamEntry::Error:
1140 return Error("Malformed block");
1141 case BitstreamEntry::EndBlock:
1142 return std::error_code();
1143 case BitstreamEntry::Record:
1144 // The interesting case.
1150 switch (Stream.readRecord(Entry.ID, Record)) {
1151 default: // Default behavior: unknown type.
1153 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1154 if (ConvertToString(Record, 1, ValueName))
1155 return Error("Invalid record");
1156 unsigned ValueID = Record[0];
1157 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1158 return Error("Invalid record");
1159 Value *V = ValueList[ValueID];
1161 V->setName(StringRef(ValueName.data(), ValueName.size()));
1162 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1163 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1164 if (TT.isOSBinFormatMachO())
1165 GO->setComdat(nullptr);
1167 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1173 case bitc::VST_CODE_BBENTRY: {
1174 if (ConvertToString(Record, 1, ValueName))
1175 return Error("Invalid record");
1176 BasicBlock *BB = getBasicBlock(Record[0]);
1178 return Error("Invalid record");
1180 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1188 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1190 std::error_code BitcodeReader::ParseMetadata() {
1191 unsigned NextMDValueNo = MDValueList.size();
1193 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1194 return Error("Invalid record");
1196 SmallVector<uint64_t, 64> Record;
1199 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1200 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1202 return getMD(ID - 1);
1205 auto getMDString = [&](unsigned ID) -> MDString *{
1206 // This requires that the ID is not really a forward reference. In
1207 // particular, the MDString must already have been resolved.
1208 return cast_or_null<MDString>(getMDOrNull(ID));
1211 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1212 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1214 // Read all the records.
1216 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1218 switch (Entry.Kind) {
1219 case BitstreamEntry::SubBlock: // Handled for us already.
1220 case BitstreamEntry::Error:
1221 return Error("Malformed block");
1222 case BitstreamEntry::EndBlock:
1223 MDValueList.tryToResolveCycles();
1224 return std::error_code();
1225 case BitstreamEntry::Record:
1226 // The interesting case.
1232 unsigned Code = Stream.readRecord(Entry.ID, Record);
1233 bool IsDistinct = false;
1235 default: // Default behavior: ignore.
1237 case bitc::METADATA_NAME: {
1238 // Read name of the named metadata.
1239 SmallString<8> Name(Record.begin(), Record.end());
1241 Code = Stream.ReadCode();
1243 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1244 unsigned NextBitCode = Stream.readRecord(Code, Record);
1245 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1247 // Read named metadata elements.
1248 unsigned Size = Record.size();
1249 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1250 for (unsigned i = 0; i != Size; ++i) {
1251 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1253 return Error("Invalid record");
1254 NMD->addOperand(MD);
1258 case bitc::METADATA_OLD_FN_NODE: {
1259 // FIXME: Remove in 4.0.
1260 // This is a LocalAsMetadata record, the only type of function-local
1262 if (Record.size() % 2 == 1)
1263 return Error("Invalid record");
1265 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1266 // to be legal, but there's no upgrade path.
1267 auto dropRecord = [&] {
1268 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1270 if (Record.size() != 2) {
1275 Type *Ty = getTypeByID(Record[0]);
1276 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1281 MDValueList.AssignValue(
1282 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1286 case bitc::METADATA_OLD_NODE: {
1287 // FIXME: Remove in 4.0.
1288 if (Record.size() % 2 == 1)
1289 return Error("Invalid record");
1291 unsigned Size = Record.size();
1292 SmallVector<Metadata *, 8> Elts;
1293 for (unsigned i = 0; i != Size; i += 2) {
1294 Type *Ty = getTypeByID(Record[i]);
1296 return Error("Invalid record");
1297 if (Ty->isMetadataTy())
1298 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1299 else if (!Ty->isVoidTy()) {
1301 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1302 assert(isa<ConstantAsMetadata>(MD) &&
1303 "Expected non-function-local metadata");
1306 Elts.push_back(nullptr);
1308 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1311 case bitc::METADATA_VALUE: {
1312 if (Record.size() != 2)
1313 return Error("Invalid record");
1315 Type *Ty = getTypeByID(Record[0]);
1316 if (Ty->isMetadataTy() || Ty->isVoidTy())
1317 return Error("Invalid record");
1319 MDValueList.AssignValue(
1320 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1324 case bitc::METADATA_DISTINCT_NODE:
1327 case bitc::METADATA_NODE: {
1328 SmallVector<Metadata *, 8> Elts;
1329 Elts.reserve(Record.size());
1330 for (unsigned ID : Record)
1331 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1332 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1333 : MDNode::get(Context, Elts),
1337 case bitc::METADATA_LOCATION: {
1338 if (Record.size() != 5)
1339 return Error("Invalid record");
1341 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1342 unsigned Line = Record[1];
1343 unsigned Column = Record[2];
1344 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1345 Metadata *InlinedAt =
1346 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1347 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1351 case bitc::METADATA_GENERIC_DEBUG: {
1352 if (Record.size() < 4)
1353 return Error("Invalid record");
1355 unsigned Tag = Record[1];
1356 unsigned Version = Record[2];
1358 if (Tag >= 1u << 16 || Version != 0)
1359 return Error("Invalid record");
1361 auto *Header = getMDString(Record[3]);
1362 SmallVector<Metadata *, 8> DwarfOps;
1363 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1364 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1366 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1367 (Context, Tag, Header, DwarfOps)),
1371 case bitc::METADATA_SUBRANGE: {
1372 if (Record.size() != 3)
1373 return Error("Invalid record");
1375 MDValueList.AssignValue(
1376 GET_OR_DISTINCT(MDSubrange, Record[0],
1377 (Context, Record[1], unrotateSign(Record[2]))),
1381 case bitc::METADATA_ENUMERATOR: {
1382 if (Record.size() != 3)
1383 return Error("Invalid record");
1385 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1386 (Context, unrotateSign(Record[1]),
1387 getMDString(Record[2]))),
1391 case bitc::METADATA_BASIC_TYPE: {
1392 if (Record.size() != 6)
1393 return Error("Invalid record");
1395 MDValueList.AssignValue(
1396 GET_OR_DISTINCT(MDBasicType, Record[0],
1397 (Context, Record[1], getMDString(Record[2]),
1398 Record[3], Record[4], Record[5])),
1402 case bitc::METADATA_DERIVED_TYPE: {
1403 if (Record.size() != 12)
1404 return Error("Invalid record");
1406 MDValueList.AssignValue(
1407 GET_OR_DISTINCT(MDDerivedType, Record[0],
1408 (Context, Record[1], getMDString(Record[2]),
1409 getMDOrNull(Record[3]), Record[4],
1410 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1411 Record[7], Record[8], Record[9], Record[10],
1412 getMDOrNull(Record[11]))),
1416 case bitc::METADATA_COMPOSITE_TYPE: {
1417 if (Record.size() != 16)
1418 return Error("Invalid record");
1420 MDValueList.AssignValue(
1421 GET_OR_DISTINCT(MDCompositeType, Record[0],
1422 (Context, Record[1], getMDString(Record[2]),
1423 getMDOrNull(Record[3]), Record[4],
1424 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1425 Record[7], Record[8], Record[9], Record[10],
1426 getMDOrNull(Record[11]), Record[12],
1427 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1428 getMDString(Record[15]))),
1432 case bitc::METADATA_SUBROUTINE_TYPE: {
1433 if (Record.size() != 3)
1434 return Error("Invalid record");
1436 MDValueList.AssignValue(
1437 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1438 (Context, Record[1], getMDOrNull(Record[2]))),
1442 case bitc::METADATA_FILE: {
1443 if (Record.size() != 3)
1444 return Error("Invalid record");
1446 MDValueList.AssignValue(
1447 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1448 getMDString(Record[2]))),
1452 case bitc::METADATA_COMPILE_UNIT: {
1453 if (Record.size() != 14)
1454 return Error("Invalid record");
1456 MDValueList.AssignValue(
1457 GET_OR_DISTINCT(MDCompileUnit, Record[0],
1458 (Context, Record[1], getMDOrNull(Record[2]),
1459 getMDString(Record[3]), Record[4],
1460 getMDString(Record[5]), Record[6],
1461 getMDString(Record[7]), Record[8],
1462 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1463 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1464 getMDOrNull(Record[13]))),
1468 case bitc::METADATA_SUBPROGRAM: {
1469 if (Record.size() != 19)
1470 return Error("Invalid record");
1472 MDValueList.AssignValue(
1474 MDSubprogram, Record[0],
1475 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1476 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1477 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1478 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1479 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1480 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1484 case bitc::METADATA_LEXICAL_BLOCK: {
1485 if (Record.size() != 5)
1486 return Error("Invalid record");
1488 MDValueList.AssignValue(
1489 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1490 (Context, getMDOrNull(Record[1]),
1491 getMDOrNull(Record[2]), Record[3], Record[4])),
1495 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1496 if (Record.size() != 4)
1497 return Error("Invalid record");
1499 MDValueList.AssignValue(
1500 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1501 (Context, getMDOrNull(Record[1]),
1502 getMDOrNull(Record[2]), Record[3])),
1506 case bitc::METADATA_NAMESPACE: {
1507 if (Record.size() != 5)
1508 return Error("Invalid record");
1510 MDValueList.AssignValue(
1511 GET_OR_DISTINCT(MDNamespace, Record[0],
1512 (Context, getMDOrNull(Record[1]),
1513 getMDOrNull(Record[2]), getMDString(Record[3]),
1518 case bitc::METADATA_TEMPLATE_TYPE: {
1519 if (Record.size() != 3)
1520 return Error("Invalid record");
1522 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1524 (Context, getMDString(Record[1]),
1525 getMDOrNull(Record[2]))),
1529 case bitc::METADATA_TEMPLATE_VALUE: {
1530 if (Record.size() != 5)
1531 return Error("Invalid record");
1533 MDValueList.AssignValue(
1534 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1535 (Context, Record[1], getMDString(Record[2]),
1536 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1540 case bitc::METADATA_GLOBAL_VAR: {
1541 if (Record.size() != 11)
1542 return Error("Invalid record");
1544 MDValueList.AssignValue(
1545 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1546 (Context, getMDOrNull(Record[1]),
1547 getMDString(Record[2]), getMDString(Record[3]),
1548 getMDOrNull(Record[4]), Record[5],
1549 getMDOrNull(Record[6]), Record[7], Record[8],
1550 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1554 case bitc::METADATA_LOCAL_VAR: {
1555 if (Record.size() != 10)
1556 return Error("Invalid record");
1558 MDValueList.AssignValue(
1559 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1560 (Context, Record[1], getMDOrNull(Record[2]),
1561 getMDString(Record[3]), getMDOrNull(Record[4]),
1562 Record[5], getMDOrNull(Record[6]), Record[7],
1563 Record[8], getMDOrNull(Record[9]))),
1567 case bitc::METADATA_EXPRESSION: {
1568 if (Record.size() < 1)
1569 return Error("Invalid record");
1571 MDValueList.AssignValue(
1572 GET_OR_DISTINCT(MDExpression, Record[0],
1573 (Context, makeArrayRef(Record).slice(1))),
1577 case bitc::METADATA_OBJC_PROPERTY: {
1578 if (Record.size() != 8)
1579 return Error("Invalid record");
1581 MDValueList.AssignValue(
1582 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1583 (Context, getMDString(Record[1]),
1584 getMDOrNull(Record[2]), Record[3],
1585 getMDString(Record[4]), getMDString(Record[5]),
1586 Record[6], getMDOrNull(Record[7]))),
1590 case bitc::METADATA_IMPORTED_ENTITY: {
1591 if (Record.size() != 6)
1592 return Error("Invalid record");
1594 MDValueList.AssignValue(
1595 GET_OR_DISTINCT(MDImportedEntity, Record[0],
1596 (Context, Record[1], getMDOrNull(Record[2]),
1597 getMDOrNull(Record[3]), Record[4],
1598 getMDString(Record[5]))),
1602 case bitc::METADATA_STRING: {
1603 std::string String(Record.begin(), Record.end());
1604 llvm::UpgradeMDStringConstant(String);
1605 Metadata *MD = MDString::get(Context, String);
1606 MDValueList.AssignValue(MD, NextMDValueNo++);
1609 case bitc::METADATA_KIND: {
1610 if (Record.size() < 2)
1611 return Error("Invalid record");
1613 unsigned Kind = Record[0];
1614 SmallString<8> Name(Record.begin()+1, Record.end());
1616 unsigned NewKind = TheModule->getMDKindID(Name.str());
1617 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1618 return Error("Conflicting METADATA_KIND records");
1623 #undef GET_OR_DISTINCT
1626 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1627 /// the LSB for dense VBR encoding.
1628 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1633 // There is no such thing as -0 with integers. "-0" really means MININT.
1637 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1638 /// values and aliases that we can.
1639 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1640 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1641 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1642 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1643 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1645 GlobalInitWorklist.swap(GlobalInits);
1646 AliasInitWorklist.swap(AliasInits);
1647 FunctionPrefixWorklist.swap(FunctionPrefixes);
1648 FunctionPrologueWorklist.swap(FunctionPrologues);
1650 while (!GlobalInitWorklist.empty()) {
1651 unsigned ValID = GlobalInitWorklist.back().second;
1652 if (ValID >= ValueList.size()) {
1653 // Not ready to resolve this yet, it requires something later in the file.
1654 GlobalInits.push_back(GlobalInitWorklist.back());
1656 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1657 GlobalInitWorklist.back().first->setInitializer(C);
1659 return Error("Expected a constant");
1661 GlobalInitWorklist.pop_back();
1664 while (!AliasInitWorklist.empty()) {
1665 unsigned ValID = AliasInitWorklist.back().second;
1666 if (ValID >= ValueList.size()) {
1667 AliasInits.push_back(AliasInitWorklist.back());
1669 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1670 AliasInitWorklist.back().first->setAliasee(C);
1672 return Error("Expected a constant");
1674 AliasInitWorklist.pop_back();
1677 while (!FunctionPrefixWorklist.empty()) {
1678 unsigned ValID = FunctionPrefixWorklist.back().second;
1679 if (ValID >= ValueList.size()) {
1680 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1682 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1683 FunctionPrefixWorklist.back().first->setPrefixData(C);
1685 return Error("Expected a constant");
1687 FunctionPrefixWorklist.pop_back();
1690 while (!FunctionPrologueWorklist.empty()) {
1691 unsigned ValID = FunctionPrologueWorklist.back().second;
1692 if (ValID >= ValueList.size()) {
1693 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1695 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1696 FunctionPrologueWorklist.back().first->setPrologueData(C);
1698 return Error("Expected a constant");
1700 FunctionPrologueWorklist.pop_back();
1703 return std::error_code();
1706 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1707 SmallVector<uint64_t, 8> Words(Vals.size());
1708 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1709 BitcodeReader::decodeSignRotatedValue);
1711 return APInt(TypeBits, Words);
1714 std::error_code BitcodeReader::ParseConstants() {
1715 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1716 return Error("Invalid record");
1718 SmallVector<uint64_t, 64> Record;
1720 // Read all the records for this value table.
1721 Type *CurTy = Type::getInt32Ty(Context);
1722 unsigned NextCstNo = ValueList.size();
1724 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1726 switch (Entry.Kind) {
1727 case BitstreamEntry::SubBlock: // Handled for us already.
1728 case BitstreamEntry::Error:
1729 return Error("Malformed block");
1730 case BitstreamEntry::EndBlock:
1731 if (NextCstNo != ValueList.size())
1732 return Error("Invalid ronstant reference");
1734 // Once all the constants have been read, go through and resolve forward
1736 ValueList.ResolveConstantForwardRefs();
1737 return std::error_code();
1738 case BitstreamEntry::Record:
1739 // The interesting case.
1746 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1748 default: // Default behavior: unknown constant
1749 case bitc::CST_CODE_UNDEF: // UNDEF
1750 V = UndefValue::get(CurTy);
1752 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1754 return Error("Invalid record");
1755 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1756 return Error("Invalid record");
1757 CurTy = TypeList[Record[0]];
1758 continue; // Skip the ValueList manipulation.
1759 case bitc::CST_CODE_NULL: // NULL
1760 V = Constant::getNullValue(CurTy);
1762 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1763 if (!CurTy->isIntegerTy() || Record.empty())
1764 return Error("Invalid record");
1765 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1767 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1768 if (!CurTy->isIntegerTy() || Record.empty())
1769 return Error("Invalid record");
1771 APInt VInt = ReadWideAPInt(Record,
1772 cast<IntegerType>(CurTy)->getBitWidth());
1773 V = ConstantInt::get(Context, VInt);
1777 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1779 return Error("Invalid record");
1780 if (CurTy->isHalfTy())
1781 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1782 APInt(16, (uint16_t)Record[0])));
1783 else if (CurTy->isFloatTy())
1784 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1785 APInt(32, (uint32_t)Record[0])));
1786 else if (CurTy->isDoubleTy())
1787 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1788 APInt(64, Record[0])));
1789 else if (CurTy->isX86_FP80Ty()) {
1790 // Bits are not stored the same way as a normal i80 APInt, compensate.
1791 uint64_t Rearrange[2];
1792 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1793 Rearrange[1] = Record[0] >> 48;
1794 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1795 APInt(80, Rearrange)));
1796 } else if (CurTy->isFP128Ty())
1797 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1798 APInt(128, Record)));
1799 else if (CurTy->isPPC_FP128Ty())
1800 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1801 APInt(128, Record)));
1803 V = UndefValue::get(CurTy);
1807 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1809 return Error("Invalid record");
1811 unsigned Size = Record.size();
1812 SmallVector<Constant*, 16> Elts;
1814 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1815 for (unsigned i = 0; i != Size; ++i)
1816 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1817 STy->getElementType(i)));
1818 V = ConstantStruct::get(STy, Elts);
1819 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1820 Type *EltTy = ATy->getElementType();
1821 for (unsigned i = 0; i != Size; ++i)
1822 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1823 V = ConstantArray::get(ATy, Elts);
1824 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1825 Type *EltTy = VTy->getElementType();
1826 for (unsigned i = 0; i != Size; ++i)
1827 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1828 V = ConstantVector::get(Elts);
1830 V = UndefValue::get(CurTy);
1834 case bitc::CST_CODE_STRING: // STRING: [values]
1835 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1837 return Error("Invalid record");
1839 SmallString<16> Elts(Record.begin(), Record.end());
1840 V = ConstantDataArray::getString(Context, Elts,
1841 BitCode == bitc::CST_CODE_CSTRING);
1844 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1846 return Error("Invalid record");
1848 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1849 unsigned Size = Record.size();
1851 if (EltTy->isIntegerTy(8)) {
1852 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1853 if (isa<VectorType>(CurTy))
1854 V = ConstantDataVector::get(Context, Elts);
1856 V = ConstantDataArray::get(Context, Elts);
1857 } else if (EltTy->isIntegerTy(16)) {
1858 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1859 if (isa<VectorType>(CurTy))
1860 V = ConstantDataVector::get(Context, Elts);
1862 V = ConstantDataArray::get(Context, Elts);
1863 } else if (EltTy->isIntegerTy(32)) {
1864 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1865 if (isa<VectorType>(CurTy))
1866 V = ConstantDataVector::get(Context, Elts);
1868 V = ConstantDataArray::get(Context, Elts);
1869 } else if (EltTy->isIntegerTy(64)) {
1870 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1871 if (isa<VectorType>(CurTy))
1872 V = ConstantDataVector::get(Context, Elts);
1874 V = ConstantDataArray::get(Context, Elts);
1875 } else if (EltTy->isFloatTy()) {
1876 SmallVector<float, 16> Elts(Size);
1877 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1878 if (isa<VectorType>(CurTy))
1879 V = ConstantDataVector::get(Context, Elts);
1881 V = ConstantDataArray::get(Context, Elts);
1882 } else if (EltTy->isDoubleTy()) {
1883 SmallVector<double, 16> Elts(Size);
1884 std::transform(Record.begin(), Record.end(), Elts.begin(),
1886 if (isa<VectorType>(CurTy))
1887 V = ConstantDataVector::get(Context, Elts);
1889 V = ConstantDataArray::get(Context, Elts);
1891 return Error("Invalid type for value");
1896 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1897 if (Record.size() < 3)
1898 return Error("Invalid record");
1899 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1901 V = UndefValue::get(CurTy); // Unknown binop.
1903 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1904 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1906 if (Record.size() >= 4) {
1907 if (Opc == Instruction::Add ||
1908 Opc == Instruction::Sub ||
1909 Opc == Instruction::Mul ||
1910 Opc == Instruction::Shl) {
1911 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1912 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1913 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1914 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1915 } else if (Opc == Instruction::SDiv ||
1916 Opc == Instruction::UDiv ||
1917 Opc == Instruction::LShr ||
1918 Opc == Instruction::AShr) {
1919 if (Record[3] & (1 << bitc::PEO_EXACT))
1920 Flags |= SDivOperator::IsExact;
1923 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1927 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1928 if (Record.size() < 3)
1929 return Error("Invalid record");
1930 int Opc = GetDecodedCastOpcode(Record[0]);
1932 V = UndefValue::get(CurTy); // Unknown cast.
1934 Type *OpTy = getTypeByID(Record[1]);
1936 return Error("Invalid record");
1937 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1938 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1939 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1943 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1944 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1945 if (Record.size() & 1)
1946 return Error("Invalid record");
1947 SmallVector<Constant*, 16> Elts;
1948 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1949 Type *ElTy = getTypeByID(Record[i]);
1951 return Error("Invalid record");
1952 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1954 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1955 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1957 bitc::CST_CODE_CE_INBOUNDS_GEP);
1960 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1961 if (Record.size() < 3)
1962 return Error("Invalid record");
1964 Type *SelectorTy = Type::getInt1Ty(Context);
1966 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1967 // vector. Otherwise, it must be a single bit.
1968 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1969 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1970 VTy->getNumElements());
1972 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1974 ValueList.getConstantFwdRef(Record[1],CurTy),
1975 ValueList.getConstantFwdRef(Record[2],CurTy));
1978 case bitc::CST_CODE_CE_EXTRACTELT
1979 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1980 if (Record.size() < 3)
1981 return Error("Invalid record");
1983 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1985 return Error("Invalid record");
1986 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1987 Constant *Op1 = nullptr;
1988 if (Record.size() == 4) {
1989 Type *IdxTy = getTypeByID(Record[2]);
1991 return Error("Invalid record");
1992 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1993 } else // TODO: Remove with llvm 4.0
1994 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1996 return Error("Invalid record");
1997 V = ConstantExpr::getExtractElement(Op0, Op1);
2000 case bitc::CST_CODE_CE_INSERTELT
2001 : { // CE_INSERTELT: [opval, opval, opty, opval]
2002 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2003 if (Record.size() < 3 || !OpTy)
2004 return Error("Invalid record");
2005 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2006 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2007 OpTy->getElementType());
2008 Constant *Op2 = nullptr;
2009 if (Record.size() == 4) {
2010 Type *IdxTy = getTypeByID(Record[2]);
2012 return Error("Invalid record");
2013 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2014 } else // TODO: Remove with llvm 4.0
2015 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2017 return Error("Invalid record");
2018 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2021 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2022 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2023 if (Record.size() < 3 || !OpTy)
2024 return Error("Invalid record");
2025 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2026 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2027 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2028 OpTy->getNumElements());
2029 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2030 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2033 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2034 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2036 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2037 if (Record.size() < 4 || !RTy || !OpTy)
2038 return Error("Invalid record");
2039 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2040 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2041 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2042 RTy->getNumElements());
2043 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2044 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2047 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2048 if (Record.size() < 4)
2049 return Error("Invalid record");
2050 Type *OpTy = getTypeByID(Record[0]);
2052 return Error("Invalid record");
2053 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2054 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2056 if (OpTy->isFPOrFPVectorTy())
2057 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2059 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2062 // This maintains backward compatibility, pre-asm dialect keywords.
2063 // FIXME: Remove with the 4.0 release.
2064 case bitc::CST_CODE_INLINEASM_OLD: {
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;
2070 unsigned AsmStrSize = Record[1];
2071 if (2+AsmStrSize >= Record.size())
2072 return Error("Invalid record");
2073 unsigned ConstStrSize = Record[2+AsmStrSize];
2074 if (3+AsmStrSize+ConstStrSize > Record.size())
2075 return Error("Invalid record");
2077 for (unsigned i = 0; i != AsmStrSize; ++i)
2078 AsmStr += (char)Record[2+i];
2079 for (unsigned i = 0; i != ConstStrSize; ++i)
2080 ConstrStr += (char)Record[3+AsmStrSize+i];
2081 PointerType *PTy = cast<PointerType>(CurTy);
2082 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2083 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2086 // This version adds support for the asm dialect keywords (e.g.,
2088 case bitc::CST_CODE_INLINEASM: {
2089 if (Record.size() < 2)
2090 return Error("Invalid record");
2091 std::string AsmStr, ConstrStr;
2092 bool HasSideEffects = Record[0] & 1;
2093 bool IsAlignStack = (Record[0] >> 1) & 1;
2094 unsigned AsmDialect = Record[0] >> 2;
2095 unsigned AsmStrSize = Record[1];
2096 if (2+AsmStrSize >= Record.size())
2097 return Error("Invalid record");
2098 unsigned ConstStrSize = Record[2+AsmStrSize];
2099 if (3+AsmStrSize+ConstStrSize > Record.size())
2100 return Error("Invalid record");
2102 for (unsigned i = 0; i != AsmStrSize; ++i)
2103 AsmStr += (char)Record[2+i];
2104 for (unsigned i = 0; i != ConstStrSize; ++i)
2105 ConstrStr += (char)Record[3+AsmStrSize+i];
2106 PointerType *PTy = cast<PointerType>(CurTy);
2107 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2108 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2109 InlineAsm::AsmDialect(AsmDialect));
2112 case bitc::CST_CODE_BLOCKADDRESS:{
2113 if (Record.size() < 3)
2114 return Error("Invalid record");
2115 Type *FnTy = getTypeByID(Record[0]);
2117 return Error("Invalid record");
2119 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2121 return Error("Invalid record");
2123 // Don't let Fn get dematerialized.
2124 BlockAddressesTaken.insert(Fn);
2126 // If the function is already parsed we can insert the block address right
2129 unsigned BBID = Record[2];
2131 // Invalid reference to entry block.
2132 return Error("Invalid ID");
2134 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2135 for (size_t I = 0, E = BBID; I != E; ++I) {
2137 return Error("Invalid ID");
2142 // Otherwise insert a placeholder and remember it so it can be inserted
2143 // when the function is parsed.
2144 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2146 BasicBlockFwdRefQueue.push_back(Fn);
2147 if (FwdBBs.size() < BBID + 1)
2148 FwdBBs.resize(BBID + 1);
2150 FwdBBs[BBID] = BasicBlock::Create(Context);
2153 V = BlockAddress::get(Fn, BB);
2158 ValueList.AssignValue(V, NextCstNo);
2163 std::error_code BitcodeReader::ParseUseLists() {
2164 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2165 return Error("Invalid record");
2167 // Read all the records.
2168 SmallVector<uint64_t, 64> Record;
2170 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2172 switch (Entry.Kind) {
2173 case BitstreamEntry::SubBlock: // Handled for us already.
2174 case BitstreamEntry::Error:
2175 return Error("Malformed block");
2176 case BitstreamEntry::EndBlock:
2177 return std::error_code();
2178 case BitstreamEntry::Record:
2179 // The interesting case.
2183 // Read a use list record.
2186 switch (Stream.readRecord(Entry.ID, Record)) {
2187 default: // Default behavior: unknown type.
2189 case bitc::USELIST_CODE_BB:
2192 case bitc::USELIST_CODE_DEFAULT: {
2193 unsigned RecordLength = Record.size();
2194 if (RecordLength < 3)
2195 // Records should have at least an ID and two indexes.
2196 return Error("Invalid record");
2197 unsigned ID = Record.back();
2202 assert(ID < FunctionBBs.size() && "Basic block not found");
2203 V = FunctionBBs[ID];
2206 unsigned NumUses = 0;
2207 SmallDenseMap<const Use *, unsigned, 16> Order;
2208 for (const Use &U : V->uses()) {
2209 if (++NumUses > Record.size())
2211 Order[&U] = Record[NumUses - 1];
2213 if (Order.size() != Record.size() || NumUses > Record.size())
2214 // Mismatches can happen if the functions are being materialized lazily
2215 // (out-of-order), or a value has been upgraded.
2218 V->sortUseList([&](const Use &L, const Use &R) {
2219 return Order.lookup(&L) < Order.lookup(&R);
2227 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2228 /// remember where it is and then skip it. This lets us lazily deserialize the
2230 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2231 // Get the function we are talking about.
2232 if (FunctionsWithBodies.empty())
2233 return Error("Insufficient function protos");
2235 Function *Fn = FunctionsWithBodies.back();
2236 FunctionsWithBodies.pop_back();
2238 // Save the current stream state.
2239 uint64_t CurBit = Stream.GetCurrentBitNo();
2240 DeferredFunctionInfo[Fn] = CurBit;
2242 // Skip over the function block for now.
2243 if (Stream.SkipBlock())
2244 return Error("Invalid record");
2245 return std::error_code();
2248 std::error_code BitcodeReader::GlobalCleanup() {
2249 // Patch the initializers for globals and aliases up.
2250 ResolveGlobalAndAliasInits();
2251 if (!GlobalInits.empty() || !AliasInits.empty())
2252 return Error("Malformed global initializer set");
2254 // Look for intrinsic functions which need to be upgraded at some point
2255 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2258 if (UpgradeIntrinsicFunction(FI, NewFn))
2259 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2262 // Look for global variables which need to be renamed.
2263 for (Module::global_iterator
2264 GI = TheModule->global_begin(), GE = TheModule->global_end();
2266 GlobalVariable *GV = GI++;
2267 UpgradeGlobalVariable(GV);
2270 // Force deallocation of memory for these vectors to favor the client that
2271 // want lazy deserialization.
2272 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2273 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2274 return std::error_code();
2277 std::error_code BitcodeReader::ParseModule(bool Resume) {
2279 Stream.JumpToBit(NextUnreadBit);
2280 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2281 return Error("Invalid record");
2283 SmallVector<uint64_t, 64> Record;
2284 std::vector<std::string> SectionTable;
2285 std::vector<std::string> GCTable;
2287 // Read all the records for this module.
2289 BitstreamEntry Entry = Stream.advance();
2291 switch (Entry.Kind) {
2292 case BitstreamEntry::Error:
2293 return Error("Malformed block");
2294 case BitstreamEntry::EndBlock:
2295 return GlobalCleanup();
2297 case BitstreamEntry::SubBlock:
2299 default: // Skip unknown content.
2300 if (Stream.SkipBlock())
2301 return Error("Invalid record");
2303 case bitc::BLOCKINFO_BLOCK_ID:
2304 if (Stream.ReadBlockInfoBlock())
2305 return Error("Malformed block");
2307 case bitc::PARAMATTR_BLOCK_ID:
2308 if (std::error_code EC = ParseAttributeBlock())
2311 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2312 if (std::error_code EC = ParseAttributeGroupBlock())
2315 case bitc::TYPE_BLOCK_ID_NEW:
2316 if (std::error_code EC = ParseTypeTable())
2319 case bitc::VALUE_SYMTAB_BLOCK_ID:
2320 if (std::error_code EC = ParseValueSymbolTable())
2322 SeenValueSymbolTable = true;
2324 case bitc::CONSTANTS_BLOCK_ID:
2325 if (std::error_code EC = ParseConstants())
2327 if (std::error_code EC = ResolveGlobalAndAliasInits())
2330 case bitc::METADATA_BLOCK_ID:
2331 if (std::error_code EC = ParseMetadata())
2334 case bitc::FUNCTION_BLOCK_ID:
2335 // If this is the first function body we've seen, reverse the
2336 // FunctionsWithBodies list.
2337 if (!SeenFirstFunctionBody) {
2338 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2339 if (std::error_code EC = GlobalCleanup())
2341 SeenFirstFunctionBody = true;
2344 if (std::error_code EC = RememberAndSkipFunctionBody())
2346 // For streaming bitcode, suspend parsing when we reach the function
2347 // bodies. Subsequent materialization calls will resume it when
2348 // necessary. For streaming, the function bodies must be at the end of
2349 // the bitcode. If the bitcode file is old, the symbol table will be
2350 // at the end instead and will not have been seen yet. In this case,
2351 // just finish the parse now.
2352 if (LazyStreamer && SeenValueSymbolTable) {
2353 NextUnreadBit = Stream.GetCurrentBitNo();
2354 return std::error_code();
2357 case bitc::USELIST_BLOCK_ID:
2358 if (std::error_code EC = ParseUseLists())
2364 case BitstreamEntry::Record:
2365 // The interesting case.
2371 switch (Stream.readRecord(Entry.ID, Record)) {
2372 default: break; // Default behavior, ignore unknown content.
2373 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2374 if (Record.size() < 1)
2375 return Error("Invalid record");
2376 // Only version #0 and #1 are supported so far.
2377 unsigned module_version = Record[0];
2378 switch (module_version) {
2380 return Error("Invalid value");
2382 UseRelativeIDs = false;
2385 UseRelativeIDs = true;
2390 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2392 if (ConvertToString(Record, 0, S))
2393 return Error("Invalid record");
2394 TheModule->setTargetTriple(S);
2397 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2399 if (ConvertToString(Record, 0, S))
2400 return Error("Invalid record");
2401 TheModule->setDataLayout(S);
2404 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2406 if (ConvertToString(Record, 0, S))
2407 return Error("Invalid record");
2408 TheModule->setModuleInlineAsm(S);
2411 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2412 // FIXME: Remove in 4.0.
2414 if (ConvertToString(Record, 0, S))
2415 return Error("Invalid record");
2419 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2421 if (ConvertToString(Record, 0, S))
2422 return Error("Invalid record");
2423 SectionTable.push_back(S);
2426 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2428 if (ConvertToString(Record, 0, S))
2429 return Error("Invalid record");
2430 GCTable.push_back(S);
2433 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2434 if (Record.size() < 2)
2435 return Error("Invalid record");
2436 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2437 unsigned ComdatNameSize = Record[1];
2438 std::string ComdatName;
2439 ComdatName.reserve(ComdatNameSize);
2440 for (unsigned i = 0; i != ComdatNameSize; ++i)
2441 ComdatName += (char)Record[2 + i];
2442 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2443 C->setSelectionKind(SK);
2444 ComdatList.push_back(C);
2447 // GLOBALVAR: [pointer type, isconst, initid,
2448 // linkage, alignment, section, visibility, threadlocal,
2449 // unnamed_addr, externally_initialized, dllstorageclass,
2451 case bitc::MODULE_CODE_GLOBALVAR: {
2452 if (Record.size() < 6)
2453 return Error("Invalid record");
2454 Type *Ty = getTypeByID(Record[0]);
2456 return Error("Invalid record");
2457 if (!Ty->isPointerTy())
2458 return Error("Invalid type for value");
2459 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2460 Ty = cast<PointerType>(Ty)->getElementType();
2462 bool isConstant = Record[1];
2463 uint64_t RawLinkage = Record[3];
2464 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2465 unsigned Alignment = (1 << Record[4]) >> 1;
2466 std::string Section;
2468 if (Record[5]-1 >= SectionTable.size())
2469 return Error("Invalid ID");
2470 Section = SectionTable[Record[5]-1];
2472 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2473 // Local linkage must have default visibility.
2474 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2475 // FIXME: Change to an error if non-default in 4.0.
2476 Visibility = GetDecodedVisibility(Record[6]);
2478 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2479 if (Record.size() > 7)
2480 TLM = GetDecodedThreadLocalMode(Record[7]);
2482 bool UnnamedAddr = false;
2483 if (Record.size() > 8)
2484 UnnamedAddr = Record[8];
2486 bool ExternallyInitialized = false;
2487 if (Record.size() > 9)
2488 ExternallyInitialized = Record[9];
2490 GlobalVariable *NewGV =
2491 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2492 TLM, AddressSpace, ExternallyInitialized);
2493 NewGV->setAlignment(Alignment);
2494 if (!Section.empty())
2495 NewGV->setSection(Section);
2496 NewGV->setVisibility(Visibility);
2497 NewGV->setUnnamedAddr(UnnamedAddr);
2499 if (Record.size() > 10)
2500 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2502 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2504 ValueList.push_back(NewGV);
2506 // Remember which value to use for the global initializer.
2507 if (unsigned InitID = Record[2])
2508 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2510 if (Record.size() > 11) {
2511 if (unsigned ComdatID = Record[11]) {
2512 assert(ComdatID <= ComdatList.size());
2513 NewGV->setComdat(ComdatList[ComdatID - 1]);
2515 } else if (hasImplicitComdat(RawLinkage)) {
2516 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2520 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2521 // alignment, section, visibility, gc, unnamed_addr,
2522 // prologuedata, dllstorageclass, comdat, prefixdata]
2523 case bitc::MODULE_CODE_FUNCTION: {
2524 if (Record.size() < 8)
2525 return Error("Invalid record");
2526 Type *Ty = getTypeByID(Record[0]);
2528 return Error("Invalid record");
2529 if (!Ty->isPointerTy())
2530 return Error("Invalid type for value");
2532 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2534 return Error("Invalid type for value");
2536 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2539 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2540 bool isProto = Record[2];
2541 uint64_t RawLinkage = Record[3];
2542 Func->setLinkage(getDecodedLinkage(RawLinkage));
2543 Func->setAttributes(getAttributes(Record[4]));
2545 Func->setAlignment((1 << Record[5]) >> 1);
2547 if (Record[6]-1 >= SectionTable.size())
2548 return Error("Invalid ID");
2549 Func->setSection(SectionTable[Record[6]-1]);
2551 // Local linkage must have default visibility.
2552 if (!Func->hasLocalLinkage())
2553 // FIXME: Change to an error if non-default in 4.0.
2554 Func->setVisibility(GetDecodedVisibility(Record[7]));
2555 if (Record.size() > 8 && Record[8]) {
2556 if (Record[8]-1 > GCTable.size())
2557 return Error("Invalid ID");
2558 Func->setGC(GCTable[Record[8]-1].c_str());
2560 bool UnnamedAddr = false;
2561 if (Record.size() > 9)
2562 UnnamedAddr = Record[9];
2563 Func->setUnnamedAddr(UnnamedAddr);
2564 if (Record.size() > 10 && Record[10] != 0)
2565 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2567 if (Record.size() > 11)
2568 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2570 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2572 if (Record.size() > 12) {
2573 if (unsigned ComdatID = Record[12]) {
2574 assert(ComdatID <= ComdatList.size());
2575 Func->setComdat(ComdatList[ComdatID - 1]);
2577 } else if (hasImplicitComdat(RawLinkage)) {
2578 Func->setComdat(reinterpret_cast<Comdat *>(1));
2581 if (Record.size() > 13 && Record[13] != 0)
2582 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2584 ValueList.push_back(Func);
2586 // If this is a function with a body, remember the prototype we are
2587 // creating now, so that we can match up the body with them later.
2589 Func->setIsMaterializable(true);
2590 FunctionsWithBodies.push_back(Func);
2592 DeferredFunctionInfo[Func] = 0;
2596 // ALIAS: [alias type, aliasee val#, linkage]
2597 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2598 case bitc::MODULE_CODE_ALIAS: {
2599 if (Record.size() < 3)
2600 return Error("Invalid record");
2601 Type *Ty = getTypeByID(Record[0]);
2603 return Error("Invalid record");
2604 auto *PTy = dyn_cast<PointerType>(Ty);
2606 return Error("Invalid type for value");
2609 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2610 getDecodedLinkage(Record[2]), "", TheModule);
2611 // Old bitcode files didn't have visibility field.
2612 // Local linkage must have default visibility.
2613 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2614 // FIXME: Change to an error if non-default in 4.0.
2615 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2616 if (Record.size() > 4)
2617 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2619 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2620 if (Record.size() > 5)
2621 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2622 if (Record.size() > 6)
2623 NewGA->setUnnamedAddr(Record[6]);
2624 ValueList.push_back(NewGA);
2625 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2628 /// MODULE_CODE_PURGEVALS: [numvals]
2629 case bitc::MODULE_CODE_PURGEVALS:
2630 // Trim down the value list to the specified size.
2631 if (Record.size() < 1 || Record[0] > ValueList.size())
2632 return Error("Invalid record");
2633 ValueList.shrinkTo(Record[0]);
2640 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2641 TheModule = nullptr;
2643 if (std::error_code EC = InitStream())
2646 // Sniff for the signature.
2647 if (Stream.Read(8) != 'B' ||
2648 Stream.Read(8) != 'C' ||
2649 Stream.Read(4) != 0x0 ||
2650 Stream.Read(4) != 0xC ||
2651 Stream.Read(4) != 0xE ||
2652 Stream.Read(4) != 0xD)
2653 return Error("Invalid bitcode signature");
2655 // We expect a number of well-defined blocks, though we don't necessarily
2656 // need to understand them all.
2658 if (Stream.AtEndOfStream())
2659 return std::error_code();
2661 BitstreamEntry Entry =
2662 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2664 switch (Entry.Kind) {
2665 case BitstreamEntry::Error:
2666 return Error("Malformed block");
2667 case BitstreamEntry::EndBlock:
2668 return std::error_code();
2670 case BitstreamEntry::SubBlock:
2672 case bitc::BLOCKINFO_BLOCK_ID:
2673 if (Stream.ReadBlockInfoBlock())
2674 return Error("Malformed block");
2676 case bitc::MODULE_BLOCK_ID:
2677 // Reject multiple MODULE_BLOCK's in a single bitstream.
2679 return Error("Invalid multiple blocks");
2681 if (std::error_code EC = ParseModule(false))
2684 return std::error_code();
2687 if (Stream.SkipBlock())
2688 return Error("Invalid record");
2692 case BitstreamEntry::Record:
2693 // There should be no records in the top-level of blocks.
2695 // The ranlib in Xcode 4 will align archive members by appending newlines
2696 // to the end of them. If this file size is a multiple of 4 but not 8, we
2697 // have to read and ignore these final 4 bytes :-(
2698 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2699 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2700 Stream.AtEndOfStream())
2701 return std::error_code();
2703 return Error("Invalid record");
2708 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2709 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2710 return Error("Invalid record");
2712 SmallVector<uint64_t, 64> Record;
2715 // Read all the records for this module.
2717 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2719 switch (Entry.Kind) {
2720 case BitstreamEntry::SubBlock: // Handled for us already.
2721 case BitstreamEntry::Error:
2722 return Error("Malformed block");
2723 case BitstreamEntry::EndBlock:
2725 case BitstreamEntry::Record:
2726 // The interesting case.
2731 switch (Stream.readRecord(Entry.ID, Record)) {
2732 default: break; // Default behavior, ignore unknown content.
2733 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2735 if (ConvertToString(Record, 0, S))
2736 return Error("Invalid record");
2743 llvm_unreachable("Exit infinite loop");
2746 ErrorOr<std::string> BitcodeReader::parseTriple() {
2747 if (std::error_code EC = InitStream())
2750 // Sniff for the signature.
2751 if (Stream.Read(8) != 'B' ||
2752 Stream.Read(8) != 'C' ||
2753 Stream.Read(4) != 0x0 ||
2754 Stream.Read(4) != 0xC ||
2755 Stream.Read(4) != 0xE ||
2756 Stream.Read(4) != 0xD)
2757 return Error("Invalid bitcode signature");
2759 // We expect a number of well-defined blocks, though we don't necessarily
2760 // need to understand them all.
2762 BitstreamEntry Entry = Stream.advance();
2764 switch (Entry.Kind) {
2765 case BitstreamEntry::Error:
2766 return Error("Malformed block");
2767 case BitstreamEntry::EndBlock:
2768 return std::error_code();
2770 case BitstreamEntry::SubBlock:
2771 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2772 return parseModuleTriple();
2774 // Ignore other sub-blocks.
2775 if (Stream.SkipBlock())
2776 return Error("Malformed block");
2779 case BitstreamEntry::Record:
2780 Stream.skipRecord(Entry.ID);
2786 /// ParseMetadataAttachment - Parse metadata attachments.
2787 std::error_code BitcodeReader::ParseMetadataAttachment() {
2788 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2789 return Error("Invalid record");
2791 SmallVector<uint64_t, 64> Record;
2793 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2795 switch (Entry.Kind) {
2796 case BitstreamEntry::SubBlock: // Handled for us already.
2797 case BitstreamEntry::Error:
2798 return Error("Malformed block");
2799 case BitstreamEntry::EndBlock:
2800 return std::error_code();
2801 case BitstreamEntry::Record:
2802 // The interesting case.
2806 // Read a metadata attachment record.
2808 switch (Stream.readRecord(Entry.ID, Record)) {
2809 default: // Default behavior: ignore.
2811 case bitc::METADATA_ATTACHMENT: {
2812 unsigned RecordLength = Record.size();
2813 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2814 return Error("Invalid record");
2815 Instruction *Inst = InstructionList[Record[0]];
2816 for (unsigned i = 1; i != RecordLength; i = i+2) {
2817 unsigned Kind = Record[i];
2818 DenseMap<unsigned, unsigned>::iterator I =
2819 MDKindMap.find(Kind);
2820 if (I == MDKindMap.end())
2821 return Error("Invalid ID");
2822 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2823 if (isa<LocalAsMetadata>(Node))
2824 // Drop the attachment. This used to be legal, but there's no
2827 Inst->setMetadata(I->second, cast<MDNode>(Node));
2828 if (I->second == LLVMContext::MD_tbaa)
2829 InstsWithTBAATag.push_back(Inst);
2837 /// ParseFunctionBody - Lazily parse the specified function body block.
2838 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2839 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2840 return Error("Invalid record");
2842 InstructionList.clear();
2843 unsigned ModuleValueListSize = ValueList.size();
2844 unsigned ModuleMDValueListSize = MDValueList.size();
2846 // Add all the function arguments to the value table.
2847 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2848 ValueList.push_back(I);
2850 unsigned NextValueNo = ValueList.size();
2851 BasicBlock *CurBB = nullptr;
2852 unsigned CurBBNo = 0;
2855 auto getLastInstruction = [&]() -> Instruction * {
2856 if (CurBB && !CurBB->empty())
2857 return &CurBB->back();
2858 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2859 !FunctionBBs[CurBBNo - 1]->empty())
2860 return &FunctionBBs[CurBBNo - 1]->back();
2864 // Read all the records.
2865 SmallVector<uint64_t, 64> Record;
2867 BitstreamEntry Entry = Stream.advance();
2869 switch (Entry.Kind) {
2870 case BitstreamEntry::Error:
2871 return Error("Malformed block");
2872 case BitstreamEntry::EndBlock:
2873 goto OutOfRecordLoop;
2875 case BitstreamEntry::SubBlock:
2877 default: // Skip unknown content.
2878 if (Stream.SkipBlock())
2879 return Error("Invalid record");
2881 case bitc::CONSTANTS_BLOCK_ID:
2882 if (std::error_code EC = ParseConstants())
2884 NextValueNo = ValueList.size();
2886 case bitc::VALUE_SYMTAB_BLOCK_ID:
2887 if (std::error_code EC = ParseValueSymbolTable())
2890 case bitc::METADATA_ATTACHMENT_ID:
2891 if (std::error_code EC = ParseMetadataAttachment())
2894 case bitc::METADATA_BLOCK_ID:
2895 if (std::error_code EC = ParseMetadata())
2898 case bitc::USELIST_BLOCK_ID:
2899 if (std::error_code EC = ParseUseLists())
2905 case BitstreamEntry::Record:
2906 // The interesting case.
2912 Instruction *I = nullptr;
2913 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2915 default: // Default behavior: reject
2916 return Error("Invalid value");
2917 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2918 if (Record.size() < 1 || Record[0] == 0)
2919 return Error("Invalid record");
2920 // Create all the basic blocks for the function.
2921 FunctionBBs.resize(Record[0]);
2923 // See if anything took the address of blocks in this function.
2924 auto BBFRI = BasicBlockFwdRefs.find(F);
2925 if (BBFRI == BasicBlockFwdRefs.end()) {
2926 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2927 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2929 auto &BBRefs = BBFRI->second;
2930 // Check for invalid basic block references.
2931 if (BBRefs.size() > FunctionBBs.size())
2932 return Error("Invalid ID");
2933 assert(!BBRefs.empty() && "Unexpected empty array");
2934 assert(!BBRefs.front() && "Invalid reference to entry block");
2935 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2937 if (I < RE && BBRefs[I]) {
2938 BBRefs[I]->insertInto(F);
2939 FunctionBBs[I] = BBRefs[I];
2941 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2944 // Erase from the table.
2945 BasicBlockFwdRefs.erase(BBFRI);
2948 CurBB = FunctionBBs[0];
2952 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2953 // This record indicates that the last instruction is at the same
2954 // location as the previous instruction with a location.
2955 I = getLastInstruction();
2958 return Error("Invalid record");
2959 I->setDebugLoc(LastLoc);
2963 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2964 I = getLastInstruction();
2965 if (!I || Record.size() < 4)
2966 return Error("Invalid record");
2968 unsigned Line = Record[0], Col = Record[1];
2969 unsigned ScopeID = Record[2], IAID = Record[3];
2971 MDNode *Scope = nullptr, *IA = nullptr;
2972 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2973 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2974 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2975 I->setDebugLoc(LastLoc);
2980 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2983 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2984 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2985 OpNum+1 > Record.size())
2986 return Error("Invalid record");
2988 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2990 return Error("Invalid record");
2991 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2992 InstructionList.push_back(I);
2993 if (OpNum < Record.size()) {
2994 if (Opc == Instruction::Add ||
2995 Opc == Instruction::Sub ||
2996 Opc == Instruction::Mul ||
2997 Opc == Instruction::Shl) {
2998 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2999 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3000 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3001 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3002 } else if (Opc == Instruction::SDiv ||
3003 Opc == Instruction::UDiv ||
3004 Opc == Instruction::LShr ||
3005 Opc == Instruction::AShr) {
3006 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3007 cast<BinaryOperator>(I)->setIsExact(true);
3008 } else if (isa<FPMathOperator>(I)) {
3010 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3011 FMF.setUnsafeAlgebra();
3012 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3014 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3016 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3017 FMF.setNoSignedZeros();
3018 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3019 FMF.setAllowReciprocal();
3021 I->setFastMathFlags(FMF);
3027 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3030 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3031 OpNum+2 != Record.size())
3032 return Error("Invalid record");
3034 Type *ResTy = getTypeByID(Record[OpNum]);
3035 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3036 if (Opc == -1 || !ResTy)
3037 return Error("Invalid record");
3038 Instruction *Temp = nullptr;
3039 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3041 InstructionList.push_back(Temp);
3042 CurBB->getInstList().push_back(Temp);
3045 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3047 InstructionList.push_back(I);
3050 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
3051 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
3054 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3055 return Error("Invalid record");
3057 SmallVector<Value*, 16> GEPIdx;
3058 while (OpNum != Record.size()) {
3060 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3061 return Error("Invalid record");
3062 GEPIdx.push_back(Op);
3065 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
3066 InstructionList.push_back(I);
3067 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
3068 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3072 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3073 // EXTRACTVAL: [opty, opval, n x indices]
3076 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3077 return Error("Invalid record");
3079 SmallVector<unsigned, 4> EXTRACTVALIdx;
3080 Type *CurTy = Agg->getType();
3081 for (unsigned RecSize = Record.size();
3082 OpNum != RecSize; ++OpNum) {
3083 bool IsArray = CurTy->isArrayTy();
3084 bool IsStruct = CurTy->isStructTy();
3085 uint64_t Index = Record[OpNum];
3087 if (!IsStruct && !IsArray)
3088 return Error("EXTRACTVAL: Invalid type");
3089 if ((unsigned)Index != Index)
3090 return Error("Invalid value");
3091 if (IsStruct && Index >= CurTy->subtypes().size())
3092 return Error("EXTRACTVAL: Invalid struct index");
3093 if (IsArray && Index >= CurTy->getArrayNumElements())
3094 return Error("EXTRACTVAL: Invalid array index");
3095 EXTRACTVALIdx.push_back((unsigned)Index);
3098 CurTy = CurTy->subtypes()[Index];
3100 CurTy = CurTy->subtypes()[0];
3103 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3104 InstructionList.push_back(I);
3108 case bitc::FUNC_CODE_INST_INSERTVAL: {
3109 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3112 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3113 return Error("Invalid record");
3115 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3116 return Error("Invalid record");
3118 SmallVector<unsigned, 4> INSERTVALIdx;
3119 Type *CurTy = Agg->getType();
3120 for (unsigned RecSize = Record.size();
3121 OpNum != RecSize; ++OpNum) {
3122 bool IsArray = CurTy->isArrayTy();
3123 bool IsStruct = CurTy->isStructTy();
3124 uint64_t Index = Record[OpNum];
3126 if (!IsStruct && !IsArray)
3127 return Error("INSERTVAL: Invalid type");
3128 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3129 return Error("Invalid type");
3130 if ((unsigned)Index != Index)
3131 return Error("Invalid value");
3132 if (IsStruct && Index >= CurTy->subtypes().size())
3133 return Error("INSERTVAL: Invalid struct index");
3134 if (IsArray && Index >= CurTy->getArrayNumElements())
3135 return Error("INSERTVAL: Invalid array index");
3137 INSERTVALIdx.push_back((unsigned)Index);
3139 CurTy = CurTy->subtypes()[Index];
3141 CurTy = CurTy->subtypes()[0];
3144 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3145 InstructionList.push_back(I);
3149 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3150 // obsolete form of select
3151 // handles select i1 ... in old bitcode
3153 Value *TrueVal, *FalseVal, *Cond;
3154 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3155 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3156 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3157 return Error("Invalid record");
3159 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3160 InstructionList.push_back(I);
3164 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3165 // new form of select
3166 // handles select i1 or select [N x i1]
3168 Value *TrueVal, *FalseVal, *Cond;
3169 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3170 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3171 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3172 return Error("Invalid record");
3174 // select condition can be either i1 or [N x i1]
3175 if (VectorType* vector_type =
3176 dyn_cast<VectorType>(Cond->getType())) {
3178 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3179 return Error("Invalid type for value");
3182 if (Cond->getType() != Type::getInt1Ty(Context))
3183 return Error("Invalid type for value");
3186 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3187 InstructionList.push_back(I);
3191 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3194 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3195 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3196 return Error("Invalid record");
3197 I = ExtractElementInst::Create(Vec, Idx);
3198 InstructionList.push_back(I);
3202 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3204 Value *Vec, *Elt, *Idx;
3205 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3206 popValue(Record, OpNum, NextValueNo,
3207 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3208 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3209 return Error("Invalid record");
3210 I = InsertElementInst::Create(Vec, Elt, Idx);
3211 InstructionList.push_back(I);
3215 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3217 Value *Vec1, *Vec2, *Mask;
3218 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3219 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3220 return Error("Invalid record");
3222 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3223 return Error("Invalid record");
3224 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3225 InstructionList.push_back(I);
3229 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3230 // Old form of ICmp/FCmp returning bool
3231 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3232 // both legal on vectors but had different behaviour.
3233 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3234 // FCmp/ICmp returning bool or vector of bool
3238 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3239 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3240 OpNum+1 != Record.size())
3241 return Error("Invalid record");
3243 if (LHS->getType()->isFPOrFPVectorTy())
3244 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3246 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3247 InstructionList.push_back(I);
3251 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3253 unsigned Size = Record.size();
3255 I = ReturnInst::Create(Context);
3256 InstructionList.push_back(I);
3261 Value *Op = nullptr;
3262 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3263 return Error("Invalid record");
3264 if (OpNum != Record.size())
3265 return Error("Invalid record");
3267 I = ReturnInst::Create(Context, Op);
3268 InstructionList.push_back(I);
3271 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3272 if (Record.size() != 1 && Record.size() != 3)
3273 return Error("Invalid record");
3274 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3276 return Error("Invalid record");
3278 if (Record.size() == 1) {
3279 I = BranchInst::Create(TrueDest);
3280 InstructionList.push_back(I);
3283 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3284 Value *Cond = getValue(Record, 2, NextValueNo,
3285 Type::getInt1Ty(Context));
3286 if (!FalseDest || !Cond)
3287 return Error("Invalid record");
3288 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3289 InstructionList.push_back(I);
3293 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3295 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3296 // "New" SwitchInst format with case ranges. The changes to write this
3297 // format were reverted but we still recognize bitcode that uses it.
3298 // Hopefully someday we will have support for case ranges and can use
3299 // this format again.
3301 Type *OpTy = getTypeByID(Record[1]);
3302 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3304 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3305 BasicBlock *Default = getBasicBlock(Record[3]);
3306 if (!OpTy || !Cond || !Default)
3307 return Error("Invalid record");
3309 unsigned NumCases = Record[4];
3311 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3312 InstructionList.push_back(SI);
3314 unsigned CurIdx = 5;
3315 for (unsigned i = 0; i != NumCases; ++i) {
3316 SmallVector<ConstantInt*, 1> CaseVals;
3317 unsigned NumItems = Record[CurIdx++];
3318 for (unsigned ci = 0; ci != NumItems; ++ci) {
3319 bool isSingleNumber = Record[CurIdx++];
3322 unsigned ActiveWords = 1;
3323 if (ValueBitWidth > 64)
3324 ActiveWords = Record[CurIdx++];
3325 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3327 CurIdx += ActiveWords;
3329 if (!isSingleNumber) {
3331 if (ValueBitWidth > 64)
3332 ActiveWords = Record[CurIdx++];
3334 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3336 CurIdx += ActiveWords;
3338 // FIXME: It is not clear whether values in the range should be
3339 // compared as signed or unsigned values. The partially
3340 // implemented changes that used this format in the past used
3341 // unsigned comparisons.
3342 for ( ; Low.ule(High); ++Low)
3343 CaseVals.push_back(ConstantInt::get(Context, Low));
3345 CaseVals.push_back(ConstantInt::get(Context, Low));
3347 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3348 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3349 cve = CaseVals.end(); cvi != cve; ++cvi)
3350 SI->addCase(*cvi, DestBB);
3356 // Old SwitchInst format without case ranges.
3358 if (Record.size() < 3 || (Record.size() & 1) == 0)
3359 return Error("Invalid record");
3360 Type *OpTy = getTypeByID(Record[0]);
3361 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3362 BasicBlock *Default = getBasicBlock(Record[2]);
3363 if (!OpTy || !Cond || !Default)
3364 return Error("Invalid record");
3365 unsigned NumCases = (Record.size()-3)/2;
3366 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3367 InstructionList.push_back(SI);
3368 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3369 ConstantInt *CaseVal =
3370 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3371 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3372 if (!CaseVal || !DestBB) {
3374 return Error("Invalid record");
3376 SI->addCase(CaseVal, DestBB);
3381 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3382 if (Record.size() < 2)
3383 return Error("Invalid record");
3384 Type *OpTy = getTypeByID(Record[0]);
3385 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3386 if (!OpTy || !Address)
3387 return Error("Invalid record");
3388 unsigned NumDests = Record.size()-2;
3389 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3390 InstructionList.push_back(IBI);
3391 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3392 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3393 IBI->addDestination(DestBB);
3396 return Error("Invalid record");
3403 case bitc::FUNC_CODE_INST_INVOKE: {
3404 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3405 if (Record.size() < 4)
3406 return Error("Invalid record");
3407 AttributeSet PAL = getAttributes(Record[0]);
3408 unsigned CCInfo = Record[1];
3409 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3410 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3414 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3415 return Error("Invalid record");
3417 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3418 FunctionType *FTy = !CalleeTy ? nullptr :
3419 dyn_cast<FunctionType>(CalleeTy->getElementType());
3421 // Check that the right number of fixed parameters are here.
3422 if (!FTy || !NormalBB || !UnwindBB ||
3423 Record.size() < OpNum+FTy->getNumParams())
3424 return Error("Invalid record");
3426 SmallVector<Value*, 16> Ops;
3427 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3428 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3429 FTy->getParamType(i)));
3431 return Error("Invalid record");
3434 if (!FTy->isVarArg()) {
3435 if (Record.size() != OpNum)
3436 return Error("Invalid record");
3438 // Read type/value pairs for varargs params.
3439 while (OpNum != Record.size()) {
3441 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3442 return Error("Invalid record");
3447 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3448 InstructionList.push_back(I);
3449 cast<InvokeInst>(I)->setCallingConv(
3450 static_cast<CallingConv::ID>(CCInfo));
3451 cast<InvokeInst>(I)->setAttributes(PAL);
3454 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3456 Value *Val = nullptr;
3457 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3458 return Error("Invalid record");
3459 I = ResumeInst::Create(Val);
3460 InstructionList.push_back(I);
3463 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3464 I = new UnreachableInst(Context);
3465 InstructionList.push_back(I);
3467 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3468 if (Record.size() < 1 || ((Record.size()-1)&1))
3469 return Error("Invalid record");
3470 Type *Ty = getTypeByID(Record[0]);
3472 return Error("Invalid record");
3474 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3475 InstructionList.push_back(PN);
3477 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3479 // With the new function encoding, it is possible that operands have
3480 // negative IDs (for forward references). Use a signed VBR
3481 // representation to keep the encoding small.
3483 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3485 V = getValue(Record, 1+i, NextValueNo, Ty);
3486 BasicBlock *BB = getBasicBlock(Record[2+i]);
3488 return Error("Invalid record");
3489 PN->addIncoming(V, BB);
3495 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3496 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3498 if (Record.size() < 4)
3499 return Error("Invalid record");
3500 Type *Ty = getTypeByID(Record[Idx++]);
3502 return Error("Invalid record");
3503 Value *PersFn = nullptr;
3504 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3505 return Error("Invalid record");
3507 bool IsCleanup = !!Record[Idx++];
3508 unsigned NumClauses = Record[Idx++];
3509 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3510 LP->setCleanup(IsCleanup);
3511 for (unsigned J = 0; J != NumClauses; ++J) {
3512 LandingPadInst::ClauseType CT =
3513 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3516 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3518 return Error("Invalid record");
3521 assert((CT != LandingPadInst::Catch ||
3522 !isa<ArrayType>(Val->getType())) &&
3523 "Catch clause has a invalid type!");
3524 assert((CT != LandingPadInst::Filter ||
3525 isa<ArrayType>(Val->getType())) &&
3526 "Filter clause has invalid type!");
3527 LP->addClause(cast<Constant>(Val));
3531 InstructionList.push_back(I);
3535 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3536 if (Record.size() != 4)
3537 return Error("Invalid record");
3539 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3540 Type *OpTy = getTypeByID(Record[1]);
3541 Value *Size = getFnValueByID(Record[2], OpTy);
3542 unsigned AlignRecord = Record[3];
3543 bool InAlloca = AlignRecord & (1 << 5);
3544 unsigned Align = AlignRecord & ((1 << 5) - 1);
3546 return Error("Invalid record");
3547 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3548 AI->setUsedWithInAlloca(InAlloca);
3550 InstructionList.push_back(I);
3553 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3556 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3557 OpNum+2 != Record.size())
3558 return Error("Invalid record");
3560 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3561 InstructionList.push_back(I);
3564 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3565 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3568 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3569 OpNum+4 != Record.size())
3570 return Error("Invalid record");
3572 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3573 if (Ordering == NotAtomic || Ordering == Release ||
3574 Ordering == AcquireRelease)
3575 return Error("Invalid record");
3576 if (Ordering != NotAtomic && Record[OpNum] == 0)
3577 return Error("Invalid record");
3578 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3580 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3581 Ordering, SynchScope);
3582 InstructionList.push_back(I);
3585 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3588 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3589 popValue(Record, OpNum, NextValueNo,
3590 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3591 OpNum+2 != Record.size())
3592 return Error("Invalid record");
3594 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3595 InstructionList.push_back(I);
3598 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3599 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3602 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3603 popValue(Record, OpNum, NextValueNo,
3604 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3605 OpNum+4 != Record.size())
3606 return Error("Invalid record");
3608 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3609 if (Ordering == NotAtomic || Ordering == Acquire ||
3610 Ordering == AcquireRelease)
3611 return Error("Invalid record");
3612 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3613 if (Ordering != NotAtomic && Record[OpNum] == 0)
3614 return Error("Invalid record");
3616 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3617 Ordering, SynchScope);
3618 InstructionList.push_back(I);
3621 case bitc::FUNC_CODE_INST_CMPXCHG: {
3622 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3623 // failureordering?, isweak?]
3625 Value *Ptr, *Cmp, *New;
3626 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3627 popValue(Record, OpNum, NextValueNo,
3628 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3629 popValue(Record, OpNum, NextValueNo,
3630 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3631 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3632 return Error("Invalid record");
3633 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3634 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3635 return Error("Invalid record");
3636 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3638 AtomicOrdering FailureOrdering;
3639 if (Record.size() < 7)
3641 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3643 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3645 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3647 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3649 if (Record.size() < 8) {
3650 // Before weak cmpxchgs existed, the instruction simply returned the
3651 // value loaded from memory, so bitcode files from that era will be
3652 // expecting the first component of a modern cmpxchg.
3653 CurBB->getInstList().push_back(I);
3654 I = ExtractValueInst::Create(I, 0);
3656 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3659 InstructionList.push_back(I);
3662 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3663 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3666 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3667 popValue(Record, OpNum, NextValueNo,
3668 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3669 OpNum+4 != Record.size())
3670 return Error("Invalid record");
3671 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3672 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3673 Operation > AtomicRMWInst::LAST_BINOP)
3674 return Error("Invalid record");
3675 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3676 if (Ordering == NotAtomic || Ordering == Unordered)
3677 return Error("Invalid record");
3678 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3679 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3680 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3681 InstructionList.push_back(I);
3684 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3685 if (2 != Record.size())
3686 return Error("Invalid record");
3687 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3688 if (Ordering == NotAtomic || Ordering == Unordered ||
3689 Ordering == Monotonic)
3690 return Error("Invalid record");
3691 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3692 I = new FenceInst(Context, Ordering, SynchScope);
3693 InstructionList.push_back(I);
3696 case bitc::FUNC_CODE_INST_CALL: {
3697 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3698 if (Record.size() < 3)
3699 return Error("Invalid record");
3701 AttributeSet PAL = getAttributes(Record[0]);
3702 unsigned CCInfo = Record[1];
3706 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3707 return Error("Invalid record");
3709 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3710 FunctionType *FTy = nullptr;
3711 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3712 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3713 return Error("Invalid record");
3715 SmallVector<Value*, 16> Args;
3716 // Read the fixed params.
3717 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3718 if (FTy->getParamType(i)->isLabelTy())
3719 Args.push_back(getBasicBlock(Record[OpNum]));
3721 Args.push_back(getValue(Record, OpNum, NextValueNo,
3722 FTy->getParamType(i)));
3724 return Error("Invalid record");
3727 // Read type/value pairs for varargs params.
3728 if (!FTy->isVarArg()) {
3729 if (OpNum != Record.size())
3730 return Error("Invalid record");
3732 while (OpNum != Record.size()) {
3734 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3735 return Error("Invalid record");
3740 I = CallInst::Create(Callee, Args);
3741 InstructionList.push_back(I);
3742 cast<CallInst>(I)->setCallingConv(
3743 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3744 CallInst::TailCallKind TCK = CallInst::TCK_None;
3746 TCK = CallInst::TCK_Tail;
3747 if (CCInfo & (1 << 14))
3748 TCK = CallInst::TCK_MustTail;
3749 cast<CallInst>(I)->setTailCallKind(TCK);
3750 cast<CallInst>(I)->setAttributes(PAL);
3753 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3754 if (Record.size() < 3)
3755 return Error("Invalid record");
3756 Type *OpTy = getTypeByID(Record[0]);
3757 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3758 Type *ResTy = getTypeByID(Record[2]);
3759 if (!OpTy || !Op || !ResTy)
3760 return Error("Invalid record");
3761 I = new VAArgInst(Op, ResTy);
3762 InstructionList.push_back(I);
3767 // Add instruction to end of current BB. If there is no current BB, reject
3771 return Error("Invalid instruction with no BB");
3773 CurBB->getInstList().push_back(I);
3775 // If this was a terminator instruction, move to the next block.
3776 if (isa<TerminatorInst>(I)) {
3778 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3781 // Non-void values get registered in the value table for future use.
3782 if (I && !I->getType()->isVoidTy())
3783 ValueList.AssignValue(I, NextValueNo++);
3788 // Check the function list for unresolved values.
3789 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3790 if (!A->getParent()) {
3791 // We found at least one unresolved value. Nuke them all to avoid leaks.
3792 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3793 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3794 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3798 return Error("Never resolved value found in function");
3802 // FIXME: Check for unresolved forward-declared metadata references
3803 // and clean up leaks.
3805 // Trim the value list down to the size it was before we parsed this function.
3806 ValueList.shrinkTo(ModuleValueListSize);
3807 MDValueList.shrinkTo(ModuleMDValueListSize);
3808 std::vector<BasicBlock*>().swap(FunctionBBs);
3809 return std::error_code();
3812 /// Find the function body in the bitcode stream
3813 std::error_code BitcodeReader::FindFunctionInStream(
3815 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3816 while (DeferredFunctionInfoIterator->second == 0) {
3817 if (Stream.AtEndOfStream())
3818 return Error("Could not find function in stream");
3819 // ParseModule will parse the next body in the stream and set its
3820 // position in the DeferredFunctionInfo map.
3821 if (std::error_code EC = ParseModule(true))
3824 return std::error_code();
3827 //===----------------------------------------------------------------------===//
3828 // GVMaterializer implementation
3829 //===----------------------------------------------------------------------===//
3831 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3833 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3834 Function *F = dyn_cast<Function>(GV);
3835 // If it's not a function or is already material, ignore the request.
3836 if (!F || !F->isMaterializable())
3837 return std::error_code();
3839 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3840 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3841 // If its position is recorded as 0, its body is somewhere in the stream
3842 // but we haven't seen it yet.
3843 if (DFII->second == 0 && LazyStreamer)
3844 if (std::error_code EC = FindFunctionInStream(F, DFII))
3847 // Move the bit stream to the saved position of the deferred function body.
3848 Stream.JumpToBit(DFII->second);
3850 if (std::error_code EC = ParseFunctionBody(F))
3852 F->setIsMaterializable(false);
3854 // Upgrade any old intrinsic calls in the function.
3855 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3856 E = UpgradedIntrinsics.end(); I != E; ++I) {
3857 if (I->first != I->second) {
3858 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3860 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3861 UpgradeIntrinsicCall(CI, I->second);
3866 // Bring in any functions that this function forward-referenced via
3868 return materializeForwardReferencedFunctions();
3871 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3872 const Function *F = dyn_cast<Function>(GV);
3873 if (!F || F->isDeclaration())
3876 // Dematerializing F would leave dangling references that wouldn't be
3877 // reconnected on re-materialization.
3878 if (BlockAddressesTaken.count(F))
3881 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3884 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3885 Function *F = dyn_cast<Function>(GV);
3886 // If this function isn't dematerializable, this is a noop.
3887 if (!F || !isDematerializable(F))
3890 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3892 // Just forget the function body, we can remat it later.
3893 F->dropAllReferences();
3894 F->setIsMaterializable(true);
3897 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3898 assert(M == TheModule &&
3899 "Can only Materialize the Module this BitcodeReader is attached to.");
3901 // Promise to materialize all forward references.
3902 WillMaterializeAllForwardRefs = true;
3904 // Iterate over the module, deserializing any functions that are still on
3906 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3908 if (std::error_code EC = materialize(F))
3911 // At this point, if there are any function bodies, the current bit is
3912 // pointing to the END_BLOCK record after them. Now make sure the rest
3913 // of the bits in the module have been read.
3917 // Check that all block address forward references got resolved (as we
3919 if (!BasicBlockFwdRefs.empty())
3920 return Error("Never resolved function from blockaddress");
3922 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3923 // delete the old functions to clean up. We can't do this unless the entire
3924 // module is materialized because there could always be another function body
3925 // with calls to the old function.
3926 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3927 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3928 if (I->first != I->second) {
3929 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3931 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3932 UpgradeIntrinsicCall(CI, I->second);
3934 if (!I->first->use_empty())
3935 I->first->replaceAllUsesWith(I->second);
3936 I->first->eraseFromParent();
3939 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3941 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3942 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3944 UpgradeDebugInfo(*M);
3945 return std::error_code();
3948 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3949 return IdentifiedStructTypes;
3952 std::error_code BitcodeReader::InitStream() {
3954 return InitLazyStream();
3955 return InitStreamFromBuffer();
3958 std::error_code BitcodeReader::InitStreamFromBuffer() {
3959 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3960 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3962 if (Buffer->getBufferSize() & 3)
3963 return Error("Invalid bitcode signature");
3965 // If we have a wrapper header, parse it and ignore the non-bc file contents.
3966 // The magic number is 0x0B17C0DE stored in little endian.
3967 if (isBitcodeWrapper(BufPtr, BufEnd))
3968 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3969 return Error("Invalid bitcode wrapper header");
3971 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3972 Stream.init(&*StreamFile);
3974 return std::error_code();
3977 std::error_code BitcodeReader::InitLazyStream() {
3978 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3980 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3981 StreamingMemoryObject &Bytes = *OwnedBytes;
3982 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3983 Stream.init(&*StreamFile);
3985 unsigned char buf[16];
3986 if (Bytes.readBytes(buf, 16, 0) != 16)
3987 return Error("Invalid bitcode signature");
3989 if (!isBitcode(buf, buf + 16))
3990 return Error("Invalid bitcode signature");
3992 if (isBitcodeWrapper(buf, buf + 4)) {
3993 const unsigned char *bitcodeStart = buf;
3994 const unsigned char *bitcodeEnd = buf + 16;
3995 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3996 Bytes.dropLeadingBytes(bitcodeStart - buf);
3997 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3999 return std::error_code();
4003 class BitcodeErrorCategoryType : public std::error_category {
4004 const char *name() const LLVM_NOEXCEPT override {
4005 return "llvm.bitcode";
4007 std::string message(int IE) const override {
4008 BitcodeError E = static_cast<BitcodeError>(IE);
4010 case BitcodeError::InvalidBitcodeSignature:
4011 return "Invalid bitcode signature";
4012 case BitcodeError::CorruptedBitcode:
4013 return "Corrupted bitcode";
4015 llvm_unreachable("Unknown error type!");
4020 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4022 const std::error_category &llvm::BitcodeErrorCategory() {
4023 return *ErrorCategory;
4026 //===----------------------------------------------------------------------===//
4027 // External interface
4028 //===----------------------------------------------------------------------===//
4030 /// \brief Get a lazy one-at-time loading module from bitcode.
4032 /// This isn't always used in a lazy context. In particular, it's also used by
4033 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4034 /// in forward-referenced functions from block address references.
4036 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4037 /// materialize everything -- in particular, if this isn't truly lazy.
4038 static ErrorOr<Module *>
4039 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4040 LLVMContext &Context, bool WillMaterializeAll,
4041 DiagnosticHandlerFunction DiagnosticHandler) {
4042 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4044 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4045 M->setMaterializer(R);
4047 auto cleanupOnError = [&](std::error_code EC) {
4048 R->releaseBuffer(); // Never take ownership on error.
4049 delete M; // Also deletes R.
4053 if (std::error_code EC = R->ParseBitcodeInto(M))
4054 return cleanupOnError(EC);
4056 if (!WillMaterializeAll)
4057 // Resolve forward references from blockaddresses.
4058 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4059 return cleanupOnError(EC);
4061 Buffer.release(); // The BitcodeReader owns it now.
4066 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4067 LLVMContext &Context,
4068 DiagnosticHandlerFunction DiagnosticHandler) {
4069 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4073 ErrorOr<std::unique_ptr<Module>>
4074 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4075 LLVMContext &Context,
4076 DiagnosticHandlerFunction DiagnosticHandler) {
4077 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4078 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4079 M->setMaterializer(R);
4080 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4082 return std::move(M);
4086 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4087 DiagnosticHandlerFunction DiagnosticHandler) {
4088 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4089 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4090 std::move(Buf), Context, true, DiagnosticHandler);
4093 Module *M = ModuleOrErr.get();
4094 // Read in the entire module, and destroy the BitcodeReader.
4095 if (std::error_code EC = M->materializeAllPermanently()) {
4100 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4101 // written. We must defer until the Module has been fully materialized.
4107 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4108 DiagnosticHandlerFunction DiagnosticHandler) {
4109 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4110 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4112 ErrorOr<std::string> Triple = R->parseTriple();
4113 if (Triple.getError())
4115 return Triple.get();