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 "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/DataStream.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/raw_ostream.h"
41 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
44 class BitcodeReaderValueList {
45 std::vector<WeakVH> ValuePtrs;
47 /// As we resolve forward-referenced constants, we add information about them
48 /// to this vector. This allows us to resolve them in bulk instead of
49 /// resolving each reference at a time. See the code in
50 /// ResolveConstantForwardRefs for more information about this.
52 /// The key of this vector is the placeholder constant, the value is the slot
53 /// number that holds the resolved value.
54 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
55 ResolveConstantsTy ResolveConstants;
58 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
59 ~BitcodeReaderValueList() {
60 assert(ResolveConstants.empty() && "Constants not resolved?");
63 // vector compatibility methods
64 unsigned size() const { return ValuePtrs.size(); }
65 void resize(unsigned N) { ValuePtrs.resize(N); }
66 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
69 assert(ResolveConstants.empty() && "Constants not resolved?");
73 Value *operator[](unsigned i) const {
74 assert(i < ValuePtrs.size());
78 Value *back() const { return ValuePtrs.back(); }
79 void pop_back() { ValuePtrs.pop_back(); }
80 bool empty() const { return ValuePtrs.empty(); }
81 void shrinkTo(unsigned N) {
82 assert(N <= size() && "Invalid shrinkTo request!");
86 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
87 Value *getValueFwdRef(unsigned Idx, Type *Ty);
89 void assignValue(Value *V, unsigned Idx);
91 /// Once all constants are read, this method bulk resolves any forward
93 void resolveConstantForwardRefs();
96 class BitcodeReaderMDValueList {
101 std::vector<TrackingMDRef> MDValuePtrs;
103 LLVMContext &Context;
105 BitcodeReaderMDValueList(LLVMContext &C)
106 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
108 // vector compatibility methods
109 unsigned size() const { return MDValuePtrs.size(); }
110 void resize(unsigned N) { MDValuePtrs.resize(N); }
111 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
112 void clear() { MDValuePtrs.clear(); }
113 Metadata *back() const { return MDValuePtrs.back(); }
114 void pop_back() { MDValuePtrs.pop_back(); }
115 bool empty() const { return MDValuePtrs.empty(); }
117 Metadata *operator[](unsigned i) const {
118 assert(i < MDValuePtrs.size());
119 return MDValuePtrs[i];
122 void shrinkTo(unsigned N) {
123 assert(N <= size() && "Invalid shrinkTo request!");
124 MDValuePtrs.resize(N);
127 Metadata *getValueFwdRef(unsigned Idx);
128 void assignValue(Metadata *MD, unsigned Idx);
129 void tryToResolveCycles();
132 class BitcodeReader : public GVMaterializer {
133 LLVMContext &Context;
134 DiagnosticHandlerFunction DiagnosticHandler;
135 Module *TheModule = nullptr;
136 std::unique_ptr<MemoryBuffer> Buffer;
137 std::unique_ptr<BitstreamReader> StreamFile;
138 BitstreamCursor Stream;
140 uint64_t NextUnreadBit = 0;
141 bool SeenValueSymbolTable = false;
143 std::vector<Type*> TypeList;
144 BitcodeReaderValueList ValueList;
145 BitcodeReaderMDValueList MDValueList;
146 std::vector<Comdat *> ComdatList;
147 SmallVector<Instruction *, 64> InstructionList;
149 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
150 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
151 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
152 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
154 SmallVector<Instruction*, 64> InstsWithTBAATag;
156 /// The set of attributes by index. Index zero in the file is for null, and
157 /// is thus not represented here. As such all indices are off by one.
158 std::vector<AttributeSet> MAttributes;
160 /// \brief The set of attribute groups.
161 std::map<unsigned, AttributeSet> MAttributeGroups;
163 /// While parsing a function body, this is a list of the basic blocks for the
165 std::vector<BasicBlock*> FunctionBBs;
167 // When reading the module header, this list is populated with functions that
168 // have bodies later in the file.
169 std::vector<Function*> FunctionsWithBodies;
171 // When intrinsic functions are encountered which require upgrading they are
172 // stored here with their replacement function.
173 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
174 UpgradedIntrinsicMap UpgradedIntrinsics;
176 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
177 DenseMap<unsigned, unsigned> MDKindMap;
179 // Several operations happen after the module header has been read, but
180 // before function bodies are processed. This keeps track of whether
181 // we've done this yet.
182 bool SeenFirstFunctionBody = false;
184 /// When function bodies are initially scanned, this map contains info about
185 /// where to find deferred function body in the stream.
186 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
188 /// When Metadata block is initially scanned when parsing the module, we may
189 /// choose to defer parsing of the metadata. This vector contains info about
190 /// which Metadata blocks are deferred.
191 std::vector<uint64_t> DeferredMetadataInfo;
193 /// These are basic blocks forward-referenced by block addresses. They are
194 /// inserted lazily into functions when they're loaded. The basic block ID is
195 /// its index into the vector.
196 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
197 std::deque<Function *> BasicBlockFwdRefQueue;
199 /// Indicates that we are using a new encoding for instruction operands where
200 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
201 /// instruction number, for a more compact encoding. Some instruction
202 /// operands are not relative to the instruction ID: basic block numbers, and
203 /// types. Once the old style function blocks have been phased out, we would
204 /// not need this flag.
205 bool UseRelativeIDs = false;
207 /// True if all functions will be materialized, negating the need to process
208 /// (e.g.) blockaddress forward references.
209 bool WillMaterializeAllForwardRefs = false;
211 /// Functions that have block addresses taken. This is usually empty.
212 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
214 /// True if any Metadata block has been materialized.
215 bool IsMetadataMaterialized = false;
217 bool StripDebugInfo = false;
220 std::error_code error(BitcodeError E, const Twine &Message);
221 std::error_code error(BitcodeError E);
222 std::error_code error(const Twine &Message);
224 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
225 DiagnosticHandlerFunction DiagnosticHandler);
226 BitcodeReader(LLVMContext &Context,
227 DiagnosticHandlerFunction DiagnosticHandler);
228 ~BitcodeReader() override { freeState(); }
230 std::error_code materializeForwardReferencedFunctions();
234 void releaseBuffer();
236 bool isDematerializable(const GlobalValue *GV) const override;
237 std::error_code materialize(GlobalValue *GV) override;
238 std::error_code materializeModule(Module *M) override;
239 std::vector<StructType *> getIdentifiedStructTypes() const override;
240 void dematerialize(GlobalValue *GV) override;
242 /// \brief Main interface to parsing a bitcode buffer.
243 /// \returns true if an error occurred.
244 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
246 bool ShouldLazyLoadMetadata = false);
248 /// \brief Cheap mechanism to just extract module triple
249 /// \returns true if an error occurred.
250 ErrorOr<std::string> parseTriple();
252 static uint64_t decodeSignRotatedValue(uint64_t V);
254 /// Materialize any deferred Metadata block.
255 std::error_code materializeMetadata() override;
257 void setStripDebugInfo() override;
260 std::vector<StructType *> IdentifiedStructTypes;
261 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
262 StructType *createIdentifiedStructType(LLVMContext &Context);
264 Type *getTypeByID(unsigned ID);
265 Value *getFnValueByID(unsigned ID, Type *Ty) {
266 if (Ty && Ty->isMetadataTy())
267 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
268 return ValueList.getValueFwdRef(ID, Ty);
270 Metadata *getFnMetadataByID(unsigned ID) {
271 return MDValueList.getValueFwdRef(ID);
273 BasicBlock *getBasicBlock(unsigned ID) const {
274 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
275 return FunctionBBs[ID];
277 AttributeSet getAttributes(unsigned i) const {
278 if (i-1 < MAttributes.size())
279 return MAttributes[i-1];
280 return AttributeSet();
283 /// Read a value/type pair out of the specified record from slot 'Slot'.
284 /// Increment Slot past the number of slots used in the record. Return true on
286 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
287 unsigned InstNum, Value *&ResVal) {
288 if (Slot == Record.size()) return true;
289 unsigned ValNo = (unsigned)Record[Slot++];
290 // Adjust the ValNo, if it was encoded relative to the InstNum.
292 ValNo = InstNum - ValNo;
293 if (ValNo < InstNum) {
294 // If this is not a forward reference, just return the value we already
296 ResVal = getFnValueByID(ValNo, nullptr);
297 return ResVal == nullptr;
299 if (Slot == Record.size())
302 unsigned TypeNo = (unsigned)Record[Slot++];
303 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
304 return ResVal == nullptr;
307 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
308 /// past the number of slots used by the value in the record. Return true if
309 /// there is an error.
310 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
311 unsigned InstNum, Type *Ty, Value *&ResVal) {
312 if (getValue(Record, Slot, InstNum, Ty, ResVal))
314 // All values currently take a single record slot.
319 /// Like popValue, but does not increment the Slot number.
320 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
321 unsigned InstNum, Type *Ty, Value *&ResVal) {
322 ResVal = getValue(Record, Slot, InstNum, Ty);
323 return ResVal == nullptr;
326 /// Version of getValue that returns ResVal directly, or 0 if there is an
328 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
329 unsigned InstNum, Type *Ty) {
330 if (Slot == Record.size()) return nullptr;
331 unsigned ValNo = (unsigned)Record[Slot];
332 // Adjust the ValNo, if it was encoded relative to the InstNum.
334 ValNo = InstNum - ValNo;
335 return getFnValueByID(ValNo, Ty);
338 /// Like getValue, but decodes signed VBRs.
339 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
340 unsigned InstNum, Type *Ty) {
341 if (Slot == Record.size()) return nullptr;
342 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
343 // Adjust the ValNo, if it was encoded relative to the InstNum.
345 ValNo = InstNum - ValNo;
346 return getFnValueByID(ValNo, Ty);
349 /// Converts alignment exponent (i.e. power of two (or zero)) to the
350 /// corresponding alignment to use. If alignment is too large, returns
351 /// a corresponding error code.
352 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
353 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
354 std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
355 std::error_code parseAttributeBlock();
356 std::error_code parseAttributeGroupBlock();
357 std::error_code parseTypeTable();
358 std::error_code parseTypeTableBody();
360 std::error_code parseValueSymbolTable();
361 std::error_code parseConstants();
362 std::error_code rememberAndSkipFunctionBody();
363 /// Save the positions of the Metadata blocks and skip parsing the blocks.
364 std::error_code rememberAndSkipMetadata();
365 std::error_code parseFunctionBody(Function *F);
366 std::error_code globalCleanup();
367 std::error_code resolveGlobalAndAliasInits();
368 std::error_code parseMetadata();
369 std::error_code parseMetadataAttachment(Function &F);
370 ErrorOr<std::string> parseModuleTriple();
371 std::error_code parseUseLists();
372 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
373 std::error_code initStreamFromBuffer();
374 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
375 std::error_code findFunctionInStream(
377 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
381 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
382 DiagnosticSeverity Severity,
384 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
386 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
388 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
389 std::error_code EC, const Twine &Message) {
390 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
391 DiagnosticHandler(DI);
395 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
396 std::error_code EC) {
397 return error(DiagnosticHandler, EC, EC.message());
400 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
401 const Twine &Message) {
402 return error(DiagnosticHandler,
403 make_error_code(BitcodeError::CorruptedBitcode), Message);
406 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
407 return ::error(DiagnosticHandler, make_error_code(E), Message);
410 std::error_code BitcodeReader::error(const Twine &Message) {
411 return ::error(DiagnosticHandler,
412 make_error_code(BitcodeError::CorruptedBitcode), Message);
415 std::error_code BitcodeReader::error(BitcodeError E) {
416 return ::error(DiagnosticHandler, make_error_code(E));
419 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
423 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
426 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
427 DiagnosticHandlerFunction DiagnosticHandler)
429 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
430 Buffer(Buffer), IsStreamed(false), ValueList(Context),
431 MDValueList(Context) {}
433 BitcodeReader::BitcodeReader(LLVMContext &Context,
434 DiagnosticHandlerFunction DiagnosticHandler)
436 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
437 Buffer(nullptr), IsStreamed(true), ValueList(Context),
438 MDValueList(Context) {}
440 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
441 if (WillMaterializeAllForwardRefs)
442 return std::error_code();
444 // Prevent recursion.
445 WillMaterializeAllForwardRefs = true;
447 while (!BasicBlockFwdRefQueue.empty()) {
448 Function *F = BasicBlockFwdRefQueue.front();
449 BasicBlockFwdRefQueue.pop_front();
450 assert(F && "Expected valid function");
451 if (!BasicBlockFwdRefs.count(F))
452 // Already materialized.
455 // Check for a function that isn't materializable to prevent an infinite
456 // loop. When parsing a blockaddress stored in a global variable, there
457 // isn't a trivial way to check if a function will have a body without a
458 // linear search through FunctionsWithBodies, so just check it here.
459 if (!F->isMaterializable())
460 return error("Never resolved function from blockaddress");
462 // Try to materialize F.
463 if (std::error_code EC = materialize(F))
466 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
469 WillMaterializeAllForwardRefs = false;
470 return std::error_code();
473 void BitcodeReader::freeState() {
475 std::vector<Type*>().swap(TypeList);
478 std::vector<Comdat *>().swap(ComdatList);
480 std::vector<AttributeSet>().swap(MAttributes);
481 std::vector<BasicBlock*>().swap(FunctionBBs);
482 std::vector<Function*>().swap(FunctionsWithBodies);
483 DeferredFunctionInfo.clear();
484 DeferredMetadataInfo.clear();
487 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
488 BasicBlockFwdRefQueue.clear();
491 //===----------------------------------------------------------------------===//
492 // Helper functions to implement forward reference resolution, etc.
493 //===----------------------------------------------------------------------===//
495 /// Convert a string from a record into an std::string, return true on failure.
496 template <typename StrTy>
497 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
499 if (Idx > Record.size())
502 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
503 Result += (char)Record[i];
507 static bool hasImplicitComdat(size_t Val) {
511 case 1: // Old WeakAnyLinkage
512 case 4: // Old LinkOnceAnyLinkage
513 case 10: // Old WeakODRLinkage
514 case 11: // Old LinkOnceODRLinkage
519 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
521 default: // Map unknown/new linkages to external
523 return GlobalValue::ExternalLinkage;
525 return GlobalValue::AppendingLinkage;
527 return GlobalValue::InternalLinkage;
529 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
531 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
533 return GlobalValue::ExternalWeakLinkage;
535 return GlobalValue::CommonLinkage;
537 return GlobalValue::PrivateLinkage;
539 return GlobalValue::AvailableExternallyLinkage;
541 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
543 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
545 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
546 case 1: // Old value with implicit comdat.
548 return GlobalValue::WeakAnyLinkage;
549 case 10: // Old value with implicit comdat.
551 return GlobalValue::WeakODRLinkage;
552 case 4: // Old value with implicit comdat.
554 return GlobalValue::LinkOnceAnyLinkage;
555 case 11: // Old value with implicit comdat.
557 return GlobalValue::LinkOnceODRLinkage;
561 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
563 default: // Map unknown visibilities to default.
564 case 0: return GlobalValue::DefaultVisibility;
565 case 1: return GlobalValue::HiddenVisibility;
566 case 2: return GlobalValue::ProtectedVisibility;
570 static GlobalValue::DLLStorageClassTypes
571 getDecodedDLLStorageClass(unsigned Val) {
573 default: // Map unknown values to default.
574 case 0: return GlobalValue::DefaultStorageClass;
575 case 1: return GlobalValue::DLLImportStorageClass;
576 case 2: return GlobalValue::DLLExportStorageClass;
580 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
582 case 0: return GlobalVariable::NotThreadLocal;
583 default: // Map unknown non-zero value to general dynamic.
584 case 1: return GlobalVariable::GeneralDynamicTLSModel;
585 case 2: return GlobalVariable::LocalDynamicTLSModel;
586 case 3: return GlobalVariable::InitialExecTLSModel;
587 case 4: return GlobalVariable::LocalExecTLSModel;
591 static int getDecodedCastOpcode(unsigned Val) {
594 case bitc::CAST_TRUNC : return Instruction::Trunc;
595 case bitc::CAST_ZEXT : return Instruction::ZExt;
596 case bitc::CAST_SEXT : return Instruction::SExt;
597 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
598 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
599 case bitc::CAST_UITOFP : return Instruction::UIToFP;
600 case bitc::CAST_SITOFP : return Instruction::SIToFP;
601 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
602 case bitc::CAST_FPEXT : return Instruction::FPExt;
603 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
604 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
605 case bitc::CAST_BITCAST : return Instruction::BitCast;
606 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
610 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
611 bool IsFP = Ty->isFPOrFPVectorTy();
612 // BinOps are only valid for int/fp or vector of int/fp types
613 if (!IsFP && !Ty->isIntOrIntVectorTy())
619 case bitc::BINOP_ADD:
620 return IsFP ? Instruction::FAdd : Instruction::Add;
621 case bitc::BINOP_SUB:
622 return IsFP ? Instruction::FSub : Instruction::Sub;
623 case bitc::BINOP_MUL:
624 return IsFP ? Instruction::FMul : Instruction::Mul;
625 case bitc::BINOP_UDIV:
626 return IsFP ? -1 : Instruction::UDiv;
627 case bitc::BINOP_SDIV:
628 return IsFP ? Instruction::FDiv : Instruction::SDiv;
629 case bitc::BINOP_UREM:
630 return IsFP ? -1 : Instruction::URem;
631 case bitc::BINOP_SREM:
632 return IsFP ? Instruction::FRem : Instruction::SRem;
633 case bitc::BINOP_SHL:
634 return IsFP ? -1 : Instruction::Shl;
635 case bitc::BINOP_LSHR:
636 return IsFP ? -1 : Instruction::LShr;
637 case bitc::BINOP_ASHR:
638 return IsFP ? -1 : Instruction::AShr;
639 case bitc::BINOP_AND:
640 return IsFP ? -1 : Instruction::And;
642 return IsFP ? -1 : Instruction::Or;
643 case bitc::BINOP_XOR:
644 return IsFP ? -1 : Instruction::Xor;
648 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
650 default: return AtomicRMWInst::BAD_BINOP;
651 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
652 case bitc::RMW_ADD: return AtomicRMWInst::Add;
653 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
654 case bitc::RMW_AND: return AtomicRMWInst::And;
655 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
656 case bitc::RMW_OR: return AtomicRMWInst::Or;
657 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
658 case bitc::RMW_MAX: return AtomicRMWInst::Max;
659 case bitc::RMW_MIN: return AtomicRMWInst::Min;
660 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
661 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
665 static AtomicOrdering getDecodedOrdering(unsigned Val) {
667 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
668 case bitc::ORDERING_UNORDERED: return Unordered;
669 case bitc::ORDERING_MONOTONIC: return Monotonic;
670 case bitc::ORDERING_ACQUIRE: return Acquire;
671 case bitc::ORDERING_RELEASE: return Release;
672 case bitc::ORDERING_ACQREL: return AcquireRelease;
673 default: // Map unknown orderings to sequentially-consistent.
674 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
678 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
680 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
681 default: // Map unknown scopes to cross-thread.
682 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
686 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
688 default: // Map unknown selection kinds to any.
689 case bitc::COMDAT_SELECTION_KIND_ANY:
691 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
692 return Comdat::ExactMatch;
693 case bitc::COMDAT_SELECTION_KIND_LARGEST:
694 return Comdat::Largest;
695 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
696 return Comdat::NoDuplicates;
697 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
698 return Comdat::SameSize;
702 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
704 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
705 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
711 /// \brief A class for maintaining the slot number definition
712 /// as a placeholder for the actual definition for forward constants defs.
713 class ConstantPlaceHolder : public ConstantExpr {
714 void operator=(const ConstantPlaceHolder &) = delete;
717 // allocate space for exactly one operand
718 void *operator new(size_t s) { return User::operator new(s, 1); }
719 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
720 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
721 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
724 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
725 static bool classof(const Value *V) {
726 return isa<ConstantExpr>(V) &&
727 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
730 /// Provide fast operand accessors
731 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
735 // FIXME: can we inherit this from ConstantExpr?
737 struct OperandTraits<ConstantPlaceHolder> :
738 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
740 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
743 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
752 WeakVH &OldV = ValuePtrs[Idx];
758 // Handle constants and non-constants (e.g. instrs) differently for
760 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
761 ResolveConstants.push_back(std::make_pair(PHC, Idx));
764 // If there was a forward reference to this value, replace it.
765 Value *PrevVal = OldV;
766 OldV->replaceAllUsesWith(V);
772 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
777 if (Value *V = ValuePtrs[Idx]) {
778 if (Ty != V->getType())
779 report_fatal_error("Type mismatch in constant table!");
780 return cast<Constant>(V);
783 // Create and return a placeholder, which will later be RAUW'd.
784 Constant *C = new ConstantPlaceHolder(Ty, Context);
789 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
790 // Bail out for a clearly invalid value. This would make us call resize(0)
797 if (Value *V = ValuePtrs[Idx]) {
798 // If the types don't match, it's invalid.
799 if (Ty && Ty != V->getType())
804 // No type specified, must be invalid reference.
805 if (!Ty) return nullptr;
807 // Create and return a placeholder, which will later be RAUW'd.
808 Value *V = new Argument(Ty);
813 /// Once all constants are read, this method bulk resolves any forward
814 /// references. The idea behind this is that we sometimes get constants (such
815 /// as large arrays) which reference *many* forward ref constants. Replacing
816 /// each of these causes a lot of thrashing when building/reuniquing the
817 /// constant. Instead of doing this, we look at all the uses and rewrite all
818 /// the place holders at once for any constant that uses a placeholder.
819 void BitcodeReaderValueList::resolveConstantForwardRefs() {
820 // Sort the values by-pointer so that they are efficient to look up with a
822 std::sort(ResolveConstants.begin(), ResolveConstants.end());
824 SmallVector<Constant*, 64> NewOps;
826 while (!ResolveConstants.empty()) {
827 Value *RealVal = operator[](ResolveConstants.back().second);
828 Constant *Placeholder = ResolveConstants.back().first;
829 ResolveConstants.pop_back();
831 // Loop over all users of the placeholder, updating them to reference the
832 // new value. If they reference more than one placeholder, update them all
834 while (!Placeholder->use_empty()) {
835 auto UI = Placeholder->user_begin();
838 // If the using object isn't uniqued, just update the operands. This
839 // handles instructions and initializers for global variables.
840 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
841 UI.getUse().set(RealVal);
845 // Otherwise, we have a constant that uses the placeholder. Replace that
846 // constant with a new constant that has *all* placeholder uses updated.
847 Constant *UserC = cast<Constant>(U);
848 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
851 if (!isa<ConstantPlaceHolder>(*I)) {
852 // Not a placeholder reference.
854 } else if (*I == Placeholder) {
855 // Common case is that it just references this one placeholder.
858 // Otherwise, look up the placeholder in ResolveConstants.
859 ResolveConstantsTy::iterator It =
860 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
861 std::pair<Constant*, unsigned>(cast<Constant>(*I),
863 assert(It != ResolveConstants.end() && It->first == *I);
864 NewOp = operator[](It->second);
867 NewOps.push_back(cast<Constant>(NewOp));
870 // Make the new constant.
872 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
873 NewC = ConstantArray::get(UserCA->getType(), NewOps);
874 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
875 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
876 } else if (isa<ConstantVector>(UserC)) {
877 NewC = ConstantVector::get(NewOps);
879 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
880 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
883 UserC->replaceAllUsesWith(NewC);
884 UserC->destroyConstant();
888 // Update all ValueHandles, they should be the only users at this point.
889 Placeholder->replaceAllUsesWith(RealVal);
894 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
903 TrackingMDRef &OldMD = MDValuePtrs[Idx];
909 // If there was a forward reference to this value, replace it.
910 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
911 PrevMD->replaceAllUsesWith(MD);
915 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
919 if (Metadata *MD = MDValuePtrs[Idx])
922 // Track forward refs to be resolved later.
924 MinFwdRef = std::min(MinFwdRef, Idx);
925 MaxFwdRef = std::max(MaxFwdRef, Idx);
928 MinFwdRef = MaxFwdRef = Idx;
932 // Create and return a placeholder, which will later be RAUW'd.
933 Metadata *MD = MDNode::getTemporary(Context, None).release();
934 MDValuePtrs[Idx].reset(MD);
938 void BitcodeReaderMDValueList::tryToResolveCycles() {
944 // Still forward references... can't resolve cycles.
947 // Resolve any cycles.
948 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
949 auto &MD = MDValuePtrs[I];
950 auto *N = dyn_cast_or_null<MDNode>(MD);
954 assert(!N->isTemporary() && "Unexpected forward reference");
958 // Make sure we return early again until there's another forward ref.
962 Type *BitcodeReader::getTypeByID(unsigned ID) {
963 // The type table size is always specified correctly.
964 if (ID >= TypeList.size())
967 if (Type *Ty = TypeList[ID])
970 // If we have a forward reference, the only possible case is when it is to a
971 // named struct. Just create a placeholder for now.
972 return TypeList[ID] = createIdentifiedStructType(Context);
975 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
977 auto *Ret = StructType::create(Context, Name);
978 IdentifiedStructTypes.push_back(Ret);
982 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
983 auto *Ret = StructType::create(Context);
984 IdentifiedStructTypes.push_back(Ret);
989 //===----------------------------------------------------------------------===//
990 // Functions for parsing blocks from the bitcode file
991 //===----------------------------------------------------------------------===//
994 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
995 /// been decoded from the given integer. This function must stay in sync with
996 /// 'encodeLLVMAttributesForBitcode'.
997 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
998 uint64_t EncodedAttrs) {
999 // FIXME: Remove in 4.0.
1001 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1002 // the bits above 31 down by 11 bits.
1003 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1004 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1005 "Alignment must be a power of two.");
1008 B.addAlignmentAttr(Alignment);
1009 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1010 (EncodedAttrs & 0xffff));
1013 std::error_code BitcodeReader::parseAttributeBlock() {
1014 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1015 return error("Invalid record");
1017 if (!MAttributes.empty())
1018 return error("Invalid multiple blocks");
1020 SmallVector<uint64_t, 64> Record;
1022 SmallVector<AttributeSet, 8> Attrs;
1024 // Read all the records.
1026 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1028 switch (Entry.Kind) {
1029 case BitstreamEntry::SubBlock: // Handled for us already.
1030 case BitstreamEntry::Error:
1031 return error("Malformed block");
1032 case BitstreamEntry::EndBlock:
1033 return std::error_code();
1034 case BitstreamEntry::Record:
1035 // The interesting case.
1041 switch (Stream.readRecord(Entry.ID, Record)) {
1042 default: // Default behavior: ignore.
1044 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1045 // FIXME: Remove in 4.0.
1046 if (Record.size() & 1)
1047 return error("Invalid record");
1049 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1051 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1052 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1055 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1059 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1060 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1061 Attrs.push_back(MAttributeGroups[Record[i]]);
1063 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1071 // Returns Attribute::None on unrecognized codes.
1072 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1075 return Attribute::None;
1076 case bitc::ATTR_KIND_ALIGNMENT:
1077 return Attribute::Alignment;
1078 case bitc::ATTR_KIND_ALWAYS_INLINE:
1079 return Attribute::AlwaysInline;
1080 case bitc::ATTR_KIND_BUILTIN:
1081 return Attribute::Builtin;
1082 case bitc::ATTR_KIND_BY_VAL:
1083 return Attribute::ByVal;
1084 case bitc::ATTR_KIND_IN_ALLOCA:
1085 return Attribute::InAlloca;
1086 case bitc::ATTR_KIND_COLD:
1087 return Attribute::Cold;
1088 case bitc::ATTR_KIND_CONVERGENT:
1089 return Attribute::Convergent;
1090 case bitc::ATTR_KIND_INLINE_HINT:
1091 return Attribute::InlineHint;
1092 case bitc::ATTR_KIND_IN_REG:
1093 return Attribute::InReg;
1094 case bitc::ATTR_KIND_JUMP_TABLE:
1095 return Attribute::JumpTable;
1096 case bitc::ATTR_KIND_MIN_SIZE:
1097 return Attribute::MinSize;
1098 case bitc::ATTR_KIND_NAKED:
1099 return Attribute::Naked;
1100 case bitc::ATTR_KIND_NEST:
1101 return Attribute::Nest;
1102 case bitc::ATTR_KIND_NO_ALIAS:
1103 return Attribute::NoAlias;
1104 case bitc::ATTR_KIND_NO_BUILTIN:
1105 return Attribute::NoBuiltin;
1106 case bitc::ATTR_KIND_NO_CAPTURE:
1107 return Attribute::NoCapture;
1108 case bitc::ATTR_KIND_NO_DUPLICATE:
1109 return Attribute::NoDuplicate;
1110 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1111 return Attribute::NoImplicitFloat;
1112 case bitc::ATTR_KIND_NO_INLINE:
1113 return Attribute::NoInline;
1114 case bitc::ATTR_KIND_NON_LAZY_BIND:
1115 return Attribute::NonLazyBind;
1116 case bitc::ATTR_KIND_NON_NULL:
1117 return Attribute::NonNull;
1118 case bitc::ATTR_KIND_DEREFERENCEABLE:
1119 return Attribute::Dereferenceable;
1120 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1121 return Attribute::DereferenceableOrNull;
1122 case bitc::ATTR_KIND_NO_RED_ZONE:
1123 return Attribute::NoRedZone;
1124 case bitc::ATTR_KIND_NO_RETURN:
1125 return Attribute::NoReturn;
1126 case bitc::ATTR_KIND_NO_UNWIND:
1127 return Attribute::NoUnwind;
1128 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1129 return Attribute::OptimizeForSize;
1130 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1131 return Attribute::OptimizeNone;
1132 case bitc::ATTR_KIND_READ_NONE:
1133 return Attribute::ReadNone;
1134 case bitc::ATTR_KIND_READ_ONLY:
1135 return Attribute::ReadOnly;
1136 case bitc::ATTR_KIND_RETURNED:
1137 return Attribute::Returned;
1138 case bitc::ATTR_KIND_RETURNS_TWICE:
1139 return Attribute::ReturnsTwice;
1140 case bitc::ATTR_KIND_S_EXT:
1141 return Attribute::SExt;
1142 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1143 return Attribute::StackAlignment;
1144 case bitc::ATTR_KIND_STACK_PROTECT:
1145 return Attribute::StackProtect;
1146 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1147 return Attribute::StackProtectReq;
1148 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1149 return Attribute::StackProtectStrong;
1150 case bitc::ATTR_KIND_SAFESTACK:
1151 return Attribute::SafeStack;
1152 case bitc::ATTR_KIND_STRUCT_RET:
1153 return Attribute::StructRet;
1154 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1155 return Attribute::SanitizeAddress;
1156 case bitc::ATTR_KIND_SANITIZE_THREAD:
1157 return Attribute::SanitizeThread;
1158 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1159 return Attribute::SanitizeMemory;
1160 case bitc::ATTR_KIND_UW_TABLE:
1161 return Attribute::UWTable;
1162 case bitc::ATTR_KIND_Z_EXT:
1163 return Attribute::ZExt;
1167 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1168 unsigned &Alignment) {
1169 // Note: Alignment in bitcode files is incremented by 1, so that zero
1170 // can be used for default alignment.
1171 if (Exponent > Value::MaxAlignmentExponent + 1)
1172 return error("Invalid alignment value");
1173 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1174 return std::error_code();
1177 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1178 Attribute::AttrKind *Kind) {
1179 *Kind = getAttrFromCode(Code);
1180 if (*Kind == Attribute::None)
1181 return error(BitcodeError::CorruptedBitcode,
1182 "Unknown attribute kind (" + Twine(Code) + ")");
1183 return std::error_code();
1186 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1187 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1188 return error("Invalid record");
1190 if (!MAttributeGroups.empty())
1191 return error("Invalid multiple blocks");
1193 SmallVector<uint64_t, 64> Record;
1195 // Read all the records.
1197 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1199 switch (Entry.Kind) {
1200 case BitstreamEntry::SubBlock: // Handled for us already.
1201 case BitstreamEntry::Error:
1202 return error("Malformed block");
1203 case BitstreamEntry::EndBlock:
1204 return std::error_code();
1205 case BitstreamEntry::Record:
1206 // The interesting case.
1212 switch (Stream.readRecord(Entry.ID, Record)) {
1213 default: // Default behavior: ignore.
1215 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1216 if (Record.size() < 3)
1217 return error("Invalid record");
1219 uint64_t GrpID = Record[0];
1220 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1223 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1224 if (Record[i] == 0) { // Enum attribute
1225 Attribute::AttrKind Kind;
1226 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1229 B.addAttribute(Kind);
1230 } else if (Record[i] == 1) { // Integer attribute
1231 Attribute::AttrKind Kind;
1232 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1234 if (Kind == Attribute::Alignment)
1235 B.addAlignmentAttr(Record[++i]);
1236 else if (Kind == Attribute::StackAlignment)
1237 B.addStackAlignmentAttr(Record[++i]);
1238 else if (Kind == Attribute::Dereferenceable)
1239 B.addDereferenceableAttr(Record[++i]);
1240 else if (Kind == Attribute::DereferenceableOrNull)
1241 B.addDereferenceableOrNullAttr(Record[++i]);
1242 } else { // String attribute
1243 assert((Record[i] == 3 || Record[i] == 4) &&
1244 "Invalid attribute group entry");
1245 bool HasValue = (Record[i++] == 4);
1246 SmallString<64> KindStr;
1247 SmallString<64> ValStr;
1249 while (Record[i] != 0 && i != e)
1250 KindStr += Record[i++];
1251 assert(Record[i] == 0 && "Kind string not null terminated");
1254 // Has a value associated with it.
1255 ++i; // Skip the '0' that terminates the "kind" string.
1256 while (Record[i] != 0 && i != e)
1257 ValStr += Record[i++];
1258 assert(Record[i] == 0 && "Value string not null terminated");
1261 B.addAttribute(KindStr.str(), ValStr.str());
1265 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1272 std::error_code BitcodeReader::parseTypeTable() {
1273 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1274 return error("Invalid record");
1276 return parseTypeTableBody();
1279 std::error_code BitcodeReader::parseTypeTableBody() {
1280 if (!TypeList.empty())
1281 return error("Invalid multiple blocks");
1283 SmallVector<uint64_t, 64> Record;
1284 unsigned NumRecords = 0;
1286 SmallString<64> TypeName;
1288 // Read all the records for this type table.
1290 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1292 switch (Entry.Kind) {
1293 case BitstreamEntry::SubBlock: // Handled for us already.
1294 case BitstreamEntry::Error:
1295 return error("Malformed block");
1296 case BitstreamEntry::EndBlock:
1297 if (NumRecords != TypeList.size())
1298 return error("Malformed block");
1299 return std::error_code();
1300 case BitstreamEntry::Record:
1301 // The interesting case.
1307 Type *ResultTy = nullptr;
1308 switch (Stream.readRecord(Entry.ID, Record)) {
1310 return error("Invalid value");
1311 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1312 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1313 // type list. This allows us to reserve space.
1314 if (Record.size() < 1)
1315 return error("Invalid record");
1316 TypeList.resize(Record[0]);
1318 case bitc::TYPE_CODE_VOID: // VOID
1319 ResultTy = Type::getVoidTy(Context);
1321 case bitc::TYPE_CODE_HALF: // HALF
1322 ResultTy = Type::getHalfTy(Context);
1324 case bitc::TYPE_CODE_FLOAT: // FLOAT
1325 ResultTy = Type::getFloatTy(Context);
1327 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1328 ResultTy = Type::getDoubleTy(Context);
1330 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1331 ResultTy = Type::getX86_FP80Ty(Context);
1333 case bitc::TYPE_CODE_FP128: // FP128
1334 ResultTy = Type::getFP128Ty(Context);
1336 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1337 ResultTy = Type::getPPC_FP128Ty(Context);
1339 case bitc::TYPE_CODE_LABEL: // LABEL
1340 ResultTy = Type::getLabelTy(Context);
1342 case bitc::TYPE_CODE_METADATA: // METADATA
1343 ResultTy = Type::getMetadataTy(Context);
1345 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1346 ResultTy = Type::getX86_MMXTy(Context);
1348 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1349 if (Record.size() < 1)
1350 return error("Invalid record");
1352 uint64_t NumBits = Record[0];
1353 if (NumBits < IntegerType::MIN_INT_BITS ||
1354 NumBits > IntegerType::MAX_INT_BITS)
1355 return error("Bitwidth for integer type out of range");
1356 ResultTy = IntegerType::get(Context, NumBits);
1359 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1360 // [pointee type, address space]
1361 if (Record.size() < 1)
1362 return error("Invalid record");
1363 unsigned AddressSpace = 0;
1364 if (Record.size() == 2)
1365 AddressSpace = Record[1];
1366 ResultTy = getTypeByID(Record[0]);
1368 !PointerType::isValidElementType(ResultTy))
1369 return error("Invalid type");
1370 ResultTy = PointerType::get(ResultTy, AddressSpace);
1373 case bitc::TYPE_CODE_FUNCTION_OLD: {
1374 // FIXME: attrid is dead, remove it in LLVM 4.0
1375 // FUNCTION: [vararg, attrid, retty, paramty x N]
1376 if (Record.size() < 3)
1377 return error("Invalid record");
1378 SmallVector<Type*, 8> ArgTys;
1379 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1380 if (Type *T = getTypeByID(Record[i]))
1381 ArgTys.push_back(T);
1386 ResultTy = getTypeByID(Record[2]);
1387 if (!ResultTy || ArgTys.size() < Record.size()-3)
1388 return error("Invalid type");
1390 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1393 case bitc::TYPE_CODE_FUNCTION: {
1394 // FUNCTION: [vararg, retty, paramty x N]
1395 if (Record.size() < 2)
1396 return error("Invalid record");
1397 SmallVector<Type*, 8> ArgTys;
1398 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1399 if (Type *T = getTypeByID(Record[i])) {
1400 if (!FunctionType::isValidArgumentType(T))
1401 return error("Invalid function argument type");
1402 ArgTys.push_back(T);
1408 ResultTy = getTypeByID(Record[1]);
1409 if (!ResultTy || ArgTys.size() < Record.size()-2)
1410 return error("Invalid type");
1412 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1415 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1416 if (Record.size() < 1)
1417 return error("Invalid record");
1418 SmallVector<Type*, 8> EltTys;
1419 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1420 if (Type *T = getTypeByID(Record[i]))
1421 EltTys.push_back(T);
1425 if (EltTys.size() != Record.size()-1)
1426 return error("Invalid type");
1427 ResultTy = StructType::get(Context, EltTys, Record[0]);
1430 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1431 if (convertToString(Record, 0, TypeName))
1432 return error("Invalid record");
1435 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1436 if (Record.size() < 1)
1437 return error("Invalid record");
1439 if (NumRecords >= TypeList.size())
1440 return error("Invalid TYPE table");
1442 // Check to see if this was forward referenced, if so fill in the temp.
1443 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1445 Res->setName(TypeName);
1446 TypeList[NumRecords] = nullptr;
1447 } else // Otherwise, create a new struct.
1448 Res = createIdentifiedStructType(Context, TypeName);
1451 SmallVector<Type*, 8> EltTys;
1452 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1453 if (Type *T = getTypeByID(Record[i]))
1454 EltTys.push_back(T);
1458 if (EltTys.size() != Record.size()-1)
1459 return error("Invalid record");
1460 Res->setBody(EltTys, Record[0]);
1464 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1465 if (Record.size() != 1)
1466 return error("Invalid record");
1468 if (NumRecords >= TypeList.size())
1469 return error("Invalid TYPE table");
1471 // Check to see if this was forward referenced, if so fill in the temp.
1472 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1474 Res->setName(TypeName);
1475 TypeList[NumRecords] = nullptr;
1476 } else // Otherwise, create a new struct with no body.
1477 Res = createIdentifiedStructType(Context, TypeName);
1482 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1483 if (Record.size() < 2)
1484 return error("Invalid record");
1485 ResultTy = getTypeByID(Record[1]);
1486 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1487 return error("Invalid type");
1488 ResultTy = ArrayType::get(ResultTy, Record[0]);
1490 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1491 if (Record.size() < 2)
1492 return error("Invalid record");
1494 return error("Invalid vector length");
1495 ResultTy = getTypeByID(Record[1]);
1496 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1497 return error("Invalid type");
1498 ResultTy = VectorType::get(ResultTy, Record[0]);
1502 if (NumRecords >= TypeList.size())
1503 return error("Invalid TYPE table");
1504 if (TypeList[NumRecords])
1506 "Invalid TYPE table: Only named structs can be forward referenced");
1507 assert(ResultTy && "Didn't read a type?");
1508 TypeList[NumRecords++] = ResultTy;
1512 std::error_code BitcodeReader::parseValueSymbolTable() {
1513 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1514 return error("Invalid record");
1516 SmallVector<uint64_t, 64> Record;
1518 Triple TT(TheModule->getTargetTriple());
1520 // Read all the records for this value table.
1521 SmallString<128> ValueName;
1523 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1525 switch (Entry.Kind) {
1526 case BitstreamEntry::SubBlock: // Handled for us already.
1527 case BitstreamEntry::Error:
1528 return error("Malformed block");
1529 case BitstreamEntry::EndBlock:
1530 return std::error_code();
1531 case BitstreamEntry::Record:
1532 // The interesting case.
1538 switch (Stream.readRecord(Entry.ID, Record)) {
1539 default: // Default behavior: unknown type.
1541 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1542 if (convertToString(Record, 1, ValueName))
1543 return error("Invalid record");
1544 unsigned ValueID = Record[0];
1545 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1546 return error("Invalid record");
1547 Value *V = ValueList[ValueID];
1549 V->setName(StringRef(ValueName.data(), ValueName.size()));
1550 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1551 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1552 if (TT.isOSBinFormatMachO())
1553 GO->setComdat(nullptr);
1555 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1561 case bitc::VST_CODE_BBENTRY: {
1562 if (convertToString(Record, 1, ValueName))
1563 return error("Invalid record");
1564 BasicBlock *BB = getBasicBlock(Record[0]);
1566 return error("Invalid record");
1568 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1576 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1578 std::error_code BitcodeReader::parseMetadata() {
1579 IsMetadataMaterialized = true;
1580 unsigned NextMDValueNo = MDValueList.size();
1582 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1583 return error("Invalid record");
1585 SmallVector<uint64_t, 64> Record;
1588 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1589 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1591 return getMD(ID - 1);
1594 auto getMDString = [&](unsigned ID) -> MDString *{
1595 // This requires that the ID is not really a forward reference. In
1596 // particular, the MDString must already have been resolved.
1597 return cast_or_null<MDString>(getMDOrNull(ID));
1600 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1601 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1603 // Read all the records.
1605 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1607 switch (Entry.Kind) {
1608 case BitstreamEntry::SubBlock: // Handled for us already.
1609 case BitstreamEntry::Error:
1610 return error("Malformed block");
1611 case BitstreamEntry::EndBlock:
1612 MDValueList.tryToResolveCycles();
1613 return std::error_code();
1614 case BitstreamEntry::Record:
1615 // The interesting case.
1621 unsigned Code = Stream.readRecord(Entry.ID, Record);
1622 bool IsDistinct = false;
1624 default: // Default behavior: ignore.
1626 case bitc::METADATA_NAME: {
1627 // Read name of the named metadata.
1628 SmallString<8> Name(Record.begin(), Record.end());
1630 Code = Stream.ReadCode();
1632 unsigned NextBitCode = Stream.readRecord(Code, Record);
1633 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1634 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1636 // Read named metadata elements.
1637 unsigned Size = Record.size();
1638 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1639 for (unsigned i = 0; i != Size; ++i) {
1640 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1642 return error("Invalid record");
1643 NMD->addOperand(MD);
1647 case bitc::METADATA_OLD_FN_NODE: {
1648 // FIXME: Remove in 4.0.
1649 // This is a LocalAsMetadata record, the only type of function-local
1651 if (Record.size() % 2 == 1)
1652 return error("Invalid record");
1654 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1655 // to be legal, but there's no upgrade path.
1656 auto dropRecord = [&] {
1657 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1659 if (Record.size() != 2) {
1664 Type *Ty = getTypeByID(Record[0]);
1665 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1670 MDValueList.assignValue(
1671 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1675 case bitc::METADATA_OLD_NODE: {
1676 // FIXME: Remove in 4.0.
1677 if (Record.size() % 2 == 1)
1678 return error("Invalid record");
1680 unsigned Size = Record.size();
1681 SmallVector<Metadata *, 8> Elts;
1682 for (unsigned i = 0; i != Size; i += 2) {
1683 Type *Ty = getTypeByID(Record[i]);
1685 return error("Invalid record");
1686 if (Ty->isMetadataTy())
1687 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1688 else if (!Ty->isVoidTy()) {
1690 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1691 assert(isa<ConstantAsMetadata>(MD) &&
1692 "Expected non-function-local metadata");
1695 Elts.push_back(nullptr);
1697 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1700 case bitc::METADATA_VALUE: {
1701 if (Record.size() != 2)
1702 return error("Invalid record");
1704 Type *Ty = getTypeByID(Record[0]);
1705 if (Ty->isMetadataTy() || Ty->isVoidTy())
1706 return error("Invalid record");
1708 MDValueList.assignValue(
1709 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1713 case bitc::METADATA_DISTINCT_NODE:
1716 case bitc::METADATA_NODE: {
1717 SmallVector<Metadata *, 8> Elts;
1718 Elts.reserve(Record.size());
1719 for (unsigned ID : Record)
1720 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1721 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1722 : MDNode::get(Context, Elts),
1726 case bitc::METADATA_LOCATION: {
1727 if (Record.size() != 5)
1728 return error("Invalid record");
1730 unsigned Line = Record[1];
1731 unsigned Column = Record[2];
1732 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1733 Metadata *InlinedAt =
1734 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1735 MDValueList.assignValue(
1736 GET_OR_DISTINCT(DILocation, Record[0],
1737 (Context, Line, Column, Scope, InlinedAt)),
1741 case bitc::METADATA_GENERIC_DEBUG: {
1742 if (Record.size() < 4)
1743 return error("Invalid record");
1745 unsigned Tag = Record[1];
1746 unsigned Version = Record[2];
1748 if (Tag >= 1u << 16 || Version != 0)
1749 return error("Invalid record");
1751 auto *Header = getMDString(Record[3]);
1752 SmallVector<Metadata *, 8> DwarfOps;
1753 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1754 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1756 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1757 (Context, Tag, Header, DwarfOps)),
1761 case bitc::METADATA_SUBRANGE: {
1762 if (Record.size() != 3)
1763 return error("Invalid record");
1765 MDValueList.assignValue(
1766 GET_OR_DISTINCT(DISubrange, Record[0],
1767 (Context, Record[1], unrotateSign(Record[2]))),
1771 case bitc::METADATA_ENUMERATOR: {
1772 if (Record.size() != 3)
1773 return error("Invalid record");
1775 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1776 (Context, unrotateSign(Record[1]),
1777 getMDString(Record[2]))),
1781 case bitc::METADATA_BASIC_TYPE: {
1782 if (Record.size() != 6)
1783 return error("Invalid record");
1785 MDValueList.assignValue(
1786 GET_OR_DISTINCT(DIBasicType, Record[0],
1787 (Context, Record[1], getMDString(Record[2]),
1788 Record[3], Record[4], Record[5])),
1792 case bitc::METADATA_DERIVED_TYPE: {
1793 if (Record.size() != 12)
1794 return error("Invalid record");
1796 MDValueList.assignValue(
1797 GET_OR_DISTINCT(DIDerivedType, Record[0],
1798 (Context, Record[1], getMDString(Record[2]),
1799 getMDOrNull(Record[3]), Record[4],
1800 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1801 Record[7], Record[8], Record[9], Record[10],
1802 getMDOrNull(Record[11]))),
1806 case bitc::METADATA_COMPOSITE_TYPE: {
1807 if (Record.size() != 16)
1808 return error("Invalid record");
1810 MDValueList.assignValue(
1811 GET_OR_DISTINCT(DICompositeType, Record[0],
1812 (Context, Record[1], getMDString(Record[2]),
1813 getMDOrNull(Record[3]), Record[4],
1814 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1815 Record[7], Record[8], Record[9], Record[10],
1816 getMDOrNull(Record[11]), Record[12],
1817 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1818 getMDString(Record[15]))),
1822 case bitc::METADATA_SUBROUTINE_TYPE: {
1823 if (Record.size() != 3)
1824 return error("Invalid record");
1826 MDValueList.assignValue(
1827 GET_OR_DISTINCT(DISubroutineType, Record[0],
1828 (Context, Record[1], getMDOrNull(Record[2]))),
1832 case bitc::METADATA_FILE: {
1833 if (Record.size() != 3)
1834 return error("Invalid record");
1836 MDValueList.assignValue(
1837 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1838 getMDString(Record[2]))),
1842 case bitc::METADATA_COMPILE_UNIT: {
1843 if (Record.size() < 14 || Record.size() > 15)
1844 return error("Invalid record");
1846 MDValueList.assignValue(
1848 DICompileUnit, Record[0],
1849 (Context, Record[1], getMDOrNull(Record[2]),
1850 getMDString(Record[3]), Record[4], getMDString(Record[5]),
1851 Record[6], getMDString(Record[7]), Record[8],
1852 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1853 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1854 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14])),
1858 case bitc::METADATA_SUBPROGRAM: {
1859 if (Record.size() != 19)
1860 return error("Invalid record");
1862 MDValueList.assignValue(
1864 DISubprogram, Record[0],
1865 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1866 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1867 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1868 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1869 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1870 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1874 case bitc::METADATA_LEXICAL_BLOCK: {
1875 if (Record.size() != 5)
1876 return error("Invalid record");
1878 MDValueList.assignValue(
1879 GET_OR_DISTINCT(DILexicalBlock, Record[0],
1880 (Context, getMDOrNull(Record[1]),
1881 getMDOrNull(Record[2]), Record[3], Record[4])),
1885 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1886 if (Record.size() != 4)
1887 return error("Invalid record");
1889 MDValueList.assignValue(
1890 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1891 (Context, getMDOrNull(Record[1]),
1892 getMDOrNull(Record[2]), Record[3])),
1896 case bitc::METADATA_NAMESPACE: {
1897 if (Record.size() != 5)
1898 return error("Invalid record");
1900 MDValueList.assignValue(
1901 GET_OR_DISTINCT(DINamespace, Record[0],
1902 (Context, getMDOrNull(Record[1]),
1903 getMDOrNull(Record[2]), getMDString(Record[3]),
1908 case bitc::METADATA_TEMPLATE_TYPE: {
1909 if (Record.size() != 3)
1910 return error("Invalid record");
1912 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1914 (Context, getMDString(Record[1]),
1915 getMDOrNull(Record[2]))),
1919 case bitc::METADATA_TEMPLATE_VALUE: {
1920 if (Record.size() != 5)
1921 return error("Invalid record");
1923 MDValueList.assignValue(
1924 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1925 (Context, Record[1], getMDString(Record[2]),
1926 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1930 case bitc::METADATA_GLOBAL_VAR: {
1931 if (Record.size() != 11)
1932 return error("Invalid record");
1934 MDValueList.assignValue(
1935 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1936 (Context, getMDOrNull(Record[1]),
1937 getMDString(Record[2]), getMDString(Record[3]),
1938 getMDOrNull(Record[4]), Record[5],
1939 getMDOrNull(Record[6]), Record[7], Record[8],
1940 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1944 case bitc::METADATA_LOCAL_VAR: {
1945 // 10th field is for the obseleted 'inlinedAt:' field.
1946 if (Record.size() != 9 && Record.size() != 10)
1947 return error("Invalid record");
1949 MDValueList.assignValue(
1950 GET_OR_DISTINCT(DILocalVariable, Record[0],
1951 (Context, Record[1], getMDOrNull(Record[2]),
1952 getMDString(Record[3]), getMDOrNull(Record[4]),
1953 Record[5], getMDOrNull(Record[6]), Record[7],
1958 case bitc::METADATA_EXPRESSION: {
1959 if (Record.size() < 1)
1960 return error("Invalid record");
1962 MDValueList.assignValue(
1963 GET_OR_DISTINCT(DIExpression, Record[0],
1964 (Context, makeArrayRef(Record).slice(1))),
1968 case bitc::METADATA_OBJC_PROPERTY: {
1969 if (Record.size() != 8)
1970 return error("Invalid record");
1972 MDValueList.assignValue(
1973 GET_OR_DISTINCT(DIObjCProperty, Record[0],
1974 (Context, getMDString(Record[1]),
1975 getMDOrNull(Record[2]), Record[3],
1976 getMDString(Record[4]), getMDString(Record[5]),
1977 Record[6], getMDOrNull(Record[7]))),
1981 case bitc::METADATA_IMPORTED_ENTITY: {
1982 if (Record.size() != 6)
1983 return error("Invalid record");
1985 MDValueList.assignValue(
1986 GET_OR_DISTINCT(DIImportedEntity, Record[0],
1987 (Context, Record[1], getMDOrNull(Record[2]),
1988 getMDOrNull(Record[3]), Record[4],
1989 getMDString(Record[5]))),
1993 case bitc::METADATA_STRING: {
1994 std::string String(Record.begin(), Record.end());
1995 llvm::UpgradeMDStringConstant(String);
1996 Metadata *MD = MDString::get(Context, String);
1997 MDValueList.assignValue(MD, NextMDValueNo++);
2000 case bitc::METADATA_KIND: {
2001 if (Record.size() < 2)
2002 return error("Invalid record");
2004 unsigned Kind = Record[0];
2005 SmallString<8> Name(Record.begin()+1, Record.end());
2007 unsigned NewKind = TheModule->getMDKindID(Name.str());
2008 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2009 return error("Conflicting METADATA_KIND records");
2014 #undef GET_OR_DISTINCT
2017 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2019 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2024 // There is no such thing as -0 with integers. "-0" really means MININT.
2028 /// Resolve all of the initializers for global values and aliases that we can.
2029 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2030 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2031 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2032 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2033 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2035 GlobalInitWorklist.swap(GlobalInits);
2036 AliasInitWorklist.swap(AliasInits);
2037 FunctionPrefixWorklist.swap(FunctionPrefixes);
2038 FunctionPrologueWorklist.swap(FunctionPrologues);
2040 while (!GlobalInitWorklist.empty()) {
2041 unsigned ValID = GlobalInitWorklist.back().second;
2042 if (ValID >= ValueList.size()) {
2043 // Not ready to resolve this yet, it requires something later in the file.
2044 GlobalInits.push_back(GlobalInitWorklist.back());
2046 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2047 GlobalInitWorklist.back().first->setInitializer(C);
2049 return error("Expected a constant");
2051 GlobalInitWorklist.pop_back();
2054 while (!AliasInitWorklist.empty()) {
2055 unsigned ValID = AliasInitWorklist.back().second;
2056 if (ValID >= ValueList.size()) {
2057 AliasInits.push_back(AliasInitWorklist.back());
2059 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2061 return error("Expected a constant");
2062 GlobalAlias *Alias = AliasInitWorklist.back().first;
2063 if (C->getType() != Alias->getType())
2064 return error("Alias and aliasee types don't match");
2065 Alias->setAliasee(C);
2067 AliasInitWorklist.pop_back();
2070 while (!FunctionPrefixWorklist.empty()) {
2071 unsigned ValID = FunctionPrefixWorklist.back().second;
2072 if (ValID >= ValueList.size()) {
2073 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2075 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2076 FunctionPrefixWorklist.back().first->setPrefixData(C);
2078 return error("Expected a constant");
2080 FunctionPrefixWorklist.pop_back();
2083 while (!FunctionPrologueWorklist.empty()) {
2084 unsigned ValID = FunctionPrologueWorklist.back().second;
2085 if (ValID >= ValueList.size()) {
2086 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2088 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2089 FunctionPrologueWorklist.back().first->setPrologueData(C);
2091 return error("Expected a constant");
2093 FunctionPrologueWorklist.pop_back();
2096 return std::error_code();
2099 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2100 SmallVector<uint64_t, 8> Words(Vals.size());
2101 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2102 BitcodeReader::decodeSignRotatedValue);
2104 return APInt(TypeBits, Words);
2107 std::error_code BitcodeReader::parseConstants() {
2108 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2109 return error("Invalid record");
2111 SmallVector<uint64_t, 64> Record;
2113 // Read all the records for this value table.
2114 Type *CurTy = Type::getInt32Ty(Context);
2115 unsigned NextCstNo = ValueList.size();
2117 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2119 switch (Entry.Kind) {
2120 case BitstreamEntry::SubBlock: // Handled for us already.
2121 case BitstreamEntry::Error:
2122 return error("Malformed block");
2123 case BitstreamEntry::EndBlock:
2124 if (NextCstNo != ValueList.size())
2125 return error("Invalid ronstant reference");
2127 // Once all the constants have been read, go through and resolve forward
2129 ValueList.resolveConstantForwardRefs();
2130 return std::error_code();
2131 case BitstreamEntry::Record:
2132 // The interesting case.
2139 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2141 default: // Default behavior: unknown constant
2142 case bitc::CST_CODE_UNDEF: // UNDEF
2143 V = UndefValue::get(CurTy);
2145 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2147 return error("Invalid record");
2148 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2149 return error("Invalid record");
2150 CurTy = TypeList[Record[0]];
2151 continue; // Skip the ValueList manipulation.
2152 case bitc::CST_CODE_NULL: // NULL
2153 V = Constant::getNullValue(CurTy);
2155 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2156 if (!CurTy->isIntegerTy() || Record.empty())
2157 return error("Invalid record");
2158 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2160 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2161 if (!CurTy->isIntegerTy() || Record.empty())
2162 return error("Invalid record");
2165 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2166 V = ConstantInt::get(Context, VInt);
2170 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2172 return error("Invalid record");
2173 if (CurTy->isHalfTy())
2174 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2175 APInt(16, (uint16_t)Record[0])));
2176 else if (CurTy->isFloatTy())
2177 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2178 APInt(32, (uint32_t)Record[0])));
2179 else if (CurTy->isDoubleTy())
2180 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2181 APInt(64, Record[0])));
2182 else if (CurTy->isX86_FP80Ty()) {
2183 // Bits are not stored the same way as a normal i80 APInt, compensate.
2184 uint64_t Rearrange[2];
2185 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2186 Rearrange[1] = Record[0] >> 48;
2187 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2188 APInt(80, Rearrange)));
2189 } else if (CurTy->isFP128Ty())
2190 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2191 APInt(128, Record)));
2192 else if (CurTy->isPPC_FP128Ty())
2193 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2194 APInt(128, Record)));
2196 V = UndefValue::get(CurTy);
2200 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2202 return error("Invalid record");
2204 unsigned Size = Record.size();
2205 SmallVector<Constant*, 16> Elts;
2207 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2208 for (unsigned i = 0; i != Size; ++i)
2209 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2210 STy->getElementType(i)));
2211 V = ConstantStruct::get(STy, Elts);
2212 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2213 Type *EltTy = ATy->getElementType();
2214 for (unsigned i = 0; i != Size; ++i)
2215 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2216 V = ConstantArray::get(ATy, Elts);
2217 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2218 Type *EltTy = VTy->getElementType();
2219 for (unsigned i = 0; i != Size; ++i)
2220 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2221 V = ConstantVector::get(Elts);
2223 V = UndefValue::get(CurTy);
2227 case bitc::CST_CODE_STRING: // STRING: [values]
2228 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2230 return error("Invalid record");
2232 SmallString<16> Elts(Record.begin(), Record.end());
2233 V = ConstantDataArray::getString(Context, Elts,
2234 BitCode == bitc::CST_CODE_CSTRING);
2237 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2239 return error("Invalid record");
2241 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2242 unsigned Size = Record.size();
2244 if (EltTy->isIntegerTy(8)) {
2245 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2246 if (isa<VectorType>(CurTy))
2247 V = ConstantDataVector::get(Context, Elts);
2249 V = ConstantDataArray::get(Context, Elts);
2250 } else if (EltTy->isIntegerTy(16)) {
2251 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2252 if (isa<VectorType>(CurTy))
2253 V = ConstantDataVector::get(Context, Elts);
2255 V = ConstantDataArray::get(Context, Elts);
2256 } else if (EltTy->isIntegerTy(32)) {
2257 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2258 if (isa<VectorType>(CurTy))
2259 V = ConstantDataVector::get(Context, Elts);
2261 V = ConstantDataArray::get(Context, Elts);
2262 } else if (EltTy->isIntegerTy(64)) {
2263 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2264 if (isa<VectorType>(CurTy))
2265 V = ConstantDataVector::get(Context, Elts);
2267 V = ConstantDataArray::get(Context, Elts);
2268 } else if (EltTy->isFloatTy()) {
2269 SmallVector<float, 16> Elts(Size);
2270 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2271 if (isa<VectorType>(CurTy))
2272 V = ConstantDataVector::get(Context, Elts);
2274 V = ConstantDataArray::get(Context, Elts);
2275 } else if (EltTy->isDoubleTy()) {
2276 SmallVector<double, 16> Elts(Size);
2277 std::transform(Record.begin(), Record.end(), Elts.begin(),
2279 if (isa<VectorType>(CurTy))
2280 V = ConstantDataVector::get(Context, Elts);
2282 V = ConstantDataArray::get(Context, Elts);
2284 return error("Invalid type for value");
2289 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2290 if (Record.size() < 3)
2291 return error("Invalid record");
2292 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2294 V = UndefValue::get(CurTy); // Unknown binop.
2296 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2297 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2299 if (Record.size() >= 4) {
2300 if (Opc == Instruction::Add ||
2301 Opc == Instruction::Sub ||
2302 Opc == Instruction::Mul ||
2303 Opc == Instruction::Shl) {
2304 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2305 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2306 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2307 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2308 } else if (Opc == Instruction::SDiv ||
2309 Opc == Instruction::UDiv ||
2310 Opc == Instruction::LShr ||
2311 Opc == Instruction::AShr) {
2312 if (Record[3] & (1 << bitc::PEO_EXACT))
2313 Flags |= SDivOperator::IsExact;
2316 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2320 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2321 if (Record.size() < 3)
2322 return error("Invalid record");
2323 int Opc = getDecodedCastOpcode(Record[0]);
2325 V = UndefValue::get(CurTy); // Unknown cast.
2327 Type *OpTy = getTypeByID(Record[1]);
2329 return error("Invalid record");
2330 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2331 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2332 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2336 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2337 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2339 Type *PointeeType = nullptr;
2340 if (Record.size() % 2)
2341 PointeeType = getTypeByID(Record[OpNum++]);
2342 SmallVector<Constant*, 16> Elts;
2343 while (OpNum != Record.size()) {
2344 Type *ElTy = getTypeByID(Record[OpNum++]);
2346 return error("Invalid record");
2347 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2352 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2354 return error("Explicit gep operator type does not match pointee type "
2355 "of pointer operand");
2357 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2358 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2360 bitc::CST_CODE_CE_INBOUNDS_GEP);
2363 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2364 if (Record.size() < 3)
2365 return error("Invalid record");
2367 Type *SelectorTy = Type::getInt1Ty(Context);
2369 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2370 // vector. Otherwise, it must be a single bit.
2371 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2372 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2373 VTy->getNumElements());
2375 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2377 ValueList.getConstantFwdRef(Record[1],CurTy),
2378 ValueList.getConstantFwdRef(Record[2],CurTy));
2381 case bitc::CST_CODE_CE_EXTRACTELT
2382 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2383 if (Record.size() < 3)
2384 return error("Invalid record");
2386 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2388 return error("Invalid record");
2389 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2390 Constant *Op1 = nullptr;
2391 if (Record.size() == 4) {
2392 Type *IdxTy = getTypeByID(Record[2]);
2394 return error("Invalid record");
2395 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2396 } else // TODO: Remove with llvm 4.0
2397 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2399 return error("Invalid record");
2400 V = ConstantExpr::getExtractElement(Op0, Op1);
2403 case bitc::CST_CODE_CE_INSERTELT
2404 : { // CE_INSERTELT: [opval, opval, opty, opval]
2405 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2406 if (Record.size() < 3 || !OpTy)
2407 return error("Invalid record");
2408 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2409 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2410 OpTy->getElementType());
2411 Constant *Op2 = nullptr;
2412 if (Record.size() == 4) {
2413 Type *IdxTy = getTypeByID(Record[2]);
2415 return error("Invalid record");
2416 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2417 } else // TODO: Remove with llvm 4.0
2418 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2420 return error("Invalid record");
2421 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2424 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2425 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2426 if (Record.size() < 3 || !OpTy)
2427 return error("Invalid record");
2428 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2429 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2430 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2431 OpTy->getNumElements());
2432 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2433 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2436 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2437 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2439 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2440 if (Record.size() < 4 || !RTy || !OpTy)
2441 return error("Invalid record");
2442 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2443 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2444 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2445 RTy->getNumElements());
2446 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2447 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2450 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2451 if (Record.size() < 4)
2452 return error("Invalid record");
2453 Type *OpTy = getTypeByID(Record[0]);
2455 return error("Invalid record");
2456 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2457 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2459 if (OpTy->isFPOrFPVectorTy())
2460 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2462 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2465 // This maintains backward compatibility, pre-asm dialect keywords.
2466 // FIXME: Remove with the 4.0 release.
2467 case bitc::CST_CODE_INLINEASM_OLD: {
2468 if (Record.size() < 2)
2469 return error("Invalid record");
2470 std::string AsmStr, ConstrStr;
2471 bool HasSideEffects = Record[0] & 1;
2472 bool IsAlignStack = Record[0] >> 1;
2473 unsigned AsmStrSize = Record[1];
2474 if (2+AsmStrSize >= Record.size())
2475 return error("Invalid record");
2476 unsigned ConstStrSize = Record[2+AsmStrSize];
2477 if (3+AsmStrSize+ConstStrSize > Record.size())
2478 return error("Invalid record");
2480 for (unsigned i = 0; i != AsmStrSize; ++i)
2481 AsmStr += (char)Record[2+i];
2482 for (unsigned i = 0; i != ConstStrSize; ++i)
2483 ConstrStr += (char)Record[3+AsmStrSize+i];
2484 PointerType *PTy = cast<PointerType>(CurTy);
2485 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2486 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2489 // This version adds support for the asm dialect keywords (e.g.,
2491 case bitc::CST_CODE_INLINEASM: {
2492 if (Record.size() < 2)
2493 return error("Invalid record");
2494 std::string AsmStr, ConstrStr;
2495 bool HasSideEffects = Record[0] & 1;
2496 bool IsAlignStack = (Record[0] >> 1) & 1;
2497 unsigned AsmDialect = Record[0] >> 2;
2498 unsigned AsmStrSize = Record[1];
2499 if (2+AsmStrSize >= Record.size())
2500 return error("Invalid record");
2501 unsigned ConstStrSize = Record[2+AsmStrSize];
2502 if (3+AsmStrSize+ConstStrSize > Record.size())
2503 return error("Invalid record");
2505 for (unsigned i = 0; i != AsmStrSize; ++i)
2506 AsmStr += (char)Record[2+i];
2507 for (unsigned i = 0; i != ConstStrSize; ++i)
2508 ConstrStr += (char)Record[3+AsmStrSize+i];
2509 PointerType *PTy = cast<PointerType>(CurTy);
2510 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2511 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2512 InlineAsm::AsmDialect(AsmDialect));
2515 case bitc::CST_CODE_BLOCKADDRESS:{
2516 if (Record.size() < 3)
2517 return error("Invalid record");
2518 Type *FnTy = getTypeByID(Record[0]);
2520 return error("Invalid record");
2522 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2524 return error("Invalid record");
2526 // Don't let Fn get dematerialized.
2527 BlockAddressesTaken.insert(Fn);
2529 // If the function is already parsed we can insert the block address right
2532 unsigned BBID = Record[2];
2534 // Invalid reference to entry block.
2535 return error("Invalid ID");
2537 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2538 for (size_t I = 0, E = BBID; I != E; ++I) {
2540 return error("Invalid ID");
2545 // Otherwise insert a placeholder and remember it so it can be inserted
2546 // when the function is parsed.
2547 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2549 BasicBlockFwdRefQueue.push_back(Fn);
2550 if (FwdBBs.size() < BBID + 1)
2551 FwdBBs.resize(BBID + 1);
2553 FwdBBs[BBID] = BasicBlock::Create(Context);
2556 V = BlockAddress::get(Fn, BB);
2561 ValueList.assignValue(V, NextCstNo);
2566 std::error_code BitcodeReader::parseUseLists() {
2567 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2568 return error("Invalid record");
2570 // Read all the records.
2571 SmallVector<uint64_t, 64> Record;
2573 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2575 switch (Entry.Kind) {
2576 case BitstreamEntry::SubBlock: // Handled for us already.
2577 case BitstreamEntry::Error:
2578 return error("Malformed block");
2579 case BitstreamEntry::EndBlock:
2580 return std::error_code();
2581 case BitstreamEntry::Record:
2582 // The interesting case.
2586 // Read a use list record.
2589 switch (Stream.readRecord(Entry.ID, Record)) {
2590 default: // Default behavior: unknown type.
2592 case bitc::USELIST_CODE_BB:
2595 case bitc::USELIST_CODE_DEFAULT: {
2596 unsigned RecordLength = Record.size();
2597 if (RecordLength < 3)
2598 // Records should have at least an ID and two indexes.
2599 return error("Invalid record");
2600 unsigned ID = Record.back();
2605 assert(ID < FunctionBBs.size() && "Basic block not found");
2606 V = FunctionBBs[ID];
2609 unsigned NumUses = 0;
2610 SmallDenseMap<const Use *, unsigned, 16> Order;
2611 for (const Use &U : V->uses()) {
2612 if (++NumUses > Record.size())
2614 Order[&U] = Record[NumUses - 1];
2616 if (Order.size() != Record.size() || NumUses > Record.size())
2617 // Mismatches can happen if the functions are being materialized lazily
2618 // (out-of-order), or a value has been upgraded.
2621 V->sortUseList([&](const Use &L, const Use &R) {
2622 return Order.lookup(&L) < Order.lookup(&R);
2630 /// When we see the block for metadata, remember where it is and then skip it.
2631 /// This lets us lazily deserialize the metadata.
2632 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2633 // Save the current stream state.
2634 uint64_t CurBit = Stream.GetCurrentBitNo();
2635 DeferredMetadataInfo.push_back(CurBit);
2637 // Skip over the block for now.
2638 if (Stream.SkipBlock())
2639 return error("Invalid record");
2640 return std::error_code();
2643 std::error_code BitcodeReader::materializeMetadata() {
2644 for (uint64_t BitPos : DeferredMetadataInfo) {
2645 // Move the bit stream to the saved position.
2646 Stream.JumpToBit(BitPos);
2647 if (std::error_code EC = parseMetadata())
2650 DeferredMetadataInfo.clear();
2651 return std::error_code();
2654 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2656 /// When we see the block for a function body, remember where it is and then
2657 /// skip it. This lets us lazily deserialize the functions.
2658 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2659 // Get the function we are talking about.
2660 if (FunctionsWithBodies.empty())
2661 return error("Insufficient function protos");
2663 Function *Fn = FunctionsWithBodies.back();
2664 FunctionsWithBodies.pop_back();
2666 // Save the current stream state.
2667 uint64_t CurBit = Stream.GetCurrentBitNo();
2668 DeferredFunctionInfo[Fn] = CurBit;
2670 // Skip over the function block for now.
2671 if (Stream.SkipBlock())
2672 return error("Invalid record");
2673 return std::error_code();
2676 std::error_code BitcodeReader::globalCleanup() {
2677 // Patch the initializers for globals and aliases up.
2678 resolveGlobalAndAliasInits();
2679 if (!GlobalInits.empty() || !AliasInits.empty())
2680 return error("Malformed global initializer set");
2682 // Look for intrinsic functions which need to be upgraded at some point
2683 for (Function &F : *TheModule) {
2685 if (UpgradeIntrinsicFunction(&F, NewFn))
2686 UpgradedIntrinsics.push_back(std::make_pair(&F, NewFn));
2689 // Look for global variables which need to be renamed.
2690 for (GlobalVariable &GV : TheModule->globals())
2691 UpgradeGlobalVariable(&GV);
2693 // Force deallocation of memory for these vectors to favor the client that
2694 // want lazy deserialization.
2695 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2696 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2697 return std::error_code();
2700 std::error_code BitcodeReader::parseModule(bool Resume,
2701 bool ShouldLazyLoadMetadata) {
2703 Stream.JumpToBit(NextUnreadBit);
2704 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2705 return error("Invalid record");
2707 SmallVector<uint64_t, 64> Record;
2708 std::vector<std::string> SectionTable;
2709 std::vector<std::string> GCTable;
2711 // Read all the records for this module.
2713 BitstreamEntry Entry = Stream.advance();
2715 switch (Entry.Kind) {
2716 case BitstreamEntry::Error:
2717 return error("Malformed block");
2718 case BitstreamEntry::EndBlock:
2719 return globalCleanup();
2721 case BitstreamEntry::SubBlock:
2723 default: // Skip unknown content.
2724 if (Stream.SkipBlock())
2725 return error("Invalid record");
2727 case bitc::BLOCKINFO_BLOCK_ID:
2728 if (Stream.ReadBlockInfoBlock())
2729 return error("Malformed block");
2731 case bitc::PARAMATTR_BLOCK_ID:
2732 if (std::error_code EC = parseAttributeBlock())
2735 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2736 if (std::error_code EC = parseAttributeGroupBlock())
2739 case bitc::TYPE_BLOCK_ID_NEW:
2740 if (std::error_code EC = parseTypeTable())
2743 case bitc::VALUE_SYMTAB_BLOCK_ID:
2744 if (std::error_code EC = parseValueSymbolTable())
2746 SeenValueSymbolTable = true;
2748 case bitc::CONSTANTS_BLOCK_ID:
2749 if (std::error_code EC = parseConstants())
2751 if (std::error_code EC = resolveGlobalAndAliasInits())
2754 case bitc::METADATA_BLOCK_ID:
2755 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2756 if (std::error_code EC = rememberAndSkipMetadata())
2760 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2761 if (std::error_code EC = parseMetadata())
2764 case bitc::FUNCTION_BLOCK_ID:
2765 // If this is the first function body we've seen, reverse the
2766 // FunctionsWithBodies list.
2767 if (!SeenFirstFunctionBody) {
2768 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2769 if (std::error_code EC = globalCleanup())
2771 SeenFirstFunctionBody = true;
2774 if (std::error_code EC = rememberAndSkipFunctionBody())
2776 // For streaming bitcode, suspend parsing when we reach the function
2777 // bodies. Subsequent materialization calls will resume it when
2778 // necessary. For streaming, the function bodies must be at the end of
2779 // the bitcode. If the bitcode file is old, the symbol table will be
2780 // at the end instead and will not have been seen yet. In this case,
2781 // just finish the parse now.
2782 if (IsStreamed && SeenValueSymbolTable) {
2783 NextUnreadBit = Stream.GetCurrentBitNo();
2784 return std::error_code();
2787 case bitc::USELIST_BLOCK_ID:
2788 if (std::error_code EC = parseUseLists())
2794 case BitstreamEntry::Record:
2795 // The interesting case.
2801 switch (Stream.readRecord(Entry.ID, Record)) {
2802 default: break; // Default behavior, ignore unknown content.
2803 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2804 if (Record.size() < 1)
2805 return error("Invalid record");
2806 // Only version #0 and #1 are supported so far.
2807 unsigned module_version = Record[0];
2808 switch (module_version) {
2810 return error("Invalid value");
2812 UseRelativeIDs = false;
2815 UseRelativeIDs = true;
2820 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2822 if (convertToString(Record, 0, S))
2823 return error("Invalid record");
2824 TheModule->setTargetTriple(S);
2827 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2829 if (convertToString(Record, 0, S))
2830 return error("Invalid record");
2831 TheModule->setDataLayout(S);
2834 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2836 if (convertToString(Record, 0, S))
2837 return error("Invalid record");
2838 TheModule->setModuleInlineAsm(S);
2841 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2842 // FIXME: Remove in 4.0.
2844 if (convertToString(Record, 0, S))
2845 return error("Invalid record");
2849 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2851 if (convertToString(Record, 0, S))
2852 return error("Invalid record");
2853 SectionTable.push_back(S);
2856 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2858 if (convertToString(Record, 0, S))
2859 return error("Invalid record");
2860 GCTable.push_back(S);
2863 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2864 if (Record.size() < 2)
2865 return error("Invalid record");
2866 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2867 unsigned ComdatNameSize = Record[1];
2868 std::string ComdatName;
2869 ComdatName.reserve(ComdatNameSize);
2870 for (unsigned i = 0; i != ComdatNameSize; ++i)
2871 ComdatName += (char)Record[2 + i];
2872 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2873 C->setSelectionKind(SK);
2874 ComdatList.push_back(C);
2877 // GLOBALVAR: [pointer type, isconst, initid,
2878 // linkage, alignment, section, visibility, threadlocal,
2879 // unnamed_addr, externally_initialized, dllstorageclass,
2881 case bitc::MODULE_CODE_GLOBALVAR: {
2882 if (Record.size() < 6)
2883 return error("Invalid record");
2884 Type *Ty = getTypeByID(Record[0]);
2886 return error("Invalid record");
2887 bool isConstant = Record[1] & 1;
2888 bool explicitType = Record[1] & 2;
2889 unsigned AddressSpace;
2891 AddressSpace = Record[1] >> 2;
2893 if (!Ty->isPointerTy())
2894 return error("Invalid type for value");
2895 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2896 Ty = cast<PointerType>(Ty)->getElementType();
2899 uint64_t RawLinkage = Record[3];
2900 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2902 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2904 std::string Section;
2906 if (Record[5]-1 >= SectionTable.size())
2907 return error("Invalid ID");
2908 Section = SectionTable[Record[5]-1];
2910 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2911 // Local linkage must have default visibility.
2912 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2913 // FIXME: Change to an error if non-default in 4.0.
2914 Visibility = getDecodedVisibility(Record[6]);
2916 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2917 if (Record.size() > 7)
2918 TLM = getDecodedThreadLocalMode(Record[7]);
2920 bool UnnamedAddr = false;
2921 if (Record.size() > 8)
2922 UnnamedAddr = Record[8];
2924 bool ExternallyInitialized = false;
2925 if (Record.size() > 9)
2926 ExternallyInitialized = Record[9];
2928 GlobalVariable *NewGV =
2929 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2930 TLM, AddressSpace, ExternallyInitialized);
2931 NewGV->setAlignment(Alignment);
2932 if (!Section.empty())
2933 NewGV->setSection(Section);
2934 NewGV->setVisibility(Visibility);
2935 NewGV->setUnnamedAddr(UnnamedAddr);
2937 if (Record.size() > 10)
2938 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2940 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2942 ValueList.push_back(NewGV);
2944 // Remember which value to use for the global initializer.
2945 if (unsigned InitID = Record[2])
2946 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2948 if (Record.size() > 11) {
2949 if (unsigned ComdatID = Record[11]) {
2950 if (ComdatID > ComdatList.size())
2951 return error("Invalid global variable comdat ID");
2952 NewGV->setComdat(ComdatList[ComdatID - 1]);
2954 } else if (hasImplicitComdat(RawLinkage)) {
2955 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2959 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2960 // alignment, section, visibility, gc, unnamed_addr,
2961 // prologuedata, dllstorageclass, comdat, prefixdata]
2962 case bitc::MODULE_CODE_FUNCTION: {
2963 if (Record.size() < 8)
2964 return error("Invalid record");
2965 Type *Ty = getTypeByID(Record[0]);
2967 return error("Invalid record");
2968 if (auto *PTy = dyn_cast<PointerType>(Ty))
2969 Ty = PTy->getElementType();
2970 auto *FTy = dyn_cast<FunctionType>(Ty);
2972 return error("Invalid type for value");
2974 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2977 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2978 bool isProto = Record[2];
2979 uint64_t RawLinkage = Record[3];
2980 Func->setLinkage(getDecodedLinkage(RawLinkage));
2981 Func->setAttributes(getAttributes(Record[4]));
2984 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2986 Func->setAlignment(Alignment);
2988 if (Record[6]-1 >= SectionTable.size())
2989 return error("Invalid ID");
2990 Func->setSection(SectionTable[Record[6]-1]);
2992 // Local linkage must have default visibility.
2993 if (!Func->hasLocalLinkage())
2994 // FIXME: Change to an error if non-default in 4.0.
2995 Func->setVisibility(getDecodedVisibility(Record[7]));
2996 if (Record.size() > 8 && Record[8]) {
2997 if (Record[8]-1 >= GCTable.size())
2998 return error("Invalid ID");
2999 Func->setGC(GCTable[Record[8]-1].c_str());
3001 bool UnnamedAddr = false;
3002 if (Record.size() > 9)
3003 UnnamedAddr = Record[9];
3004 Func->setUnnamedAddr(UnnamedAddr);
3005 if (Record.size() > 10 && Record[10] != 0)
3006 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3008 if (Record.size() > 11)
3009 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3011 upgradeDLLImportExportLinkage(Func, RawLinkage);
3013 if (Record.size() > 12) {
3014 if (unsigned ComdatID = Record[12]) {
3015 if (ComdatID > ComdatList.size())
3016 return error("Invalid function comdat ID");
3017 Func->setComdat(ComdatList[ComdatID - 1]);
3019 } else if (hasImplicitComdat(RawLinkage)) {
3020 Func->setComdat(reinterpret_cast<Comdat *>(1));
3023 if (Record.size() > 13 && Record[13] != 0)
3024 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3026 ValueList.push_back(Func);
3028 // If this is a function with a body, remember the prototype we are
3029 // creating now, so that we can match up the body with them later.
3031 Func->setIsMaterializable(true);
3032 FunctionsWithBodies.push_back(Func);
3034 DeferredFunctionInfo[Func] = 0;
3038 // ALIAS: [alias type, aliasee val#, linkage]
3039 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3040 case bitc::MODULE_CODE_ALIAS: {
3041 if (Record.size() < 3)
3042 return error("Invalid record");
3043 Type *Ty = getTypeByID(Record[0]);
3045 return error("Invalid record");
3046 auto *PTy = dyn_cast<PointerType>(Ty);
3048 return error("Invalid type for value");
3051 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3052 // Old bitcode files didn't have visibility field.
3053 // Local linkage must have default visibility.
3054 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3055 // FIXME: Change to an error if non-default in 4.0.
3056 NewGA->setVisibility(getDecodedVisibility(Record[3]));
3057 if (Record.size() > 4)
3058 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
3060 upgradeDLLImportExportLinkage(NewGA, Record[2]);
3061 if (Record.size() > 5)
3062 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
3063 if (Record.size() > 6)
3064 NewGA->setUnnamedAddr(Record[6]);
3065 ValueList.push_back(NewGA);
3066 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3069 /// MODULE_CODE_PURGEVALS: [numvals]
3070 case bitc::MODULE_CODE_PURGEVALS:
3071 // Trim down the value list to the specified size.
3072 if (Record.size() < 1 || Record[0] > ValueList.size())
3073 return error("Invalid record");
3074 ValueList.shrinkTo(Record[0]);
3082 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3083 Module *M, bool ShouldLazyLoadMetadata) {
3086 if (std::error_code EC = initStream(std::move(Streamer)))
3089 // Sniff for the signature.
3090 if (Stream.Read(8) != 'B' ||
3091 Stream.Read(8) != 'C' ||
3092 Stream.Read(4) != 0x0 ||
3093 Stream.Read(4) != 0xC ||
3094 Stream.Read(4) != 0xE ||
3095 Stream.Read(4) != 0xD)
3096 return error("Invalid bitcode signature");
3098 // We expect a number of well-defined blocks, though we don't necessarily
3099 // need to understand them all.
3101 if (Stream.AtEndOfStream()) {
3102 // We didn't really read a proper Module.
3103 return error("Malformed IR file");
3106 BitstreamEntry Entry =
3107 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3109 if (Entry.Kind != BitstreamEntry::SubBlock)
3110 return error("Malformed block");
3112 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3113 return parseModule(false, ShouldLazyLoadMetadata);
3115 if (Stream.SkipBlock())
3116 return error("Invalid record");
3120 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3121 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3122 return error("Invalid record");
3124 SmallVector<uint64_t, 64> Record;
3127 // Read all the records for this module.
3129 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3131 switch (Entry.Kind) {
3132 case BitstreamEntry::SubBlock: // Handled for us already.
3133 case BitstreamEntry::Error:
3134 return error("Malformed block");
3135 case BitstreamEntry::EndBlock:
3137 case BitstreamEntry::Record:
3138 // The interesting case.
3143 switch (Stream.readRecord(Entry.ID, Record)) {
3144 default: break; // Default behavior, ignore unknown content.
3145 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3147 if (convertToString(Record, 0, S))
3148 return error("Invalid record");
3155 llvm_unreachable("Exit infinite loop");
3158 ErrorOr<std::string> BitcodeReader::parseTriple() {
3159 if (std::error_code EC = initStream(nullptr))
3162 // Sniff for the signature.
3163 if (Stream.Read(8) != 'B' ||
3164 Stream.Read(8) != 'C' ||
3165 Stream.Read(4) != 0x0 ||
3166 Stream.Read(4) != 0xC ||
3167 Stream.Read(4) != 0xE ||
3168 Stream.Read(4) != 0xD)
3169 return error("Invalid bitcode signature");
3171 // We expect a number of well-defined blocks, though we don't necessarily
3172 // need to understand them all.
3174 BitstreamEntry Entry = Stream.advance();
3176 switch (Entry.Kind) {
3177 case BitstreamEntry::Error:
3178 return error("Malformed block");
3179 case BitstreamEntry::EndBlock:
3180 return std::error_code();
3182 case BitstreamEntry::SubBlock:
3183 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3184 return parseModuleTriple();
3186 // Ignore other sub-blocks.
3187 if (Stream.SkipBlock())
3188 return error("Malformed block");
3191 case BitstreamEntry::Record:
3192 Stream.skipRecord(Entry.ID);
3198 /// Parse metadata attachments.
3199 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3200 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3201 return error("Invalid record");
3203 SmallVector<uint64_t, 64> Record;
3205 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3207 switch (Entry.Kind) {
3208 case BitstreamEntry::SubBlock: // Handled for us already.
3209 case BitstreamEntry::Error:
3210 return error("Malformed block");
3211 case BitstreamEntry::EndBlock:
3212 return std::error_code();
3213 case BitstreamEntry::Record:
3214 // The interesting case.
3218 // Read a metadata attachment record.
3220 switch (Stream.readRecord(Entry.ID, Record)) {
3221 default: // Default behavior: ignore.
3223 case bitc::METADATA_ATTACHMENT: {
3224 unsigned RecordLength = Record.size();
3226 return error("Invalid record");
3227 if (RecordLength % 2 == 0) {
3228 // A function attachment.
3229 for (unsigned I = 0; I != RecordLength; I += 2) {
3230 auto K = MDKindMap.find(Record[I]);
3231 if (K == MDKindMap.end())
3232 return error("Invalid ID");
3233 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3234 F.setMetadata(K->second, cast<MDNode>(MD));
3239 // An instruction attachment.
3240 Instruction *Inst = InstructionList[Record[0]];
3241 for (unsigned i = 1; i != RecordLength; i = i+2) {
3242 unsigned Kind = Record[i];
3243 DenseMap<unsigned, unsigned>::iterator I =
3244 MDKindMap.find(Kind);
3245 if (I == MDKindMap.end())
3246 return error("Invalid ID");
3247 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3248 if (isa<LocalAsMetadata>(Node))
3249 // Drop the attachment. This used to be legal, but there's no
3252 Inst->setMetadata(I->second, cast<MDNode>(Node));
3253 if (I->second == LLVMContext::MD_tbaa)
3254 InstsWithTBAATag.push_back(Inst);
3262 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3263 Type *ValType, Type *PtrType) {
3264 if (!isa<PointerType>(PtrType))
3265 return error(DH, "Load/Store operand is not a pointer type");
3266 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3268 if (ValType && ValType != ElemType)
3269 return error(DH, "Explicit load/store type does not match pointee type of "
3271 if (!PointerType::isLoadableOrStorableType(ElemType))
3272 return error(DH, "Cannot load/store from pointer");
3273 return std::error_code();
3276 /// Lazily parse the specified function body block.
3277 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3278 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3279 return error("Invalid record");
3281 InstructionList.clear();
3282 unsigned ModuleValueListSize = ValueList.size();
3283 unsigned ModuleMDValueListSize = MDValueList.size();
3285 // Add all the function arguments to the value table.
3286 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3287 ValueList.push_back(I);
3289 unsigned NextValueNo = ValueList.size();
3290 BasicBlock *CurBB = nullptr;
3291 unsigned CurBBNo = 0;
3294 auto getLastInstruction = [&]() -> Instruction * {
3295 if (CurBB && !CurBB->empty())
3296 return &CurBB->back();
3297 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3298 !FunctionBBs[CurBBNo - 1]->empty())
3299 return &FunctionBBs[CurBBNo - 1]->back();
3303 // Read all the records.
3304 SmallVector<uint64_t, 64> Record;
3306 BitstreamEntry Entry = Stream.advance();
3308 switch (Entry.Kind) {
3309 case BitstreamEntry::Error:
3310 return error("Malformed block");
3311 case BitstreamEntry::EndBlock:
3312 goto OutOfRecordLoop;
3314 case BitstreamEntry::SubBlock:
3316 default: // Skip unknown content.
3317 if (Stream.SkipBlock())
3318 return error("Invalid record");
3320 case bitc::CONSTANTS_BLOCK_ID:
3321 if (std::error_code EC = parseConstants())
3323 NextValueNo = ValueList.size();
3325 case bitc::VALUE_SYMTAB_BLOCK_ID:
3326 if (std::error_code EC = parseValueSymbolTable())
3329 case bitc::METADATA_ATTACHMENT_ID:
3330 if (std::error_code EC = parseMetadataAttachment(*F))
3333 case bitc::METADATA_BLOCK_ID:
3334 if (std::error_code EC = parseMetadata())
3337 case bitc::USELIST_BLOCK_ID:
3338 if (std::error_code EC = parseUseLists())
3344 case BitstreamEntry::Record:
3345 // The interesting case.
3351 Instruction *I = nullptr;
3352 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3354 default: // Default behavior: reject
3355 return error("Invalid value");
3356 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3357 if (Record.size() < 1 || Record[0] == 0)
3358 return error("Invalid record");
3359 // Create all the basic blocks for the function.
3360 FunctionBBs.resize(Record[0]);
3362 // See if anything took the address of blocks in this function.
3363 auto BBFRI = BasicBlockFwdRefs.find(F);
3364 if (BBFRI == BasicBlockFwdRefs.end()) {
3365 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3366 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3368 auto &BBRefs = BBFRI->second;
3369 // Check for invalid basic block references.
3370 if (BBRefs.size() > FunctionBBs.size())
3371 return error("Invalid ID");
3372 assert(!BBRefs.empty() && "Unexpected empty array");
3373 assert(!BBRefs.front() && "Invalid reference to entry block");
3374 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3376 if (I < RE && BBRefs[I]) {
3377 BBRefs[I]->insertInto(F);
3378 FunctionBBs[I] = BBRefs[I];
3380 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3383 // Erase from the table.
3384 BasicBlockFwdRefs.erase(BBFRI);
3387 CurBB = FunctionBBs[0];
3391 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3392 // This record indicates that the last instruction is at the same
3393 // location as the previous instruction with a location.
3394 I = getLastInstruction();
3397 return error("Invalid record");
3398 I->setDebugLoc(LastLoc);
3402 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3403 I = getLastInstruction();
3404 if (!I || Record.size() < 4)
3405 return error("Invalid record");
3407 unsigned Line = Record[0], Col = Record[1];
3408 unsigned ScopeID = Record[2], IAID = Record[3];
3410 MDNode *Scope = nullptr, *IA = nullptr;
3411 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3412 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3413 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3414 I->setDebugLoc(LastLoc);
3419 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3422 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3423 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3424 OpNum+1 > Record.size())
3425 return error("Invalid record");
3427 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3429 return error("Invalid record");
3430 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3431 InstructionList.push_back(I);
3432 if (OpNum < Record.size()) {
3433 if (Opc == Instruction::Add ||
3434 Opc == Instruction::Sub ||
3435 Opc == Instruction::Mul ||
3436 Opc == Instruction::Shl) {
3437 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3438 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3439 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3440 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3441 } else if (Opc == Instruction::SDiv ||
3442 Opc == Instruction::UDiv ||
3443 Opc == Instruction::LShr ||
3444 Opc == Instruction::AShr) {
3445 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3446 cast<BinaryOperator>(I)->setIsExact(true);
3447 } else if (isa<FPMathOperator>(I)) {
3449 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3450 FMF.setUnsafeAlgebra();
3451 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3453 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3455 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3456 FMF.setNoSignedZeros();
3457 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3458 FMF.setAllowReciprocal();
3460 I->setFastMathFlags(FMF);
3466 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3469 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3470 OpNum+2 != Record.size())
3471 return error("Invalid record");
3473 Type *ResTy = getTypeByID(Record[OpNum]);
3474 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3475 if (Opc == -1 || !ResTy)
3476 return error("Invalid record");
3477 Instruction *Temp = nullptr;
3478 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3480 InstructionList.push_back(Temp);
3481 CurBB->getInstList().push_back(Temp);
3484 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3486 InstructionList.push_back(I);
3489 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3490 case bitc::FUNC_CODE_INST_GEP_OLD:
3491 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3497 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3498 InBounds = Record[OpNum++];
3499 Ty = getTypeByID(Record[OpNum++]);
3501 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3506 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3507 return error("Invalid record");
3510 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3513 cast<SequentialType>(BasePtr->getType()->getScalarType())
3516 "Explicit gep type does not match pointee type of pointer operand");
3518 SmallVector<Value*, 16> GEPIdx;
3519 while (OpNum != Record.size()) {
3521 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3522 return error("Invalid record");
3523 GEPIdx.push_back(Op);
3526 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3528 InstructionList.push_back(I);
3530 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3534 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3535 // EXTRACTVAL: [opty, opval, n x indices]
3538 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3539 return error("Invalid record");
3541 unsigned RecSize = Record.size();
3542 if (OpNum == RecSize)
3543 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3545 SmallVector<unsigned, 4> EXTRACTVALIdx;
3546 Type *CurTy = Agg->getType();
3547 for (; OpNum != RecSize; ++OpNum) {
3548 bool IsArray = CurTy->isArrayTy();
3549 bool IsStruct = CurTy->isStructTy();
3550 uint64_t Index = Record[OpNum];
3552 if (!IsStruct && !IsArray)
3553 return error("EXTRACTVAL: Invalid type");
3554 if ((unsigned)Index != Index)
3555 return error("Invalid value");
3556 if (IsStruct && Index >= CurTy->subtypes().size())
3557 return error("EXTRACTVAL: Invalid struct index");
3558 if (IsArray && Index >= CurTy->getArrayNumElements())
3559 return error("EXTRACTVAL: Invalid array index");
3560 EXTRACTVALIdx.push_back((unsigned)Index);
3563 CurTy = CurTy->subtypes()[Index];
3565 CurTy = CurTy->subtypes()[0];
3568 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3569 InstructionList.push_back(I);
3573 case bitc::FUNC_CODE_INST_INSERTVAL: {
3574 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3577 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3578 return error("Invalid record");
3580 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3581 return error("Invalid record");
3583 unsigned RecSize = Record.size();
3584 if (OpNum == RecSize)
3585 return error("INSERTVAL: Invalid instruction with 0 indices");
3587 SmallVector<unsigned, 4> INSERTVALIdx;
3588 Type *CurTy = Agg->getType();
3589 for (; OpNum != RecSize; ++OpNum) {
3590 bool IsArray = CurTy->isArrayTy();
3591 bool IsStruct = CurTy->isStructTy();
3592 uint64_t Index = Record[OpNum];
3594 if (!IsStruct && !IsArray)
3595 return error("INSERTVAL: Invalid type");
3596 if ((unsigned)Index != Index)
3597 return error("Invalid value");
3598 if (IsStruct && Index >= CurTy->subtypes().size())
3599 return error("INSERTVAL: Invalid struct index");
3600 if (IsArray && Index >= CurTy->getArrayNumElements())
3601 return error("INSERTVAL: Invalid array index");
3603 INSERTVALIdx.push_back((unsigned)Index);
3605 CurTy = CurTy->subtypes()[Index];
3607 CurTy = CurTy->subtypes()[0];
3610 if (CurTy != Val->getType())
3611 return error("Inserted value type doesn't match aggregate type");
3613 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3614 InstructionList.push_back(I);
3618 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3619 // obsolete form of select
3620 // handles select i1 ... in old bitcode
3622 Value *TrueVal, *FalseVal, *Cond;
3623 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3624 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3625 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3626 return error("Invalid record");
3628 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3629 InstructionList.push_back(I);
3633 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3634 // new form of select
3635 // handles select i1 or select [N x i1]
3637 Value *TrueVal, *FalseVal, *Cond;
3638 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3639 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3640 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3641 return error("Invalid record");
3643 // select condition can be either i1 or [N x i1]
3644 if (VectorType* vector_type =
3645 dyn_cast<VectorType>(Cond->getType())) {
3647 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3648 return error("Invalid type for value");
3651 if (Cond->getType() != Type::getInt1Ty(Context))
3652 return error("Invalid type for value");
3655 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3656 InstructionList.push_back(I);
3660 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3663 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3664 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3665 return error("Invalid record");
3666 if (!Vec->getType()->isVectorTy())
3667 return error("Invalid type for value");
3668 I = ExtractElementInst::Create(Vec, Idx);
3669 InstructionList.push_back(I);
3673 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3675 Value *Vec, *Elt, *Idx;
3676 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3677 return error("Invalid record");
3678 if (!Vec->getType()->isVectorTy())
3679 return error("Invalid type for value");
3680 if (popValue(Record, OpNum, NextValueNo,
3681 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3682 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3683 return error("Invalid record");
3684 I = InsertElementInst::Create(Vec, Elt, Idx);
3685 InstructionList.push_back(I);
3689 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3691 Value *Vec1, *Vec2, *Mask;
3692 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3693 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3694 return error("Invalid record");
3696 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3697 return error("Invalid record");
3698 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3699 return error("Invalid type for value");
3700 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3701 InstructionList.push_back(I);
3705 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3706 // Old form of ICmp/FCmp returning bool
3707 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3708 // both legal on vectors but had different behaviour.
3709 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3710 // FCmp/ICmp returning bool or vector of bool
3714 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3715 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3716 OpNum+1 != Record.size())
3717 return error("Invalid record");
3719 if (LHS->getType()->isFPOrFPVectorTy())
3720 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3722 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3723 InstructionList.push_back(I);
3727 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3729 unsigned Size = Record.size();
3731 I = ReturnInst::Create(Context);
3732 InstructionList.push_back(I);
3737 Value *Op = nullptr;
3738 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3739 return error("Invalid record");
3740 if (OpNum != Record.size())
3741 return error("Invalid record");
3743 I = ReturnInst::Create(Context, Op);
3744 InstructionList.push_back(I);
3747 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3748 if (Record.size() != 1 && Record.size() != 3)
3749 return error("Invalid record");
3750 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3752 return error("Invalid record");
3754 if (Record.size() == 1) {
3755 I = BranchInst::Create(TrueDest);
3756 InstructionList.push_back(I);
3759 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3760 Value *Cond = getValue(Record, 2, NextValueNo,
3761 Type::getInt1Ty(Context));
3762 if (!FalseDest || !Cond)
3763 return error("Invalid record");
3764 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3765 InstructionList.push_back(I);
3769 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3771 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3772 // "New" SwitchInst format with case ranges. The changes to write this
3773 // format were reverted but we still recognize bitcode that uses it.
3774 // Hopefully someday we will have support for case ranges and can use
3775 // this format again.
3777 Type *OpTy = getTypeByID(Record[1]);
3778 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3780 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3781 BasicBlock *Default = getBasicBlock(Record[3]);
3782 if (!OpTy || !Cond || !Default)
3783 return error("Invalid record");
3785 unsigned NumCases = Record[4];
3787 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3788 InstructionList.push_back(SI);
3790 unsigned CurIdx = 5;
3791 for (unsigned i = 0; i != NumCases; ++i) {
3792 SmallVector<ConstantInt*, 1> CaseVals;
3793 unsigned NumItems = Record[CurIdx++];
3794 for (unsigned ci = 0; ci != NumItems; ++ci) {
3795 bool isSingleNumber = Record[CurIdx++];
3798 unsigned ActiveWords = 1;
3799 if (ValueBitWidth > 64)
3800 ActiveWords = Record[CurIdx++];
3801 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3803 CurIdx += ActiveWords;
3805 if (!isSingleNumber) {
3807 if (ValueBitWidth > 64)
3808 ActiveWords = Record[CurIdx++];
3809 APInt High = readWideAPInt(
3810 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3811 CurIdx += ActiveWords;
3813 // FIXME: It is not clear whether values in the range should be
3814 // compared as signed or unsigned values. The partially
3815 // implemented changes that used this format in the past used
3816 // unsigned comparisons.
3817 for ( ; Low.ule(High); ++Low)
3818 CaseVals.push_back(ConstantInt::get(Context, Low));
3820 CaseVals.push_back(ConstantInt::get(Context, Low));
3822 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3823 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3824 cve = CaseVals.end(); cvi != cve; ++cvi)
3825 SI->addCase(*cvi, DestBB);
3831 // Old SwitchInst format without case ranges.
3833 if (Record.size() < 3 || (Record.size() & 1) == 0)
3834 return error("Invalid record");
3835 Type *OpTy = getTypeByID(Record[0]);
3836 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3837 BasicBlock *Default = getBasicBlock(Record[2]);
3838 if (!OpTy || !Cond || !Default)
3839 return error("Invalid record");
3840 unsigned NumCases = (Record.size()-3)/2;
3841 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3842 InstructionList.push_back(SI);
3843 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3844 ConstantInt *CaseVal =
3845 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3846 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3847 if (!CaseVal || !DestBB) {
3849 return error("Invalid record");
3851 SI->addCase(CaseVal, DestBB);
3856 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3857 if (Record.size() < 2)
3858 return error("Invalid record");
3859 Type *OpTy = getTypeByID(Record[0]);
3860 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3861 if (!OpTy || !Address)
3862 return error("Invalid record");
3863 unsigned NumDests = Record.size()-2;
3864 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3865 InstructionList.push_back(IBI);
3866 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3867 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3868 IBI->addDestination(DestBB);
3871 return error("Invalid record");
3878 case bitc::FUNC_CODE_INST_INVOKE: {
3879 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3880 if (Record.size() < 4)
3881 return error("Invalid record");
3883 AttributeSet PAL = getAttributes(Record[OpNum++]);
3884 unsigned CCInfo = Record[OpNum++];
3885 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3886 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3888 FunctionType *FTy = nullptr;
3889 if (CCInfo >> 13 & 1 &&
3890 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3891 return error("Explicit invoke type is not a function type");
3894 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3895 return error("Invalid record");
3897 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3899 return error("Callee is not a pointer");
3901 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3903 return error("Callee is not of pointer to function type");
3904 } else if (CalleeTy->getElementType() != FTy)
3905 return error("Explicit invoke type does not match pointee type of "
3907 if (Record.size() < FTy->getNumParams() + OpNum)
3908 return error("Insufficient operands to call");
3910 SmallVector<Value*, 16> Ops;
3911 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3912 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3913 FTy->getParamType(i)));
3915 return error("Invalid record");
3918 if (!FTy->isVarArg()) {
3919 if (Record.size() != OpNum)
3920 return error("Invalid record");
3922 // Read type/value pairs for varargs params.
3923 while (OpNum != Record.size()) {
3925 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3926 return error("Invalid record");
3931 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3932 InstructionList.push_back(I);
3934 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
3935 cast<InvokeInst>(I)->setAttributes(PAL);
3938 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3940 Value *Val = nullptr;
3941 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3942 return error("Invalid record");
3943 I = ResumeInst::Create(Val);
3944 InstructionList.push_back(I);
3947 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3948 I = new UnreachableInst(Context);
3949 InstructionList.push_back(I);
3951 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3952 if (Record.size() < 1 || ((Record.size()-1)&1))
3953 return error("Invalid record");
3954 Type *Ty = getTypeByID(Record[0]);
3956 return error("Invalid record");
3958 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3959 InstructionList.push_back(PN);
3961 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3963 // With the new function encoding, it is possible that operands have
3964 // negative IDs (for forward references). Use a signed VBR
3965 // representation to keep the encoding small.
3967 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3969 V = getValue(Record, 1+i, NextValueNo, Ty);
3970 BasicBlock *BB = getBasicBlock(Record[2+i]);
3972 return error("Invalid record");
3973 PN->addIncoming(V, BB);
3979 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3980 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3982 if (Record.size() < 4)
3983 return error("Invalid record");
3984 Type *Ty = getTypeByID(Record[Idx++]);
3986 return error("Invalid record");
3987 Value *PersFn = nullptr;
3988 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3989 return error("Invalid record");
3991 bool IsCleanup = !!Record[Idx++];
3992 unsigned NumClauses = Record[Idx++];
3993 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3994 LP->setCleanup(IsCleanup);
3995 for (unsigned J = 0; J != NumClauses; ++J) {
3996 LandingPadInst::ClauseType CT =
3997 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4000 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4002 return error("Invalid record");
4005 assert((CT != LandingPadInst::Catch ||
4006 !isa<ArrayType>(Val->getType())) &&
4007 "Catch clause has a invalid type!");
4008 assert((CT != LandingPadInst::Filter ||
4009 isa<ArrayType>(Val->getType())) &&
4010 "Filter clause has invalid type!");
4011 LP->addClause(cast<Constant>(Val));
4015 InstructionList.push_back(I);
4019 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4020 if (Record.size() != 4)
4021 return error("Invalid record");
4022 uint64_t AlignRecord = Record[3];
4023 const uint64_t InAllocaMask = uint64_t(1) << 5;
4024 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4025 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4026 bool InAlloca = AlignRecord & InAllocaMask;
4027 Type *Ty = getTypeByID(Record[0]);
4028 if ((AlignRecord & ExplicitTypeMask) == 0) {
4029 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4031 return error("Old-style alloca with a non-pointer type");
4032 Ty = PTy->getElementType();
4034 Type *OpTy = getTypeByID(Record[1]);
4035 Value *Size = getFnValueByID(Record[2], OpTy);
4037 if (std::error_code EC =
4038 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4042 return error("Invalid record");
4043 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4044 AI->setUsedWithInAlloca(InAlloca);
4046 InstructionList.push_back(I);
4049 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4052 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4053 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4054 return error("Invalid record");
4057 if (OpNum + 3 == Record.size())
4058 Ty = getTypeByID(Record[OpNum++]);
4059 if (std::error_code EC =
4060 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4063 Ty = cast<PointerType>(Op->getType())->getElementType();
4066 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4068 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4070 InstructionList.push_back(I);
4073 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4074 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4077 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4078 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4079 return error("Invalid record");
4082 if (OpNum + 5 == Record.size())
4083 Ty = getTypeByID(Record[OpNum++]);
4084 if (std::error_code EC =
4085 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4088 Ty = cast<PointerType>(Op->getType())->getElementType();
4090 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4091 if (Ordering == NotAtomic || Ordering == Release ||
4092 Ordering == AcquireRelease)
4093 return error("Invalid record");
4094 if (Ordering != NotAtomic && Record[OpNum] == 0)
4095 return error("Invalid record");
4096 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4099 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4101 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4103 InstructionList.push_back(I);
4106 case bitc::FUNC_CODE_INST_STORE:
4107 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4110 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4111 (BitCode == bitc::FUNC_CODE_INST_STORE
4112 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4113 : popValue(Record, OpNum, NextValueNo,
4114 cast<PointerType>(Ptr->getType())->getElementType(),
4116 OpNum + 2 != Record.size())
4117 return error("Invalid record");
4119 if (std::error_code EC = typeCheckLoadStoreInst(
4120 DiagnosticHandler, Val->getType(), Ptr->getType()))
4123 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4125 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4126 InstructionList.push_back(I);
4129 case bitc::FUNC_CODE_INST_STOREATOMIC:
4130 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4131 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4134 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4135 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4136 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4137 : popValue(Record, OpNum, NextValueNo,
4138 cast<PointerType>(Ptr->getType())->getElementType(),
4140 OpNum + 4 != Record.size())
4141 return error("Invalid record");
4143 if (std::error_code EC = typeCheckLoadStoreInst(
4144 DiagnosticHandler, Val->getType(), Ptr->getType()))
4146 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4147 if (Ordering == NotAtomic || Ordering == Acquire ||
4148 Ordering == AcquireRelease)
4149 return error("Invalid record");
4150 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4151 if (Ordering != NotAtomic && Record[OpNum] == 0)
4152 return error("Invalid record");
4155 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4157 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4158 InstructionList.push_back(I);
4161 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4162 case bitc::FUNC_CODE_INST_CMPXCHG: {
4163 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4164 // failureordering?, isweak?]
4166 Value *Ptr, *Cmp, *New;
4167 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4168 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4169 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4170 : popValue(Record, OpNum, NextValueNo,
4171 cast<PointerType>(Ptr->getType())->getElementType(),
4173 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4174 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4175 return error("Invalid record");
4176 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4177 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4178 return error("Invalid record");
4179 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4181 if (std::error_code EC = typeCheckLoadStoreInst(
4182 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4184 AtomicOrdering FailureOrdering;
4185 if (Record.size() < 7)
4187 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4189 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4191 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4193 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4195 if (Record.size() < 8) {
4196 // Before weak cmpxchgs existed, the instruction simply returned the
4197 // value loaded from memory, so bitcode files from that era will be
4198 // expecting the first component of a modern cmpxchg.
4199 CurBB->getInstList().push_back(I);
4200 I = ExtractValueInst::Create(I, 0);
4202 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4205 InstructionList.push_back(I);
4208 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4209 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4212 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4213 popValue(Record, OpNum, NextValueNo,
4214 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4215 OpNum+4 != Record.size())
4216 return error("Invalid record");
4217 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4218 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4219 Operation > AtomicRMWInst::LAST_BINOP)
4220 return error("Invalid record");
4221 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4222 if (Ordering == NotAtomic || Ordering == Unordered)
4223 return error("Invalid record");
4224 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4225 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4226 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4227 InstructionList.push_back(I);
4230 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4231 if (2 != Record.size())
4232 return error("Invalid record");
4233 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4234 if (Ordering == NotAtomic || Ordering == Unordered ||
4235 Ordering == Monotonic)
4236 return error("Invalid record");
4237 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4238 I = new FenceInst(Context, Ordering, SynchScope);
4239 InstructionList.push_back(I);
4242 case bitc::FUNC_CODE_INST_CALL: {
4243 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4244 if (Record.size() < 3)
4245 return error("Invalid record");
4248 AttributeSet PAL = getAttributes(Record[OpNum++]);
4249 unsigned CCInfo = Record[OpNum++];
4251 FunctionType *FTy = nullptr;
4252 if (CCInfo >> 15 & 1 &&
4253 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4254 return error("Explicit call type is not a function type");
4257 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4258 return error("Invalid record");
4260 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4262 return error("Callee is not a pointer type");
4264 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4266 return error("Callee is not of pointer to function type");
4267 } else if (OpTy->getElementType() != FTy)
4268 return error("Explicit call type does not match pointee type of "
4270 if (Record.size() < FTy->getNumParams() + OpNum)
4271 return error("Insufficient operands to call");
4273 SmallVector<Value*, 16> Args;
4274 // Read the fixed params.
4275 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4276 if (FTy->getParamType(i)->isLabelTy())
4277 Args.push_back(getBasicBlock(Record[OpNum]));
4279 Args.push_back(getValue(Record, OpNum, NextValueNo,
4280 FTy->getParamType(i)));
4282 return error("Invalid record");
4285 // Read type/value pairs for varargs params.
4286 if (!FTy->isVarArg()) {
4287 if (OpNum != Record.size())
4288 return error("Invalid record");
4290 while (OpNum != Record.size()) {
4292 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4293 return error("Invalid record");
4298 I = CallInst::Create(FTy, Callee, Args);
4299 InstructionList.push_back(I);
4300 cast<CallInst>(I)->setCallingConv(
4301 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4302 CallInst::TailCallKind TCK = CallInst::TCK_None;
4304 TCK = CallInst::TCK_Tail;
4305 if (CCInfo & (1 << 14))
4306 TCK = CallInst::TCK_MustTail;
4307 cast<CallInst>(I)->setTailCallKind(TCK);
4308 cast<CallInst>(I)->setAttributes(PAL);
4311 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4312 if (Record.size() < 3)
4313 return error("Invalid record");
4314 Type *OpTy = getTypeByID(Record[0]);
4315 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4316 Type *ResTy = getTypeByID(Record[2]);
4317 if (!OpTy || !Op || !ResTy)
4318 return error("Invalid record");
4319 I = new VAArgInst(Op, ResTy);
4320 InstructionList.push_back(I);
4325 // Add instruction to end of current BB. If there is no current BB, reject
4329 return error("Invalid instruction with no BB");
4331 CurBB->getInstList().push_back(I);
4333 // If this was a terminator instruction, move to the next block.
4334 if (isa<TerminatorInst>(I)) {
4336 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4339 // Non-void values get registered in the value table for future use.
4340 if (I && !I->getType()->isVoidTy())
4341 ValueList.assignValue(I, NextValueNo++);
4346 // Check the function list for unresolved values.
4347 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4348 if (!A->getParent()) {
4349 // We found at least one unresolved value. Nuke them all to avoid leaks.
4350 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4351 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4352 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4356 return error("Never resolved value found in function");
4360 // FIXME: Check for unresolved forward-declared metadata references
4361 // and clean up leaks.
4363 // Trim the value list down to the size it was before we parsed this function.
4364 ValueList.shrinkTo(ModuleValueListSize);
4365 MDValueList.shrinkTo(ModuleMDValueListSize);
4366 std::vector<BasicBlock*>().swap(FunctionBBs);
4367 return std::error_code();
4370 /// Find the function body in the bitcode stream
4371 std::error_code BitcodeReader::findFunctionInStream(
4373 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4374 while (DeferredFunctionInfoIterator->second == 0) {
4375 if (Stream.AtEndOfStream())
4376 return error("Could not find function in stream");
4377 // ParseModule will parse the next body in the stream and set its
4378 // position in the DeferredFunctionInfo map.
4379 if (std::error_code EC = parseModule(true))
4382 return std::error_code();
4385 //===----------------------------------------------------------------------===//
4386 // GVMaterializer implementation
4387 //===----------------------------------------------------------------------===//
4389 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4391 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4392 if (std::error_code EC = materializeMetadata())
4395 Function *F = dyn_cast<Function>(GV);
4396 // If it's not a function or is already material, ignore the request.
4397 if (!F || !F->isMaterializable())
4398 return std::error_code();
4400 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4401 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4402 // If its position is recorded as 0, its body is somewhere in the stream
4403 // but we haven't seen it yet.
4404 if (DFII->second == 0 && IsStreamed)
4405 if (std::error_code EC = findFunctionInStream(F, DFII))
4408 // Move the bit stream to the saved position of the deferred function body.
4409 Stream.JumpToBit(DFII->second);
4411 if (std::error_code EC = parseFunctionBody(F))
4413 F->setIsMaterializable(false);
4418 // Upgrade any old intrinsic calls in the function.
4419 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4420 E = UpgradedIntrinsics.end(); I != E; ++I) {
4421 if (I->first != I->second) {
4422 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4424 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4425 UpgradeIntrinsicCall(CI, I->second);
4430 // Bring in any functions that this function forward-referenced via
4432 return materializeForwardReferencedFunctions();
4435 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4436 const Function *F = dyn_cast<Function>(GV);
4437 if (!F || F->isDeclaration())
4440 // Dematerializing F would leave dangling references that wouldn't be
4441 // reconnected on re-materialization.
4442 if (BlockAddressesTaken.count(F))
4445 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4448 void BitcodeReader::dematerialize(GlobalValue *GV) {
4449 Function *F = dyn_cast<Function>(GV);
4450 // If this function isn't dematerializable, this is a noop.
4451 if (!F || !isDematerializable(F))
4454 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4456 // Just forget the function body, we can remat it later.
4457 F->dropAllReferences();
4458 F->setIsMaterializable(true);
4461 std::error_code BitcodeReader::materializeModule(Module *M) {
4462 assert(M == TheModule &&
4463 "Can only Materialize the Module this BitcodeReader is attached to.");
4465 if (std::error_code EC = materializeMetadata())
4468 // Promise to materialize all forward references.
4469 WillMaterializeAllForwardRefs = true;
4471 // Iterate over the module, deserializing any functions that are still on
4473 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4475 if (std::error_code EC = materialize(F))
4478 // At this point, if there are any function bodies, the current bit is
4479 // pointing to the END_BLOCK record after them. Now make sure the rest
4480 // of the bits in the module have been read.
4484 // Check that all block address forward references got resolved (as we
4486 if (!BasicBlockFwdRefs.empty())
4487 return error("Never resolved function from blockaddress");
4489 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4490 // delete the old functions to clean up. We can't do this unless the entire
4491 // module is materialized because there could always be another function body
4492 // with calls to the old function.
4493 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4494 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4495 if (I->first != I->second) {
4496 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4498 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4499 UpgradeIntrinsicCall(CI, I->second);
4501 if (!I->first->use_empty())
4502 I->first->replaceAllUsesWith(I->second);
4503 I->first->eraseFromParent();
4506 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4508 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4509 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4511 UpgradeDebugInfo(*M);
4512 return std::error_code();
4515 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4516 return IdentifiedStructTypes;
4520 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
4522 return initLazyStream(std::move(Streamer));
4523 return initStreamFromBuffer();
4526 std::error_code BitcodeReader::initStreamFromBuffer() {
4527 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4528 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4530 if (Buffer->getBufferSize() & 3)
4531 return error("Invalid bitcode signature");
4533 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4534 // The magic number is 0x0B17C0DE stored in little endian.
4535 if (isBitcodeWrapper(BufPtr, BufEnd))
4536 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4537 return error("Invalid bitcode wrapper header");
4539 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4540 Stream.init(&*StreamFile);
4542 return std::error_code();
4546 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
4547 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4550 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
4551 StreamingMemoryObject &Bytes = *OwnedBytes;
4552 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4553 Stream.init(&*StreamFile);
4555 unsigned char buf[16];
4556 if (Bytes.readBytes(buf, 16, 0) != 16)
4557 return error("Invalid bitcode signature");
4559 if (!isBitcode(buf, buf + 16))
4560 return error("Invalid bitcode signature");
4562 if (isBitcodeWrapper(buf, buf + 4)) {
4563 const unsigned char *bitcodeStart = buf;
4564 const unsigned char *bitcodeEnd = buf + 16;
4565 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4566 Bytes.dropLeadingBytes(bitcodeStart - buf);
4567 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4569 return std::error_code();
4573 class BitcodeErrorCategoryType : public std::error_category {
4574 const char *name() const LLVM_NOEXCEPT override {
4575 return "llvm.bitcode";
4577 std::string message(int IE) const override {
4578 BitcodeError E = static_cast<BitcodeError>(IE);
4580 case BitcodeError::InvalidBitcodeSignature:
4581 return "Invalid bitcode signature";
4582 case BitcodeError::CorruptedBitcode:
4583 return "Corrupted bitcode";
4585 llvm_unreachable("Unknown error type!");
4590 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4592 const std::error_category &llvm::BitcodeErrorCategory() {
4593 return *ErrorCategory;
4596 //===----------------------------------------------------------------------===//
4597 // External interface
4598 //===----------------------------------------------------------------------===//
4600 static ErrorOr<std::unique_ptr<Module>>
4601 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
4602 BitcodeReader *R, LLVMContext &Context,
4603 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
4604 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4605 M->setMaterializer(R);
4607 auto cleanupOnError = [&](std::error_code EC) {
4608 R->releaseBuffer(); // Never take ownership on error.
4612 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4613 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
4614 ShouldLazyLoadMetadata))
4615 return cleanupOnError(EC);
4617 if (MaterializeAll) {
4618 // Read in the entire module, and destroy the BitcodeReader.
4619 if (std::error_code EC = M->materializeAllPermanently())
4620 return cleanupOnError(EC);
4622 // Resolve forward references from blockaddresses.
4623 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4624 return cleanupOnError(EC);
4626 return std::move(M);
4629 /// \brief Get a lazy one-at-time loading module from bitcode.
4631 /// This isn't always used in a lazy context. In particular, it's also used by
4632 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4633 /// in forward-referenced functions from block address references.
4635 /// \param[in] MaterializeAll Set to \c true if we should materialize
4637 static ErrorOr<std::unique_ptr<Module>>
4638 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4639 LLVMContext &Context, bool MaterializeAll,
4640 DiagnosticHandlerFunction DiagnosticHandler,
4641 bool ShouldLazyLoadMetadata = false) {
4643 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4645 ErrorOr<std::unique_ptr<Module>> Ret =
4646 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
4647 MaterializeAll, ShouldLazyLoadMetadata);
4651 Buffer.release(); // The BitcodeReader owns it now.
4655 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
4656 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
4657 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
4658 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4659 DiagnosticHandler, ShouldLazyLoadMetadata);
4662 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
4663 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
4664 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
4665 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4666 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
4668 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
4672 ErrorOr<std::unique_ptr<Module>>
4673 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4674 DiagnosticHandlerFunction DiagnosticHandler) {
4675 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4676 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
4678 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4679 // written. We must defer until the Module has been fully materialized.
4683 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4684 DiagnosticHandlerFunction DiagnosticHandler) {
4685 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4686 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4688 ErrorOr<std::string> Triple = R->parseTriple();
4689 if (Triple.getError())
4691 return Triple.get();