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/STLExtras.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/OperandTraits.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/Support/DataStream.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/raw_ostream.h"
37 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
40 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
41 DiagnosticSeverity Severity,
43 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
45 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
47 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
48 std::error_code EC, const Twine &Message) {
49 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
50 DiagnosticHandler(DI);
54 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
56 return Error(DiagnosticHandler, EC, EC.message());
59 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
60 return ::Error(DiagnosticHandler, make_error_code(E), Message);
63 std::error_code BitcodeReader::Error(const Twine &Message) {
64 return ::Error(DiagnosticHandler,
65 make_error_code(BitcodeError::CorruptedBitcode), Message);
68 std::error_code BitcodeReader::Error(BitcodeError E) {
69 return ::Error(DiagnosticHandler, make_error_code(E));
72 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
76 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
79 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
80 DiagnosticHandlerFunction DiagnosticHandler)
81 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
82 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
83 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
84 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
85 WillMaterializeAllForwardRefs(false) {}
87 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
88 DiagnosticHandlerFunction DiagnosticHandler)
89 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
90 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
91 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
92 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
93 WillMaterializeAllForwardRefs(false) {}
95 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
96 if (WillMaterializeAllForwardRefs)
97 return std::error_code();
100 WillMaterializeAllForwardRefs = true;
102 while (!BasicBlockFwdRefQueue.empty()) {
103 Function *F = BasicBlockFwdRefQueue.front();
104 BasicBlockFwdRefQueue.pop_front();
105 assert(F && "Expected valid function");
106 if (!BasicBlockFwdRefs.count(F))
107 // Already materialized.
110 // Check for a function that isn't materializable to prevent an infinite
111 // loop. When parsing a blockaddress stored in a global variable, there
112 // isn't a trivial way to check if a function will have a body without a
113 // linear search through FunctionsWithBodies, so just check it here.
114 if (!F->isMaterializable())
115 return Error("Never resolved function from blockaddress");
117 // Try to materialize F.
118 if (std::error_code EC = materialize(F))
121 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
124 WillMaterializeAllForwardRefs = false;
125 return std::error_code();
128 void BitcodeReader::FreeState() {
130 std::vector<Type*>().swap(TypeList);
133 std::vector<Comdat *>().swap(ComdatList);
135 std::vector<AttributeSet>().swap(MAttributes);
136 std::vector<BasicBlock*>().swap(FunctionBBs);
137 std::vector<Function*>().swap(FunctionsWithBodies);
138 DeferredFunctionInfo.clear();
141 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
142 BasicBlockFwdRefQueue.clear();
145 //===----------------------------------------------------------------------===//
146 // Helper functions to implement forward reference resolution, etc.
147 //===----------------------------------------------------------------------===//
149 /// ConvertToString - Convert a string from a record into an std::string, return
151 template<typename StrTy>
152 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
154 if (Idx > Record.size())
157 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
158 Result += (char)Record[i];
162 static bool hasImplicitComdat(size_t Val) {
166 case 1: // Old WeakAnyLinkage
167 case 4: // Old LinkOnceAnyLinkage
168 case 10: // Old WeakODRLinkage
169 case 11: // Old LinkOnceODRLinkage
174 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
176 default: // Map unknown/new linkages to external
178 return GlobalValue::ExternalLinkage;
180 return GlobalValue::AppendingLinkage;
182 return GlobalValue::InternalLinkage;
184 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
186 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
188 return GlobalValue::ExternalWeakLinkage;
190 return GlobalValue::CommonLinkage;
192 return GlobalValue::PrivateLinkage;
194 return GlobalValue::AvailableExternallyLinkage;
196 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
198 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
200 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
201 case 1: // Old value with implicit comdat.
203 return GlobalValue::WeakAnyLinkage;
204 case 10: // Old value with implicit comdat.
206 return GlobalValue::WeakODRLinkage;
207 case 4: // Old value with implicit comdat.
209 return GlobalValue::LinkOnceAnyLinkage;
210 case 11: // Old value with implicit comdat.
212 return GlobalValue::LinkOnceODRLinkage;
216 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
218 default: // Map unknown visibilities to default.
219 case 0: return GlobalValue::DefaultVisibility;
220 case 1: return GlobalValue::HiddenVisibility;
221 case 2: return GlobalValue::ProtectedVisibility;
225 static GlobalValue::DLLStorageClassTypes
226 GetDecodedDLLStorageClass(unsigned Val) {
228 default: // Map unknown values to default.
229 case 0: return GlobalValue::DefaultStorageClass;
230 case 1: return GlobalValue::DLLImportStorageClass;
231 case 2: return GlobalValue::DLLExportStorageClass;
235 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
237 case 0: return GlobalVariable::NotThreadLocal;
238 default: // Map unknown non-zero value to general dynamic.
239 case 1: return GlobalVariable::GeneralDynamicTLSModel;
240 case 2: return GlobalVariable::LocalDynamicTLSModel;
241 case 3: return GlobalVariable::InitialExecTLSModel;
242 case 4: return GlobalVariable::LocalExecTLSModel;
246 static int GetDecodedCastOpcode(unsigned Val) {
249 case bitc::CAST_TRUNC : return Instruction::Trunc;
250 case bitc::CAST_ZEXT : return Instruction::ZExt;
251 case bitc::CAST_SEXT : return Instruction::SExt;
252 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
253 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
254 case bitc::CAST_UITOFP : return Instruction::UIToFP;
255 case bitc::CAST_SITOFP : return Instruction::SIToFP;
256 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
257 case bitc::CAST_FPEXT : return Instruction::FPExt;
258 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
259 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
260 case bitc::CAST_BITCAST : return Instruction::BitCast;
261 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
264 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
267 case bitc::BINOP_ADD:
268 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
269 case bitc::BINOP_SUB:
270 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
271 case bitc::BINOP_MUL:
272 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
273 case bitc::BINOP_UDIV: return Instruction::UDiv;
274 case bitc::BINOP_SDIV:
275 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
276 case bitc::BINOP_UREM: return Instruction::URem;
277 case bitc::BINOP_SREM:
278 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
279 case bitc::BINOP_SHL: return Instruction::Shl;
280 case bitc::BINOP_LSHR: return Instruction::LShr;
281 case bitc::BINOP_ASHR: return Instruction::AShr;
282 case bitc::BINOP_AND: return Instruction::And;
283 case bitc::BINOP_OR: return Instruction::Or;
284 case bitc::BINOP_XOR: return Instruction::Xor;
288 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
290 default: return AtomicRMWInst::BAD_BINOP;
291 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
292 case bitc::RMW_ADD: return AtomicRMWInst::Add;
293 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
294 case bitc::RMW_AND: return AtomicRMWInst::And;
295 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
296 case bitc::RMW_OR: return AtomicRMWInst::Or;
297 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
298 case bitc::RMW_MAX: return AtomicRMWInst::Max;
299 case bitc::RMW_MIN: return AtomicRMWInst::Min;
300 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
301 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
305 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
307 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
308 case bitc::ORDERING_UNORDERED: return Unordered;
309 case bitc::ORDERING_MONOTONIC: return Monotonic;
310 case bitc::ORDERING_ACQUIRE: return Acquire;
311 case bitc::ORDERING_RELEASE: return Release;
312 case bitc::ORDERING_ACQREL: return AcquireRelease;
313 default: // Map unknown orderings to sequentially-consistent.
314 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
318 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
320 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
321 default: // Map unknown scopes to cross-thread.
322 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
326 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
328 default: // Map unknown selection kinds to any.
329 case bitc::COMDAT_SELECTION_KIND_ANY:
331 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
332 return Comdat::ExactMatch;
333 case bitc::COMDAT_SELECTION_KIND_LARGEST:
334 return Comdat::Largest;
335 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
336 return Comdat::NoDuplicates;
337 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
338 return Comdat::SameSize;
342 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
344 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
345 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
351 /// @brief A class for maintaining the slot number definition
352 /// as a placeholder for the actual definition for forward constants defs.
353 class ConstantPlaceHolder : public ConstantExpr {
354 void operator=(const ConstantPlaceHolder &) = delete;
356 // allocate space for exactly one operand
357 void *operator new(size_t s) {
358 return User::operator new(s, 1);
360 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
361 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
362 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
365 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
366 static bool classof(const Value *V) {
367 return isa<ConstantExpr>(V) &&
368 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
372 /// Provide fast operand accessors
373 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
377 // FIXME: can we inherit this from ConstantExpr?
379 struct OperandTraits<ConstantPlaceHolder> :
380 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
382 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
386 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
395 WeakVH &OldV = ValuePtrs[Idx];
401 // Handle constants and non-constants (e.g. instrs) differently for
403 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
404 ResolveConstants.push_back(std::make_pair(PHC, Idx));
407 // If there was a forward reference to this value, replace it.
408 Value *PrevVal = OldV;
409 OldV->replaceAllUsesWith(V);
415 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
420 if (Value *V = ValuePtrs[Idx]) {
421 assert(Ty == V->getType() && "Type mismatch in constant table!");
422 return cast<Constant>(V);
425 // Create and return a placeholder, which will later be RAUW'd.
426 Constant *C = new ConstantPlaceHolder(Ty, Context);
431 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
435 if (Value *V = ValuePtrs[Idx]) {
436 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
440 // No type specified, must be invalid reference.
441 if (!Ty) return nullptr;
443 // Create and return a placeholder, which will later be RAUW'd.
444 Value *V = new Argument(Ty);
449 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
450 /// resolves any forward references. The idea behind this is that we sometimes
451 /// get constants (such as large arrays) which reference *many* forward ref
452 /// constants. Replacing each of these causes a lot of thrashing when
453 /// building/reuniquing the constant. Instead of doing this, we look at all the
454 /// uses and rewrite all the place holders at once for any constant that uses
456 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
457 // Sort the values by-pointer so that they are efficient to look up with a
459 std::sort(ResolveConstants.begin(), ResolveConstants.end());
461 SmallVector<Constant*, 64> NewOps;
463 while (!ResolveConstants.empty()) {
464 Value *RealVal = operator[](ResolveConstants.back().second);
465 Constant *Placeholder = ResolveConstants.back().first;
466 ResolveConstants.pop_back();
468 // Loop over all users of the placeholder, updating them to reference the
469 // new value. If they reference more than one placeholder, update them all
471 while (!Placeholder->use_empty()) {
472 auto UI = Placeholder->user_begin();
475 // If the using object isn't uniqued, just update the operands. This
476 // handles instructions and initializers for global variables.
477 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
478 UI.getUse().set(RealVal);
482 // Otherwise, we have a constant that uses the placeholder. Replace that
483 // constant with a new constant that has *all* placeholder uses updated.
484 Constant *UserC = cast<Constant>(U);
485 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
488 if (!isa<ConstantPlaceHolder>(*I)) {
489 // Not a placeholder reference.
491 } else if (*I == Placeholder) {
492 // Common case is that it just references this one placeholder.
495 // Otherwise, look up the placeholder in ResolveConstants.
496 ResolveConstantsTy::iterator It =
497 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
498 std::pair<Constant*, unsigned>(cast<Constant>(*I),
500 assert(It != ResolveConstants.end() && It->first == *I);
501 NewOp = operator[](It->second);
504 NewOps.push_back(cast<Constant>(NewOp));
507 // Make the new constant.
509 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
510 NewC = ConstantArray::get(UserCA->getType(), NewOps);
511 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
512 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
513 } else if (isa<ConstantVector>(UserC)) {
514 NewC = ConstantVector::get(NewOps);
516 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
517 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
520 UserC->replaceAllUsesWith(NewC);
521 UserC->destroyConstant();
525 // Update all ValueHandles, they should be the only users at this point.
526 Placeholder->replaceAllUsesWith(RealVal);
531 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
540 TrackingMDRef &OldMD = MDValuePtrs[Idx];
546 // If there was a forward reference to this value, replace it.
547 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
548 PrevMD->replaceAllUsesWith(MD);
552 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
556 if (Metadata *MD = MDValuePtrs[Idx])
559 // Track forward refs to be resolved later.
561 MinFwdRef = std::min(MinFwdRef, Idx);
562 MaxFwdRef = std::max(MaxFwdRef, Idx);
565 MinFwdRef = MaxFwdRef = Idx;
569 // Create and return a placeholder, which will later be RAUW'd.
570 Metadata *MD = MDNode::getTemporary(Context, None).release();
571 MDValuePtrs[Idx].reset(MD);
575 void BitcodeReaderMDValueList::tryToResolveCycles() {
581 // Still forward references... can't resolve cycles.
584 // Resolve any cycles.
585 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
586 auto &MD = MDValuePtrs[I];
587 auto *N = dyn_cast_or_null<MDNode>(MD);
591 assert(!N->isTemporary() && "Unexpected forward reference");
595 // Make sure we return early again until there's another forward ref.
599 Type *BitcodeReader::getTypeByID(unsigned ID) {
600 // The type table size is always specified correctly.
601 if (ID >= TypeList.size())
604 if (Type *Ty = TypeList[ID])
607 // If we have a forward reference, the only possible case is when it is to a
608 // named struct. Just create a placeholder for now.
609 return TypeList[ID] = createIdentifiedStructType(Context);
612 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
614 auto *Ret = StructType::create(Context, Name);
615 IdentifiedStructTypes.push_back(Ret);
619 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
620 auto *Ret = StructType::create(Context);
621 IdentifiedStructTypes.push_back(Ret);
626 //===----------------------------------------------------------------------===//
627 // Functions for parsing blocks from the bitcode file
628 //===----------------------------------------------------------------------===//
631 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
632 /// been decoded from the given integer. This function must stay in sync with
633 /// 'encodeLLVMAttributesForBitcode'.
634 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
635 uint64_t EncodedAttrs) {
636 // FIXME: Remove in 4.0.
638 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
639 // the bits above 31 down by 11 bits.
640 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
641 assert((!Alignment || isPowerOf2_32(Alignment)) &&
642 "Alignment must be a power of two.");
645 B.addAlignmentAttr(Alignment);
646 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
647 (EncodedAttrs & 0xffff));
650 std::error_code BitcodeReader::ParseAttributeBlock() {
651 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
652 return Error("Invalid record");
654 if (!MAttributes.empty())
655 return Error("Invalid multiple blocks");
657 SmallVector<uint64_t, 64> Record;
659 SmallVector<AttributeSet, 8> Attrs;
661 // Read all the records.
663 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
665 switch (Entry.Kind) {
666 case BitstreamEntry::SubBlock: // Handled for us already.
667 case BitstreamEntry::Error:
668 return Error("Malformed block");
669 case BitstreamEntry::EndBlock:
670 return std::error_code();
671 case BitstreamEntry::Record:
672 // The interesting case.
678 switch (Stream.readRecord(Entry.ID, Record)) {
679 default: // Default behavior: ignore.
681 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
682 // FIXME: Remove in 4.0.
683 if (Record.size() & 1)
684 return Error("Invalid record");
686 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
688 decodeLLVMAttributesForBitcode(B, Record[i+1]);
689 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
692 MAttributes.push_back(AttributeSet::get(Context, Attrs));
696 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
697 for (unsigned i = 0, e = Record.size(); i != e; ++i)
698 Attrs.push_back(MAttributeGroups[Record[i]]);
700 MAttributes.push_back(AttributeSet::get(Context, Attrs));
708 // Returns Attribute::None on unrecognized codes.
709 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
712 return Attribute::None;
713 case bitc::ATTR_KIND_ALIGNMENT:
714 return Attribute::Alignment;
715 case bitc::ATTR_KIND_ALWAYS_INLINE:
716 return Attribute::AlwaysInline;
717 case bitc::ATTR_KIND_BUILTIN:
718 return Attribute::Builtin;
719 case bitc::ATTR_KIND_BY_VAL:
720 return Attribute::ByVal;
721 case bitc::ATTR_KIND_IN_ALLOCA:
722 return Attribute::InAlloca;
723 case bitc::ATTR_KIND_COLD:
724 return Attribute::Cold;
725 case bitc::ATTR_KIND_INLINE_HINT:
726 return Attribute::InlineHint;
727 case bitc::ATTR_KIND_IN_REG:
728 return Attribute::InReg;
729 case bitc::ATTR_KIND_JUMP_TABLE:
730 return Attribute::JumpTable;
731 case bitc::ATTR_KIND_MIN_SIZE:
732 return Attribute::MinSize;
733 case bitc::ATTR_KIND_NAKED:
734 return Attribute::Naked;
735 case bitc::ATTR_KIND_NEST:
736 return Attribute::Nest;
737 case bitc::ATTR_KIND_NO_ALIAS:
738 return Attribute::NoAlias;
739 case bitc::ATTR_KIND_NO_BUILTIN:
740 return Attribute::NoBuiltin;
741 case bitc::ATTR_KIND_NO_CAPTURE:
742 return Attribute::NoCapture;
743 case bitc::ATTR_KIND_NO_DUPLICATE:
744 return Attribute::NoDuplicate;
745 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
746 return Attribute::NoImplicitFloat;
747 case bitc::ATTR_KIND_NO_INLINE:
748 return Attribute::NoInline;
749 case bitc::ATTR_KIND_NON_LAZY_BIND:
750 return Attribute::NonLazyBind;
751 case bitc::ATTR_KIND_NON_NULL:
752 return Attribute::NonNull;
753 case bitc::ATTR_KIND_DEREFERENCEABLE:
754 return Attribute::Dereferenceable;
755 case bitc::ATTR_KIND_NO_RED_ZONE:
756 return Attribute::NoRedZone;
757 case bitc::ATTR_KIND_NO_RETURN:
758 return Attribute::NoReturn;
759 case bitc::ATTR_KIND_NO_UNWIND:
760 return Attribute::NoUnwind;
761 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
762 return Attribute::OptimizeForSize;
763 case bitc::ATTR_KIND_OPTIMIZE_NONE:
764 return Attribute::OptimizeNone;
765 case bitc::ATTR_KIND_READ_NONE:
766 return Attribute::ReadNone;
767 case bitc::ATTR_KIND_READ_ONLY:
768 return Attribute::ReadOnly;
769 case bitc::ATTR_KIND_RETURNED:
770 return Attribute::Returned;
771 case bitc::ATTR_KIND_RETURNS_TWICE:
772 return Attribute::ReturnsTwice;
773 case bitc::ATTR_KIND_S_EXT:
774 return Attribute::SExt;
775 case bitc::ATTR_KIND_STACK_ALIGNMENT:
776 return Attribute::StackAlignment;
777 case bitc::ATTR_KIND_STACK_PROTECT:
778 return Attribute::StackProtect;
779 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
780 return Attribute::StackProtectReq;
781 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
782 return Attribute::StackProtectStrong;
783 case bitc::ATTR_KIND_STRUCT_RET:
784 return Attribute::StructRet;
785 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
786 return Attribute::SanitizeAddress;
787 case bitc::ATTR_KIND_SANITIZE_THREAD:
788 return Attribute::SanitizeThread;
789 case bitc::ATTR_KIND_SANITIZE_MEMORY:
790 return Attribute::SanitizeMemory;
791 case bitc::ATTR_KIND_UW_TABLE:
792 return Attribute::UWTable;
793 case bitc::ATTR_KIND_Z_EXT:
794 return Attribute::ZExt;
798 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
799 unsigned &Alignment) {
800 // Note: Alignment in bitcode files is incremented by 1, so that zero
801 // can be used for default alignment.
802 if (Exponent > Value::MaxAlignmentExponent + 1)
803 return Error("Invalid alignment value");
804 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
805 return std::error_code();
808 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
809 Attribute::AttrKind *Kind) {
810 *Kind = GetAttrFromCode(Code);
811 if (*Kind == Attribute::None)
812 return Error(BitcodeError::CorruptedBitcode,
813 "Unknown attribute kind (" + Twine(Code) + ")");
814 return std::error_code();
817 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
818 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
819 return Error("Invalid record");
821 if (!MAttributeGroups.empty())
822 return Error("Invalid multiple blocks");
824 SmallVector<uint64_t, 64> Record;
826 // Read all the records.
828 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
830 switch (Entry.Kind) {
831 case BitstreamEntry::SubBlock: // Handled for us already.
832 case BitstreamEntry::Error:
833 return Error("Malformed block");
834 case BitstreamEntry::EndBlock:
835 return std::error_code();
836 case BitstreamEntry::Record:
837 // The interesting case.
843 switch (Stream.readRecord(Entry.ID, Record)) {
844 default: // Default behavior: ignore.
846 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
847 if (Record.size() < 3)
848 return Error("Invalid record");
850 uint64_t GrpID = Record[0];
851 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
854 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
855 if (Record[i] == 0) { // Enum attribute
856 Attribute::AttrKind Kind;
857 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
860 B.addAttribute(Kind);
861 } else if (Record[i] == 1) { // Integer attribute
862 Attribute::AttrKind Kind;
863 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
865 if (Kind == Attribute::Alignment)
866 B.addAlignmentAttr(Record[++i]);
867 else if (Kind == Attribute::StackAlignment)
868 B.addStackAlignmentAttr(Record[++i]);
869 else if (Kind == Attribute::Dereferenceable)
870 B.addDereferenceableAttr(Record[++i]);
871 } else { // String attribute
872 assert((Record[i] == 3 || Record[i] == 4) &&
873 "Invalid attribute group entry");
874 bool HasValue = (Record[i++] == 4);
875 SmallString<64> KindStr;
876 SmallString<64> ValStr;
878 while (Record[i] != 0 && i != e)
879 KindStr += Record[i++];
880 assert(Record[i] == 0 && "Kind string not null terminated");
883 // Has a value associated with it.
884 ++i; // Skip the '0' that terminates the "kind" string.
885 while (Record[i] != 0 && i != e)
886 ValStr += Record[i++];
887 assert(Record[i] == 0 && "Value string not null terminated");
890 B.addAttribute(KindStr.str(), ValStr.str());
894 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
901 std::error_code BitcodeReader::ParseTypeTable() {
902 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
903 return Error("Invalid record");
905 return ParseTypeTableBody();
908 std::error_code BitcodeReader::ParseTypeTableBody() {
909 if (!TypeList.empty())
910 return Error("Invalid multiple blocks");
912 SmallVector<uint64_t, 64> Record;
913 unsigned NumRecords = 0;
915 SmallString<64> TypeName;
917 // Read all the records for this type table.
919 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
921 switch (Entry.Kind) {
922 case BitstreamEntry::SubBlock: // Handled for us already.
923 case BitstreamEntry::Error:
924 return Error("Malformed block");
925 case BitstreamEntry::EndBlock:
926 if (NumRecords != TypeList.size())
927 return Error("Malformed block");
928 return std::error_code();
929 case BitstreamEntry::Record:
930 // The interesting case.
936 Type *ResultTy = nullptr;
937 switch (Stream.readRecord(Entry.ID, Record)) {
939 return Error("Invalid value");
940 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
941 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
942 // type list. This allows us to reserve space.
943 if (Record.size() < 1)
944 return Error("Invalid record");
945 TypeList.resize(Record[0]);
947 case bitc::TYPE_CODE_VOID: // VOID
948 ResultTy = Type::getVoidTy(Context);
950 case bitc::TYPE_CODE_HALF: // HALF
951 ResultTy = Type::getHalfTy(Context);
953 case bitc::TYPE_CODE_FLOAT: // FLOAT
954 ResultTy = Type::getFloatTy(Context);
956 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
957 ResultTy = Type::getDoubleTy(Context);
959 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
960 ResultTy = Type::getX86_FP80Ty(Context);
962 case bitc::TYPE_CODE_FP128: // FP128
963 ResultTy = Type::getFP128Ty(Context);
965 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
966 ResultTy = Type::getPPC_FP128Ty(Context);
968 case bitc::TYPE_CODE_LABEL: // LABEL
969 ResultTy = Type::getLabelTy(Context);
971 case bitc::TYPE_CODE_METADATA: // METADATA
972 ResultTy = Type::getMetadataTy(Context);
974 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
975 ResultTy = Type::getX86_MMXTy(Context);
977 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
978 if (Record.size() < 1)
979 return Error("Invalid record");
981 uint64_t NumBits = Record[0];
982 if (NumBits < IntegerType::MIN_INT_BITS ||
983 NumBits > IntegerType::MAX_INT_BITS)
984 return Error("Bitwidth for integer type out of range");
985 ResultTy = IntegerType::get(Context, NumBits);
988 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
989 // [pointee type, address space]
990 if (Record.size() < 1)
991 return Error("Invalid record");
992 unsigned AddressSpace = 0;
993 if (Record.size() == 2)
994 AddressSpace = Record[1];
995 ResultTy = getTypeByID(Record[0]);
997 return Error("Invalid type");
998 ResultTy = PointerType::get(ResultTy, AddressSpace);
1001 case bitc::TYPE_CODE_FUNCTION_OLD: {
1002 // FIXME: attrid is dead, remove it in LLVM 4.0
1003 // FUNCTION: [vararg, attrid, retty, paramty x N]
1004 if (Record.size() < 3)
1005 return Error("Invalid record");
1006 SmallVector<Type*, 8> ArgTys;
1007 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1008 if (Type *T = getTypeByID(Record[i]))
1009 ArgTys.push_back(T);
1014 ResultTy = getTypeByID(Record[2]);
1015 if (!ResultTy || ArgTys.size() < Record.size()-3)
1016 return Error("Invalid type");
1018 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1021 case bitc::TYPE_CODE_FUNCTION: {
1022 // FUNCTION: [vararg, retty, paramty x N]
1023 if (Record.size() < 2)
1024 return Error("Invalid record");
1025 SmallVector<Type*, 8> ArgTys;
1026 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1027 if (Type *T = getTypeByID(Record[i]))
1028 ArgTys.push_back(T);
1033 ResultTy = getTypeByID(Record[1]);
1034 if (!ResultTy || ArgTys.size() < Record.size()-2)
1035 return Error("Invalid type");
1037 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1040 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1041 if (Record.size() < 1)
1042 return Error("Invalid record");
1043 SmallVector<Type*, 8> EltTys;
1044 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1045 if (Type *T = getTypeByID(Record[i]))
1046 EltTys.push_back(T);
1050 if (EltTys.size() != Record.size()-1)
1051 return Error("Invalid type");
1052 ResultTy = StructType::get(Context, EltTys, Record[0]);
1055 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1056 if (ConvertToString(Record, 0, TypeName))
1057 return Error("Invalid record");
1060 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1061 if (Record.size() < 1)
1062 return Error("Invalid record");
1064 if (NumRecords >= TypeList.size())
1065 return Error("Invalid TYPE table");
1067 // Check to see if this was forward referenced, if so fill in the temp.
1068 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1070 Res->setName(TypeName);
1071 TypeList[NumRecords] = nullptr;
1072 } else // Otherwise, create a new struct.
1073 Res = createIdentifiedStructType(Context, TypeName);
1076 SmallVector<Type*, 8> EltTys;
1077 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1078 if (Type *T = getTypeByID(Record[i]))
1079 EltTys.push_back(T);
1083 if (EltTys.size() != Record.size()-1)
1084 return Error("Invalid record");
1085 Res->setBody(EltTys, Record[0]);
1089 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1090 if (Record.size() != 1)
1091 return Error("Invalid record");
1093 if (NumRecords >= TypeList.size())
1094 return Error("Invalid TYPE table");
1096 // Check to see if this was forward referenced, if so fill in the temp.
1097 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1099 Res->setName(TypeName);
1100 TypeList[NumRecords] = nullptr;
1101 } else // Otherwise, create a new struct with no body.
1102 Res = createIdentifiedStructType(Context, TypeName);
1107 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1108 if (Record.size() < 2)
1109 return Error("Invalid record");
1110 if ((ResultTy = getTypeByID(Record[1])))
1111 ResultTy = ArrayType::get(ResultTy, Record[0]);
1113 return Error("Invalid type");
1115 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1116 if (Record.size() < 2)
1117 return Error("Invalid record");
1118 if ((ResultTy = getTypeByID(Record[1])))
1119 ResultTy = VectorType::get(ResultTy, Record[0]);
1121 return Error("Invalid type");
1125 if (NumRecords >= TypeList.size())
1126 return Error("Invalid TYPE table");
1127 if (TypeList[NumRecords])
1129 "Invalid TYPE table: Only named structs can be forward referenced");
1130 assert(ResultTy && "Didn't read a type?");
1131 TypeList[NumRecords++] = ResultTy;
1135 std::error_code BitcodeReader::ParseValueSymbolTable() {
1136 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1137 return Error("Invalid record");
1139 SmallVector<uint64_t, 64> Record;
1141 Triple TT(TheModule->getTargetTriple());
1143 // Read all the records for this value table.
1144 SmallString<128> ValueName;
1146 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1148 switch (Entry.Kind) {
1149 case BitstreamEntry::SubBlock: // Handled for us already.
1150 case BitstreamEntry::Error:
1151 return Error("Malformed block");
1152 case BitstreamEntry::EndBlock:
1153 return std::error_code();
1154 case BitstreamEntry::Record:
1155 // The interesting case.
1161 switch (Stream.readRecord(Entry.ID, Record)) {
1162 default: // Default behavior: unknown type.
1164 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1165 if (ConvertToString(Record, 1, ValueName))
1166 return Error("Invalid record");
1167 unsigned ValueID = Record[0];
1168 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1169 return Error("Invalid record");
1170 Value *V = ValueList[ValueID];
1172 V->setName(StringRef(ValueName.data(), ValueName.size()));
1173 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1174 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1175 if (TT.isOSBinFormatMachO())
1176 GO->setComdat(nullptr);
1178 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1184 case bitc::VST_CODE_BBENTRY: {
1185 if (ConvertToString(Record, 1, ValueName))
1186 return Error("Invalid record");
1187 BasicBlock *BB = getBasicBlock(Record[0]);
1189 return Error("Invalid record");
1191 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1199 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1201 std::error_code BitcodeReader::ParseMetadata() {
1202 unsigned NextMDValueNo = MDValueList.size();
1204 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1205 return Error("Invalid record");
1207 SmallVector<uint64_t, 64> Record;
1210 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1211 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1213 return getMD(ID - 1);
1216 auto getMDString = [&](unsigned ID) -> MDString *{
1217 // This requires that the ID is not really a forward reference. In
1218 // particular, the MDString must already have been resolved.
1219 return cast_or_null<MDString>(getMDOrNull(ID));
1222 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1223 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1225 // Read all the records.
1227 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1229 switch (Entry.Kind) {
1230 case BitstreamEntry::SubBlock: // Handled for us already.
1231 case BitstreamEntry::Error:
1232 return Error("Malformed block");
1233 case BitstreamEntry::EndBlock:
1234 MDValueList.tryToResolveCycles();
1235 return std::error_code();
1236 case BitstreamEntry::Record:
1237 // The interesting case.
1243 unsigned Code = Stream.readRecord(Entry.ID, Record);
1244 bool IsDistinct = false;
1246 default: // Default behavior: ignore.
1248 case bitc::METADATA_NAME: {
1249 // Read name of the named metadata.
1250 SmallString<8> Name(Record.begin(), Record.end());
1252 Code = Stream.ReadCode();
1254 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1255 unsigned NextBitCode = Stream.readRecord(Code, Record);
1256 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1258 // Read named metadata elements.
1259 unsigned Size = Record.size();
1260 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1261 for (unsigned i = 0; i != Size; ++i) {
1262 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1264 return Error("Invalid record");
1265 NMD->addOperand(MD);
1269 case bitc::METADATA_OLD_FN_NODE: {
1270 // FIXME: Remove in 4.0.
1271 // This is a LocalAsMetadata record, the only type of function-local
1273 if (Record.size() % 2 == 1)
1274 return Error("Invalid record");
1276 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1277 // to be legal, but there's no upgrade path.
1278 auto dropRecord = [&] {
1279 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1281 if (Record.size() != 2) {
1286 Type *Ty = getTypeByID(Record[0]);
1287 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1292 MDValueList.AssignValue(
1293 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1297 case bitc::METADATA_OLD_NODE: {
1298 // FIXME: Remove in 4.0.
1299 if (Record.size() % 2 == 1)
1300 return Error("Invalid record");
1302 unsigned Size = Record.size();
1303 SmallVector<Metadata *, 8> Elts;
1304 for (unsigned i = 0; i != Size; i += 2) {
1305 Type *Ty = getTypeByID(Record[i]);
1307 return Error("Invalid record");
1308 if (Ty->isMetadataTy())
1309 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1310 else if (!Ty->isVoidTy()) {
1312 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1313 assert(isa<ConstantAsMetadata>(MD) &&
1314 "Expected non-function-local metadata");
1317 Elts.push_back(nullptr);
1319 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1322 case bitc::METADATA_VALUE: {
1323 if (Record.size() != 2)
1324 return Error("Invalid record");
1326 Type *Ty = getTypeByID(Record[0]);
1327 if (Ty->isMetadataTy() || Ty->isVoidTy())
1328 return Error("Invalid record");
1330 MDValueList.AssignValue(
1331 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1335 case bitc::METADATA_DISTINCT_NODE:
1338 case bitc::METADATA_NODE: {
1339 SmallVector<Metadata *, 8> Elts;
1340 Elts.reserve(Record.size());
1341 for (unsigned ID : Record)
1342 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1343 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1344 : MDNode::get(Context, Elts),
1348 case bitc::METADATA_LOCATION: {
1349 if (Record.size() != 5)
1350 return Error("Invalid record");
1352 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get;
1353 unsigned Line = Record[1];
1354 unsigned Column = Record[2];
1355 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1356 Metadata *InlinedAt =
1357 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1358 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt),
1362 case bitc::METADATA_GENERIC_DEBUG: {
1363 if (Record.size() < 4)
1364 return Error("Invalid record");
1366 unsigned Tag = Record[1];
1367 unsigned Version = Record[2];
1369 if (Tag >= 1u << 16 || Version != 0)
1370 return Error("Invalid record");
1372 auto *Header = getMDString(Record[3]);
1373 SmallVector<Metadata *, 8> DwarfOps;
1374 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1375 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1377 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1378 (Context, Tag, Header, DwarfOps)),
1382 case bitc::METADATA_SUBRANGE: {
1383 if (Record.size() != 3)
1384 return Error("Invalid record");
1386 MDValueList.AssignValue(
1387 GET_OR_DISTINCT(MDSubrange, Record[0],
1388 (Context, Record[1], unrotateSign(Record[2]))),
1392 case bitc::METADATA_ENUMERATOR: {
1393 if (Record.size() != 3)
1394 return Error("Invalid record");
1396 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1397 (Context, unrotateSign(Record[1]),
1398 getMDString(Record[2]))),
1402 case bitc::METADATA_BASIC_TYPE: {
1403 if (Record.size() != 6)
1404 return Error("Invalid record");
1406 MDValueList.AssignValue(
1407 GET_OR_DISTINCT(MDBasicType, Record[0],
1408 (Context, Record[1], getMDString(Record[2]),
1409 Record[3], Record[4], Record[5])),
1413 case bitc::METADATA_DERIVED_TYPE: {
1414 if (Record.size() != 12)
1415 return Error("Invalid record");
1417 MDValueList.AssignValue(
1418 GET_OR_DISTINCT(MDDerivedType, Record[0],
1419 (Context, Record[1], getMDString(Record[2]),
1420 getMDOrNull(Record[3]), Record[4],
1421 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1422 Record[7], Record[8], Record[9], Record[10],
1423 getMDOrNull(Record[11]))),
1427 case bitc::METADATA_COMPOSITE_TYPE: {
1428 if (Record.size() != 16)
1429 return Error("Invalid record");
1431 MDValueList.AssignValue(
1432 GET_OR_DISTINCT(MDCompositeType, Record[0],
1433 (Context, Record[1], getMDString(Record[2]),
1434 getMDOrNull(Record[3]), Record[4],
1435 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1436 Record[7], Record[8], Record[9], Record[10],
1437 getMDOrNull(Record[11]), Record[12],
1438 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1439 getMDString(Record[15]))),
1443 case bitc::METADATA_SUBROUTINE_TYPE: {
1444 if (Record.size() != 3)
1445 return Error("Invalid record");
1447 MDValueList.AssignValue(
1448 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1449 (Context, Record[1], getMDOrNull(Record[2]))),
1453 case bitc::METADATA_FILE: {
1454 if (Record.size() != 3)
1455 return Error("Invalid record");
1457 MDValueList.AssignValue(
1458 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1459 getMDString(Record[2]))),
1463 case bitc::METADATA_COMPILE_UNIT: {
1464 if (Record.size() != 14)
1465 return Error("Invalid record");
1467 MDValueList.AssignValue(
1468 GET_OR_DISTINCT(MDCompileUnit, Record[0],
1469 (Context, Record[1], getMDOrNull(Record[2]),
1470 getMDString(Record[3]), Record[4],
1471 getMDString(Record[5]), Record[6],
1472 getMDString(Record[7]), Record[8],
1473 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1474 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1475 getMDOrNull(Record[13]))),
1479 case bitc::METADATA_SUBPROGRAM: {
1480 if (Record.size() != 19)
1481 return Error("Invalid record");
1483 MDValueList.AssignValue(
1485 MDSubprogram, Record[0],
1486 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1487 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1488 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1489 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1490 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1491 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1495 case bitc::METADATA_LEXICAL_BLOCK: {
1496 if (Record.size() != 5)
1497 return Error("Invalid record");
1499 MDValueList.AssignValue(
1500 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1501 (Context, getMDOrNull(Record[1]),
1502 getMDOrNull(Record[2]), Record[3], Record[4])),
1506 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1507 if (Record.size() != 4)
1508 return Error("Invalid record");
1510 MDValueList.AssignValue(
1511 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1512 (Context, getMDOrNull(Record[1]),
1513 getMDOrNull(Record[2]), Record[3])),
1517 case bitc::METADATA_NAMESPACE: {
1518 if (Record.size() != 5)
1519 return Error("Invalid record");
1521 MDValueList.AssignValue(
1522 GET_OR_DISTINCT(MDNamespace, Record[0],
1523 (Context, getMDOrNull(Record[1]),
1524 getMDOrNull(Record[2]), getMDString(Record[3]),
1529 case bitc::METADATA_TEMPLATE_TYPE: {
1530 if (Record.size() != 3)
1531 return Error("Invalid record");
1533 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1535 (Context, getMDString(Record[1]),
1536 getMDOrNull(Record[2]))),
1540 case bitc::METADATA_TEMPLATE_VALUE: {
1541 if (Record.size() != 5)
1542 return Error("Invalid record");
1544 MDValueList.AssignValue(
1545 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1546 (Context, Record[1], getMDString(Record[2]),
1547 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1551 case bitc::METADATA_GLOBAL_VAR: {
1552 if (Record.size() != 11)
1553 return Error("Invalid record");
1555 MDValueList.AssignValue(
1556 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1557 (Context, getMDOrNull(Record[1]),
1558 getMDString(Record[2]), getMDString(Record[3]),
1559 getMDOrNull(Record[4]), Record[5],
1560 getMDOrNull(Record[6]), Record[7], Record[8],
1561 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1565 case bitc::METADATA_LOCAL_VAR: {
1566 if (Record.size() != 10)
1567 return Error("Invalid record");
1569 MDValueList.AssignValue(
1570 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1571 (Context, Record[1], getMDOrNull(Record[2]),
1572 getMDString(Record[3]), getMDOrNull(Record[4]),
1573 Record[5], getMDOrNull(Record[6]), Record[7],
1574 Record[8], getMDOrNull(Record[9]))),
1578 case bitc::METADATA_EXPRESSION: {
1579 if (Record.size() < 1)
1580 return Error("Invalid record");
1582 MDValueList.AssignValue(
1583 GET_OR_DISTINCT(MDExpression, Record[0],
1584 (Context, makeArrayRef(Record).slice(1))),
1588 case bitc::METADATA_OBJC_PROPERTY: {
1589 if (Record.size() != 8)
1590 return Error("Invalid record");
1592 MDValueList.AssignValue(
1593 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1594 (Context, getMDString(Record[1]),
1595 getMDOrNull(Record[2]), Record[3],
1596 getMDString(Record[4]), getMDString(Record[5]),
1597 Record[6], getMDOrNull(Record[7]))),
1601 case bitc::METADATA_IMPORTED_ENTITY: {
1602 if (Record.size() != 6)
1603 return Error("Invalid record");
1605 MDValueList.AssignValue(
1606 GET_OR_DISTINCT(MDImportedEntity, Record[0],
1607 (Context, Record[1], getMDOrNull(Record[2]),
1608 getMDOrNull(Record[3]), Record[4],
1609 getMDString(Record[5]))),
1613 case bitc::METADATA_STRING: {
1614 std::string String(Record.begin(), Record.end());
1615 llvm::UpgradeMDStringConstant(String);
1616 Metadata *MD = MDString::get(Context, String);
1617 MDValueList.AssignValue(MD, NextMDValueNo++);
1620 case bitc::METADATA_KIND: {
1621 if (Record.size() < 2)
1622 return Error("Invalid record");
1624 unsigned Kind = Record[0];
1625 SmallString<8> Name(Record.begin()+1, Record.end());
1627 unsigned NewKind = TheModule->getMDKindID(Name.str());
1628 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1629 return Error("Conflicting METADATA_KIND records");
1634 #undef GET_OR_DISTINCT
1637 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1638 /// the LSB for dense VBR encoding.
1639 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1644 // There is no such thing as -0 with integers. "-0" really means MININT.
1648 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1649 /// values and aliases that we can.
1650 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1651 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1652 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1653 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1654 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1656 GlobalInitWorklist.swap(GlobalInits);
1657 AliasInitWorklist.swap(AliasInits);
1658 FunctionPrefixWorklist.swap(FunctionPrefixes);
1659 FunctionPrologueWorklist.swap(FunctionPrologues);
1661 while (!GlobalInitWorklist.empty()) {
1662 unsigned ValID = GlobalInitWorklist.back().second;
1663 if (ValID >= ValueList.size()) {
1664 // Not ready to resolve this yet, it requires something later in the file.
1665 GlobalInits.push_back(GlobalInitWorklist.back());
1667 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1668 GlobalInitWorklist.back().first->setInitializer(C);
1670 return Error("Expected a constant");
1672 GlobalInitWorklist.pop_back();
1675 while (!AliasInitWorklist.empty()) {
1676 unsigned ValID = AliasInitWorklist.back().second;
1677 if (ValID >= ValueList.size()) {
1678 AliasInits.push_back(AliasInitWorklist.back());
1680 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1681 AliasInitWorklist.back().first->setAliasee(C);
1683 return Error("Expected a constant");
1685 AliasInitWorklist.pop_back();
1688 while (!FunctionPrefixWorklist.empty()) {
1689 unsigned ValID = FunctionPrefixWorklist.back().second;
1690 if (ValID >= ValueList.size()) {
1691 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1693 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1694 FunctionPrefixWorklist.back().first->setPrefixData(C);
1696 return Error("Expected a constant");
1698 FunctionPrefixWorklist.pop_back();
1701 while (!FunctionPrologueWorklist.empty()) {
1702 unsigned ValID = FunctionPrologueWorklist.back().second;
1703 if (ValID >= ValueList.size()) {
1704 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1706 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1707 FunctionPrologueWorklist.back().first->setPrologueData(C);
1709 return Error("Expected a constant");
1711 FunctionPrologueWorklist.pop_back();
1714 return std::error_code();
1717 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1718 SmallVector<uint64_t, 8> Words(Vals.size());
1719 std::transform(Vals.begin(), Vals.end(), Words.begin(),
1720 BitcodeReader::decodeSignRotatedValue);
1722 return APInt(TypeBits, Words);
1725 std::error_code BitcodeReader::ParseConstants() {
1726 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1727 return Error("Invalid record");
1729 SmallVector<uint64_t, 64> Record;
1731 // Read all the records for this value table.
1732 Type *CurTy = Type::getInt32Ty(Context);
1733 unsigned NextCstNo = ValueList.size();
1735 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1737 switch (Entry.Kind) {
1738 case BitstreamEntry::SubBlock: // Handled for us already.
1739 case BitstreamEntry::Error:
1740 return Error("Malformed block");
1741 case BitstreamEntry::EndBlock:
1742 if (NextCstNo != ValueList.size())
1743 return Error("Invalid ronstant reference");
1745 // Once all the constants have been read, go through and resolve forward
1747 ValueList.ResolveConstantForwardRefs();
1748 return std::error_code();
1749 case BitstreamEntry::Record:
1750 // The interesting case.
1757 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1759 default: // Default behavior: unknown constant
1760 case bitc::CST_CODE_UNDEF: // UNDEF
1761 V = UndefValue::get(CurTy);
1763 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1765 return Error("Invalid record");
1766 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1767 return Error("Invalid record");
1768 CurTy = TypeList[Record[0]];
1769 continue; // Skip the ValueList manipulation.
1770 case bitc::CST_CODE_NULL: // NULL
1771 V = Constant::getNullValue(CurTy);
1773 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1774 if (!CurTy->isIntegerTy() || Record.empty())
1775 return Error("Invalid record");
1776 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1778 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1779 if (!CurTy->isIntegerTy() || Record.empty())
1780 return Error("Invalid record");
1782 APInt VInt = ReadWideAPInt(Record,
1783 cast<IntegerType>(CurTy)->getBitWidth());
1784 V = ConstantInt::get(Context, VInt);
1788 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
1790 return Error("Invalid record");
1791 if (CurTy->isHalfTy())
1792 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1793 APInt(16, (uint16_t)Record[0])));
1794 else if (CurTy->isFloatTy())
1795 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1796 APInt(32, (uint32_t)Record[0])));
1797 else if (CurTy->isDoubleTy())
1798 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1799 APInt(64, Record[0])));
1800 else if (CurTy->isX86_FP80Ty()) {
1801 // Bits are not stored the same way as a normal i80 APInt, compensate.
1802 uint64_t Rearrange[2];
1803 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1804 Rearrange[1] = Record[0] >> 48;
1805 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1806 APInt(80, Rearrange)));
1807 } else if (CurTy->isFP128Ty())
1808 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1809 APInt(128, Record)));
1810 else if (CurTy->isPPC_FP128Ty())
1811 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1812 APInt(128, Record)));
1814 V = UndefValue::get(CurTy);
1818 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1820 return Error("Invalid record");
1822 unsigned Size = Record.size();
1823 SmallVector<Constant*, 16> Elts;
1825 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1826 for (unsigned i = 0; i != Size; ++i)
1827 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1828 STy->getElementType(i)));
1829 V = ConstantStruct::get(STy, Elts);
1830 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1831 Type *EltTy = ATy->getElementType();
1832 for (unsigned i = 0; i != Size; ++i)
1833 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1834 V = ConstantArray::get(ATy, Elts);
1835 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1836 Type *EltTy = VTy->getElementType();
1837 for (unsigned i = 0; i != Size; ++i)
1838 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1839 V = ConstantVector::get(Elts);
1841 V = UndefValue::get(CurTy);
1845 case bitc::CST_CODE_STRING: // STRING: [values]
1846 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1848 return Error("Invalid record");
1850 SmallString<16> Elts(Record.begin(), Record.end());
1851 V = ConstantDataArray::getString(Context, Elts,
1852 BitCode == bitc::CST_CODE_CSTRING);
1855 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1857 return Error("Invalid record");
1859 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1860 unsigned Size = Record.size();
1862 if (EltTy->isIntegerTy(8)) {
1863 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1864 if (isa<VectorType>(CurTy))
1865 V = ConstantDataVector::get(Context, Elts);
1867 V = ConstantDataArray::get(Context, Elts);
1868 } else if (EltTy->isIntegerTy(16)) {
1869 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1870 if (isa<VectorType>(CurTy))
1871 V = ConstantDataVector::get(Context, Elts);
1873 V = ConstantDataArray::get(Context, Elts);
1874 } else if (EltTy->isIntegerTy(32)) {
1875 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1876 if (isa<VectorType>(CurTy))
1877 V = ConstantDataVector::get(Context, Elts);
1879 V = ConstantDataArray::get(Context, Elts);
1880 } else if (EltTy->isIntegerTy(64)) {
1881 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1882 if (isa<VectorType>(CurTy))
1883 V = ConstantDataVector::get(Context, Elts);
1885 V = ConstantDataArray::get(Context, Elts);
1886 } else if (EltTy->isFloatTy()) {
1887 SmallVector<float, 16> Elts(Size);
1888 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1889 if (isa<VectorType>(CurTy))
1890 V = ConstantDataVector::get(Context, Elts);
1892 V = ConstantDataArray::get(Context, Elts);
1893 } else if (EltTy->isDoubleTy()) {
1894 SmallVector<double, 16> Elts(Size);
1895 std::transform(Record.begin(), Record.end(), Elts.begin(),
1897 if (isa<VectorType>(CurTy))
1898 V = ConstantDataVector::get(Context, Elts);
1900 V = ConstantDataArray::get(Context, Elts);
1902 return Error("Invalid type for value");
1907 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1908 if (Record.size() < 3)
1909 return Error("Invalid record");
1910 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1912 V = UndefValue::get(CurTy); // Unknown binop.
1914 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1915 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1917 if (Record.size() >= 4) {
1918 if (Opc == Instruction::Add ||
1919 Opc == Instruction::Sub ||
1920 Opc == Instruction::Mul ||
1921 Opc == Instruction::Shl) {
1922 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1923 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1924 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1925 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1926 } else if (Opc == Instruction::SDiv ||
1927 Opc == Instruction::UDiv ||
1928 Opc == Instruction::LShr ||
1929 Opc == Instruction::AShr) {
1930 if (Record[3] & (1 << bitc::PEO_EXACT))
1931 Flags |= SDivOperator::IsExact;
1934 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1938 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1939 if (Record.size() < 3)
1940 return Error("Invalid record");
1941 int Opc = GetDecodedCastOpcode(Record[0]);
1943 V = UndefValue::get(CurTy); // Unknown cast.
1945 Type *OpTy = getTypeByID(Record[1]);
1947 return Error("Invalid record");
1948 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1949 V = UpgradeBitCastExpr(Opc, Op, CurTy);
1950 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1954 case bitc::CST_CODE_CE_INBOUNDS_GEP:
1955 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1956 if (Record.size() & 1)
1957 return Error("Invalid record");
1958 SmallVector<Constant*, 16> Elts;
1959 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1960 Type *ElTy = getTypeByID(Record[i]);
1962 return Error("Invalid record");
1963 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1965 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1966 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1968 bitc::CST_CODE_CE_INBOUNDS_GEP);
1971 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
1972 if (Record.size() < 3)
1973 return Error("Invalid record");
1975 Type *SelectorTy = Type::getInt1Ty(Context);
1977 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1978 // vector. Otherwise, it must be a single bit.
1979 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1980 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1981 VTy->getNumElements());
1983 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1985 ValueList.getConstantFwdRef(Record[1],CurTy),
1986 ValueList.getConstantFwdRef(Record[2],CurTy));
1989 case bitc::CST_CODE_CE_EXTRACTELT
1990 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1991 if (Record.size() < 3)
1992 return Error("Invalid record");
1994 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1996 return Error("Invalid record");
1997 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1998 Constant *Op1 = nullptr;
1999 if (Record.size() == 4) {
2000 Type *IdxTy = getTypeByID(Record[2]);
2002 return Error("Invalid record");
2003 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2004 } else // TODO: Remove with llvm 4.0
2005 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2007 return Error("Invalid record");
2008 V = ConstantExpr::getExtractElement(Op0, Op1);
2011 case bitc::CST_CODE_CE_INSERTELT
2012 : { // CE_INSERTELT: [opval, opval, opty, opval]
2013 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2014 if (Record.size() < 3 || !OpTy)
2015 return Error("Invalid record");
2016 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2017 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2018 OpTy->getElementType());
2019 Constant *Op2 = nullptr;
2020 if (Record.size() == 4) {
2021 Type *IdxTy = getTypeByID(Record[2]);
2023 return Error("Invalid record");
2024 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2025 } else // TODO: Remove with llvm 4.0
2026 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2028 return Error("Invalid record");
2029 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2032 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2033 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2034 if (Record.size() < 3 || !OpTy)
2035 return Error("Invalid record");
2036 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2037 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2038 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2039 OpTy->getNumElements());
2040 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2041 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2044 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2045 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2047 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2048 if (Record.size() < 4 || !RTy || !OpTy)
2049 return Error("Invalid record");
2050 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2051 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2052 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2053 RTy->getNumElements());
2054 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2055 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2058 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2059 if (Record.size() < 4)
2060 return Error("Invalid record");
2061 Type *OpTy = getTypeByID(Record[0]);
2063 return Error("Invalid record");
2064 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2065 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2067 if (OpTy->isFPOrFPVectorTy())
2068 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2070 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2073 // This maintains backward compatibility, pre-asm dialect keywords.
2074 // FIXME: Remove with the 4.0 release.
2075 case bitc::CST_CODE_INLINEASM_OLD: {
2076 if (Record.size() < 2)
2077 return Error("Invalid record");
2078 std::string AsmStr, ConstrStr;
2079 bool HasSideEffects = Record[0] & 1;
2080 bool IsAlignStack = Record[0] >> 1;
2081 unsigned AsmStrSize = Record[1];
2082 if (2+AsmStrSize >= Record.size())
2083 return Error("Invalid record");
2084 unsigned ConstStrSize = Record[2+AsmStrSize];
2085 if (3+AsmStrSize+ConstStrSize > Record.size())
2086 return Error("Invalid record");
2088 for (unsigned i = 0; i != AsmStrSize; ++i)
2089 AsmStr += (char)Record[2+i];
2090 for (unsigned i = 0; i != ConstStrSize; ++i)
2091 ConstrStr += (char)Record[3+AsmStrSize+i];
2092 PointerType *PTy = cast<PointerType>(CurTy);
2093 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2094 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2097 // This version adds support for the asm dialect keywords (e.g.,
2099 case bitc::CST_CODE_INLINEASM: {
2100 if (Record.size() < 2)
2101 return Error("Invalid record");
2102 std::string AsmStr, ConstrStr;
2103 bool HasSideEffects = Record[0] & 1;
2104 bool IsAlignStack = (Record[0] >> 1) & 1;
2105 unsigned AsmDialect = Record[0] >> 2;
2106 unsigned AsmStrSize = Record[1];
2107 if (2+AsmStrSize >= Record.size())
2108 return Error("Invalid record");
2109 unsigned ConstStrSize = Record[2+AsmStrSize];
2110 if (3+AsmStrSize+ConstStrSize > Record.size())
2111 return Error("Invalid record");
2113 for (unsigned i = 0; i != AsmStrSize; ++i)
2114 AsmStr += (char)Record[2+i];
2115 for (unsigned i = 0; i != ConstStrSize; ++i)
2116 ConstrStr += (char)Record[3+AsmStrSize+i];
2117 PointerType *PTy = cast<PointerType>(CurTy);
2118 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2119 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2120 InlineAsm::AsmDialect(AsmDialect));
2123 case bitc::CST_CODE_BLOCKADDRESS:{
2124 if (Record.size() < 3)
2125 return Error("Invalid record");
2126 Type *FnTy = getTypeByID(Record[0]);
2128 return Error("Invalid record");
2130 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2132 return Error("Invalid record");
2134 // Don't let Fn get dematerialized.
2135 BlockAddressesTaken.insert(Fn);
2137 // If the function is already parsed we can insert the block address right
2140 unsigned BBID = Record[2];
2142 // Invalid reference to entry block.
2143 return Error("Invalid ID");
2145 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2146 for (size_t I = 0, E = BBID; I != E; ++I) {
2148 return Error("Invalid ID");
2153 // Otherwise insert a placeholder and remember it so it can be inserted
2154 // when the function is parsed.
2155 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2157 BasicBlockFwdRefQueue.push_back(Fn);
2158 if (FwdBBs.size() < BBID + 1)
2159 FwdBBs.resize(BBID + 1);
2161 FwdBBs[BBID] = BasicBlock::Create(Context);
2164 V = BlockAddress::get(Fn, BB);
2169 ValueList.AssignValue(V, NextCstNo);
2174 std::error_code BitcodeReader::ParseUseLists() {
2175 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2176 return Error("Invalid record");
2178 // Read all the records.
2179 SmallVector<uint64_t, 64> Record;
2181 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2183 switch (Entry.Kind) {
2184 case BitstreamEntry::SubBlock: // Handled for us already.
2185 case BitstreamEntry::Error:
2186 return Error("Malformed block");
2187 case BitstreamEntry::EndBlock:
2188 return std::error_code();
2189 case BitstreamEntry::Record:
2190 // The interesting case.
2194 // Read a use list record.
2197 switch (Stream.readRecord(Entry.ID, Record)) {
2198 default: // Default behavior: unknown type.
2200 case bitc::USELIST_CODE_BB:
2203 case bitc::USELIST_CODE_DEFAULT: {
2204 unsigned RecordLength = Record.size();
2205 if (RecordLength < 3)
2206 // Records should have at least an ID and two indexes.
2207 return Error("Invalid record");
2208 unsigned ID = Record.back();
2213 assert(ID < FunctionBBs.size() && "Basic block not found");
2214 V = FunctionBBs[ID];
2217 unsigned NumUses = 0;
2218 SmallDenseMap<const Use *, unsigned, 16> Order;
2219 for (const Use &U : V->uses()) {
2220 if (++NumUses > Record.size())
2222 Order[&U] = Record[NumUses - 1];
2224 if (Order.size() != Record.size() || NumUses > Record.size())
2225 // Mismatches can happen if the functions are being materialized lazily
2226 // (out-of-order), or a value has been upgraded.
2229 V->sortUseList([&](const Use &L, const Use &R) {
2230 return Order.lookup(&L) < Order.lookup(&R);
2238 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2239 /// remember where it is and then skip it. This lets us lazily deserialize the
2241 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2242 // Get the function we are talking about.
2243 if (FunctionsWithBodies.empty())
2244 return Error("Insufficient function protos");
2246 Function *Fn = FunctionsWithBodies.back();
2247 FunctionsWithBodies.pop_back();
2249 // Save the current stream state.
2250 uint64_t CurBit = Stream.GetCurrentBitNo();
2251 DeferredFunctionInfo[Fn] = CurBit;
2253 // Skip over the function block for now.
2254 if (Stream.SkipBlock())
2255 return Error("Invalid record");
2256 return std::error_code();
2259 std::error_code BitcodeReader::GlobalCleanup() {
2260 // Patch the initializers for globals and aliases up.
2261 ResolveGlobalAndAliasInits();
2262 if (!GlobalInits.empty() || !AliasInits.empty())
2263 return Error("Malformed global initializer set");
2265 // Look for intrinsic functions which need to be upgraded at some point
2266 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2269 if (UpgradeIntrinsicFunction(FI, NewFn))
2270 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2273 // Look for global variables which need to be renamed.
2274 for (Module::global_iterator
2275 GI = TheModule->global_begin(), GE = TheModule->global_end();
2277 GlobalVariable *GV = GI++;
2278 UpgradeGlobalVariable(GV);
2281 // Force deallocation of memory for these vectors to favor the client that
2282 // want lazy deserialization.
2283 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2284 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2285 return std::error_code();
2288 std::error_code BitcodeReader::ParseModule(bool Resume) {
2290 Stream.JumpToBit(NextUnreadBit);
2291 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2292 return Error("Invalid record");
2294 SmallVector<uint64_t, 64> Record;
2295 std::vector<std::string> SectionTable;
2296 std::vector<std::string> GCTable;
2298 // Read all the records for this module.
2300 BitstreamEntry Entry = Stream.advance();
2302 switch (Entry.Kind) {
2303 case BitstreamEntry::Error:
2304 return Error("Malformed block");
2305 case BitstreamEntry::EndBlock:
2306 return GlobalCleanup();
2308 case BitstreamEntry::SubBlock:
2310 default: // Skip unknown content.
2311 if (Stream.SkipBlock())
2312 return Error("Invalid record");
2314 case bitc::BLOCKINFO_BLOCK_ID:
2315 if (Stream.ReadBlockInfoBlock())
2316 return Error("Malformed block");
2318 case bitc::PARAMATTR_BLOCK_ID:
2319 if (std::error_code EC = ParseAttributeBlock())
2322 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2323 if (std::error_code EC = ParseAttributeGroupBlock())
2326 case bitc::TYPE_BLOCK_ID_NEW:
2327 if (std::error_code EC = ParseTypeTable())
2330 case bitc::VALUE_SYMTAB_BLOCK_ID:
2331 if (std::error_code EC = ParseValueSymbolTable())
2333 SeenValueSymbolTable = true;
2335 case bitc::CONSTANTS_BLOCK_ID:
2336 if (std::error_code EC = ParseConstants())
2338 if (std::error_code EC = ResolveGlobalAndAliasInits())
2341 case bitc::METADATA_BLOCK_ID:
2342 if (std::error_code EC = ParseMetadata())
2345 case bitc::FUNCTION_BLOCK_ID:
2346 // If this is the first function body we've seen, reverse the
2347 // FunctionsWithBodies list.
2348 if (!SeenFirstFunctionBody) {
2349 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2350 if (std::error_code EC = GlobalCleanup())
2352 SeenFirstFunctionBody = true;
2355 if (std::error_code EC = RememberAndSkipFunctionBody())
2357 // For streaming bitcode, suspend parsing when we reach the function
2358 // bodies. Subsequent materialization calls will resume it when
2359 // necessary. For streaming, the function bodies must be at the end of
2360 // the bitcode. If the bitcode file is old, the symbol table will be
2361 // at the end instead and will not have been seen yet. In this case,
2362 // just finish the parse now.
2363 if (LazyStreamer && SeenValueSymbolTable) {
2364 NextUnreadBit = Stream.GetCurrentBitNo();
2365 return std::error_code();
2368 case bitc::USELIST_BLOCK_ID:
2369 if (std::error_code EC = ParseUseLists())
2375 case BitstreamEntry::Record:
2376 // The interesting case.
2382 switch (Stream.readRecord(Entry.ID, Record)) {
2383 default: break; // Default behavior, ignore unknown content.
2384 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2385 if (Record.size() < 1)
2386 return Error("Invalid record");
2387 // Only version #0 and #1 are supported so far.
2388 unsigned module_version = Record[0];
2389 switch (module_version) {
2391 return Error("Invalid value");
2393 UseRelativeIDs = false;
2396 UseRelativeIDs = true;
2401 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2403 if (ConvertToString(Record, 0, S))
2404 return Error("Invalid record");
2405 TheModule->setTargetTriple(S);
2408 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2410 if (ConvertToString(Record, 0, S))
2411 return Error("Invalid record");
2412 TheModule->setDataLayout(S);
2415 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2417 if (ConvertToString(Record, 0, S))
2418 return Error("Invalid record");
2419 TheModule->setModuleInlineAsm(S);
2422 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2423 // FIXME: Remove in 4.0.
2425 if (ConvertToString(Record, 0, S))
2426 return Error("Invalid record");
2430 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2432 if (ConvertToString(Record, 0, S))
2433 return Error("Invalid record");
2434 SectionTable.push_back(S);
2437 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2439 if (ConvertToString(Record, 0, S))
2440 return Error("Invalid record");
2441 GCTable.push_back(S);
2444 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2445 if (Record.size() < 2)
2446 return Error("Invalid record");
2447 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2448 unsigned ComdatNameSize = Record[1];
2449 std::string ComdatName;
2450 ComdatName.reserve(ComdatNameSize);
2451 for (unsigned i = 0; i != ComdatNameSize; ++i)
2452 ComdatName += (char)Record[2 + i];
2453 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2454 C->setSelectionKind(SK);
2455 ComdatList.push_back(C);
2458 // GLOBALVAR: [pointer type, isconst, initid,
2459 // linkage, alignment, section, visibility, threadlocal,
2460 // unnamed_addr, externally_initialized, dllstorageclass,
2462 case bitc::MODULE_CODE_GLOBALVAR: {
2463 if (Record.size() < 6)
2464 return Error("Invalid record");
2465 Type *Ty = getTypeByID(Record[0]);
2467 return Error("Invalid record");
2468 if (!Ty->isPointerTy())
2469 return Error("Invalid type for value");
2470 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2471 Ty = cast<PointerType>(Ty)->getElementType();
2473 bool isConstant = Record[1];
2474 uint64_t RawLinkage = Record[3];
2475 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2477 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2479 std::string Section;
2481 if (Record[5]-1 >= SectionTable.size())
2482 return Error("Invalid ID");
2483 Section = SectionTable[Record[5]-1];
2485 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2486 // Local linkage must have default visibility.
2487 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2488 // FIXME: Change to an error if non-default in 4.0.
2489 Visibility = GetDecodedVisibility(Record[6]);
2491 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2492 if (Record.size() > 7)
2493 TLM = GetDecodedThreadLocalMode(Record[7]);
2495 bool UnnamedAddr = false;
2496 if (Record.size() > 8)
2497 UnnamedAddr = Record[8];
2499 bool ExternallyInitialized = false;
2500 if (Record.size() > 9)
2501 ExternallyInitialized = Record[9];
2503 GlobalVariable *NewGV =
2504 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2505 TLM, AddressSpace, ExternallyInitialized);
2506 NewGV->setAlignment(Alignment);
2507 if (!Section.empty())
2508 NewGV->setSection(Section);
2509 NewGV->setVisibility(Visibility);
2510 NewGV->setUnnamedAddr(UnnamedAddr);
2512 if (Record.size() > 10)
2513 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2515 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2517 ValueList.push_back(NewGV);
2519 // Remember which value to use for the global initializer.
2520 if (unsigned InitID = Record[2])
2521 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2523 if (Record.size() > 11) {
2524 if (unsigned ComdatID = Record[11]) {
2525 assert(ComdatID <= ComdatList.size());
2526 NewGV->setComdat(ComdatList[ComdatID - 1]);
2528 } else if (hasImplicitComdat(RawLinkage)) {
2529 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2533 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2534 // alignment, section, visibility, gc, unnamed_addr,
2535 // prologuedata, dllstorageclass, comdat, prefixdata]
2536 case bitc::MODULE_CODE_FUNCTION: {
2537 if (Record.size() < 8)
2538 return Error("Invalid record");
2539 Type *Ty = getTypeByID(Record[0]);
2541 return Error("Invalid record");
2542 if (!Ty->isPointerTy())
2543 return Error("Invalid type for value");
2545 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2547 return Error("Invalid type for value");
2549 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2552 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2553 bool isProto = Record[2];
2554 uint64_t RawLinkage = Record[3];
2555 Func->setLinkage(getDecodedLinkage(RawLinkage));
2556 Func->setAttributes(getAttributes(Record[4]));
2559 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2561 Func->setAlignment(Alignment);
2563 if (Record[6]-1 >= SectionTable.size())
2564 return Error("Invalid ID");
2565 Func->setSection(SectionTable[Record[6]-1]);
2567 // Local linkage must have default visibility.
2568 if (!Func->hasLocalLinkage())
2569 // FIXME: Change to an error if non-default in 4.0.
2570 Func->setVisibility(GetDecodedVisibility(Record[7]));
2571 if (Record.size() > 8 && Record[8]) {
2572 if (Record[8]-1 > GCTable.size())
2573 return Error("Invalid ID");
2574 Func->setGC(GCTable[Record[8]-1].c_str());
2576 bool UnnamedAddr = false;
2577 if (Record.size() > 9)
2578 UnnamedAddr = Record[9];
2579 Func->setUnnamedAddr(UnnamedAddr);
2580 if (Record.size() > 10 && Record[10] != 0)
2581 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2583 if (Record.size() > 11)
2584 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2586 UpgradeDLLImportExportLinkage(Func, RawLinkage);
2588 if (Record.size() > 12) {
2589 if (unsigned ComdatID = Record[12]) {
2590 assert(ComdatID <= ComdatList.size());
2591 Func->setComdat(ComdatList[ComdatID - 1]);
2593 } else if (hasImplicitComdat(RawLinkage)) {
2594 Func->setComdat(reinterpret_cast<Comdat *>(1));
2597 if (Record.size() > 13 && Record[13] != 0)
2598 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2600 ValueList.push_back(Func);
2602 // If this is a function with a body, remember the prototype we are
2603 // creating now, so that we can match up the body with them later.
2605 Func->setIsMaterializable(true);
2606 FunctionsWithBodies.push_back(Func);
2608 DeferredFunctionInfo[Func] = 0;
2612 // ALIAS: [alias type, aliasee val#, linkage]
2613 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2614 case bitc::MODULE_CODE_ALIAS: {
2615 if (Record.size() < 3)
2616 return Error("Invalid record");
2617 Type *Ty = getTypeByID(Record[0]);
2619 return Error("Invalid record");
2620 auto *PTy = dyn_cast<PointerType>(Ty);
2622 return Error("Invalid type for value");
2625 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2626 getDecodedLinkage(Record[2]), "", TheModule);
2627 // Old bitcode files didn't have visibility field.
2628 // Local linkage must have default visibility.
2629 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2630 // FIXME: Change to an error if non-default in 4.0.
2631 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2632 if (Record.size() > 4)
2633 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2635 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2636 if (Record.size() > 5)
2637 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2638 if (Record.size() > 6)
2639 NewGA->setUnnamedAddr(Record[6]);
2640 ValueList.push_back(NewGA);
2641 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2644 /// MODULE_CODE_PURGEVALS: [numvals]
2645 case bitc::MODULE_CODE_PURGEVALS:
2646 // Trim down the value list to the specified size.
2647 if (Record.size() < 1 || Record[0] > ValueList.size())
2648 return Error("Invalid record");
2649 ValueList.shrinkTo(Record[0]);
2656 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2657 TheModule = nullptr;
2659 if (std::error_code EC = InitStream())
2662 // Sniff for the signature.
2663 if (Stream.Read(8) != 'B' ||
2664 Stream.Read(8) != 'C' ||
2665 Stream.Read(4) != 0x0 ||
2666 Stream.Read(4) != 0xC ||
2667 Stream.Read(4) != 0xE ||
2668 Stream.Read(4) != 0xD)
2669 return Error("Invalid bitcode signature");
2671 // We expect a number of well-defined blocks, though we don't necessarily
2672 // need to understand them all.
2674 if (Stream.AtEndOfStream())
2675 return std::error_code();
2677 BitstreamEntry Entry =
2678 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2680 switch (Entry.Kind) {
2681 case BitstreamEntry::Error:
2682 return Error("Malformed block");
2683 case BitstreamEntry::EndBlock:
2684 return std::error_code();
2686 case BitstreamEntry::SubBlock:
2688 case bitc::BLOCKINFO_BLOCK_ID:
2689 if (Stream.ReadBlockInfoBlock())
2690 return Error("Malformed block");
2692 case bitc::MODULE_BLOCK_ID:
2693 // Reject multiple MODULE_BLOCK's in a single bitstream.
2695 return Error("Invalid multiple blocks");
2697 if (std::error_code EC = ParseModule(false))
2700 return std::error_code();
2703 if (Stream.SkipBlock())
2704 return Error("Invalid record");
2708 case BitstreamEntry::Record:
2709 // There should be no records in the top-level of blocks.
2711 // The ranlib in Xcode 4 will align archive members by appending newlines
2712 // to the end of them. If this file size is a multiple of 4 but not 8, we
2713 // have to read and ignore these final 4 bytes :-(
2714 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2715 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2716 Stream.AtEndOfStream())
2717 return std::error_code();
2719 return Error("Invalid record");
2724 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2725 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2726 return Error("Invalid record");
2728 SmallVector<uint64_t, 64> Record;
2731 // Read all the records for this module.
2733 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2735 switch (Entry.Kind) {
2736 case BitstreamEntry::SubBlock: // Handled for us already.
2737 case BitstreamEntry::Error:
2738 return Error("Malformed block");
2739 case BitstreamEntry::EndBlock:
2741 case BitstreamEntry::Record:
2742 // The interesting case.
2747 switch (Stream.readRecord(Entry.ID, Record)) {
2748 default: break; // Default behavior, ignore unknown content.
2749 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2751 if (ConvertToString(Record, 0, S))
2752 return Error("Invalid record");
2759 llvm_unreachable("Exit infinite loop");
2762 ErrorOr<std::string> BitcodeReader::parseTriple() {
2763 if (std::error_code EC = InitStream())
2766 // Sniff for the signature.
2767 if (Stream.Read(8) != 'B' ||
2768 Stream.Read(8) != 'C' ||
2769 Stream.Read(4) != 0x0 ||
2770 Stream.Read(4) != 0xC ||
2771 Stream.Read(4) != 0xE ||
2772 Stream.Read(4) != 0xD)
2773 return Error("Invalid bitcode signature");
2775 // We expect a number of well-defined blocks, though we don't necessarily
2776 // need to understand them all.
2778 BitstreamEntry Entry = Stream.advance();
2780 switch (Entry.Kind) {
2781 case BitstreamEntry::Error:
2782 return Error("Malformed block");
2783 case BitstreamEntry::EndBlock:
2784 return std::error_code();
2786 case BitstreamEntry::SubBlock:
2787 if (Entry.ID == bitc::MODULE_BLOCK_ID)
2788 return parseModuleTriple();
2790 // Ignore other sub-blocks.
2791 if (Stream.SkipBlock())
2792 return Error("Malformed block");
2795 case BitstreamEntry::Record:
2796 Stream.skipRecord(Entry.ID);
2802 /// ParseMetadataAttachment - Parse metadata attachments.
2803 std::error_code BitcodeReader::ParseMetadataAttachment() {
2804 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2805 return Error("Invalid record");
2807 SmallVector<uint64_t, 64> Record;
2809 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2811 switch (Entry.Kind) {
2812 case BitstreamEntry::SubBlock: // Handled for us already.
2813 case BitstreamEntry::Error:
2814 return Error("Malformed block");
2815 case BitstreamEntry::EndBlock:
2816 return std::error_code();
2817 case BitstreamEntry::Record:
2818 // The interesting case.
2822 // Read a metadata attachment record.
2824 switch (Stream.readRecord(Entry.ID, Record)) {
2825 default: // Default behavior: ignore.
2827 case bitc::METADATA_ATTACHMENT: {
2828 unsigned RecordLength = Record.size();
2829 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2830 return Error("Invalid record");
2831 Instruction *Inst = InstructionList[Record[0]];
2832 for (unsigned i = 1; i != RecordLength; i = i+2) {
2833 unsigned Kind = Record[i];
2834 DenseMap<unsigned, unsigned>::iterator I =
2835 MDKindMap.find(Kind);
2836 if (I == MDKindMap.end())
2837 return Error("Invalid ID");
2838 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2839 if (isa<LocalAsMetadata>(Node))
2840 // Drop the attachment. This used to be legal, but there's no
2843 Inst->setMetadata(I->second, cast<MDNode>(Node));
2844 if (I->second == LLVMContext::MD_tbaa)
2845 InstsWithTBAATag.push_back(Inst);
2853 /// ParseFunctionBody - Lazily parse the specified function body block.
2854 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2855 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2856 return Error("Invalid record");
2858 InstructionList.clear();
2859 unsigned ModuleValueListSize = ValueList.size();
2860 unsigned ModuleMDValueListSize = MDValueList.size();
2862 // Add all the function arguments to the value table.
2863 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2864 ValueList.push_back(I);
2866 unsigned NextValueNo = ValueList.size();
2867 BasicBlock *CurBB = nullptr;
2868 unsigned CurBBNo = 0;
2871 auto getLastInstruction = [&]() -> Instruction * {
2872 if (CurBB && !CurBB->empty())
2873 return &CurBB->back();
2874 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
2875 !FunctionBBs[CurBBNo - 1]->empty())
2876 return &FunctionBBs[CurBBNo - 1]->back();
2880 // Read all the records.
2881 SmallVector<uint64_t, 64> Record;
2883 BitstreamEntry Entry = Stream.advance();
2885 switch (Entry.Kind) {
2886 case BitstreamEntry::Error:
2887 return Error("Malformed block");
2888 case BitstreamEntry::EndBlock:
2889 goto OutOfRecordLoop;
2891 case BitstreamEntry::SubBlock:
2893 default: // Skip unknown content.
2894 if (Stream.SkipBlock())
2895 return Error("Invalid record");
2897 case bitc::CONSTANTS_BLOCK_ID:
2898 if (std::error_code EC = ParseConstants())
2900 NextValueNo = ValueList.size();
2902 case bitc::VALUE_SYMTAB_BLOCK_ID:
2903 if (std::error_code EC = ParseValueSymbolTable())
2906 case bitc::METADATA_ATTACHMENT_ID:
2907 if (std::error_code EC = ParseMetadataAttachment())
2910 case bitc::METADATA_BLOCK_ID:
2911 if (std::error_code EC = ParseMetadata())
2914 case bitc::USELIST_BLOCK_ID:
2915 if (std::error_code EC = ParseUseLists())
2921 case BitstreamEntry::Record:
2922 // The interesting case.
2928 Instruction *I = nullptr;
2929 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2931 default: // Default behavior: reject
2932 return Error("Invalid value");
2933 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
2934 if (Record.size() < 1 || Record[0] == 0)
2935 return Error("Invalid record");
2936 // Create all the basic blocks for the function.
2937 FunctionBBs.resize(Record[0]);
2939 // See if anything took the address of blocks in this function.
2940 auto BBFRI = BasicBlockFwdRefs.find(F);
2941 if (BBFRI == BasicBlockFwdRefs.end()) {
2942 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2943 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2945 auto &BBRefs = BBFRI->second;
2946 // Check for invalid basic block references.
2947 if (BBRefs.size() > FunctionBBs.size())
2948 return Error("Invalid ID");
2949 assert(!BBRefs.empty() && "Unexpected empty array");
2950 assert(!BBRefs.front() && "Invalid reference to entry block");
2951 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2953 if (I < RE && BBRefs[I]) {
2954 BBRefs[I]->insertInto(F);
2955 FunctionBBs[I] = BBRefs[I];
2957 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2960 // Erase from the table.
2961 BasicBlockFwdRefs.erase(BBFRI);
2964 CurBB = FunctionBBs[0];
2968 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2969 // This record indicates that the last instruction is at the same
2970 // location as the previous instruction with a location.
2971 I = getLastInstruction();
2974 return Error("Invalid record");
2975 I->setDebugLoc(LastLoc);
2979 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
2980 I = getLastInstruction();
2981 if (!I || Record.size() < 4)
2982 return Error("Invalid record");
2984 unsigned Line = Record[0], Col = Record[1];
2985 unsigned ScopeID = Record[2], IAID = Record[3];
2987 MDNode *Scope = nullptr, *IA = nullptr;
2988 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2989 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2990 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2991 I->setDebugLoc(LastLoc);
2996 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2999 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3000 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3001 OpNum+1 > Record.size())
3002 return Error("Invalid record");
3004 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3006 return Error("Invalid record");
3007 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3008 InstructionList.push_back(I);
3009 if (OpNum < Record.size()) {
3010 if (Opc == Instruction::Add ||
3011 Opc == Instruction::Sub ||
3012 Opc == Instruction::Mul ||
3013 Opc == Instruction::Shl) {
3014 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3015 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3016 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3017 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3018 } else if (Opc == Instruction::SDiv ||
3019 Opc == Instruction::UDiv ||
3020 Opc == Instruction::LShr ||
3021 Opc == Instruction::AShr) {
3022 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3023 cast<BinaryOperator>(I)->setIsExact(true);
3024 } else if (isa<FPMathOperator>(I)) {
3026 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3027 FMF.setUnsafeAlgebra();
3028 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3030 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3032 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3033 FMF.setNoSignedZeros();
3034 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3035 FMF.setAllowReciprocal();
3037 I->setFastMathFlags(FMF);
3043 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3046 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3047 OpNum+2 != Record.size())
3048 return Error("Invalid record");
3050 Type *ResTy = getTypeByID(Record[OpNum]);
3051 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3052 if (Opc == -1 || !ResTy)
3053 return Error("Invalid record");
3054 Instruction *Temp = nullptr;
3055 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3057 InstructionList.push_back(Temp);
3058 CurBB->getInstList().push_back(Temp);
3061 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3063 InstructionList.push_back(I);
3066 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3067 case bitc::FUNC_CODE_INST_GEP_OLD:
3068 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3074 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3075 InBounds = Record[OpNum++];
3076 Ty = getTypeByID(Record[OpNum++]);
3078 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3083 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3084 return Error("Invalid record");
3086 SmallVector<Value*, 16> GEPIdx;
3087 while (OpNum != Record.size()) {
3089 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3090 return Error("Invalid record");
3091 GEPIdx.push_back(Op);
3094 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
3096 assert(!Ty || Ty == cast<GetElementPtrInst>(I)->getSourceElementType());
3097 InstructionList.push_back(I);
3099 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3103 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3104 // EXTRACTVAL: [opty, opval, n x indices]
3107 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3108 return Error("Invalid record");
3110 SmallVector<unsigned, 4> EXTRACTVALIdx;
3111 Type *CurTy = Agg->getType();
3112 for (unsigned RecSize = Record.size();
3113 OpNum != RecSize; ++OpNum) {
3114 bool IsArray = CurTy->isArrayTy();
3115 bool IsStruct = CurTy->isStructTy();
3116 uint64_t Index = Record[OpNum];
3118 if (!IsStruct && !IsArray)
3119 return Error("EXTRACTVAL: Invalid type");
3120 if ((unsigned)Index != Index)
3121 return Error("Invalid value");
3122 if (IsStruct && Index >= CurTy->subtypes().size())
3123 return Error("EXTRACTVAL: Invalid struct index");
3124 if (IsArray && Index >= CurTy->getArrayNumElements())
3125 return Error("EXTRACTVAL: Invalid array index");
3126 EXTRACTVALIdx.push_back((unsigned)Index);
3129 CurTy = CurTy->subtypes()[Index];
3131 CurTy = CurTy->subtypes()[0];
3134 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3135 InstructionList.push_back(I);
3139 case bitc::FUNC_CODE_INST_INSERTVAL: {
3140 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3143 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3144 return Error("Invalid record");
3146 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3147 return Error("Invalid record");
3149 SmallVector<unsigned, 4> INSERTVALIdx;
3150 Type *CurTy = Agg->getType();
3151 for (unsigned RecSize = Record.size();
3152 OpNum != RecSize; ++OpNum) {
3153 bool IsArray = CurTy->isArrayTy();
3154 bool IsStruct = CurTy->isStructTy();
3155 uint64_t Index = Record[OpNum];
3157 if (!IsStruct && !IsArray)
3158 return Error("INSERTVAL: Invalid type");
3159 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3160 return Error("Invalid type");
3161 if ((unsigned)Index != Index)
3162 return Error("Invalid value");
3163 if (IsStruct && Index >= CurTy->subtypes().size())
3164 return Error("INSERTVAL: Invalid struct index");
3165 if (IsArray && Index >= CurTy->getArrayNumElements())
3166 return Error("INSERTVAL: Invalid array index");
3168 INSERTVALIdx.push_back((unsigned)Index);
3170 CurTy = CurTy->subtypes()[Index];
3172 CurTy = CurTy->subtypes()[0];
3175 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3176 InstructionList.push_back(I);
3180 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3181 // obsolete form of select
3182 // handles select i1 ... in old bitcode
3184 Value *TrueVal, *FalseVal, *Cond;
3185 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3186 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3187 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3188 return Error("Invalid record");
3190 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3191 InstructionList.push_back(I);
3195 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3196 // new form of select
3197 // handles select i1 or select [N x i1]
3199 Value *TrueVal, *FalseVal, *Cond;
3200 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3201 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3202 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3203 return Error("Invalid record");
3205 // select condition can be either i1 or [N x i1]
3206 if (VectorType* vector_type =
3207 dyn_cast<VectorType>(Cond->getType())) {
3209 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3210 return Error("Invalid type for value");
3213 if (Cond->getType() != Type::getInt1Ty(Context))
3214 return Error("Invalid type for value");
3217 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3218 InstructionList.push_back(I);
3222 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3225 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3226 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3227 return Error("Invalid record");
3228 I = ExtractElementInst::Create(Vec, Idx);
3229 InstructionList.push_back(I);
3233 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3235 Value *Vec, *Elt, *Idx;
3236 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3237 popValue(Record, OpNum, NextValueNo,
3238 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3239 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3240 return Error("Invalid record");
3241 I = InsertElementInst::Create(Vec, Elt, Idx);
3242 InstructionList.push_back(I);
3246 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3248 Value *Vec1, *Vec2, *Mask;
3249 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3250 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3251 return Error("Invalid record");
3253 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3254 return Error("Invalid record");
3255 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3256 InstructionList.push_back(I);
3260 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3261 // Old form of ICmp/FCmp returning bool
3262 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3263 // both legal on vectors but had different behaviour.
3264 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3265 // FCmp/ICmp returning bool or vector of bool
3269 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3270 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3271 OpNum+1 != Record.size())
3272 return Error("Invalid record");
3274 if (LHS->getType()->isFPOrFPVectorTy())
3275 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3277 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3278 InstructionList.push_back(I);
3282 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3284 unsigned Size = Record.size();
3286 I = ReturnInst::Create(Context);
3287 InstructionList.push_back(I);
3292 Value *Op = nullptr;
3293 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3294 return Error("Invalid record");
3295 if (OpNum != Record.size())
3296 return Error("Invalid record");
3298 I = ReturnInst::Create(Context, Op);
3299 InstructionList.push_back(I);
3302 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3303 if (Record.size() != 1 && Record.size() != 3)
3304 return Error("Invalid record");
3305 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3307 return Error("Invalid record");
3309 if (Record.size() == 1) {
3310 I = BranchInst::Create(TrueDest);
3311 InstructionList.push_back(I);
3314 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3315 Value *Cond = getValue(Record, 2, NextValueNo,
3316 Type::getInt1Ty(Context));
3317 if (!FalseDest || !Cond)
3318 return Error("Invalid record");
3319 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3320 InstructionList.push_back(I);
3324 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3326 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3327 // "New" SwitchInst format with case ranges. The changes to write this
3328 // format were reverted but we still recognize bitcode that uses it.
3329 // Hopefully someday we will have support for case ranges and can use
3330 // this format again.
3332 Type *OpTy = getTypeByID(Record[1]);
3333 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3335 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3336 BasicBlock *Default = getBasicBlock(Record[3]);
3337 if (!OpTy || !Cond || !Default)
3338 return Error("Invalid record");
3340 unsigned NumCases = Record[4];
3342 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3343 InstructionList.push_back(SI);
3345 unsigned CurIdx = 5;
3346 for (unsigned i = 0; i != NumCases; ++i) {
3347 SmallVector<ConstantInt*, 1> CaseVals;
3348 unsigned NumItems = Record[CurIdx++];
3349 for (unsigned ci = 0; ci != NumItems; ++ci) {
3350 bool isSingleNumber = Record[CurIdx++];
3353 unsigned ActiveWords = 1;
3354 if (ValueBitWidth > 64)
3355 ActiveWords = Record[CurIdx++];
3356 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3358 CurIdx += ActiveWords;
3360 if (!isSingleNumber) {
3362 if (ValueBitWidth > 64)
3363 ActiveWords = Record[CurIdx++];
3365 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3367 CurIdx += ActiveWords;
3369 // FIXME: It is not clear whether values in the range should be
3370 // compared as signed or unsigned values. The partially
3371 // implemented changes that used this format in the past used
3372 // unsigned comparisons.
3373 for ( ; Low.ule(High); ++Low)
3374 CaseVals.push_back(ConstantInt::get(Context, Low));
3376 CaseVals.push_back(ConstantInt::get(Context, Low));
3378 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3379 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3380 cve = CaseVals.end(); cvi != cve; ++cvi)
3381 SI->addCase(*cvi, DestBB);
3387 // Old SwitchInst format without case ranges.
3389 if (Record.size() < 3 || (Record.size() & 1) == 0)
3390 return Error("Invalid record");
3391 Type *OpTy = getTypeByID(Record[0]);
3392 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3393 BasicBlock *Default = getBasicBlock(Record[2]);
3394 if (!OpTy || !Cond || !Default)
3395 return Error("Invalid record");
3396 unsigned NumCases = (Record.size()-3)/2;
3397 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3398 InstructionList.push_back(SI);
3399 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3400 ConstantInt *CaseVal =
3401 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3402 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3403 if (!CaseVal || !DestBB) {
3405 return Error("Invalid record");
3407 SI->addCase(CaseVal, DestBB);
3412 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3413 if (Record.size() < 2)
3414 return Error("Invalid record");
3415 Type *OpTy = getTypeByID(Record[0]);
3416 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3417 if (!OpTy || !Address)
3418 return Error("Invalid record");
3419 unsigned NumDests = Record.size()-2;
3420 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3421 InstructionList.push_back(IBI);
3422 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3423 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3424 IBI->addDestination(DestBB);
3427 return Error("Invalid record");
3434 case bitc::FUNC_CODE_INST_INVOKE: {
3435 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3436 if (Record.size() < 4)
3437 return Error("Invalid record");
3438 AttributeSet PAL = getAttributes(Record[0]);
3439 unsigned CCInfo = Record[1];
3440 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3441 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3445 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3446 return Error("Invalid record");
3448 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3449 FunctionType *FTy = !CalleeTy ? nullptr :
3450 dyn_cast<FunctionType>(CalleeTy->getElementType());
3452 // Check that the right number of fixed parameters are here.
3453 if (!FTy || !NormalBB || !UnwindBB ||
3454 Record.size() < OpNum+FTy->getNumParams())
3455 return Error("Invalid record");
3457 SmallVector<Value*, 16> Ops;
3458 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3459 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3460 FTy->getParamType(i)));
3462 return Error("Invalid record");
3465 if (!FTy->isVarArg()) {
3466 if (Record.size() != OpNum)
3467 return Error("Invalid record");
3469 // Read type/value pairs for varargs params.
3470 while (OpNum != Record.size()) {
3472 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3473 return Error("Invalid record");
3478 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3479 InstructionList.push_back(I);
3480 cast<InvokeInst>(I)->setCallingConv(
3481 static_cast<CallingConv::ID>(CCInfo));
3482 cast<InvokeInst>(I)->setAttributes(PAL);
3485 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3487 Value *Val = nullptr;
3488 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3489 return Error("Invalid record");
3490 I = ResumeInst::Create(Val);
3491 InstructionList.push_back(I);
3494 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3495 I = new UnreachableInst(Context);
3496 InstructionList.push_back(I);
3498 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3499 if (Record.size() < 1 || ((Record.size()-1)&1))
3500 return Error("Invalid record");
3501 Type *Ty = getTypeByID(Record[0]);
3503 return Error("Invalid record");
3505 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3506 InstructionList.push_back(PN);
3508 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3510 // With the new function encoding, it is possible that operands have
3511 // negative IDs (for forward references). Use a signed VBR
3512 // representation to keep the encoding small.
3514 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3516 V = getValue(Record, 1+i, NextValueNo, Ty);
3517 BasicBlock *BB = getBasicBlock(Record[2+i]);
3519 return Error("Invalid record");
3520 PN->addIncoming(V, BB);
3526 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3527 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3529 if (Record.size() < 4)
3530 return Error("Invalid record");
3531 Type *Ty = getTypeByID(Record[Idx++]);
3533 return Error("Invalid record");
3534 Value *PersFn = nullptr;
3535 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3536 return Error("Invalid record");
3538 bool IsCleanup = !!Record[Idx++];
3539 unsigned NumClauses = Record[Idx++];
3540 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3541 LP->setCleanup(IsCleanup);
3542 for (unsigned J = 0; J != NumClauses; ++J) {
3543 LandingPadInst::ClauseType CT =
3544 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3547 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3549 return Error("Invalid record");
3552 assert((CT != LandingPadInst::Catch ||
3553 !isa<ArrayType>(Val->getType())) &&
3554 "Catch clause has a invalid type!");
3555 assert((CT != LandingPadInst::Filter ||
3556 isa<ArrayType>(Val->getType())) &&
3557 "Filter clause has invalid type!");
3558 LP->addClause(cast<Constant>(Val));
3562 InstructionList.push_back(I);
3566 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3567 if (Record.size() != 4)
3568 return Error("Invalid record");
3570 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3571 Type *OpTy = getTypeByID(Record[1]);
3572 Value *Size = getFnValueByID(Record[2], OpTy);
3573 uint64_t AlignRecord = Record[3];
3574 const uint64_t InAllocaMask = uint64_t(1) << 5;
3575 bool InAlloca = AlignRecord & InAllocaMask;
3577 if (std::error_code EC =
3578 parseAlignmentValue(AlignRecord & ~InAllocaMask, Align)) {
3582 return Error("Invalid record");
3583 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, Align);
3584 AI->setUsedWithInAlloca(InAlloca);
3586 InstructionList.push_back(I);
3589 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3592 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3593 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
3594 return Error("Invalid record");
3597 if (OpNum + 3 == Record.size())
3598 Ty = getTypeByID(Record[OpNum++]);
3601 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3603 I = new LoadInst(Op, "", Record[OpNum+1], Align);
3606 assert((!Ty || Ty == I->getType()) &&
3607 "Explicit type doesn't match pointee type of the first operand");
3609 InstructionList.push_back(I);
3612 case bitc::FUNC_CODE_INST_LOADATOMIC: {
3613 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3616 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3617 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
3618 return Error("Invalid record");
3621 if (OpNum + 5 == Record.size())
3622 Ty = getTypeByID(Record[OpNum++]);
3624 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3625 if (Ordering == NotAtomic || Ordering == Release ||
3626 Ordering == AcquireRelease)
3627 return Error("Invalid record");
3628 if (Ordering != NotAtomic && Record[OpNum] == 0)
3629 return Error("Invalid record");
3630 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3633 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3635 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
3638 assert((!Ty || Ty == I->getType()) &&
3639 "Explicit type doesn't match pointee type of the first operand");
3641 InstructionList.push_back(I);
3644 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3647 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3648 popValue(Record, OpNum, NextValueNo,
3649 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3650 OpNum+2 != Record.size())
3651 return Error("Invalid record");
3653 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3655 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
3656 InstructionList.push_back(I);
3659 case bitc::FUNC_CODE_INST_STOREATOMIC: {
3660 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3663 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3664 popValue(Record, OpNum, NextValueNo,
3665 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3666 OpNum+4 != Record.size())
3667 return Error("Invalid record");
3669 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3670 if (Ordering == NotAtomic || Ordering == Acquire ||
3671 Ordering == AcquireRelease)
3672 return Error("Invalid record");
3673 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3674 if (Ordering != NotAtomic && Record[OpNum] == 0)
3675 return Error("Invalid record");
3678 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3680 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
3681 InstructionList.push_back(I);
3684 case bitc::FUNC_CODE_INST_CMPXCHG: {
3685 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3686 // failureordering?, isweak?]
3688 Value *Ptr, *Cmp, *New;
3689 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3690 popValue(Record, OpNum, NextValueNo,
3691 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3692 popValue(Record, OpNum, NextValueNo,
3693 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3694 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3695 return Error("Invalid record");
3696 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3697 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3698 return Error("Invalid record");
3699 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3701 AtomicOrdering FailureOrdering;
3702 if (Record.size() < 7)
3704 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3706 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3708 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3710 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3712 if (Record.size() < 8) {
3713 // Before weak cmpxchgs existed, the instruction simply returned the
3714 // value loaded from memory, so bitcode files from that era will be
3715 // expecting the first component of a modern cmpxchg.
3716 CurBB->getInstList().push_back(I);
3717 I = ExtractValueInst::Create(I, 0);
3719 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3722 InstructionList.push_back(I);
3725 case bitc::FUNC_CODE_INST_ATOMICRMW: {
3726 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3729 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3730 popValue(Record, OpNum, NextValueNo,
3731 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3732 OpNum+4 != Record.size())
3733 return Error("Invalid record");
3734 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3735 if (Operation < AtomicRMWInst::FIRST_BINOP ||
3736 Operation > AtomicRMWInst::LAST_BINOP)
3737 return Error("Invalid record");
3738 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3739 if (Ordering == NotAtomic || Ordering == Unordered)
3740 return Error("Invalid record");
3741 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3742 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3743 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3744 InstructionList.push_back(I);
3747 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3748 if (2 != Record.size())
3749 return Error("Invalid record");
3750 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3751 if (Ordering == NotAtomic || Ordering == Unordered ||
3752 Ordering == Monotonic)
3753 return Error("Invalid record");
3754 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3755 I = new FenceInst(Context, Ordering, SynchScope);
3756 InstructionList.push_back(I);
3759 case bitc::FUNC_CODE_INST_CALL: {
3760 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3761 if (Record.size() < 3)
3762 return Error("Invalid record");
3764 AttributeSet PAL = getAttributes(Record[0]);
3765 unsigned CCInfo = Record[1];
3769 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3770 return Error("Invalid record");
3772 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3773 FunctionType *FTy = nullptr;
3774 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3775 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3776 return Error("Invalid record");
3778 SmallVector<Value*, 16> Args;
3779 // Read the fixed params.
3780 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3781 if (FTy->getParamType(i)->isLabelTy())
3782 Args.push_back(getBasicBlock(Record[OpNum]));
3784 Args.push_back(getValue(Record, OpNum, NextValueNo,
3785 FTy->getParamType(i)));
3787 return Error("Invalid record");
3790 // Read type/value pairs for varargs params.
3791 if (!FTy->isVarArg()) {
3792 if (OpNum != Record.size())
3793 return Error("Invalid record");
3795 while (OpNum != Record.size()) {
3797 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3798 return Error("Invalid record");
3803 I = CallInst::Create(Callee, Args);
3804 InstructionList.push_back(I);
3805 cast<CallInst>(I)->setCallingConv(
3806 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3807 CallInst::TailCallKind TCK = CallInst::TCK_None;
3809 TCK = CallInst::TCK_Tail;
3810 if (CCInfo & (1 << 14))
3811 TCK = CallInst::TCK_MustTail;
3812 cast<CallInst>(I)->setTailCallKind(TCK);
3813 cast<CallInst>(I)->setAttributes(PAL);
3816 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3817 if (Record.size() < 3)
3818 return Error("Invalid record");
3819 Type *OpTy = getTypeByID(Record[0]);
3820 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3821 Type *ResTy = getTypeByID(Record[2]);
3822 if (!OpTy || !Op || !ResTy)
3823 return Error("Invalid record");
3824 I = new VAArgInst(Op, ResTy);
3825 InstructionList.push_back(I);
3830 // Add instruction to end of current BB. If there is no current BB, reject
3834 return Error("Invalid instruction with no BB");
3836 CurBB->getInstList().push_back(I);
3838 // If this was a terminator instruction, move to the next block.
3839 if (isa<TerminatorInst>(I)) {
3841 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3844 // Non-void values get registered in the value table for future use.
3845 if (I && !I->getType()->isVoidTy())
3846 ValueList.AssignValue(I, NextValueNo++);
3851 // Check the function list for unresolved values.
3852 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3853 if (!A->getParent()) {
3854 // We found at least one unresolved value. Nuke them all to avoid leaks.
3855 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3856 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3857 A->replaceAllUsesWith(UndefValue::get(A->getType()));
3861 return Error("Never resolved value found in function");
3865 // FIXME: Check for unresolved forward-declared metadata references
3866 // and clean up leaks.
3868 // Trim the value list down to the size it was before we parsed this function.
3869 ValueList.shrinkTo(ModuleValueListSize);
3870 MDValueList.shrinkTo(ModuleMDValueListSize);
3871 std::vector<BasicBlock*>().swap(FunctionBBs);
3872 return std::error_code();
3875 /// Find the function body in the bitcode stream
3876 std::error_code BitcodeReader::FindFunctionInStream(
3878 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3879 while (DeferredFunctionInfoIterator->second == 0) {
3880 if (Stream.AtEndOfStream())
3881 return Error("Could not find function in stream");
3882 // ParseModule will parse the next body in the stream and set its
3883 // position in the DeferredFunctionInfo map.
3884 if (std::error_code EC = ParseModule(true))
3887 return std::error_code();
3890 //===----------------------------------------------------------------------===//
3891 // GVMaterializer implementation
3892 //===----------------------------------------------------------------------===//
3894 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3896 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3897 Function *F = dyn_cast<Function>(GV);
3898 // If it's not a function or is already material, ignore the request.
3899 if (!F || !F->isMaterializable())
3900 return std::error_code();
3902 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3903 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3904 // If its position is recorded as 0, its body is somewhere in the stream
3905 // but we haven't seen it yet.
3906 if (DFII->second == 0 && LazyStreamer)
3907 if (std::error_code EC = FindFunctionInStream(F, DFII))
3910 // Move the bit stream to the saved position of the deferred function body.
3911 Stream.JumpToBit(DFII->second);
3913 if (std::error_code EC = ParseFunctionBody(F))
3915 F->setIsMaterializable(false);
3917 // Upgrade any old intrinsic calls in the function.
3918 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3919 E = UpgradedIntrinsics.end(); I != E; ++I) {
3920 if (I->first != I->second) {
3921 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3923 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3924 UpgradeIntrinsicCall(CI, I->second);
3929 // Bring in any functions that this function forward-referenced via
3931 return materializeForwardReferencedFunctions();
3934 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3935 const Function *F = dyn_cast<Function>(GV);
3936 if (!F || F->isDeclaration())
3939 // Dematerializing F would leave dangling references that wouldn't be
3940 // reconnected on re-materialization.
3941 if (BlockAddressesTaken.count(F))
3944 return DeferredFunctionInfo.count(const_cast<Function*>(F));
3947 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3948 Function *F = dyn_cast<Function>(GV);
3949 // If this function isn't dematerializable, this is a noop.
3950 if (!F || !isDematerializable(F))
3953 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3955 // Just forget the function body, we can remat it later.
3956 F->dropAllReferences();
3957 F->setIsMaterializable(true);
3960 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3961 assert(M == TheModule &&
3962 "Can only Materialize the Module this BitcodeReader is attached to.");
3964 // Promise to materialize all forward references.
3965 WillMaterializeAllForwardRefs = true;
3967 // Iterate over the module, deserializing any functions that are still on
3969 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3971 if (std::error_code EC = materialize(F))
3974 // At this point, if there are any function bodies, the current bit is
3975 // pointing to the END_BLOCK record after them. Now make sure the rest
3976 // of the bits in the module have been read.
3980 // Check that all block address forward references got resolved (as we
3982 if (!BasicBlockFwdRefs.empty())
3983 return Error("Never resolved function from blockaddress");
3985 // Upgrade any intrinsic calls that slipped through (should not happen!) and
3986 // delete the old functions to clean up. We can't do this unless the entire
3987 // module is materialized because there could always be another function body
3988 // with calls to the old function.
3989 for (std::vector<std::pair<Function*, Function*> >::iterator I =
3990 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3991 if (I->first != I->second) {
3992 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3994 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3995 UpgradeIntrinsicCall(CI, I->second);
3997 if (!I->first->use_empty())
3998 I->first->replaceAllUsesWith(I->second);
3999 I->first->eraseFromParent();
4002 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4004 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4005 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4007 UpgradeDebugInfo(*M);
4008 return std::error_code();
4011 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4012 return IdentifiedStructTypes;
4015 std::error_code BitcodeReader::InitStream() {
4017 return InitLazyStream();
4018 return InitStreamFromBuffer();
4021 std::error_code BitcodeReader::InitStreamFromBuffer() {
4022 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4023 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4025 if (Buffer->getBufferSize() & 3)
4026 return Error("Invalid bitcode signature");
4028 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4029 // The magic number is 0x0B17C0DE stored in little endian.
4030 if (isBitcodeWrapper(BufPtr, BufEnd))
4031 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4032 return Error("Invalid bitcode wrapper header");
4034 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4035 Stream.init(&*StreamFile);
4037 return std::error_code();
4040 std::error_code BitcodeReader::InitLazyStream() {
4041 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4043 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4044 StreamingMemoryObject &Bytes = *OwnedBytes;
4045 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4046 Stream.init(&*StreamFile);
4048 unsigned char buf[16];
4049 if (Bytes.readBytes(buf, 16, 0) != 16)
4050 return Error("Invalid bitcode signature");
4052 if (!isBitcode(buf, buf + 16))
4053 return Error("Invalid bitcode signature");
4055 if (isBitcodeWrapper(buf, buf + 4)) {
4056 const unsigned char *bitcodeStart = buf;
4057 const unsigned char *bitcodeEnd = buf + 16;
4058 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4059 Bytes.dropLeadingBytes(bitcodeStart - buf);
4060 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4062 return std::error_code();
4066 class BitcodeErrorCategoryType : public std::error_category {
4067 const char *name() const LLVM_NOEXCEPT override {
4068 return "llvm.bitcode";
4070 std::string message(int IE) const override {
4071 BitcodeError E = static_cast<BitcodeError>(IE);
4073 case BitcodeError::InvalidBitcodeSignature:
4074 return "Invalid bitcode signature";
4075 case BitcodeError::CorruptedBitcode:
4076 return "Corrupted bitcode";
4078 llvm_unreachable("Unknown error type!");
4083 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4085 const std::error_category &llvm::BitcodeErrorCategory() {
4086 return *ErrorCategory;
4089 //===----------------------------------------------------------------------===//
4090 // External interface
4091 //===----------------------------------------------------------------------===//
4093 /// \brief Get a lazy one-at-time loading module from bitcode.
4095 /// This isn't always used in a lazy context. In particular, it's also used by
4096 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4097 /// in forward-referenced functions from block address references.
4099 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4100 /// materialize everything -- in particular, if this isn't truly lazy.
4101 static ErrorOr<Module *>
4102 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4103 LLVMContext &Context, bool WillMaterializeAll,
4104 DiagnosticHandlerFunction DiagnosticHandler) {
4105 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4107 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4108 M->setMaterializer(R);
4110 auto cleanupOnError = [&](std::error_code EC) {
4111 R->releaseBuffer(); // Never take ownership on error.
4112 delete M; // Also deletes R.
4116 if (std::error_code EC = R->ParseBitcodeInto(M))
4117 return cleanupOnError(EC);
4119 if (!WillMaterializeAll)
4120 // Resolve forward references from blockaddresses.
4121 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4122 return cleanupOnError(EC);
4124 Buffer.release(); // The BitcodeReader owns it now.
4129 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4130 LLVMContext &Context,
4131 DiagnosticHandlerFunction DiagnosticHandler) {
4132 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4136 ErrorOr<std::unique_ptr<Module>>
4137 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4138 LLVMContext &Context,
4139 DiagnosticHandlerFunction DiagnosticHandler) {
4140 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4141 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4142 M->setMaterializer(R);
4143 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4145 return std::move(M);
4149 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4150 DiagnosticHandlerFunction DiagnosticHandler) {
4151 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4152 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4153 std::move(Buf), Context, true, DiagnosticHandler);
4156 Module *M = ModuleOrErr.get();
4157 // Read in the entire module, and destroy the BitcodeReader.
4158 if (std::error_code EC = M->materializeAllPermanently()) {
4163 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4164 // written. We must defer until the Module has been fully materialized.
4170 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4171 DiagnosticHandlerFunction DiagnosticHandler) {
4172 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4173 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4175 ErrorOr<std::string> Triple = R->parseTriple();
4176 if (Triple.getError())
4178 return Triple.get();