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;
139 uint64_t NextUnreadBit = 0;
140 bool SeenValueSymbolTable = false;
142 std::vector<Type*> TypeList;
143 BitcodeReaderValueList ValueList;
144 BitcodeReaderMDValueList MDValueList;
145 std::vector<Comdat *> ComdatList;
146 SmallVector<Instruction *, 64> InstructionList;
148 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
149 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
150 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
151 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
152 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
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 DenseMap<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), ValueList(Context), MDValueList(Context) {}
432 BitcodeReader::BitcodeReader(LLVMContext &Context,
433 DiagnosticHandlerFunction DiagnosticHandler)
435 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
436 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
438 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
439 if (WillMaterializeAllForwardRefs)
440 return std::error_code();
442 // Prevent recursion.
443 WillMaterializeAllForwardRefs = true;
445 while (!BasicBlockFwdRefQueue.empty()) {
446 Function *F = BasicBlockFwdRefQueue.front();
447 BasicBlockFwdRefQueue.pop_front();
448 assert(F && "Expected valid function");
449 if (!BasicBlockFwdRefs.count(F))
450 // Already materialized.
453 // Check for a function that isn't materializable to prevent an infinite
454 // loop. When parsing a blockaddress stored in a global variable, there
455 // isn't a trivial way to check if a function will have a body without a
456 // linear search through FunctionsWithBodies, so just check it here.
457 if (!F->isMaterializable())
458 return error("Never resolved function from blockaddress");
460 // Try to materialize F.
461 if (std::error_code EC = materialize(F))
464 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
467 WillMaterializeAllForwardRefs = false;
468 return std::error_code();
471 void BitcodeReader::freeState() {
473 std::vector<Type*>().swap(TypeList);
476 std::vector<Comdat *>().swap(ComdatList);
478 std::vector<AttributeSet>().swap(MAttributes);
479 std::vector<BasicBlock*>().swap(FunctionBBs);
480 std::vector<Function*>().swap(FunctionsWithBodies);
481 DeferredFunctionInfo.clear();
482 DeferredMetadataInfo.clear();
485 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
486 BasicBlockFwdRefQueue.clear();
489 //===----------------------------------------------------------------------===//
490 // Helper functions to implement forward reference resolution, etc.
491 //===----------------------------------------------------------------------===//
493 /// Convert a string from a record into an std::string, return true on failure.
494 template <typename StrTy>
495 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
497 if (Idx > Record.size())
500 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
501 Result += (char)Record[i];
505 static bool hasImplicitComdat(size_t Val) {
509 case 1: // Old WeakAnyLinkage
510 case 4: // Old LinkOnceAnyLinkage
511 case 10: // Old WeakODRLinkage
512 case 11: // Old LinkOnceODRLinkage
517 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
519 default: // Map unknown/new linkages to external
521 return GlobalValue::ExternalLinkage;
523 return GlobalValue::AppendingLinkage;
525 return GlobalValue::InternalLinkage;
527 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
529 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
531 return GlobalValue::ExternalWeakLinkage;
533 return GlobalValue::CommonLinkage;
535 return GlobalValue::PrivateLinkage;
537 return GlobalValue::AvailableExternallyLinkage;
539 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
541 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
543 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
544 case 1: // Old value with implicit comdat.
546 return GlobalValue::WeakAnyLinkage;
547 case 10: // Old value with implicit comdat.
549 return GlobalValue::WeakODRLinkage;
550 case 4: // Old value with implicit comdat.
552 return GlobalValue::LinkOnceAnyLinkage;
553 case 11: // Old value with implicit comdat.
555 return GlobalValue::LinkOnceODRLinkage;
559 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
561 default: // Map unknown visibilities to default.
562 case 0: return GlobalValue::DefaultVisibility;
563 case 1: return GlobalValue::HiddenVisibility;
564 case 2: return GlobalValue::ProtectedVisibility;
568 static GlobalValue::DLLStorageClassTypes
569 getDecodedDLLStorageClass(unsigned Val) {
571 default: // Map unknown values to default.
572 case 0: return GlobalValue::DefaultStorageClass;
573 case 1: return GlobalValue::DLLImportStorageClass;
574 case 2: return GlobalValue::DLLExportStorageClass;
578 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
580 case 0: return GlobalVariable::NotThreadLocal;
581 default: // Map unknown non-zero value to general dynamic.
582 case 1: return GlobalVariable::GeneralDynamicTLSModel;
583 case 2: return GlobalVariable::LocalDynamicTLSModel;
584 case 3: return GlobalVariable::InitialExecTLSModel;
585 case 4: return GlobalVariable::LocalExecTLSModel;
589 static int getDecodedCastOpcode(unsigned Val) {
592 case bitc::CAST_TRUNC : return Instruction::Trunc;
593 case bitc::CAST_ZEXT : return Instruction::ZExt;
594 case bitc::CAST_SEXT : return Instruction::SExt;
595 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
596 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
597 case bitc::CAST_UITOFP : return Instruction::UIToFP;
598 case bitc::CAST_SITOFP : return Instruction::SIToFP;
599 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
600 case bitc::CAST_FPEXT : return Instruction::FPExt;
601 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
602 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
603 case bitc::CAST_BITCAST : return Instruction::BitCast;
604 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
608 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
609 bool IsFP = Ty->isFPOrFPVectorTy();
610 // BinOps are only valid for int/fp or vector of int/fp types
611 if (!IsFP && !Ty->isIntOrIntVectorTy())
617 case bitc::BINOP_ADD:
618 return IsFP ? Instruction::FAdd : Instruction::Add;
619 case bitc::BINOP_SUB:
620 return IsFP ? Instruction::FSub : Instruction::Sub;
621 case bitc::BINOP_MUL:
622 return IsFP ? Instruction::FMul : Instruction::Mul;
623 case bitc::BINOP_UDIV:
624 return IsFP ? -1 : Instruction::UDiv;
625 case bitc::BINOP_SDIV:
626 return IsFP ? Instruction::FDiv : Instruction::SDiv;
627 case bitc::BINOP_UREM:
628 return IsFP ? -1 : Instruction::URem;
629 case bitc::BINOP_SREM:
630 return IsFP ? Instruction::FRem : Instruction::SRem;
631 case bitc::BINOP_SHL:
632 return IsFP ? -1 : Instruction::Shl;
633 case bitc::BINOP_LSHR:
634 return IsFP ? -1 : Instruction::LShr;
635 case bitc::BINOP_ASHR:
636 return IsFP ? -1 : Instruction::AShr;
637 case bitc::BINOP_AND:
638 return IsFP ? -1 : Instruction::And;
640 return IsFP ? -1 : Instruction::Or;
641 case bitc::BINOP_XOR:
642 return IsFP ? -1 : Instruction::Xor;
646 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
648 default: return AtomicRMWInst::BAD_BINOP;
649 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
650 case bitc::RMW_ADD: return AtomicRMWInst::Add;
651 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
652 case bitc::RMW_AND: return AtomicRMWInst::And;
653 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
654 case bitc::RMW_OR: return AtomicRMWInst::Or;
655 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
656 case bitc::RMW_MAX: return AtomicRMWInst::Max;
657 case bitc::RMW_MIN: return AtomicRMWInst::Min;
658 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
659 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
663 static AtomicOrdering getDecodedOrdering(unsigned Val) {
665 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
666 case bitc::ORDERING_UNORDERED: return Unordered;
667 case bitc::ORDERING_MONOTONIC: return Monotonic;
668 case bitc::ORDERING_ACQUIRE: return Acquire;
669 case bitc::ORDERING_RELEASE: return Release;
670 case bitc::ORDERING_ACQREL: return AcquireRelease;
671 default: // Map unknown orderings to sequentially-consistent.
672 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
676 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
678 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
679 default: // Map unknown scopes to cross-thread.
680 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
684 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
686 default: // Map unknown selection kinds to any.
687 case bitc::COMDAT_SELECTION_KIND_ANY:
689 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
690 return Comdat::ExactMatch;
691 case bitc::COMDAT_SELECTION_KIND_LARGEST:
692 return Comdat::Largest;
693 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
694 return Comdat::NoDuplicates;
695 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
696 return Comdat::SameSize;
700 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
702 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
703 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
709 /// \brief A class for maintaining the slot number definition
710 /// as a placeholder for the actual definition for forward constants defs.
711 class ConstantPlaceHolder : public ConstantExpr {
712 void operator=(const ConstantPlaceHolder &) = delete;
715 // allocate space for exactly one operand
716 void *operator new(size_t s) { return User::operator new(s, 1); }
717 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
718 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
719 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
722 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
723 static bool classof(const Value *V) {
724 return isa<ConstantExpr>(V) &&
725 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
728 /// Provide fast operand accessors
729 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
733 // FIXME: can we inherit this from ConstantExpr?
735 struct OperandTraits<ConstantPlaceHolder> :
736 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
738 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
741 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
750 WeakVH &OldV = ValuePtrs[Idx];
756 // Handle constants and non-constants (e.g. instrs) differently for
758 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
759 ResolveConstants.push_back(std::make_pair(PHC, Idx));
762 // If there was a forward reference to this value, replace it.
763 Value *PrevVal = OldV;
764 OldV->replaceAllUsesWith(V);
770 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
775 if (Value *V = ValuePtrs[Idx]) {
776 if (Ty != V->getType())
777 report_fatal_error("Type mismatch in constant table!");
778 return cast<Constant>(V);
781 // Create and return a placeholder, which will later be RAUW'd.
782 Constant *C = new ConstantPlaceHolder(Ty, Context);
787 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
788 // Bail out for a clearly invalid value. This would make us call resize(0)
795 if (Value *V = ValuePtrs[Idx]) {
796 // If the types don't match, it's invalid.
797 if (Ty && Ty != V->getType())
802 // No type specified, must be invalid reference.
803 if (!Ty) return nullptr;
805 // Create and return a placeholder, which will later be RAUW'd.
806 Value *V = new Argument(Ty);
811 /// Once all constants are read, this method bulk resolves any forward
812 /// references. The idea behind this is that we sometimes get constants (such
813 /// as large arrays) which reference *many* forward ref constants. Replacing
814 /// each of these causes a lot of thrashing when building/reuniquing the
815 /// constant. Instead of doing this, we look at all the uses and rewrite all
816 /// the place holders at once for any constant that uses a placeholder.
817 void BitcodeReaderValueList::resolveConstantForwardRefs() {
818 // Sort the values by-pointer so that they are efficient to look up with a
820 std::sort(ResolveConstants.begin(), ResolveConstants.end());
822 SmallVector<Constant*, 64> NewOps;
824 while (!ResolveConstants.empty()) {
825 Value *RealVal = operator[](ResolveConstants.back().second);
826 Constant *Placeholder = ResolveConstants.back().first;
827 ResolveConstants.pop_back();
829 // Loop over all users of the placeholder, updating them to reference the
830 // new value. If they reference more than one placeholder, update them all
832 while (!Placeholder->use_empty()) {
833 auto UI = Placeholder->user_begin();
836 // If the using object isn't uniqued, just update the operands. This
837 // handles instructions and initializers for global variables.
838 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
839 UI.getUse().set(RealVal);
843 // Otherwise, we have a constant that uses the placeholder. Replace that
844 // constant with a new constant that has *all* placeholder uses updated.
845 Constant *UserC = cast<Constant>(U);
846 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
849 if (!isa<ConstantPlaceHolder>(*I)) {
850 // Not a placeholder reference.
852 } else if (*I == Placeholder) {
853 // Common case is that it just references this one placeholder.
856 // Otherwise, look up the placeholder in ResolveConstants.
857 ResolveConstantsTy::iterator It =
858 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
859 std::pair<Constant*, unsigned>(cast<Constant>(*I),
861 assert(It != ResolveConstants.end() && It->first == *I);
862 NewOp = operator[](It->second);
865 NewOps.push_back(cast<Constant>(NewOp));
868 // Make the new constant.
870 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
871 NewC = ConstantArray::get(UserCA->getType(), NewOps);
872 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
873 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
874 } else if (isa<ConstantVector>(UserC)) {
875 NewC = ConstantVector::get(NewOps);
877 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
878 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
881 UserC->replaceAllUsesWith(NewC);
882 UserC->destroyConstant();
886 // Update all ValueHandles, they should be the only users at this point.
887 Placeholder->replaceAllUsesWith(RealVal);
892 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
901 TrackingMDRef &OldMD = MDValuePtrs[Idx];
907 // If there was a forward reference to this value, replace it.
908 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
909 PrevMD->replaceAllUsesWith(MD);
913 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
917 if (Metadata *MD = MDValuePtrs[Idx])
920 // Track forward refs to be resolved later.
922 MinFwdRef = std::min(MinFwdRef, Idx);
923 MaxFwdRef = std::max(MaxFwdRef, Idx);
926 MinFwdRef = MaxFwdRef = Idx;
930 // Create and return a placeholder, which will later be RAUW'd.
931 Metadata *MD = MDNode::getTemporary(Context, None).release();
932 MDValuePtrs[Idx].reset(MD);
936 void BitcodeReaderMDValueList::tryToResolveCycles() {
942 // Still forward references... can't resolve cycles.
945 // Resolve any cycles.
946 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
947 auto &MD = MDValuePtrs[I];
948 auto *N = dyn_cast_or_null<MDNode>(MD);
952 assert(!N->isTemporary() && "Unexpected forward reference");
956 // Make sure we return early again until there's another forward ref.
960 Type *BitcodeReader::getTypeByID(unsigned ID) {
961 // The type table size is always specified correctly.
962 if (ID >= TypeList.size())
965 if (Type *Ty = TypeList[ID])
968 // If we have a forward reference, the only possible case is when it is to a
969 // named struct. Just create a placeholder for now.
970 return TypeList[ID] = createIdentifiedStructType(Context);
973 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
975 auto *Ret = StructType::create(Context, Name);
976 IdentifiedStructTypes.push_back(Ret);
980 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
981 auto *Ret = StructType::create(Context);
982 IdentifiedStructTypes.push_back(Ret);
987 //===----------------------------------------------------------------------===//
988 // Functions for parsing blocks from the bitcode file
989 //===----------------------------------------------------------------------===//
992 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
993 /// been decoded from the given integer. This function must stay in sync with
994 /// 'encodeLLVMAttributesForBitcode'.
995 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
996 uint64_t EncodedAttrs) {
997 // FIXME: Remove in 4.0.
999 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1000 // the bits above 31 down by 11 bits.
1001 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1002 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1003 "Alignment must be a power of two.");
1006 B.addAlignmentAttr(Alignment);
1007 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1008 (EncodedAttrs & 0xffff));
1011 std::error_code BitcodeReader::parseAttributeBlock() {
1012 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1013 return error("Invalid record");
1015 if (!MAttributes.empty())
1016 return error("Invalid multiple blocks");
1018 SmallVector<uint64_t, 64> Record;
1020 SmallVector<AttributeSet, 8> Attrs;
1022 // Read all the records.
1024 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1026 switch (Entry.Kind) {
1027 case BitstreamEntry::SubBlock: // Handled for us already.
1028 case BitstreamEntry::Error:
1029 return error("Malformed block");
1030 case BitstreamEntry::EndBlock:
1031 return std::error_code();
1032 case BitstreamEntry::Record:
1033 // The interesting case.
1039 switch (Stream.readRecord(Entry.ID, Record)) {
1040 default: // Default behavior: ignore.
1042 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1043 // FIXME: Remove in 4.0.
1044 if (Record.size() & 1)
1045 return error("Invalid record");
1047 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1049 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1050 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1053 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1057 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1058 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1059 Attrs.push_back(MAttributeGroups[Record[i]]);
1061 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1069 // Returns Attribute::None on unrecognized codes.
1070 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1073 return Attribute::None;
1074 case bitc::ATTR_KIND_ALIGNMENT:
1075 return Attribute::Alignment;
1076 case bitc::ATTR_KIND_ALWAYS_INLINE:
1077 return Attribute::AlwaysInline;
1078 case bitc::ATTR_KIND_BUILTIN:
1079 return Attribute::Builtin;
1080 case bitc::ATTR_KIND_BY_VAL:
1081 return Attribute::ByVal;
1082 case bitc::ATTR_KIND_IN_ALLOCA:
1083 return Attribute::InAlloca;
1084 case bitc::ATTR_KIND_COLD:
1085 return Attribute::Cold;
1086 case bitc::ATTR_KIND_CONVERGENT:
1087 return Attribute::Convergent;
1088 case bitc::ATTR_KIND_INLINE_HINT:
1089 return Attribute::InlineHint;
1090 case bitc::ATTR_KIND_IN_REG:
1091 return Attribute::InReg;
1092 case bitc::ATTR_KIND_JUMP_TABLE:
1093 return Attribute::JumpTable;
1094 case bitc::ATTR_KIND_MIN_SIZE:
1095 return Attribute::MinSize;
1096 case bitc::ATTR_KIND_NAKED:
1097 return Attribute::Naked;
1098 case bitc::ATTR_KIND_NEST:
1099 return Attribute::Nest;
1100 case bitc::ATTR_KIND_NO_ALIAS:
1101 return Attribute::NoAlias;
1102 case bitc::ATTR_KIND_NO_BUILTIN:
1103 return Attribute::NoBuiltin;
1104 case bitc::ATTR_KIND_NO_CAPTURE:
1105 return Attribute::NoCapture;
1106 case bitc::ATTR_KIND_NO_DUPLICATE:
1107 return Attribute::NoDuplicate;
1108 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1109 return Attribute::NoImplicitFloat;
1110 case bitc::ATTR_KIND_NO_INLINE:
1111 return Attribute::NoInline;
1112 case bitc::ATTR_KIND_NON_LAZY_BIND:
1113 return Attribute::NonLazyBind;
1114 case bitc::ATTR_KIND_NON_NULL:
1115 return Attribute::NonNull;
1116 case bitc::ATTR_KIND_DEREFERENCEABLE:
1117 return Attribute::Dereferenceable;
1118 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1119 return Attribute::DereferenceableOrNull;
1120 case bitc::ATTR_KIND_NO_RED_ZONE:
1121 return Attribute::NoRedZone;
1122 case bitc::ATTR_KIND_NO_RETURN:
1123 return Attribute::NoReturn;
1124 case bitc::ATTR_KIND_NO_UNWIND:
1125 return Attribute::NoUnwind;
1126 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1127 return Attribute::OptimizeForSize;
1128 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1129 return Attribute::OptimizeNone;
1130 case bitc::ATTR_KIND_READ_NONE:
1131 return Attribute::ReadNone;
1132 case bitc::ATTR_KIND_READ_ONLY:
1133 return Attribute::ReadOnly;
1134 case bitc::ATTR_KIND_RETURNED:
1135 return Attribute::Returned;
1136 case bitc::ATTR_KIND_RETURNS_TWICE:
1137 return Attribute::ReturnsTwice;
1138 case bitc::ATTR_KIND_S_EXT:
1139 return Attribute::SExt;
1140 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1141 return Attribute::StackAlignment;
1142 case bitc::ATTR_KIND_STACK_PROTECT:
1143 return Attribute::StackProtect;
1144 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1145 return Attribute::StackProtectReq;
1146 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1147 return Attribute::StackProtectStrong;
1148 case bitc::ATTR_KIND_SAFESTACK:
1149 return Attribute::SafeStack;
1150 case bitc::ATTR_KIND_STRUCT_RET:
1151 return Attribute::StructRet;
1152 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1153 return Attribute::SanitizeAddress;
1154 case bitc::ATTR_KIND_SANITIZE_THREAD:
1155 return Attribute::SanitizeThread;
1156 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1157 return Attribute::SanitizeMemory;
1158 case bitc::ATTR_KIND_UW_TABLE:
1159 return Attribute::UWTable;
1160 case bitc::ATTR_KIND_Z_EXT:
1161 return Attribute::ZExt;
1165 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1166 unsigned &Alignment) {
1167 // Note: Alignment in bitcode files is incremented by 1, so that zero
1168 // can be used for default alignment.
1169 if (Exponent > Value::MaxAlignmentExponent + 1)
1170 return error("Invalid alignment value");
1171 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1172 return std::error_code();
1175 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1176 Attribute::AttrKind *Kind) {
1177 *Kind = getAttrFromCode(Code);
1178 if (*Kind == Attribute::None)
1179 return error(BitcodeError::CorruptedBitcode,
1180 "Unknown attribute kind (" + Twine(Code) + ")");
1181 return std::error_code();
1184 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1185 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1186 return error("Invalid record");
1188 if (!MAttributeGroups.empty())
1189 return error("Invalid multiple blocks");
1191 SmallVector<uint64_t, 64> Record;
1193 // Read all the records.
1195 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1197 switch (Entry.Kind) {
1198 case BitstreamEntry::SubBlock: // Handled for us already.
1199 case BitstreamEntry::Error:
1200 return error("Malformed block");
1201 case BitstreamEntry::EndBlock:
1202 return std::error_code();
1203 case BitstreamEntry::Record:
1204 // The interesting case.
1210 switch (Stream.readRecord(Entry.ID, Record)) {
1211 default: // Default behavior: ignore.
1213 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1214 if (Record.size() < 3)
1215 return error("Invalid record");
1217 uint64_t GrpID = Record[0];
1218 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1221 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1222 if (Record[i] == 0) { // Enum attribute
1223 Attribute::AttrKind Kind;
1224 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1227 B.addAttribute(Kind);
1228 } else if (Record[i] == 1) { // Integer attribute
1229 Attribute::AttrKind Kind;
1230 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1232 if (Kind == Attribute::Alignment)
1233 B.addAlignmentAttr(Record[++i]);
1234 else if (Kind == Attribute::StackAlignment)
1235 B.addStackAlignmentAttr(Record[++i]);
1236 else if (Kind == Attribute::Dereferenceable)
1237 B.addDereferenceableAttr(Record[++i]);
1238 else if (Kind == Attribute::DereferenceableOrNull)
1239 B.addDereferenceableOrNullAttr(Record[++i]);
1240 } else { // String attribute
1241 assert((Record[i] == 3 || Record[i] == 4) &&
1242 "Invalid attribute group entry");
1243 bool HasValue = (Record[i++] == 4);
1244 SmallString<64> KindStr;
1245 SmallString<64> ValStr;
1247 while (Record[i] != 0 && i != e)
1248 KindStr += Record[i++];
1249 assert(Record[i] == 0 && "Kind string not null terminated");
1252 // Has a value associated with it.
1253 ++i; // Skip the '0' that terminates the "kind" string.
1254 while (Record[i] != 0 && i != e)
1255 ValStr += Record[i++];
1256 assert(Record[i] == 0 && "Value string not null terminated");
1259 B.addAttribute(KindStr.str(), ValStr.str());
1263 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1270 std::error_code BitcodeReader::parseTypeTable() {
1271 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1272 return error("Invalid record");
1274 return parseTypeTableBody();
1277 std::error_code BitcodeReader::parseTypeTableBody() {
1278 if (!TypeList.empty())
1279 return error("Invalid multiple blocks");
1281 SmallVector<uint64_t, 64> Record;
1282 unsigned NumRecords = 0;
1284 SmallString<64> TypeName;
1286 // Read all the records for this type table.
1288 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1290 switch (Entry.Kind) {
1291 case BitstreamEntry::SubBlock: // Handled for us already.
1292 case BitstreamEntry::Error:
1293 return error("Malformed block");
1294 case BitstreamEntry::EndBlock:
1295 if (NumRecords != TypeList.size())
1296 return error("Malformed block");
1297 return std::error_code();
1298 case BitstreamEntry::Record:
1299 // The interesting case.
1305 Type *ResultTy = nullptr;
1306 switch (Stream.readRecord(Entry.ID, Record)) {
1308 return error("Invalid value");
1309 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1310 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1311 // type list. This allows us to reserve space.
1312 if (Record.size() < 1)
1313 return error("Invalid record");
1314 TypeList.resize(Record[0]);
1316 case bitc::TYPE_CODE_VOID: // VOID
1317 ResultTy = Type::getVoidTy(Context);
1319 case bitc::TYPE_CODE_HALF: // HALF
1320 ResultTy = Type::getHalfTy(Context);
1322 case bitc::TYPE_CODE_FLOAT: // FLOAT
1323 ResultTy = Type::getFloatTy(Context);
1325 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1326 ResultTy = Type::getDoubleTy(Context);
1328 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1329 ResultTy = Type::getX86_FP80Ty(Context);
1331 case bitc::TYPE_CODE_FP128: // FP128
1332 ResultTy = Type::getFP128Ty(Context);
1334 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1335 ResultTy = Type::getPPC_FP128Ty(Context);
1337 case bitc::TYPE_CODE_LABEL: // LABEL
1338 ResultTy = Type::getLabelTy(Context);
1340 case bitc::TYPE_CODE_METADATA: // METADATA
1341 ResultTy = Type::getMetadataTy(Context);
1343 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1344 ResultTy = Type::getX86_MMXTy(Context);
1346 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1347 if (Record.size() < 1)
1348 return error("Invalid record");
1350 uint64_t NumBits = Record[0];
1351 if (NumBits < IntegerType::MIN_INT_BITS ||
1352 NumBits > IntegerType::MAX_INT_BITS)
1353 return error("Bitwidth for integer type out of range");
1354 ResultTy = IntegerType::get(Context, NumBits);
1357 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1358 // [pointee type, address space]
1359 if (Record.size() < 1)
1360 return error("Invalid record");
1361 unsigned AddressSpace = 0;
1362 if (Record.size() == 2)
1363 AddressSpace = Record[1];
1364 ResultTy = getTypeByID(Record[0]);
1366 !PointerType::isValidElementType(ResultTy))
1367 return error("Invalid type");
1368 ResultTy = PointerType::get(ResultTy, AddressSpace);
1371 case bitc::TYPE_CODE_FUNCTION_OLD: {
1372 // FIXME: attrid is dead, remove it in LLVM 4.0
1373 // FUNCTION: [vararg, attrid, retty, paramty x N]
1374 if (Record.size() < 3)
1375 return error("Invalid record");
1376 SmallVector<Type*, 8> ArgTys;
1377 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1378 if (Type *T = getTypeByID(Record[i]))
1379 ArgTys.push_back(T);
1384 ResultTy = getTypeByID(Record[2]);
1385 if (!ResultTy || ArgTys.size() < Record.size()-3)
1386 return error("Invalid type");
1388 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1391 case bitc::TYPE_CODE_FUNCTION: {
1392 // FUNCTION: [vararg, retty, paramty x N]
1393 if (Record.size() < 2)
1394 return error("Invalid record");
1395 SmallVector<Type*, 8> ArgTys;
1396 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1397 if (Type *T = getTypeByID(Record[i])) {
1398 if (!FunctionType::isValidArgumentType(T))
1399 return error("Invalid function argument type");
1400 ArgTys.push_back(T);
1406 ResultTy = getTypeByID(Record[1]);
1407 if (!ResultTy || ArgTys.size() < Record.size()-2)
1408 return error("Invalid type");
1410 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1413 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1414 if (Record.size() < 1)
1415 return error("Invalid record");
1416 SmallVector<Type*, 8> EltTys;
1417 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1418 if (Type *T = getTypeByID(Record[i]))
1419 EltTys.push_back(T);
1423 if (EltTys.size() != Record.size()-1)
1424 return error("Invalid type");
1425 ResultTy = StructType::get(Context, EltTys, Record[0]);
1428 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1429 if (convertToString(Record, 0, TypeName))
1430 return error("Invalid record");
1433 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1434 if (Record.size() < 1)
1435 return error("Invalid record");
1437 if (NumRecords >= TypeList.size())
1438 return error("Invalid TYPE table");
1440 // Check to see if this was forward referenced, if so fill in the temp.
1441 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1443 Res->setName(TypeName);
1444 TypeList[NumRecords] = nullptr;
1445 } else // Otherwise, create a new struct.
1446 Res = createIdentifiedStructType(Context, TypeName);
1449 SmallVector<Type*, 8> EltTys;
1450 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1451 if (Type *T = getTypeByID(Record[i]))
1452 EltTys.push_back(T);
1456 if (EltTys.size() != Record.size()-1)
1457 return error("Invalid record");
1458 Res->setBody(EltTys, Record[0]);
1462 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1463 if (Record.size() != 1)
1464 return error("Invalid record");
1466 if (NumRecords >= TypeList.size())
1467 return error("Invalid TYPE table");
1469 // Check to see if this was forward referenced, if so fill in the temp.
1470 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1472 Res->setName(TypeName);
1473 TypeList[NumRecords] = nullptr;
1474 } else // Otherwise, create a new struct with no body.
1475 Res = createIdentifiedStructType(Context, TypeName);
1480 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1481 if (Record.size() < 2)
1482 return error("Invalid record");
1483 ResultTy = getTypeByID(Record[1]);
1484 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1485 return error("Invalid type");
1486 ResultTy = ArrayType::get(ResultTy, Record[0]);
1488 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1489 if (Record.size() < 2)
1490 return error("Invalid record");
1492 return error("Invalid vector length");
1493 ResultTy = getTypeByID(Record[1]);
1494 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1495 return error("Invalid type");
1496 ResultTy = VectorType::get(ResultTy, Record[0]);
1500 if (NumRecords >= TypeList.size())
1501 return error("Invalid TYPE table");
1502 if (TypeList[NumRecords])
1504 "Invalid TYPE table: Only named structs can be forward referenced");
1505 assert(ResultTy && "Didn't read a type?");
1506 TypeList[NumRecords++] = ResultTy;
1510 std::error_code BitcodeReader::parseValueSymbolTable() {
1511 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1512 return error("Invalid record");
1514 SmallVector<uint64_t, 64> Record;
1516 Triple TT(TheModule->getTargetTriple());
1518 // Read all the records for this value table.
1519 SmallString<128> ValueName;
1521 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1523 switch (Entry.Kind) {
1524 case BitstreamEntry::SubBlock: // Handled for us already.
1525 case BitstreamEntry::Error:
1526 return error("Malformed block");
1527 case BitstreamEntry::EndBlock:
1528 return std::error_code();
1529 case BitstreamEntry::Record:
1530 // The interesting case.
1536 switch (Stream.readRecord(Entry.ID, Record)) {
1537 default: // Default behavior: unknown type.
1539 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1540 if (convertToString(Record, 1, ValueName))
1541 return error("Invalid record");
1542 unsigned ValueID = Record[0];
1543 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1544 return error("Invalid record");
1545 Value *V = ValueList[ValueID];
1547 V->setName(StringRef(ValueName.data(), ValueName.size()));
1548 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1549 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1550 if (TT.isOSBinFormatMachO())
1551 GO->setComdat(nullptr);
1553 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1559 case bitc::VST_CODE_BBENTRY: {
1560 if (convertToString(Record, 1, ValueName))
1561 return error("Invalid record");
1562 BasicBlock *BB = getBasicBlock(Record[0]);
1564 return error("Invalid record");
1566 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1574 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1576 std::error_code BitcodeReader::parseMetadata() {
1577 IsMetadataMaterialized = true;
1578 unsigned NextMDValueNo = MDValueList.size();
1580 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1581 return error("Invalid record");
1583 SmallVector<uint64_t, 64> Record;
1586 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1587 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1589 return getMD(ID - 1);
1592 auto getMDString = [&](unsigned ID) -> MDString *{
1593 // This requires that the ID is not really a forward reference. In
1594 // particular, the MDString must already have been resolved.
1595 return cast_or_null<MDString>(getMDOrNull(ID));
1598 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1599 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1601 // Read all the records.
1603 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1605 switch (Entry.Kind) {
1606 case BitstreamEntry::SubBlock: // Handled for us already.
1607 case BitstreamEntry::Error:
1608 return error("Malformed block");
1609 case BitstreamEntry::EndBlock:
1610 MDValueList.tryToResolveCycles();
1611 return std::error_code();
1612 case BitstreamEntry::Record:
1613 // The interesting case.
1619 unsigned Code = Stream.readRecord(Entry.ID, Record);
1620 bool IsDistinct = false;
1622 default: // Default behavior: ignore.
1624 case bitc::METADATA_NAME: {
1625 // Read name of the named metadata.
1626 SmallString<8> Name(Record.begin(), Record.end());
1628 Code = Stream.ReadCode();
1630 unsigned NextBitCode = Stream.readRecord(Code, Record);
1631 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1632 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1634 // Read named metadata elements.
1635 unsigned Size = Record.size();
1636 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1637 for (unsigned i = 0; i != Size; ++i) {
1638 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1640 return error("Invalid record");
1641 NMD->addOperand(MD);
1645 case bitc::METADATA_OLD_FN_NODE: {
1646 // FIXME: Remove in 4.0.
1647 // This is a LocalAsMetadata record, the only type of function-local
1649 if (Record.size() % 2 == 1)
1650 return error("Invalid record");
1652 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1653 // to be legal, but there's no upgrade path.
1654 auto dropRecord = [&] {
1655 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1657 if (Record.size() != 2) {
1662 Type *Ty = getTypeByID(Record[0]);
1663 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1668 MDValueList.assignValue(
1669 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1673 case bitc::METADATA_OLD_NODE: {
1674 // FIXME: Remove in 4.0.
1675 if (Record.size() % 2 == 1)
1676 return error("Invalid record");
1678 unsigned Size = Record.size();
1679 SmallVector<Metadata *, 8> Elts;
1680 for (unsigned i = 0; i != Size; i += 2) {
1681 Type *Ty = getTypeByID(Record[i]);
1683 return error("Invalid record");
1684 if (Ty->isMetadataTy())
1685 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1686 else if (!Ty->isVoidTy()) {
1688 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1689 assert(isa<ConstantAsMetadata>(MD) &&
1690 "Expected non-function-local metadata");
1693 Elts.push_back(nullptr);
1695 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1698 case bitc::METADATA_VALUE: {
1699 if (Record.size() != 2)
1700 return error("Invalid record");
1702 Type *Ty = getTypeByID(Record[0]);
1703 if (Ty->isMetadataTy() || Ty->isVoidTy())
1704 return error("Invalid record");
1706 MDValueList.assignValue(
1707 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1711 case bitc::METADATA_DISTINCT_NODE:
1714 case bitc::METADATA_NODE: {
1715 SmallVector<Metadata *, 8> Elts;
1716 Elts.reserve(Record.size());
1717 for (unsigned ID : Record)
1718 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1719 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1720 : MDNode::get(Context, Elts),
1724 case bitc::METADATA_LOCATION: {
1725 if (Record.size() != 5)
1726 return error("Invalid record");
1728 unsigned Line = Record[1];
1729 unsigned Column = Record[2];
1730 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1731 Metadata *InlinedAt =
1732 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1733 MDValueList.assignValue(
1734 GET_OR_DISTINCT(DILocation, Record[0],
1735 (Context, Line, Column, Scope, InlinedAt)),
1739 case bitc::METADATA_GENERIC_DEBUG: {
1740 if (Record.size() < 4)
1741 return error("Invalid record");
1743 unsigned Tag = Record[1];
1744 unsigned Version = Record[2];
1746 if (Tag >= 1u << 16 || Version != 0)
1747 return error("Invalid record");
1749 auto *Header = getMDString(Record[3]);
1750 SmallVector<Metadata *, 8> DwarfOps;
1751 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1752 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1754 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1755 (Context, Tag, Header, DwarfOps)),
1759 case bitc::METADATA_SUBRANGE: {
1760 if (Record.size() != 3)
1761 return error("Invalid record");
1763 MDValueList.assignValue(
1764 GET_OR_DISTINCT(DISubrange, Record[0],
1765 (Context, Record[1], unrotateSign(Record[2]))),
1769 case bitc::METADATA_ENUMERATOR: {
1770 if (Record.size() != 3)
1771 return error("Invalid record");
1773 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1774 (Context, unrotateSign(Record[1]),
1775 getMDString(Record[2]))),
1779 case bitc::METADATA_BASIC_TYPE: {
1780 if (Record.size() != 6)
1781 return error("Invalid record");
1783 MDValueList.assignValue(
1784 GET_OR_DISTINCT(DIBasicType, Record[0],
1785 (Context, Record[1], getMDString(Record[2]),
1786 Record[3], Record[4], Record[5])),
1790 case bitc::METADATA_DERIVED_TYPE: {
1791 if (Record.size() != 12)
1792 return error("Invalid record");
1794 MDValueList.assignValue(
1795 GET_OR_DISTINCT(DIDerivedType, Record[0],
1796 (Context, Record[1], getMDString(Record[2]),
1797 getMDOrNull(Record[3]), Record[4],
1798 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1799 Record[7], Record[8], Record[9], Record[10],
1800 getMDOrNull(Record[11]))),
1804 case bitc::METADATA_COMPOSITE_TYPE: {
1805 if (Record.size() != 16)
1806 return error("Invalid record");
1808 MDValueList.assignValue(
1809 GET_OR_DISTINCT(DICompositeType, Record[0],
1810 (Context, Record[1], getMDString(Record[2]),
1811 getMDOrNull(Record[3]), Record[4],
1812 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1813 Record[7], Record[8], Record[9], Record[10],
1814 getMDOrNull(Record[11]), Record[12],
1815 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1816 getMDString(Record[15]))),
1820 case bitc::METADATA_SUBROUTINE_TYPE: {
1821 if (Record.size() != 3)
1822 return error("Invalid record");
1824 MDValueList.assignValue(
1825 GET_OR_DISTINCT(DISubroutineType, Record[0],
1826 (Context, Record[1], getMDOrNull(Record[2]))),
1831 case bitc::METADATA_MODULE: {
1832 if (Record.size() != 6)
1833 return error("Invalid record");
1835 MDValueList.assignValue(
1836 GET_OR_DISTINCT(DIModule, Record[0],
1837 (Context, getMDOrNull(Record[1]),
1838 getMDString(Record[2]), getMDString(Record[3]),
1839 getMDString(Record[4]), getMDString(Record[5]))),
1844 case bitc::METADATA_FILE: {
1845 if (Record.size() != 3)
1846 return error("Invalid record");
1848 MDValueList.assignValue(
1849 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1850 getMDString(Record[2]))),
1854 case bitc::METADATA_COMPILE_UNIT: {
1855 if (Record.size() < 14 || Record.size() > 15)
1856 return error("Invalid record");
1858 MDValueList.assignValue(
1860 DICompileUnit, Record[0],
1861 (Context, Record[1], getMDOrNull(Record[2]),
1862 getMDString(Record[3]), Record[4], getMDString(Record[5]),
1863 Record[6], getMDString(Record[7]), Record[8],
1864 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1865 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1866 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14])),
1870 case bitc::METADATA_SUBPROGRAM: {
1871 if (Record.size() != 19)
1872 return error("Invalid record");
1874 MDValueList.assignValue(
1876 DISubprogram, Record[0],
1877 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1878 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1879 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1880 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1881 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1882 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1886 case bitc::METADATA_LEXICAL_BLOCK: {
1887 if (Record.size() != 5)
1888 return error("Invalid record");
1890 MDValueList.assignValue(
1891 GET_OR_DISTINCT(DILexicalBlock, Record[0],
1892 (Context, getMDOrNull(Record[1]),
1893 getMDOrNull(Record[2]), Record[3], Record[4])),
1897 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1898 if (Record.size() != 4)
1899 return error("Invalid record");
1901 MDValueList.assignValue(
1902 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1903 (Context, getMDOrNull(Record[1]),
1904 getMDOrNull(Record[2]), Record[3])),
1908 case bitc::METADATA_NAMESPACE: {
1909 if (Record.size() != 5)
1910 return error("Invalid record");
1912 MDValueList.assignValue(
1913 GET_OR_DISTINCT(DINamespace, Record[0],
1914 (Context, getMDOrNull(Record[1]),
1915 getMDOrNull(Record[2]), getMDString(Record[3]),
1920 case bitc::METADATA_TEMPLATE_TYPE: {
1921 if (Record.size() != 3)
1922 return error("Invalid record");
1924 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1926 (Context, getMDString(Record[1]),
1927 getMDOrNull(Record[2]))),
1931 case bitc::METADATA_TEMPLATE_VALUE: {
1932 if (Record.size() != 5)
1933 return error("Invalid record");
1935 MDValueList.assignValue(
1936 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1937 (Context, Record[1], getMDString(Record[2]),
1938 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1942 case bitc::METADATA_GLOBAL_VAR: {
1943 if (Record.size() != 11)
1944 return error("Invalid record");
1946 MDValueList.assignValue(
1947 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1948 (Context, getMDOrNull(Record[1]),
1949 getMDString(Record[2]), getMDString(Record[3]),
1950 getMDOrNull(Record[4]), Record[5],
1951 getMDOrNull(Record[6]), Record[7], Record[8],
1952 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1956 case bitc::METADATA_LOCAL_VAR: {
1957 // 10th field is for the obseleted 'inlinedAt:' field.
1958 if (Record.size() != 9 && Record.size() != 10)
1959 return error("Invalid record");
1961 MDValueList.assignValue(
1962 GET_OR_DISTINCT(DILocalVariable, Record[0],
1963 (Context, Record[1], getMDOrNull(Record[2]),
1964 getMDString(Record[3]), getMDOrNull(Record[4]),
1965 Record[5], getMDOrNull(Record[6]), Record[7],
1970 case bitc::METADATA_EXPRESSION: {
1971 if (Record.size() < 1)
1972 return error("Invalid record");
1974 MDValueList.assignValue(
1975 GET_OR_DISTINCT(DIExpression, Record[0],
1976 (Context, makeArrayRef(Record).slice(1))),
1980 case bitc::METADATA_OBJC_PROPERTY: {
1981 if (Record.size() != 8)
1982 return error("Invalid record");
1984 MDValueList.assignValue(
1985 GET_OR_DISTINCT(DIObjCProperty, Record[0],
1986 (Context, getMDString(Record[1]),
1987 getMDOrNull(Record[2]), Record[3],
1988 getMDString(Record[4]), getMDString(Record[5]),
1989 Record[6], getMDOrNull(Record[7]))),
1993 case bitc::METADATA_IMPORTED_ENTITY: {
1994 if (Record.size() != 6)
1995 return error("Invalid record");
1997 MDValueList.assignValue(
1998 GET_OR_DISTINCT(DIImportedEntity, Record[0],
1999 (Context, Record[1], getMDOrNull(Record[2]),
2000 getMDOrNull(Record[3]), Record[4],
2001 getMDString(Record[5]))),
2005 case bitc::METADATA_STRING: {
2006 std::string String(Record.begin(), Record.end());
2007 llvm::UpgradeMDStringConstant(String);
2008 Metadata *MD = MDString::get(Context, String);
2009 MDValueList.assignValue(MD, NextMDValueNo++);
2012 case bitc::METADATA_KIND: {
2013 if (Record.size() < 2)
2014 return error("Invalid record");
2016 unsigned Kind = Record[0];
2017 SmallString<8> Name(Record.begin()+1, Record.end());
2019 unsigned NewKind = TheModule->getMDKindID(Name.str());
2020 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2021 return error("Conflicting METADATA_KIND records");
2026 #undef GET_OR_DISTINCT
2029 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2031 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2036 // There is no such thing as -0 with integers. "-0" really means MININT.
2040 /// Resolve all of the initializers for global values and aliases that we can.
2041 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2042 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2043 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2044 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2045 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2046 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2048 GlobalInitWorklist.swap(GlobalInits);
2049 AliasInitWorklist.swap(AliasInits);
2050 FunctionPrefixWorklist.swap(FunctionPrefixes);
2051 FunctionPrologueWorklist.swap(FunctionPrologues);
2052 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2054 while (!GlobalInitWorklist.empty()) {
2055 unsigned ValID = GlobalInitWorklist.back().second;
2056 if (ValID >= ValueList.size()) {
2057 // Not ready to resolve this yet, it requires something later in the file.
2058 GlobalInits.push_back(GlobalInitWorklist.back());
2060 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2061 GlobalInitWorklist.back().first->setInitializer(C);
2063 return error("Expected a constant");
2065 GlobalInitWorklist.pop_back();
2068 while (!AliasInitWorklist.empty()) {
2069 unsigned ValID = AliasInitWorklist.back().second;
2070 if (ValID >= ValueList.size()) {
2071 AliasInits.push_back(AliasInitWorklist.back());
2073 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2075 return error("Expected a constant");
2076 GlobalAlias *Alias = AliasInitWorklist.back().first;
2077 if (C->getType() != Alias->getType())
2078 return error("Alias and aliasee types don't match");
2079 Alias->setAliasee(C);
2081 AliasInitWorklist.pop_back();
2084 while (!FunctionPrefixWorklist.empty()) {
2085 unsigned ValID = FunctionPrefixWorklist.back().second;
2086 if (ValID >= ValueList.size()) {
2087 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2089 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2090 FunctionPrefixWorklist.back().first->setPrefixData(C);
2092 return error("Expected a constant");
2094 FunctionPrefixWorklist.pop_back();
2097 while (!FunctionPrologueWorklist.empty()) {
2098 unsigned ValID = FunctionPrologueWorklist.back().second;
2099 if (ValID >= ValueList.size()) {
2100 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2102 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2103 FunctionPrologueWorklist.back().first->setPrologueData(C);
2105 return error("Expected a constant");
2107 FunctionPrologueWorklist.pop_back();
2110 while (!FunctionPersonalityFnWorklist.empty()) {
2111 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2112 if (ValID >= ValueList.size()) {
2113 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2115 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2116 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2118 return error("Expected a constant");
2120 FunctionPersonalityFnWorklist.pop_back();
2123 return std::error_code();
2126 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2127 SmallVector<uint64_t, 8> Words(Vals.size());
2128 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2129 BitcodeReader::decodeSignRotatedValue);
2131 return APInt(TypeBits, Words);
2134 std::error_code BitcodeReader::parseConstants() {
2135 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2136 return error("Invalid record");
2138 SmallVector<uint64_t, 64> Record;
2140 // Read all the records for this value table.
2141 Type *CurTy = Type::getInt32Ty(Context);
2142 unsigned NextCstNo = ValueList.size();
2144 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2146 switch (Entry.Kind) {
2147 case BitstreamEntry::SubBlock: // Handled for us already.
2148 case BitstreamEntry::Error:
2149 return error("Malformed block");
2150 case BitstreamEntry::EndBlock:
2151 if (NextCstNo != ValueList.size())
2152 return error("Invalid ronstant reference");
2154 // Once all the constants have been read, go through and resolve forward
2156 ValueList.resolveConstantForwardRefs();
2157 return std::error_code();
2158 case BitstreamEntry::Record:
2159 // The interesting case.
2166 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2168 default: // Default behavior: unknown constant
2169 case bitc::CST_CODE_UNDEF: // UNDEF
2170 V = UndefValue::get(CurTy);
2172 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2174 return error("Invalid record");
2175 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2176 return error("Invalid record");
2177 CurTy = TypeList[Record[0]];
2178 continue; // Skip the ValueList manipulation.
2179 case bitc::CST_CODE_NULL: // NULL
2180 V = Constant::getNullValue(CurTy);
2182 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2183 if (!CurTy->isIntegerTy() || Record.empty())
2184 return error("Invalid record");
2185 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2187 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2188 if (!CurTy->isIntegerTy() || Record.empty())
2189 return error("Invalid record");
2192 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2193 V = ConstantInt::get(Context, VInt);
2197 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2199 return error("Invalid record");
2200 if (CurTy->isHalfTy())
2201 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2202 APInt(16, (uint16_t)Record[0])));
2203 else if (CurTy->isFloatTy())
2204 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2205 APInt(32, (uint32_t)Record[0])));
2206 else if (CurTy->isDoubleTy())
2207 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2208 APInt(64, Record[0])));
2209 else if (CurTy->isX86_FP80Ty()) {
2210 // Bits are not stored the same way as a normal i80 APInt, compensate.
2211 uint64_t Rearrange[2];
2212 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2213 Rearrange[1] = Record[0] >> 48;
2214 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2215 APInt(80, Rearrange)));
2216 } else if (CurTy->isFP128Ty())
2217 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2218 APInt(128, Record)));
2219 else if (CurTy->isPPC_FP128Ty())
2220 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2221 APInt(128, Record)));
2223 V = UndefValue::get(CurTy);
2227 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2229 return error("Invalid record");
2231 unsigned Size = Record.size();
2232 SmallVector<Constant*, 16> Elts;
2234 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2235 for (unsigned i = 0; i != Size; ++i)
2236 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2237 STy->getElementType(i)));
2238 V = ConstantStruct::get(STy, Elts);
2239 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2240 Type *EltTy = ATy->getElementType();
2241 for (unsigned i = 0; i != Size; ++i)
2242 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2243 V = ConstantArray::get(ATy, Elts);
2244 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2245 Type *EltTy = VTy->getElementType();
2246 for (unsigned i = 0; i != Size; ++i)
2247 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2248 V = ConstantVector::get(Elts);
2250 V = UndefValue::get(CurTy);
2254 case bitc::CST_CODE_STRING: // STRING: [values]
2255 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2257 return error("Invalid record");
2259 SmallString<16> Elts(Record.begin(), Record.end());
2260 V = ConstantDataArray::getString(Context, Elts,
2261 BitCode == bitc::CST_CODE_CSTRING);
2264 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2266 return error("Invalid record");
2268 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2269 unsigned Size = Record.size();
2271 if (EltTy->isIntegerTy(8)) {
2272 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2273 if (isa<VectorType>(CurTy))
2274 V = ConstantDataVector::get(Context, Elts);
2276 V = ConstantDataArray::get(Context, Elts);
2277 } else if (EltTy->isIntegerTy(16)) {
2278 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2279 if (isa<VectorType>(CurTy))
2280 V = ConstantDataVector::get(Context, Elts);
2282 V = ConstantDataArray::get(Context, Elts);
2283 } else if (EltTy->isIntegerTy(32)) {
2284 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2285 if (isa<VectorType>(CurTy))
2286 V = ConstantDataVector::get(Context, Elts);
2288 V = ConstantDataArray::get(Context, Elts);
2289 } else if (EltTy->isIntegerTy(64)) {
2290 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2291 if (isa<VectorType>(CurTy))
2292 V = ConstantDataVector::get(Context, Elts);
2294 V = ConstantDataArray::get(Context, Elts);
2295 } else if (EltTy->isFloatTy()) {
2296 SmallVector<float, 16> Elts(Size);
2297 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2298 if (isa<VectorType>(CurTy))
2299 V = ConstantDataVector::get(Context, Elts);
2301 V = ConstantDataArray::get(Context, Elts);
2302 } else if (EltTy->isDoubleTy()) {
2303 SmallVector<double, 16> Elts(Size);
2304 std::transform(Record.begin(), Record.end(), Elts.begin(),
2306 if (isa<VectorType>(CurTy))
2307 V = ConstantDataVector::get(Context, Elts);
2309 V = ConstantDataArray::get(Context, Elts);
2311 return error("Invalid type for value");
2316 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2317 if (Record.size() < 3)
2318 return error("Invalid record");
2319 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2321 V = UndefValue::get(CurTy); // Unknown binop.
2323 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2324 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2326 if (Record.size() >= 4) {
2327 if (Opc == Instruction::Add ||
2328 Opc == Instruction::Sub ||
2329 Opc == Instruction::Mul ||
2330 Opc == Instruction::Shl) {
2331 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2332 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2333 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2334 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2335 } else if (Opc == Instruction::SDiv ||
2336 Opc == Instruction::UDiv ||
2337 Opc == Instruction::LShr ||
2338 Opc == Instruction::AShr) {
2339 if (Record[3] & (1 << bitc::PEO_EXACT))
2340 Flags |= SDivOperator::IsExact;
2343 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2347 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2348 if (Record.size() < 3)
2349 return error("Invalid record");
2350 int Opc = getDecodedCastOpcode(Record[0]);
2352 V = UndefValue::get(CurTy); // Unknown cast.
2354 Type *OpTy = getTypeByID(Record[1]);
2356 return error("Invalid record");
2357 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2358 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2359 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2363 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2364 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2366 Type *PointeeType = nullptr;
2367 if (Record.size() % 2)
2368 PointeeType = getTypeByID(Record[OpNum++]);
2369 SmallVector<Constant*, 16> Elts;
2370 while (OpNum != Record.size()) {
2371 Type *ElTy = getTypeByID(Record[OpNum++]);
2373 return error("Invalid record");
2374 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2379 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2381 return error("Explicit gep operator type does not match pointee type "
2382 "of pointer operand");
2384 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2385 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2387 bitc::CST_CODE_CE_INBOUNDS_GEP);
2390 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2391 if (Record.size() < 3)
2392 return error("Invalid record");
2394 Type *SelectorTy = Type::getInt1Ty(Context);
2396 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2397 // vector. Otherwise, it must be a single bit.
2398 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2399 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2400 VTy->getNumElements());
2402 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2404 ValueList.getConstantFwdRef(Record[1],CurTy),
2405 ValueList.getConstantFwdRef(Record[2],CurTy));
2408 case bitc::CST_CODE_CE_EXTRACTELT
2409 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2410 if (Record.size() < 3)
2411 return error("Invalid record");
2413 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2415 return error("Invalid record");
2416 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2417 Constant *Op1 = nullptr;
2418 if (Record.size() == 4) {
2419 Type *IdxTy = getTypeByID(Record[2]);
2421 return error("Invalid record");
2422 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2423 } else // TODO: Remove with llvm 4.0
2424 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2426 return error("Invalid record");
2427 V = ConstantExpr::getExtractElement(Op0, Op1);
2430 case bitc::CST_CODE_CE_INSERTELT
2431 : { // CE_INSERTELT: [opval, opval, opty, opval]
2432 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2433 if (Record.size() < 3 || !OpTy)
2434 return error("Invalid record");
2435 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2436 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2437 OpTy->getElementType());
2438 Constant *Op2 = nullptr;
2439 if (Record.size() == 4) {
2440 Type *IdxTy = getTypeByID(Record[2]);
2442 return error("Invalid record");
2443 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2444 } else // TODO: Remove with llvm 4.0
2445 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2447 return error("Invalid record");
2448 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2451 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2452 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2453 if (Record.size() < 3 || !OpTy)
2454 return error("Invalid record");
2455 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2456 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2457 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2458 OpTy->getNumElements());
2459 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2460 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2463 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2464 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2466 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2467 if (Record.size() < 4 || !RTy || !OpTy)
2468 return error("Invalid record");
2469 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2470 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2471 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2472 RTy->getNumElements());
2473 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2474 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2477 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2478 if (Record.size() < 4)
2479 return error("Invalid record");
2480 Type *OpTy = getTypeByID(Record[0]);
2482 return error("Invalid record");
2483 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2484 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2486 if (OpTy->isFPOrFPVectorTy())
2487 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2489 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2492 // This maintains backward compatibility, pre-asm dialect keywords.
2493 // FIXME: Remove with the 4.0 release.
2494 case bitc::CST_CODE_INLINEASM_OLD: {
2495 if (Record.size() < 2)
2496 return error("Invalid record");
2497 std::string AsmStr, ConstrStr;
2498 bool HasSideEffects = Record[0] & 1;
2499 bool IsAlignStack = Record[0] >> 1;
2500 unsigned AsmStrSize = Record[1];
2501 if (2+AsmStrSize >= Record.size())
2502 return error("Invalid record");
2503 unsigned ConstStrSize = Record[2+AsmStrSize];
2504 if (3+AsmStrSize+ConstStrSize > Record.size())
2505 return error("Invalid record");
2507 for (unsigned i = 0; i != AsmStrSize; ++i)
2508 AsmStr += (char)Record[2+i];
2509 for (unsigned i = 0; i != ConstStrSize; ++i)
2510 ConstrStr += (char)Record[3+AsmStrSize+i];
2511 PointerType *PTy = cast<PointerType>(CurTy);
2512 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2513 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2516 // This version adds support for the asm dialect keywords (e.g.,
2518 case bitc::CST_CODE_INLINEASM: {
2519 if (Record.size() < 2)
2520 return error("Invalid record");
2521 std::string AsmStr, ConstrStr;
2522 bool HasSideEffects = Record[0] & 1;
2523 bool IsAlignStack = (Record[0] >> 1) & 1;
2524 unsigned AsmDialect = Record[0] >> 2;
2525 unsigned AsmStrSize = Record[1];
2526 if (2+AsmStrSize >= Record.size())
2527 return error("Invalid record");
2528 unsigned ConstStrSize = Record[2+AsmStrSize];
2529 if (3+AsmStrSize+ConstStrSize > Record.size())
2530 return error("Invalid record");
2532 for (unsigned i = 0; i != AsmStrSize; ++i)
2533 AsmStr += (char)Record[2+i];
2534 for (unsigned i = 0; i != ConstStrSize; ++i)
2535 ConstrStr += (char)Record[3+AsmStrSize+i];
2536 PointerType *PTy = cast<PointerType>(CurTy);
2537 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2538 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2539 InlineAsm::AsmDialect(AsmDialect));
2542 case bitc::CST_CODE_BLOCKADDRESS:{
2543 if (Record.size() < 3)
2544 return error("Invalid record");
2545 Type *FnTy = getTypeByID(Record[0]);
2547 return error("Invalid record");
2549 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2551 return error("Invalid record");
2553 // Don't let Fn get dematerialized.
2554 BlockAddressesTaken.insert(Fn);
2556 // If the function is already parsed we can insert the block address right
2559 unsigned BBID = Record[2];
2561 // Invalid reference to entry block.
2562 return error("Invalid ID");
2564 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2565 for (size_t I = 0, E = BBID; I != E; ++I) {
2567 return error("Invalid ID");
2572 // Otherwise insert a placeholder and remember it so it can be inserted
2573 // when the function is parsed.
2574 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2576 BasicBlockFwdRefQueue.push_back(Fn);
2577 if (FwdBBs.size() < BBID + 1)
2578 FwdBBs.resize(BBID + 1);
2580 FwdBBs[BBID] = BasicBlock::Create(Context);
2583 V = BlockAddress::get(Fn, BB);
2588 ValueList.assignValue(V, NextCstNo);
2593 std::error_code BitcodeReader::parseUseLists() {
2594 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2595 return error("Invalid record");
2597 // Read all the records.
2598 SmallVector<uint64_t, 64> Record;
2600 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2602 switch (Entry.Kind) {
2603 case BitstreamEntry::SubBlock: // Handled for us already.
2604 case BitstreamEntry::Error:
2605 return error("Malformed block");
2606 case BitstreamEntry::EndBlock:
2607 return std::error_code();
2608 case BitstreamEntry::Record:
2609 // The interesting case.
2613 // Read a use list record.
2616 switch (Stream.readRecord(Entry.ID, Record)) {
2617 default: // Default behavior: unknown type.
2619 case bitc::USELIST_CODE_BB:
2622 case bitc::USELIST_CODE_DEFAULT: {
2623 unsigned RecordLength = Record.size();
2624 if (RecordLength < 3)
2625 // Records should have at least an ID and two indexes.
2626 return error("Invalid record");
2627 unsigned ID = Record.back();
2632 assert(ID < FunctionBBs.size() && "Basic block not found");
2633 V = FunctionBBs[ID];
2636 unsigned NumUses = 0;
2637 SmallDenseMap<const Use *, unsigned, 16> Order;
2638 for (const Use &U : V->uses()) {
2639 if (++NumUses > Record.size())
2641 Order[&U] = Record[NumUses - 1];
2643 if (Order.size() != Record.size() || NumUses > Record.size())
2644 // Mismatches can happen if the functions are being materialized lazily
2645 // (out-of-order), or a value has been upgraded.
2648 V->sortUseList([&](const Use &L, const Use &R) {
2649 return Order.lookup(&L) < Order.lookup(&R);
2657 /// When we see the block for metadata, remember where it is and then skip it.
2658 /// This lets us lazily deserialize the metadata.
2659 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2660 // Save the current stream state.
2661 uint64_t CurBit = Stream.GetCurrentBitNo();
2662 DeferredMetadataInfo.push_back(CurBit);
2664 // Skip over the block for now.
2665 if (Stream.SkipBlock())
2666 return error("Invalid record");
2667 return std::error_code();
2670 std::error_code BitcodeReader::materializeMetadata() {
2671 for (uint64_t BitPos : DeferredMetadataInfo) {
2672 // Move the bit stream to the saved position.
2673 Stream.JumpToBit(BitPos);
2674 if (std::error_code EC = parseMetadata())
2677 DeferredMetadataInfo.clear();
2678 return std::error_code();
2681 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2683 /// When we see the block for a function body, remember where it is and then
2684 /// skip it. This lets us lazily deserialize the functions.
2685 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2686 // Get the function we are talking about.
2687 if (FunctionsWithBodies.empty())
2688 return error("Insufficient function protos");
2690 Function *Fn = FunctionsWithBodies.back();
2691 FunctionsWithBodies.pop_back();
2693 // Save the current stream state.
2694 uint64_t CurBit = Stream.GetCurrentBitNo();
2695 DeferredFunctionInfo[Fn] = CurBit;
2697 // Skip over the function block for now.
2698 if (Stream.SkipBlock())
2699 return error("Invalid record");
2700 return std::error_code();
2703 std::error_code BitcodeReader::globalCleanup() {
2704 // Patch the initializers for globals and aliases up.
2705 resolveGlobalAndAliasInits();
2706 if (!GlobalInits.empty() || !AliasInits.empty())
2707 return error("Malformed global initializer set");
2709 // Look for intrinsic functions which need to be upgraded at some point
2710 for (Function &F : *TheModule) {
2712 if (UpgradeIntrinsicFunction(&F, NewFn))
2713 UpgradedIntrinsics[&F] = NewFn;
2716 // Look for global variables which need to be renamed.
2717 for (GlobalVariable &GV : TheModule->globals())
2718 UpgradeGlobalVariable(&GV);
2720 // Force deallocation of memory for these vectors to favor the client that
2721 // want lazy deserialization.
2722 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2723 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2724 return std::error_code();
2727 std::error_code BitcodeReader::parseModule(bool Resume,
2728 bool ShouldLazyLoadMetadata) {
2730 Stream.JumpToBit(NextUnreadBit);
2731 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2732 return error("Invalid record");
2734 SmallVector<uint64_t, 64> Record;
2735 std::vector<std::string> SectionTable;
2736 std::vector<std::string> GCTable;
2738 // Read all the records for this module.
2740 BitstreamEntry Entry = Stream.advance();
2742 switch (Entry.Kind) {
2743 case BitstreamEntry::Error:
2744 return error("Malformed block");
2745 case BitstreamEntry::EndBlock:
2746 return globalCleanup();
2748 case BitstreamEntry::SubBlock:
2750 default: // Skip unknown content.
2751 if (Stream.SkipBlock())
2752 return error("Invalid record");
2754 case bitc::BLOCKINFO_BLOCK_ID:
2755 if (Stream.ReadBlockInfoBlock())
2756 return error("Malformed block");
2758 case bitc::PARAMATTR_BLOCK_ID:
2759 if (std::error_code EC = parseAttributeBlock())
2762 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2763 if (std::error_code EC = parseAttributeGroupBlock())
2766 case bitc::TYPE_BLOCK_ID_NEW:
2767 if (std::error_code EC = parseTypeTable())
2770 case bitc::VALUE_SYMTAB_BLOCK_ID:
2771 if (std::error_code EC = parseValueSymbolTable())
2773 SeenValueSymbolTable = true;
2775 case bitc::CONSTANTS_BLOCK_ID:
2776 if (std::error_code EC = parseConstants())
2778 if (std::error_code EC = resolveGlobalAndAliasInits())
2781 case bitc::METADATA_BLOCK_ID:
2782 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2783 if (std::error_code EC = rememberAndSkipMetadata())
2787 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2788 if (std::error_code EC = parseMetadata())
2791 case bitc::FUNCTION_BLOCK_ID:
2792 // If this is the first function body we've seen, reverse the
2793 // FunctionsWithBodies list.
2794 if (!SeenFirstFunctionBody) {
2795 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2796 if (std::error_code EC = globalCleanup())
2798 SeenFirstFunctionBody = true;
2801 if (std::error_code EC = rememberAndSkipFunctionBody())
2803 // Suspend parsing when we reach the function bodies. Subsequent
2804 // materialization calls will resume it when necessary. If the bitcode
2805 // file is old, the symbol table will be at the end instead and will not
2806 // have been seen yet. In this case, just finish the parse now.
2807 if (SeenValueSymbolTable) {
2808 NextUnreadBit = Stream.GetCurrentBitNo();
2809 return std::error_code();
2812 case bitc::USELIST_BLOCK_ID:
2813 if (std::error_code EC = parseUseLists())
2819 case BitstreamEntry::Record:
2820 // The interesting case.
2826 switch (Stream.readRecord(Entry.ID, Record)) {
2827 default: break; // Default behavior, ignore unknown content.
2828 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2829 if (Record.size() < 1)
2830 return error("Invalid record");
2831 // Only version #0 and #1 are supported so far.
2832 unsigned module_version = Record[0];
2833 switch (module_version) {
2835 return error("Invalid value");
2837 UseRelativeIDs = false;
2840 UseRelativeIDs = true;
2845 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2847 if (convertToString(Record, 0, S))
2848 return error("Invalid record");
2849 TheModule->setTargetTriple(S);
2852 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2854 if (convertToString(Record, 0, S))
2855 return error("Invalid record");
2856 TheModule->setDataLayout(S);
2859 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2861 if (convertToString(Record, 0, S))
2862 return error("Invalid record");
2863 TheModule->setModuleInlineAsm(S);
2866 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2867 // FIXME: Remove in 4.0.
2869 if (convertToString(Record, 0, S))
2870 return error("Invalid record");
2874 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2876 if (convertToString(Record, 0, S))
2877 return error("Invalid record");
2878 SectionTable.push_back(S);
2881 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2883 if (convertToString(Record, 0, S))
2884 return error("Invalid record");
2885 GCTable.push_back(S);
2888 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2889 if (Record.size() < 2)
2890 return error("Invalid record");
2891 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2892 unsigned ComdatNameSize = Record[1];
2893 std::string ComdatName;
2894 ComdatName.reserve(ComdatNameSize);
2895 for (unsigned i = 0; i != ComdatNameSize; ++i)
2896 ComdatName += (char)Record[2 + i];
2897 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2898 C->setSelectionKind(SK);
2899 ComdatList.push_back(C);
2902 // GLOBALVAR: [pointer type, isconst, initid,
2903 // linkage, alignment, section, visibility, threadlocal,
2904 // unnamed_addr, externally_initialized, dllstorageclass,
2906 case bitc::MODULE_CODE_GLOBALVAR: {
2907 if (Record.size() < 6)
2908 return error("Invalid record");
2909 Type *Ty = getTypeByID(Record[0]);
2911 return error("Invalid record");
2912 bool isConstant = Record[1] & 1;
2913 bool explicitType = Record[1] & 2;
2914 unsigned AddressSpace;
2916 AddressSpace = Record[1] >> 2;
2918 if (!Ty->isPointerTy())
2919 return error("Invalid type for value");
2920 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2921 Ty = cast<PointerType>(Ty)->getElementType();
2924 uint64_t RawLinkage = Record[3];
2925 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2927 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2929 std::string Section;
2931 if (Record[5]-1 >= SectionTable.size())
2932 return error("Invalid ID");
2933 Section = SectionTable[Record[5]-1];
2935 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2936 // Local linkage must have default visibility.
2937 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2938 // FIXME: Change to an error if non-default in 4.0.
2939 Visibility = getDecodedVisibility(Record[6]);
2941 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2942 if (Record.size() > 7)
2943 TLM = getDecodedThreadLocalMode(Record[7]);
2945 bool UnnamedAddr = false;
2946 if (Record.size() > 8)
2947 UnnamedAddr = Record[8];
2949 bool ExternallyInitialized = false;
2950 if (Record.size() > 9)
2951 ExternallyInitialized = Record[9];
2953 GlobalVariable *NewGV =
2954 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2955 TLM, AddressSpace, ExternallyInitialized);
2956 NewGV->setAlignment(Alignment);
2957 if (!Section.empty())
2958 NewGV->setSection(Section);
2959 NewGV->setVisibility(Visibility);
2960 NewGV->setUnnamedAddr(UnnamedAddr);
2962 if (Record.size() > 10)
2963 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2965 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2967 ValueList.push_back(NewGV);
2969 // Remember which value to use for the global initializer.
2970 if (unsigned InitID = Record[2])
2971 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2973 if (Record.size() > 11) {
2974 if (unsigned ComdatID = Record[11]) {
2975 if (ComdatID > ComdatList.size())
2976 return error("Invalid global variable comdat ID");
2977 NewGV->setComdat(ComdatList[ComdatID - 1]);
2979 } else if (hasImplicitComdat(RawLinkage)) {
2980 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2984 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2985 // alignment, section, visibility, gc, unnamed_addr,
2986 // prologuedata, dllstorageclass, comdat, prefixdata]
2987 case bitc::MODULE_CODE_FUNCTION: {
2988 if (Record.size() < 8)
2989 return error("Invalid record");
2990 Type *Ty = getTypeByID(Record[0]);
2992 return error("Invalid record");
2993 if (auto *PTy = dyn_cast<PointerType>(Ty))
2994 Ty = PTy->getElementType();
2995 auto *FTy = dyn_cast<FunctionType>(Ty);
2997 return error("Invalid type for value");
2999 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3002 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
3003 bool isProto = Record[2];
3004 uint64_t RawLinkage = Record[3];
3005 Func->setLinkage(getDecodedLinkage(RawLinkage));
3006 Func->setAttributes(getAttributes(Record[4]));
3009 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3011 Func->setAlignment(Alignment);
3013 if (Record[6]-1 >= SectionTable.size())
3014 return error("Invalid ID");
3015 Func->setSection(SectionTable[Record[6]-1]);
3017 // Local linkage must have default visibility.
3018 if (!Func->hasLocalLinkage())
3019 // FIXME: Change to an error if non-default in 4.0.
3020 Func->setVisibility(getDecodedVisibility(Record[7]));
3021 if (Record.size() > 8 && Record[8]) {
3022 if (Record[8]-1 >= GCTable.size())
3023 return error("Invalid ID");
3024 Func->setGC(GCTable[Record[8]-1].c_str());
3026 bool UnnamedAddr = false;
3027 if (Record.size() > 9)
3028 UnnamedAddr = Record[9];
3029 Func->setUnnamedAddr(UnnamedAddr);
3030 if (Record.size() > 10 && Record[10] != 0)
3031 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3033 if (Record.size() > 11)
3034 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3036 upgradeDLLImportExportLinkage(Func, RawLinkage);
3038 if (Record.size() > 12) {
3039 if (unsigned ComdatID = Record[12]) {
3040 if (ComdatID > ComdatList.size())
3041 return error("Invalid function comdat ID");
3042 Func->setComdat(ComdatList[ComdatID - 1]);
3044 } else if (hasImplicitComdat(RawLinkage)) {
3045 Func->setComdat(reinterpret_cast<Comdat *>(1));
3048 if (Record.size() > 13 && Record[13] != 0)
3049 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3051 if (Record.size() > 14 && Record[14] != 0)
3052 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3054 ValueList.push_back(Func);
3056 // If this is a function with a body, remember the prototype we are
3057 // creating now, so that we can match up the body with them later.
3059 Func->setIsMaterializable(true);
3060 FunctionsWithBodies.push_back(Func);
3061 DeferredFunctionInfo[Func] = 0;
3065 // ALIAS: [alias type, aliasee val#, linkage]
3066 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3067 case bitc::MODULE_CODE_ALIAS: {
3068 if (Record.size() < 3)
3069 return error("Invalid record");
3070 Type *Ty = getTypeByID(Record[0]);
3072 return error("Invalid record");
3073 auto *PTy = dyn_cast<PointerType>(Ty);
3075 return error("Invalid type for value");
3078 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3079 // Old bitcode files didn't have visibility field.
3080 // Local linkage must have default visibility.
3081 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3082 // FIXME: Change to an error if non-default in 4.0.
3083 NewGA->setVisibility(getDecodedVisibility(Record[3]));
3084 if (Record.size() > 4)
3085 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
3087 upgradeDLLImportExportLinkage(NewGA, Record[2]);
3088 if (Record.size() > 5)
3089 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
3090 if (Record.size() > 6)
3091 NewGA->setUnnamedAddr(Record[6]);
3092 ValueList.push_back(NewGA);
3093 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3096 /// MODULE_CODE_PURGEVALS: [numvals]
3097 case bitc::MODULE_CODE_PURGEVALS:
3098 // Trim down the value list to the specified size.
3099 if (Record.size() < 1 || Record[0] > ValueList.size())
3100 return error("Invalid record");
3101 ValueList.shrinkTo(Record[0]);
3109 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3110 Module *M, bool ShouldLazyLoadMetadata) {
3113 if (std::error_code EC = initStream(std::move(Streamer)))
3116 // Sniff for the signature.
3117 if (Stream.Read(8) != 'B' ||
3118 Stream.Read(8) != 'C' ||
3119 Stream.Read(4) != 0x0 ||
3120 Stream.Read(4) != 0xC ||
3121 Stream.Read(4) != 0xE ||
3122 Stream.Read(4) != 0xD)
3123 return error("Invalid bitcode signature");
3125 // We expect a number of well-defined blocks, though we don't necessarily
3126 // need to understand them all.
3128 if (Stream.AtEndOfStream()) {
3129 // We didn't really read a proper Module.
3130 return error("Malformed IR file");
3133 BitstreamEntry Entry =
3134 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3136 if (Entry.Kind != BitstreamEntry::SubBlock)
3137 return error("Malformed block");
3139 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3140 return parseModule(false, ShouldLazyLoadMetadata);
3142 if (Stream.SkipBlock())
3143 return error("Invalid record");
3147 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3148 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3149 return error("Invalid record");
3151 SmallVector<uint64_t, 64> Record;
3154 // Read all the records for this module.
3156 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3158 switch (Entry.Kind) {
3159 case BitstreamEntry::SubBlock: // Handled for us already.
3160 case BitstreamEntry::Error:
3161 return error("Malformed block");
3162 case BitstreamEntry::EndBlock:
3164 case BitstreamEntry::Record:
3165 // The interesting case.
3170 switch (Stream.readRecord(Entry.ID, Record)) {
3171 default: break; // Default behavior, ignore unknown content.
3172 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3174 if (convertToString(Record, 0, S))
3175 return error("Invalid record");
3182 llvm_unreachable("Exit infinite loop");
3185 ErrorOr<std::string> BitcodeReader::parseTriple() {
3186 if (std::error_code EC = initStream(nullptr))
3189 // Sniff for the signature.
3190 if (Stream.Read(8) != 'B' ||
3191 Stream.Read(8) != 'C' ||
3192 Stream.Read(4) != 0x0 ||
3193 Stream.Read(4) != 0xC ||
3194 Stream.Read(4) != 0xE ||
3195 Stream.Read(4) != 0xD)
3196 return error("Invalid bitcode signature");
3198 // We expect a number of well-defined blocks, though we don't necessarily
3199 // need to understand them all.
3201 BitstreamEntry Entry = Stream.advance();
3203 switch (Entry.Kind) {
3204 case BitstreamEntry::Error:
3205 return error("Malformed block");
3206 case BitstreamEntry::EndBlock:
3207 return std::error_code();
3209 case BitstreamEntry::SubBlock:
3210 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3211 return parseModuleTriple();
3213 // Ignore other sub-blocks.
3214 if (Stream.SkipBlock())
3215 return error("Malformed block");
3218 case BitstreamEntry::Record:
3219 Stream.skipRecord(Entry.ID);
3225 /// Parse metadata attachments.
3226 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3227 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3228 return error("Invalid record");
3230 SmallVector<uint64_t, 64> Record;
3232 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3234 switch (Entry.Kind) {
3235 case BitstreamEntry::SubBlock: // Handled for us already.
3236 case BitstreamEntry::Error:
3237 return error("Malformed block");
3238 case BitstreamEntry::EndBlock:
3239 return std::error_code();
3240 case BitstreamEntry::Record:
3241 // The interesting case.
3245 // Read a metadata attachment record.
3247 switch (Stream.readRecord(Entry.ID, Record)) {
3248 default: // Default behavior: ignore.
3250 case bitc::METADATA_ATTACHMENT: {
3251 unsigned RecordLength = Record.size();
3253 return error("Invalid record");
3254 if (RecordLength % 2 == 0) {
3255 // A function attachment.
3256 for (unsigned I = 0; I != RecordLength; I += 2) {
3257 auto K = MDKindMap.find(Record[I]);
3258 if (K == MDKindMap.end())
3259 return error("Invalid ID");
3260 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3261 F.setMetadata(K->second, cast<MDNode>(MD));
3266 // An instruction attachment.
3267 Instruction *Inst = InstructionList[Record[0]];
3268 for (unsigned i = 1; i != RecordLength; i = i+2) {
3269 unsigned Kind = Record[i];
3270 DenseMap<unsigned, unsigned>::iterator I =
3271 MDKindMap.find(Kind);
3272 if (I == MDKindMap.end())
3273 return error("Invalid ID");
3274 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3275 if (isa<LocalAsMetadata>(Node))
3276 // Drop the attachment. This used to be legal, but there's no
3279 Inst->setMetadata(I->second, cast<MDNode>(Node));
3280 if (I->second == LLVMContext::MD_tbaa)
3281 InstsWithTBAATag.push_back(Inst);
3289 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3290 Type *ValType, Type *PtrType) {
3291 if (!isa<PointerType>(PtrType))
3292 return error(DH, "Load/Store operand is not a pointer type");
3293 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3295 if (ValType && ValType != ElemType)
3296 return error(DH, "Explicit load/store type does not match pointee type of "
3298 if (!PointerType::isLoadableOrStorableType(ElemType))
3299 return error(DH, "Cannot load/store from pointer");
3300 return std::error_code();
3303 /// Lazily parse the specified function body block.
3304 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3305 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3306 return error("Invalid record");
3308 InstructionList.clear();
3309 unsigned ModuleValueListSize = ValueList.size();
3310 unsigned ModuleMDValueListSize = MDValueList.size();
3312 // Add all the function arguments to the value table.
3313 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3314 ValueList.push_back(I);
3316 unsigned NextValueNo = ValueList.size();
3317 BasicBlock *CurBB = nullptr;
3318 unsigned CurBBNo = 0;
3321 auto getLastInstruction = [&]() -> Instruction * {
3322 if (CurBB && !CurBB->empty())
3323 return &CurBB->back();
3324 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3325 !FunctionBBs[CurBBNo - 1]->empty())
3326 return &FunctionBBs[CurBBNo - 1]->back();
3330 // Read all the records.
3331 SmallVector<uint64_t, 64> Record;
3333 BitstreamEntry Entry = Stream.advance();
3335 switch (Entry.Kind) {
3336 case BitstreamEntry::Error:
3337 return error("Malformed block");
3338 case BitstreamEntry::EndBlock:
3339 goto OutOfRecordLoop;
3341 case BitstreamEntry::SubBlock:
3343 default: // Skip unknown content.
3344 if (Stream.SkipBlock())
3345 return error("Invalid record");
3347 case bitc::CONSTANTS_BLOCK_ID:
3348 if (std::error_code EC = parseConstants())
3350 NextValueNo = ValueList.size();
3352 case bitc::VALUE_SYMTAB_BLOCK_ID:
3353 if (std::error_code EC = parseValueSymbolTable())
3356 case bitc::METADATA_ATTACHMENT_ID:
3357 if (std::error_code EC = parseMetadataAttachment(*F))
3360 case bitc::METADATA_BLOCK_ID:
3361 if (std::error_code EC = parseMetadata())
3364 case bitc::USELIST_BLOCK_ID:
3365 if (std::error_code EC = parseUseLists())
3371 case BitstreamEntry::Record:
3372 // The interesting case.
3378 Instruction *I = nullptr;
3379 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3381 default: // Default behavior: reject
3382 return error("Invalid value");
3383 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3384 if (Record.size() < 1 || Record[0] == 0)
3385 return error("Invalid record");
3386 // Create all the basic blocks for the function.
3387 FunctionBBs.resize(Record[0]);
3389 // See if anything took the address of blocks in this function.
3390 auto BBFRI = BasicBlockFwdRefs.find(F);
3391 if (BBFRI == BasicBlockFwdRefs.end()) {
3392 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3393 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3395 auto &BBRefs = BBFRI->second;
3396 // Check for invalid basic block references.
3397 if (BBRefs.size() > FunctionBBs.size())
3398 return error("Invalid ID");
3399 assert(!BBRefs.empty() && "Unexpected empty array");
3400 assert(!BBRefs.front() && "Invalid reference to entry block");
3401 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3403 if (I < RE && BBRefs[I]) {
3404 BBRefs[I]->insertInto(F);
3405 FunctionBBs[I] = BBRefs[I];
3407 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3410 // Erase from the table.
3411 BasicBlockFwdRefs.erase(BBFRI);
3414 CurBB = FunctionBBs[0];
3418 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3419 // This record indicates that the last instruction is at the same
3420 // location as the previous instruction with a location.
3421 I = getLastInstruction();
3424 return error("Invalid record");
3425 I->setDebugLoc(LastLoc);
3429 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3430 I = getLastInstruction();
3431 if (!I || Record.size() < 4)
3432 return error("Invalid record");
3434 unsigned Line = Record[0], Col = Record[1];
3435 unsigned ScopeID = Record[2], IAID = Record[3];
3437 MDNode *Scope = nullptr, *IA = nullptr;
3438 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3439 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3440 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3441 I->setDebugLoc(LastLoc);
3446 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3449 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3450 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3451 OpNum+1 > Record.size())
3452 return error("Invalid record");
3454 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3456 return error("Invalid record");
3457 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3458 InstructionList.push_back(I);
3459 if (OpNum < Record.size()) {
3460 if (Opc == Instruction::Add ||
3461 Opc == Instruction::Sub ||
3462 Opc == Instruction::Mul ||
3463 Opc == Instruction::Shl) {
3464 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3465 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3466 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3467 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3468 } else if (Opc == Instruction::SDiv ||
3469 Opc == Instruction::UDiv ||
3470 Opc == Instruction::LShr ||
3471 Opc == Instruction::AShr) {
3472 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3473 cast<BinaryOperator>(I)->setIsExact(true);
3474 } else if (isa<FPMathOperator>(I)) {
3476 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3477 FMF.setUnsafeAlgebra();
3478 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3480 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3482 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3483 FMF.setNoSignedZeros();
3484 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3485 FMF.setAllowReciprocal();
3487 I->setFastMathFlags(FMF);
3493 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3496 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3497 OpNum+2 != Record.size())
3498 return error("Invalid record");
3500 Type *ResTy = getTypeByID(Record[OpNum]);
3501 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3502 if (Opc == -1 || !ResTy)
3503 return error("Invalid record");
3504 Instruction *Temp = nullptr;
3505 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3507 InstructionList.push_back(Temp);
3508 CurBB->getInstList().push_back(Temp);
3511 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3513 InstructionList.push_back(I);
3516 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3517 case bitc::FUNC_CODE_INST_GEP_OLD:
3518 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3524 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3525 InBounds = Record[OpNum++];
3526 Ty = getTypeByID(Record[OpNum++]);
3528 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3533 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3534 return error("Invalid record");
3537 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3540 cast<SequentialType>(BasePtr->getType()->getScalarType())
3543 "Explicit gep type does not match pointee type of pointer operand");
3545 SmallVector<Value*, 16> GEPIdx;
3546 while (OpNum != Record.size()) {
3548 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3549 return error("Invalid record");
3550 GEPIdx.push_back(Op);
3553 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3555 InstructionList.push_back(I);
3557 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3561 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3562 // EXTRACTVAL: [opty, opval, n x indices]
3565 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3566 return error("Invalid record");
3568 unsigned RecSize = Record.size();
3569 if (OpNum == RecSize)
3570 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3572 SmallVector<unsigned, 4> EXTRACTVALIdx;
3573 Type *CurTy = Agg->getType();
3574 for (; OpNum != RecSize; ++OpNum) {
3575 bool IsArray = CurTy->isArrayTy();
3576 bool IsStruct = CurTy->isStructTy();
3577 uint64_t Index = Record[OpNum];
3579 if (!IsStruct && !IsArray)
3580 return error("EXTRACTVAL: Invalid type");
3581 if ((unsigned)Index != Index)
3582 return error("Invalid value");
3583 if (IsStruct && Index >= CurTy->subtypes().size())
3584 return error("EXTRACTVAL: Invalid struct index");
3585 if (IsArray && Index >= CurTy->getArrayNumElements())
3586 return error("EXTRACTVAL: Invalid array index");
3587 EXTRACTVALIdx.push_back((unsigned)Index);
3590 CurTy = CurTy->subtypes()[Index];
3592 CurTy = CurTy->subtypes()[0];
3595 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3596 InstructionList.push_back(I);
3600 case bitc::FUNC_CODE_INST_INSERTVAL: {
3601 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3604 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3605 return error("Invalid record");
3607 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3608 return error("Invalid record");
3610 unsigned RecSize = Record.size();
3611 if (OpNum == RecSize)
3612 return error("INSERTVAL: Invalid instruction with 0 indices");
3614 SmallVector<unsigned, 4> INSERTVALIdx;
3615 Type *CurTy = Agg->getType();
3616 for (; OpNum != RecSize; ++OpNum) {
3617 bool IsArray = CurTy->isArrayTy();
3618 bool IsStruct = CurTy->isStructTy();
3619 uint64_t Index = Record[OpNum];
3621 if (!IsStruct && !IsArray)
3622 return error("INSERTVAL: Invalid type");
3623 if ((unsigned)Index != Index)
3624 return error("Invalid value");
3625 if (IsStruct && Index >= CurTy->subtypes().size())
3626 return error("INSERTVAL: Invalid struct index");
3627 if (IsArray && Index >= CurTy->getArrayNumElements())
3628 return error("INSERTVAL: Invalid array index");
3630 INSERTVALIdx.push_back((unsigned)Index);
3632 CurTy = CurTy->subtypes()[Index];
3634 CurTy = CurTy->subtypes()[0];
3637 if (CurTy != Val->getType())
3638 return error("Inserted value type doesn't match aggregate type");
3640 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3641 InstructionList.push_back(I);
3645 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3646 // obsolete form of select
3647 // handles select i1 ... in old bitcode
3649 Value *TrueVal, *FalseVal, *Cond;
3650 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3651 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3652 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3653 return error("Invalid record");
3655 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3656 InstructionList.push_back(I);
3660 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3661 // new form of select
3662 // handles select i1 or select [N x i1]
3664 Value *TrueVal, *FalseVal, *Cond;
3665 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3666 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3667 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3668 return error("Invalid record");
3670 // select condition can be either i1 or [N x i1]
3671 if (VectorType* vector_type =
3672 dyn_cast<VectorType>(Cond->getType())) {
3674 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3675 return error("Invalid type for value");
3678 if (Cond->getType() != Type::getInt1Ty(Context))
3679 return error("Invalid type for value");
3682 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3683 InstructionList.push_back(I);
3687 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3690 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3691 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3692 return error("Invalid record");
3693 if (!Vec->getType()->isVectorTy())
3694 return error("Invalid type for value");
3695 I = ExtractElementInst::Create(Vec, Idx);
3696 InstructionList.push_back(I);
3700 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3702 Value *Vec, *Elt, *Idx;
3703 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3704 return error("Invalid record");
3705 if (!Vec->getType()->isVectorTy())
3706 return error("Invalid type for value");
3707 if (popValue(Record, OpNum, NextValueNo,
3708 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3709 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3710 return error("Invalid record");
3711 I = InsertElementInst::Create(Vec, Elt, Idx);
3712 InstructionList.push_back(I);
3716 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3718 Value *Vec1, *Vec2, *Mask;
3719 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3720 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3721 return error("Invalid record");
3723 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3724 return error("Invalid record");
3725 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3726 return error("Invalid type for value");
3727 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3728 InstructionList.push_back(I);
3732 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3733 // Old form of ICmp/FCmp returning bool
3734 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3735 // both legal on vectors but had different behaviour.
3736 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3737 // FCmp/ICmp returning bool or vector of bool
3741 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3742 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3743 OpNum+1 != Record.size())
3744 return error("Invalid record");
3746 if (LHS->getType()->isFPOrFPVectorTy())
3747 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3749 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3750 InstructionList.push_back(I);
3754 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3756 unsigned Size = Record.size();
3758 I = ReturnInst::Create(Context);
3759 InstructionList.push_back(I);
3764 Value *Op = nullptr;
3765 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3766 return error("Invalid record");
3767 if (OpNum != Record.size())
3768 return error("Invalid record");
3770 I = ReturnInst::Create(Context, Op);
3771 InstructionList.push_back(I);
3774 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3775 if (Record.size() != 1 && Record.size() != 3)
3776 return error("Invalid record");
3777 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3779 return error("Invalid record");
3781 if (Record.size() == 1) {
3782 I = BranchInst::Create(TrueDest);
3783 InstructionList.push_back(I);
3786 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3787 Value *Cond = getValue(Record, 2, NextValueNo,
3788 Type::getInt1Ty(Context));
3789 if (!FalseDest || !Cond)
3790 return error("Invalid record");
3791 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3792 InstructionList.push_back(I);
3796 // CLEANUPRET: [] or [ty,val] or [bb#] or [ty,val,bb#]
3797 case bitc::FUNC_CODE_INST_CLEANUPRET: {
3798 if (Record.size() < 2)
3799 return error("Invalid record");
3801 bool HasReturnValue = !!Record[Idx++];
3802 bool HasUnwindDest = !!Record[Idx++];
3803 Value *RetVal = nullptr;
3804 BasicBlock *UnwindDest = nullptr;
3806 if (HasReturnValue && getValueTypePair(Record, Idx, NextValueNo, RetVal))
3807 return error("Invalid record");
3808 if (HasUnwindDest) {
3809 if (Idx == Record.size())
3810 return error("Invalid record");
3811 UnwindDest = getBasicBlock(Record[Idx++]);
3813 return error("Invalid record");
3816 if (Record.size() != Idx)
3817 return error("Invalid record");
3819 I = CleanupReturnInst::Create(Context, RetVal, UnwindDest);
3820 InstructionList.push_back(I);
3823 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [bb#]
3824 if (Record.size() != 1)
3825 return error("Invalid record");
3826 BasicBlock *BB = getBasicBlock(Record[0]);
3828 return error("Invalid record");
3829 I = CatchReturnInst::Create(BB);
3830 InstructionList.push_back(I);
3833 case bitc::FUNC_CODE_INST_CATCHBLOCK: { // CATCHBLOCK: [ty,bb#,bb#,num,(ty,val)*]
3834 if (Record.size() < 4)
3835 return error("Invalid record");
3837 Type *Ty = getTypeByID(Record[Idx++]);
3839 return error("Invalid record");
3840 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
3842 return error("Invalid record");
3843 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
3845 return error("Invalid record");
3846 unsigned NumArgOperands = Record[Idx++];
3847 SmallVector<Value *, 2> Args;
3848 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3850 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3851 return error("Invalid record");
3852 Args.push_back(Val);
3854 if (Record.size() != Idx)
3855 return error("Invalid record");
3857 I = CatchBlockInst::Create(Ty, NormalBB, UnwindBB, Args);
3858 InstructionList.push_back(I);
3861 case bitc::FUNC_CODE_INST_TERMINATEBLOCK: { // TERMINATEBLOCK: [bb#,num,(ty,val)*]
3862 if (Record.size() < 1)
3863 return error("Invalid record");
3865 bool HasUnwindDest = !!Record[Idx++];
3866 BasicBlock *UnwindDest = nullptr;
3867 if (HasUnwindDest) {
3868 if (Idx == Record.size())
3869 return error("Invalid record");
3870 UnwindDest = getBasicBlock(Record[Idx++]);
3872 return error("Invalid record");
3874 unsigned NumArgOperands = Record[Idx++];
3875 SmallVector<Value *, 2> Args;
3876 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3878 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3879 return error("Invalid record");
3880 Args.push_back(Val);
3882 if (Record.size() != Idx)
3883 return error("Invalid record");
3885 I = TerminateBlockInst::Create(Context, UnwindDest, Args);
3886 InstructionList.push_back(I);
3889 case bitc::FUNC_CODE_INST_CLEANUPBLOCK: { // CLEANUPBLOCK: [ty, num,(ty,val)*]
3890 if (Record.size() < 2)
3891 return error("Invalid record");
3893 Type *Ty = getTypeByID(Record[Idx++]);
3895 return error("Invalid record");
3896 unsigned NumArgOperands = Record[Idx++];
3897 SmallVector<Value *, 2> Args;
3898 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3900 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3901 return error("Invalid record");
3902 Args.push_back(Val);
3904 if (Record.size() != Idx)
3905 return error("Invalid record");
3907 I = CleanupBlockInst::Create(Ty, Args);
3908 InstructionList.push_back(I);
3911 case bitc::FUNC_CODE_INST_CATCHENDBLOCK: { // CATCHENDBLOCKINST: [bb#] or []
3912 if (Record.size() > 1)
3913 return error("Invalid record");
3914 BasicBlock *BB = nullptr;
3915 if (Record.size() == 1) {
3916 BB = getBasicBlock(Record[0]);
3918 return error("Invalid record");
3920 I = CatchEndBlockInst::Create(Context, BB);
3921 InstructionList.push_back(I);
3924 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3926 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3927 // "New" SwitchInst format with case ranges. The changes to write this
3928 // format were reverted but we still recognize bitcode that uses it.
3929 // Hopefully someday we will have support for case ranges and can use
3930 // this format again.
3932 Type *OpTy = getTypeByID(Record[1]);
3933 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3935 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3936 BasicBlock *Default = getBasicBlock(Record[3]);
3937 if (!OpTy || !Cond || !Default)
3938 return error("Invalid record");
3940 unsigned NumCases = Record[4];
3942 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3943 InstructionList.push_back(SI);
3945 unsigned CurIdx = 5;
3946 for (unsigned i = 0; i != NumCases; ++i) {
3947 SmallVector<ConstantInt*, 1> CaseVals;
3948 unsigned NumItems = Record[CurIdx++];
3949 for (unsigned ci = 0; ci != NumItems; ++ci) {
3950 bool isSingleNumber = Record[CurIdx++];
3953 unsigned ActiveWords = 1;
3954 if (ValueBitWidth > 64)
3955 ActiveWords = Record[CurIdx++];
3956 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3958 CurIdx += ActiveWords;
3960 if (!isSingleNumber) {
3962 if (ValueBitWidth > 64)
3963 ActiveWords = Record[CurIdx++];
3964 APInt High = readWideAPInt(
3965 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3966 CurIdx += ActiveWords;
3968 // FIXME: It is not clear whether values in the range should be
3969 // compared as signed or unsigned values. The partially
3970 // implemented changes that used this format in the past used
3971 // unsigned comparisons.
3972 for ( ; Low.ule(High); ++Low)
3973 CaseVals.push_back(ConstantInt::get(Context, Low));
3975 CaseVals.push_back(ConstantInt::get(Context, Low));
3977 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3978 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3979 cve = CaseVals.end(); cvi != cve; ++cvi)
3980 SI->addCase(*cvi, DestBB);
3986 // Old SwitchInst format without case ranges.
3988 if (Record.size() < 3 || (Record.size() & 1) == 0)
3989 return error("Invalid record");
3990 Type *OpTy = getTypeByID(Record[0]);
3991 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3992 BasicBlock *Default = getBasicBlock(Record[2]);
3993 if (!OpTy || !Cond || !Default)
3994 return error("Invalid record");
3995 unsigned NumCases = (Record.size()-3)/2;
3996 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3997 InstructionList.push_back(SI);
3998 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3999 ConstantInt *CaseVal =
4000 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4001 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4002 if (!CaseVal || !DestBB) {
4004 return error("Invalid record");
4006 SI->addCase(CaseVal, DestBB);
4011 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4012 if (Record.size() < 2)
4013 return error("Invalid record");
4014 Type *OpTy = getTypeByID(Record[0]);
4015 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4016 if (!OpTy || !Address)
4017 return error("Invalid record");
4018 unsigned NumDests = Record.size()-2;
4019 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4020 InstructionList.push_back(IBI);
4021 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4022 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4023 IBI->addDestination(DestBB);
4026 return error("Invalid record");
4033 case bitc::FUNC_CODE_INST_INVOKE: {
4034 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4035 if (Record.size() < 4)
4036 return error("Invalid record");
4038 AttributeSet PAL = getAttributes(Record[OpNum++]);
4039 unsigned CCInfo = Record[OpNum++];
4040 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4041 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4043 FunctionType *FTy = nullptr;
4044 if (CCInfo >> 13 & 1 &&
4045 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4046 return error("Explicit invoke type is not a function type");
4049 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4050 return error("Invalid record");
4052 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4054 return error("Callee is not a pointer");
4056 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4058 return error("Callee is not of pointer to function type");
4059 } else if (CalleeTy->getElementType() != FTy)
4060 return error("Explicit invoke type does not match pointee type of "
4062 if (Record.size() < FTy->getNumParams() + OpNum)
4063 return error("Insufficient operands to call");
4065 SmallVector<Value*, 16> Ops;
4066 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4067 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4068 FTy->getParamType(i)));
4070 return error("Invalid record");
4073 if (!FTy->isVarArg()) {
4074 if (Record.size() != OpNum)
4075 return error("Invalid record");
4077 // Read type/value pairs for varargs params.
4078 while (OpNum != Record.size()) {
4080 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4081 return error("Invalid record");
4086 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
4087 InstructionList.push_back(I);
4089 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
4090 cast<InvokeInst>(I)->setAttributes(PAL);
4093 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4095 Value *Val = nullptr;
4096 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4097 return error("Invalid record");
4098 I = ResumeInst::Create(Val);
4099 InstructionList.push_back(I);
4102 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4103 I = new UnreachableInst(Context);
4104 InstructionList.push_back(I);
4106 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4107 if (Record.size() < 1 || ((Record.size()-1)&1))
4108 return error("Invalid record");
4109 Type *Ty = getTypeByID(Record[0]);
4111 return error("Invalid record");
4113 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4114 InstructionList.push_back(PN);
4116 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4118 // With the new function encoding, it is possible that operands have
4119 // negative IDs (for forward references). Use a signed VBR
4120 // representation to keep the encoding small.
4122 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4124 V = getValue(Record, 1+i, NextValueNo, Ty);
4125 BasicBlock *BB = getBasicBlock(Record[2+i]);
4127 return error("Invalid record");
4128 PN->addIncoming(V, BB);
4134 case bitc::FUNC_CODE_INST_LANDINGPAD:
4135 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4136 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4138 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4139 if (Record.size() < 3)
4140 return error("Invalid record");
4142 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4143 if (Record.size() < 4)
4144 return error("Invalid record");
4146 Type *Ty = getTypeByID(Record[Idx++]);
4148 return error("Invalid record");
4149 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4150 Value *PersFn = nullptr;
4151 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4152 return error("Invalid record");
4154 if (!F->hasPersonalityFn())
4155 F->setPersonalityFn(cast<Constant>(PersFn));
4156 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4157 return error("Personality function mismatch");
4160 bool IsCleanup = !!Record[Idx++];
4161 unsigned NumClauses = Record[Idx++];
4162 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4163 LP->setCleanup(IsCleanup);
4164 for (unsigned J = 0; J != NumClauses; ++J) {
4165 LandingPadInst::ClauseType CT =
4166 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4169 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4171 return error("Invalid record");
4174 assert((CT != LandingPadInst::Catch ||
4175 !isa<ArrayType>(Val->getType())) &&
4176 "Catch clause has a invalid type!");
4177 assert((CT != LandingPadInst::Filter ||
4178 isa<ArrayType>(Val->getType())) &&
4179 "Filter clause has invalid type!");
4180 LP->addClause(cast<Constant>(Val));
4184 InstructionList.push_back(I);
4188 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4189 if (Record.size() != 4)
4190 return error("Invalid record");
4191 uint64_t AlignRecord = Record[3];
4192 const uint64_t InAllocaMask = uint64_t(1) << 5;
4193 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4194 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4195 bool InAlloca = AlignRecord & InAllocaMask;
4196 Type *Ty = getTypeByID(Record[0]);
4197 if ((AlignRecord & ExplicitTypeMask) == 0) {
4198 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4200 return error("Old-style alloca with a non-pointer type");
4201 Ty = PTy->getElementType();
4203 Type *OpTy = getTypeByID(Record[1]);
4204 Value *Size = getFnValueByID(Record[2], OpTy);
4206 if (std::error_code EC =
4207 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4211 return error("Invalid record");
4212 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4213 AI->setUsedWithInAlloca(InAlloca);
4215 InstructionList.push_back(I);
4218 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4221 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4222 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4223 return error("Invalid record");
4226 if (OpNum + 3 == Record.size())
4227 Ty = getTypeByID(Record[OpNum++]);
4228 if (std::error_code EC =
4229 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4232 Ty = cast<PointerType>(Op->getType())->getElementType();
4235 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4237 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4239 InstructionList.push_back(I);
4242 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4243 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4246 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4247 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4248 return error("Invalid record");
4251 if (OpNum + 5 == Record.size())
4252 Ty = getTypeByID(Record[OpNum++]);
4253 if (std::error_code EC =
4254 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4257 Ty = cast<PointerType>(Op->getType())->getElementType();
4259 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4260 if (Ordering == NotAtomic || Ordering == Release ||
4261 Ordering == AcquireRelease)
4262 return error("Invalid record");
4263 if (Ordering != NotAtomic && Record[OpNum] == 0)
4264 return error("Invalid record");
4265 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4268 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4270 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4272 InstructionList.push_back(I);
4275 case bitc::FUNC_CODE_INST_STORE:
4276 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4279 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4280 (BitCode == bitc::FUNC_CODE_INST_STORE
4281 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4282 : popValue(Record, OpNum, NextValueNo,
4283 cast<PointerType>(Ptr->getType())->getElementType(),
4285 OpNum + 2 != Record.size())
4286 return error("Invalid record");
4288 if (std::error_code EC = typeCheckLoadStoreInst(
4289 DiagnosticHandler, Val->getType(), Ptr->getType()))
4292 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4294 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4295 InstructionList.push_back(I);
4298 case bitc::FUNC_CODE_INST_STOREATOMIC:
4299 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4300 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4303 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4304 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4305 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4306 : popValue(Record, OpNum, NextValueNo,
4307 cast<PointerType>(Ptr->getType())->getElementType(),
4309 OpNum + 4 != Record.size())
4310 return error("Invalid record");
4312 if (std::error_code EC = typeCheckLoadStoreInst(
4313 DiagnosticHandler, Val->getType(), Ptr->getType()))
4315 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4316 if (Ordering == NotAtomic || Ordering == Acquire ||
4317 Ordering == AcquireRelease)
4318 return error("Invalid record");
4319 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4320 if (Ordering != NotAtomic && Record[OpNum] == 0)
4321 return error("Invalid record");
4324 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4326 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4327 InstructionList.push_back(I);
4330 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4331 case bitc::FUNC_CODE_INST_CMPXCHG: {
4332 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4333 // failureordering?, isweak?]
4335 Value *Ptr, *Cmp, *New;
4336 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4337 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4338 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4339 : popValue(Record, OpNum, NextValueNo,
4340 cast<PointerType>(Ptr->getType())->getElementType(),
4342 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4343 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4344 return error("Invalid record");
4345 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4346 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4347 return error("Invalid record");
4348 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4350 if (std::error_code EC = typeCheckLoadStoreInst(
4351 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4353 AtomicOrdering FailureOrdering;
4354 if (Record.size() < 7)
4356 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4358 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4360 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4362 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4364 if (Record.size() < 8) {
4365 // Before weak cmpxchgs existed, the instruction simply returned the
4366 // value loaded from memory, so bitcode files from that era will be
4367 // expecting the first component of a modern cmpxchg.
4368 CurBB->getInstList().push_back(I);
4369 I = ExtractValueInst::Create(I, 0);
4371 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4374 InstructionList.push_back(I);
4377 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4378 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4381 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4382 popValue(Record, OpNum, NextValueNo,
4383 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4384 OpNum+4 != Record.size())
4385 return error("Invalid record");
4386 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4387 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4388 Operation > AtomicRMWInst::LAST_BINOP)
4389 return error("Invalid record");
4390 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4391 if (Ordering == NotAtomic || Ordering == Unordered)
4392 return error("Invalid record");
4393 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4394 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4395 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4396 InstructionList.push_back(I);
4399 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4400 if (2 != Record.size())
4401 return error("Invalid record");
4402 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4403 if (Ordering == NotAtomic || Ordering == Unordered ||
4404 Ordering == Monotonic)
4405 return error("Invalid record");
4406 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4407 I = new FenceInst(Context, Ordering, SynchScope);
4408 InstructionList.push_back(I);
4411 case bitc::FUNC_CODE_INST_CALL: {
4412 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4413 if (Record.size() < 3)
4414 return error("Invalid record");
4417 AttributeSet PAL = getAttributes(Record[OpNum++]);
4418 unsigned CCInfo = Record[OpNum++];
4420 FunctionType *FTy = nullptr;
4421 if (CCInfo >> 15 & 1 &&
4422 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4423 return error("Explicit call type is not a function type");
4426 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4427 return error("Invalid record");
4429 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4431 return error("Callee is not a pointer type");
4433 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4435 return error("Callee is not of pointer to function type");
4436 } else if (OpTy->getElementType() != FTy)
4437 return error("Explicit call type does not match pointee type of "
4439 if (Record.size() < FTy->getNumParams() + OpNum)
4440 return error("Insufficient operands to call");
4442 SmallVector<Value*, 16> Args;
4443 // Read the fixed params.
4444 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4445 if (FTy->getParamType(i)->isLabelTy())
4446 Args.push_back(getBasicBlock(Record[OpNum]));
4448 Args.push_back(getValue(Record, OpNum, NextValueNo,
4449 FTy->getParamType(i)));
4451 return error("Invalid record");
4454 // Read type/value pairs for varargs params.
4455 if (!FTy->isVarArg()) {
4456 if (OpNum != Record.size())
4457 return error("Invalid record");
4459 while (OpNum != Record.size()) {
4461 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4462 return error("Invalid record");
4467 I = CallInst::Create(FTy, Callee, Args);
4468 InstructionList.push_back(I);
4469 cast<CallInst>(I)->setCallingConv(
4470 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4471 CallInst::TailCallKind TCK = CallInst::TCK_None;
4473 TCK = CallInst::TCK_Tail;
4474 if (CCInfo & (1 << 14))
4475 TCK = CallInst::TCK_MustTail;
4476 cast<CallInst>(I)->setTailCallKind(TCK);
4477 cast<CallInst>(I)->setAttributes(PAL);
4480 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4481 if (Record.size() < 3)
4482 return error("Invalid record");
4483 Type *OpTy = getTypeByID(Record[0]);
4484 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4485 Type *ResTy = getTypeByID(Record[2]);
4486 if (!OpTy || !Op || !ResTy)
4487 return error("Invalid record");
4488 I = new VAArgInst(Op, ResTy);
4489 InstructionList.push_back(I);
4494 // Add instruction to end of current BB. If there is no current BB, reject
4498 return error("Invalid instruction with no BB");
4500 CurBB->getInstList().push_back(I);
4502 // If this was a terminator instruction, move to the next block.
4503 if (isa<TerminatorInst>(I)) {
4505 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4508 // Non-void values get registered in the value table for future use.
4509 if (I && !I->getType()->isVoidTy())
4510 ValueList.assignValue(I, NextValueNo++);
4515 // Check the function list for unresolved values.
4516 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4517 if (!A->getParent()) {
4518 // We found at least one unresolved value. Nuke them all to avoid leaks.
4519 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4520 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4521 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4525 return error("Never resolved value found in function");
4529 // FIXME: Check for unresolved forward-declared metadata references
4530 // and clean up leaks.
4532 // Trim the value list down to the size it was before we parsed this function.
4533 ValueList.shrinkTo(ModuleValueListSize);
4534 MDValueList.shrinkTo(ModuleMDValueListSize);
4535 std::vector<BasicBlock*>().swap(FunctionBBs);
4536 return std::error_code();
4539 /// Find the function body in the bitcode stream
4540 std::error_code BitcodeReader::findFunctionInStream(
4542 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4543 while (DeferredFunctionInfoIterator->second == 0) {
4544 if (Stream.AtEndOfStream())
4545 return error("Could not find function in stream");
4546 // ParseModule will parse the next body in the stream and set its
4547 // position in the DeferredFunctionInfo map.
4548 if (std::error_code EC = parseModule(true))
4551 return std::error_code();
4554 //===----------------------------------------------------------------------===//
4555 // GVMaterializer implementation
4556 //===----------------------------------------------------------------------===//
4558 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4560 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4561 if (std::error_code EC = materializeMetadata())
4564 Function *F = dyn_cast<Function>(GV);
4565 // If it's not a function or is already material, ignore the request.
4566 if (!F || !F->isMaterializable())
4567 return std::error_code();
4569 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4570 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4571 // If its position is recorded as 0, its body is somewhere in the stream
4572 // but we haven't seen it yet.
4573 if (DFII->second == 0)
4574 if (std::error_code EC = findFunctionInStream(F, DFII))
4577 // Move the bit stream to the saved position of the deferred function body.
4578 Stream.JumpToBit(DFII->second);
4580 if (std::error_code EC = parseFunctionBody(F))
4582 F->setIsMaterializable(false);
4587 // Upgrade any old intrinsic calls in the function.
4588 for (auto &I : UpgradedIntrinsics) {
4589 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
4592 if (CallInst *CI = dyn_cast<CallInst>(U))
4593 UpgradeIntrinsicCall(CI, I.second);
4597 // Bring in any functions that this function forward-referenced via
4599 return materializeForwardReferencedFunctions();
4602 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4603 const Function *F = dyn_cast<Function>(GV);
4604 if (!F || F->isDeclaration())
4607 // Dematerializing F would leave dangling references that wouldn't be
4608 // reconnected on re-materialization.
4609 if (BlockAddressesTaken.count(F))
4612 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4615 void BitcodeReader::dematerialize(GlobalValue *GV) {
4616 Function *F = dyn_cast<Function>(GV);
4617 // If this function isn't dematerializable, this is a noop.
4618 if (!F || !isDematerializable(F))
4621 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4623 // Just forget the function body, we can remat it later.
4624 F->dropAllReferences();
4625 F->setIsMaterializable(true);
4628 std::error_code BitcodeReader::materializeModule(Module *M) {
4629 assert(M == TheModule &&
4630 "Can only Materialize the Module this BitcodeReader is attached to.");
4632 if (std::error_code EC = materializeMetadata())
4635 // Promise to materialize all forward references.
4636 WillMaterializeAllForwardRefs = true;
4638 // Iterate over the module, deserializing any functions that are still on
4640 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4642 if (std::error_code EC = materialize(F))
4645 // At this point, if there are any function bodies, the current bit is
4646 // pointing to the END_BLOCK record after them. Now make sure the rest
4647 // of the bits in the module have been read.
4651 // Check that all block address forward references got resolved (as we
4653 if (!BasicBlockFwdRefs.empty())
4654 return error("Never resolved function from blockaddress");
4656 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4657 // delete the old functions to clean up. We can't do this unless the entire
4658 // module is materialized because there could always be another function body
4659 // with calls to the old function.
4660 for (auto &I : UpgradedIntrinsics) {
4661 for (auto *U : I.first->users()) {
4662 if (CallInst *CI = dyn_cast<CallInst>(U))
4663 UpgradeIntrinsicCall(CI, I.second);
4665 if (!I.first->use_empty())
4666 I.first->replaceAllUsesWith(I.second);
4667 I.first->eraseFromParent();
4669 UpgradedIntrinsics.clear();
4671 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4672 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4674 UpgradeDebugInfo(*M);
4675 return std::error_code();
4678 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4679 return IdentifiedStructTypes;
4683 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
4685 return initLazyStream(std::move(Streamer));
4686 return initStreamFromBuffer();
4689 std::error_code BitcodeReader::initStreamFromBuffer() {
4690 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4691 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4693 if (Buffer->getBufferSize() & 3)
4694 return error("Invalid bitcode signature");
4696 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4697 // The magic number is 0x0B17C0DE stored in little endian.
4698 if (isBitcodeWrapper(BufPtr, BufEnd))
4699 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4700 return error("Invalid bitcode wrapper header");
4702 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4703 Stream.init(&*StreamFile);
4705 return std::error_code();
4709 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
4710 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4713 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
4714 StreamingMemoryObject &Bytes = *OwnedBytes;
4715 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4716 Stream.init(&*StreamFile);
4718 unsigned char buf[16];
4719 if (Bytes.readBytes(buf, 16, 0) != 16)
4720 return error("Invalid bitcode signature");
4722 if (!isBitcode(buf, buf + 16))
4723 return error("Invalid bitcode signature");
4725 if (isBitcodeWrapper(buf, buf + 4)) {
4726 const unsigned char *bitcodeStart = buf;
4727 const unsigned char *bitcodeEnd = buf + 16;
4728 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4729 Bytes.dropLeadingBytes(bitcodeStart - buf);
4730 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4732 return std::error_code();
4736 class BitcodeErrorCategoryType : public std::error_category {
4737 const char *name() const LLVM_NOEXCEPT override {
4738 return "llvm.bitcode";
4740 std::string message(int IE) const override {
4741 BitcodeError E = static_cast<BitcodeError>(IE);
4743 case BitcodeError::InvalidBitcodeSignature:
4744 return "Invalid bitcode signature";
4745 case BitcodeError::CorruptedBitcode:
4746 return "Corrupted bitcode";
4748 llvm_unreachable("Unknown error type!");
4753 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4755 const std::error_category &llvm::BitcodeErrorCategory() {
4756 return *ErrorCategory;
4759 //===----------------------------------------------------------------------===//
4760 // External interface
4761 //===----------------------------------------------------------------------===//
4763 static ErrorOr<std::unique_ptr<Module>>
4764 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
4765 BitcodeReader *R, LLVMContext &Context,
4766 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
4767 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4768 M->setMaterializer(R);
4770 auto cleanupOnError = [&](std::error_code EC) {
4771 R->releaseBuffer(); // Never take ownership on error.
4775 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4776 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
4777 ShouldLazyLoadMetadata))
4778 return cleanupOnError(EC);
4780 if (MaterializeAll) {
4781 // Read in the entire module, and destroy the BitcodeReader.
4782 if (std::error_code EC = M->materializeAllPermanently())
4783 return cleanupOnError(EC);
4785 // Resolve forward references from blockaddresses.
4786 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4787 return cleanupOnError(EC);
4789 return std::move(M);
4792 /// \brief Get a lazy one-at-time loading module from bitcode.
4794 /// This isn't always used in a lazy context. In particular, it's also used by
4795 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4796 /// in forward-referenced functions from block address references.
4798 /// \param[in] MaterializeAll Set to \c true if we should materialize
4800 static ErrorOr<std::unique_ptr<Module>>
4801 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4802 LLVMContext &Context, bool MaterializeAll,
4803 DiagnosticHandlerFunction DiagnosticHandler,
4804 bool ShouldLazyLoadMetadata = false) {
4806 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4808 ErrorOr<std::unique_ptr<Module>> Ret =
4809 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
4810 MaterializeAll, ShouldLazyLoadMetadata);
4814 Buffer.release(); // The BitcodeReader owns it now.
4818 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
4819 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
4820 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
4821 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4822 DiagnosticHandler, ShouldLazyLoadMetadata);
4825 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
4826 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
4827 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
4828 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4829 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
4831 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
4835 ErrorOr<std::unique_ptr<Module>>
4836 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4837 DiagnosticHandlerFunction DiagnosticHandler) {
4838 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4839 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
4841 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4842 // written. We must defer until the Module has been fully materialized.
4846 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4847 DiagnosticHandlerFunction DiagnosticHandler) {
4848 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4849 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4851 ErrorOr<std::string> Triple = R->parseTriple();
4852 if (Triple.getError())
4854 return Triple.get();