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 /// ResolveConstants - As we resolve forward-referenced constants, we add
48 /// information about them to this vector. This allows us to resolve them in
49 /// bulk instead of 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 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
92 /// resolves any forward references.
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 DataStreamer *Streamer;
140 uint64_t NextUnreadBit = 0;
141 bool SeenValueSymbolTable = false;
143 std::vector<Type*> TypeList;
144 BitcodeReaderValueList ValueList;
145 BitcodeReaderMDValueList MDValueList;
146 std::vector<Comdat *> ComdatList;
147 SmallVector<Instruction *, 64> InstructionList;
149 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
150 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
151 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
152 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
154 SmallVector<Instruction*, 64> InstsWithTBAATag;
156 /// MAttributes - The set of attributes by index. Index zero in the
157 /// file is for null, and is thus not represented here. As such all indices
159 std::vector<AttributeSet> MAttributes;
161 /// \brief The set of attribute groups.
162 std::map<unsigned, AttributeSet> MAttributeGroups;
164 /// FunctionBBs - While parsing a function body, this is a list of the basic
165 /// blocks for the function.
166 std::vector<BasicBlock*> FunctionBBs;
168 // When reading the module header, this list is populated with functions that
169 // have bodies later in the file.
170 std::vector<Function*> FunctionsWithBodies;
172 // When intrinsic functions are encountered which require upgrading they are
173 // stored here with their replacement function.
174 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
175 UpgradedIntrinsicMap UpgradedIntrinsics;
177 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
178 DenseMap<unsigned, unsigned> MDKindMap;
180 // Several operations happen after the module header has been read, but
181 // before function bodies are processed. This keeps track of whether
182 // we've done this yet.
183 bool SeenFirstFunctionBody = false;
185 /// DeferredFunctionInfo - When function bodies are initially scanned, this
186 /// map contains info about where to find deferred function body in the
188 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
190 /// When Metadata block is initially scanned when parsing the module, we may
191 /// choose to defer parsing of the metadata. This vector contains info about
192 /// which Metadata blocks are deferred.
193 std::vector<uint64_t> DeferredMetadataInfo;
195 /// These are basic blocks forward-referenced by block addresses. They are
196 /// inserted lazily into functions when they're loaded. The basic block ID is
197 /// its index into the vector.
198 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
199 std::deque<Function *> BasicBlockFwdRefQueue;
201 /// UseRelativeIDs - Indicates that we are using a new encoding for
202 /// instruction operands where most operands in the current
203 /// FUNCTION_BLOCK are encoded relative to the instruction number,
204 /// for a more compact encoding. Some instruction operands are not
205 /// relative to the instruction ID: basic block numbers, and types.
206 /// Once the old style function blocks have been phased out, we would
207 /// not need this flag.
208 bool UseRelativeIDs = false;
210 /// True if all functions will be materialized, negating the need to process
211 /// (e.g.) blockaddress forward references.
212 bool WillMaterializeAllForwardRefs = false;
214 /// Functions that have block addresses taken. This is usually empty.
215 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
217 /// True if any Metadata block has been materialized.
218 bool IsMetadataMaterialized = false;
220 bool StripDebugInfo = false;
223 std::error_code Error(BitcodeError E, const Twine &Message);
224 std::error_code Error(BitcodeError E);
225 std::error_code Error(const Twine &Message);
227 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
228 DiagnosticHandlerFunction DiagnosticHandler);
229 BitcodeReader(DataStreamer *Streamer, LLVMContext &Context,
230 DiagnosticHandlerFunction DiagnosticHandler);
231 ~BitcodeReader() override { FreeState(); }
233 std::error_code materializeForwardReferencedFunctions();
237 void releaseBuffer();
239 bool isDematerializable(const GlobalValue *GV) const override;
240 std::error_code materialize(GlobalValue *GV) override;
241 std::error_code materializeModule(Module *M) override;
242 std::vector<StructType *> getIdentifiedStructTypes() const override;
243 void dematerialize(GlobalValue *GV) override;
245 /// @brief Main interface to parsing a bitcode buffer.
246 /// @returns true if an error occurred.
247 std::error_code ParseBitcodeInto(Module *M,
248 bool ShouldLazyLoadMetadata = false);
250 /// @brief Cheap mechanism to just extract module triple
251 /// @returns true if an error occurred.
252 ErrorOr<std::string> parseTriple();
254 static uint64_t decodeSignRotatedValue(uint64_t V);
256 /// Materialize any deferred Metadata block.
257 std::error_code materializeMetadata() override;
259 void setStripDebugInfo() override;
262 std::vector<StructType *> IdentifiedStructTypes;
263 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
264 StructType *createIdentifiedStructType(LLVMContext &Context);
266 Type *getTypeByID(unsigned ID);
267 Value *getFnValueByID(unsigned ID, Type *Ty) {
268 if (Ty && Ty->isMetadataTy())
269 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
270 return ValueList.getValueFwdRef(ID, Ty);
272 Metadata *getFnMetadataByID(unsigned ID) {
273 return MDValueList.getValueFwdRef(ID);
275 BasicBlock *getBasicBlock(unsigned ID) const {
276 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
277 return FunctionBBs[ID];
279 AttributeSet getAttributes(unsigned i) const {
280 if (i-1 < MAttributes.size())
281 return MAttributes[i-1];
282 return AttributeSet();
285 /// getValueTypePair - Read a value/type pair out of the specified record from
286 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
287 /// Return true on failure.
288 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
289 unsigned InstNum, Value *&ResVal) {
290 if (Slot == Record.size()) return true;
291 unsigned ValNo = (unsigned)Record[Slot++];
292 // Adjust the ValNo, if it was encoded relative to the InstNum.
294 ValNo = InstNum - ValNo;
295 if (ValNo < InstNum) {
296 // If this is not a forward reference, just return the value we already
298 ResVal = getFnValueByID(ValNo, nullptr);
299 return ResVal == nullptr;
301 if (Slot == Record.size())
304 unsigned TypeNo = (unsigned)Record[Slot++];
305 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
306 return ResVal == nullptr;
309 /// popValue - Read a value out of the specified record from slot 'Slot'.
310 /// Increment Slot past the number of slots used by the value in the record.
311 /// Return true if there is an error.
312 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
313 unsigned InstNum, Type *Ty, Value *&ResVal) {
314 if (getValue(Record, Slot, InstNum, Ty, ResVal))
316 // All values currently take a single record slot.
321 /// getValue -- Like popValue, but does not increment the Slot number.
322 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
323 unsigned InstNum, Type *Ty, Value *&ResVal) {
324 ResVal = getValue(Record, Slot, InstNum, Ty);
325 return ResVal == nullptr;
328 /// getValue -- Version of getValue that returns ResVal directly,
329 /// or 0 if there is an error.
330 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
331 unsigned InstNum, Type *Ty) {
332 if (Slot == Record.size()) return nullptr;
333 unsigned ValNo = (unsigned)Record[Slot];
334 // Adjust the ValNo, if it was encoded relative to the InstNum.
336 ValNo = InstNum - ValNo;
337 return getFnValueByID(ValNo, Ty);
340 /// getValueSigned -- Like getValue, but decodes signed VBRs.
341 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
342 unsigned InstNum, Type *Ty) {
343 if (Slot == Record.size()) return nullptr;
344 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
345 // Adjust the ValNo, if it was encoded relative to the InstNum.
347 ValNo = InstNum - ValNo;
348 return getFnValueByID(ValNo, Ty);
351 /// Converts alignment exponent (i.e. power of two (or zero)) to the
352 /// corresponding alignment to use. If alignment is too large, returns
353 /// a corresponding error code.
354 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
355 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
356 std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
357 std::error_code ParseAttributeBlock();
358 std::error_code ParseAttributeGroupBlock();
359 std::error_code ParseTypeTable();
360 std::error_code ParseTypeTableBody();
362 std::error_code ParseValueSymbolTable();
363 std::error_code ParseConstants();
364 std::error_code RememberAndSkipFunctionBody();
365 /// Save the positions of the Metadata blocks and skip parsing the blocks.
366 std::error_code rememberAndSkipMetadata();
367 std::error_code ParseFunctionBody(Function *F);
368 std::error_code GlobalCleanup();
369 std::error_code ResolveGlobalAndAliasInits();
370 std::error_code ParseMetadata();
371 std::error_code ParseMetadataAttachment(Function &F);
372 ErrorOr<std::string> parseModuleTriple();
373 std::error_code ParseUseLists();
374 std::error_code InitStream();
375 std::error_code InitStreamFromBuffer();
376 std::error_code InitLazyStream();
377 std::error_code FindFunctionInStream(
379 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
383 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
384 DiagnosticSeverity Severity,
386 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
388 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
390 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
391 std::error_code EC, const Twine &Message) {
392 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
393 DiagnosticHandler(DI);
397 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
398 std::error_code EC) {
399 return Error(DiagnosticHandler, EC, EC.message());
402 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
403 const Twine &Message) {
404 return Error(DiagnosticHandler,
405 make_error_code(BitcodeError::CorruptedBitcode), Message);
408 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
409 return ::Error(DiagnosticHandler, make_error_code(E), Message);
412 std::error_code BitcodeReader::Error(const Twine &Message) {
413 return ::Error(DiagnosticHandler,
414 make_error_code(BitcodeError::CorruptedBitcode), Message);
417 std::error_code BitcodeReader::Error(BitcodeError E) {
418 return ::Error(DiagnosticHandler, make_error_code(E));
421 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
425 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
428 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
429 DiagnosticHandlerFunction DiagnosticHandler)
431 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
432 Buffer(Buffer), Streamer(nullptr), ValueList(Context),
433 MDValueList(Context) {}
435 BitcodeReader::BitcodeReader(DataStreamer *Streamer, LLVMContext &Context,
436 DiagnosticHandlerFunction DiagnosticHandler)
438 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
439 Buffer(nullptr), Streamer(Streamer), ValueList(Context),
440 MDValueList(Context) {}
442 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
443 if (WillMaterializeAllForwardRefs)
444 return std::error_code();
446 // Prevent recursion.
447 WillMaterializeAllForwardRefs = true;
449 while (!BasicBlockFwdRefQueue.empty()) {
450 Function *F = BasicBlockFwdRefQueue.front();
451 BasicBlockFwdRefQueue.pop_front();
452 assert(F && "Expected valid function");
453 if (!BasicBlockFwdRefs.count(F))
454 // Already materialized.
457 // Check for a function that isn't materializable to prevent an infinite
458 // loop. When parsing a blockaddress stored in a global variable, there
459 // isn't a trivial way to check if a function will have a body without a
460 // linear search through FunctionsWithBodies, so just check it here.
461 if (!F->isMaterializable())
462 return Error("Never resolved function from blockaddress");
464 // Try to materialize F.
465 if (std::error_code EC = materialize(F))
468 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
471 WillMaterializeAllForwardRefs = false;
472 return std::error_code();
475 void BitcodeReader::FreeState() {
477 std::vector<Type*>().swap(TypeList);
480 std::vector<Comdat *>().swap(ComdatList);
482 std::vector<AttributeSet>().swap(MAttributes);
483 std::vector<BasicBlock*>().swap(FunctionBBs);
484 std::vector<Function*>().swap(FunctionsWithBodies);
485 DeferredFunctionInfo.clear();
486 DeferredMetadataInfo.clear();
489 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
490 BasicBlockFwdRefQueue.clear();
493 //===----------------------------------------------------------------------===//
494 // Helper functions to implement forward reference resolution, etc.
495 //===----------------------------------------------------------------------===//
497 /// ConvertToString - Convert a string from a record into an std::string, return
499 template<typename StrTy>
500 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
502 if (Idx > Record.size())
505 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
506 Result += (char)Record[i];
510 static bool hasImplicitComdat(size_t Val) {
514 case 1: // Old WeakAnyLinkage
515 case 4: // Old LinkOnceAnyLinkage
516 case 10: // Old WeakODRLinkage
517 case 11: // Old LinkOnceODRLinkage
522 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
524 default: // Map unknown/new linkages to external
526 return GlobalValue::ExternalLinkage;
528 return GlobalValue::AppendingLinkage;
530 return GlobalValue::InternalLinkage;
532 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
534 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
536 return GlobalValue::ExternalWeakLinkage;
538 return GlobalValue::CommonLinkage;
540 return GlobalValue::PrivateLinkage;
542 return GlobalValue::AvailableExternallyLinkage;
544 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
546 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
548 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
549 case 1: // Old value with implicit comdat.
551 return GlobalValue::WeakAnyLinkage;
552 case 10: // Old value with implicit comdat.
554 return GlobalValue::WeakODRLinkage;
555 case 4: // Old value with implicit comdat.
557 return GlobalValue::LinkOnceAnyLinkage;
558 case 11: // Old value with implicit comdat.
560 return GlobalValue::LinkOnceODRLinkage;
564 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
566 default: // Map unknown visibilities to default.
567 case 0: return GlobalValue::DefaultVisibility;
568 case 1: return GlobalValue::HiddenVisibility;
569 case 2: return GlobalValue::ProtectedVisibility;
573 static GlobalValue::DLLStorageClassTypes
574 GetDecodedDLLStorageClass(unsigned Val) {
576 default: // Map unknown values to default.
577 case 0: return GlobalValue::DefaultStorageClass;
578 case 1: return GlobalValue::DLLImportStorageClass;
579 case 2: return GlobalValue::DLLExportStorageClass;
583 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
585 case 0: return GlobalVariable::NotThreadLocal;
586 default: // Map unknown non-zero value to general dynamic.
587 case 1: return GlobalVariable::GeneralDynamicTLSModel;
588 case 2: return GlobalVariable::LocalDynamicTLSModel;
589 case 3: return GlobalVariable::InitialExecTLSModel;
590 case 4: return GlobalVariable::LocalExecTLSModel;
594 static int GetDecodedCastOpcode(unsigned Val) {
597 case bitc::CAST_TRUNC : return Instruction::Trunc;
598 case bitc::CAST_ZEXT : return Instruction::ZExt;
599 case bitc::CAST_SEXT : return Instruction::SExt;
600 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
601 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
602 case bitc::CAST_UITOFP : return Instruction::UIToFP;
603 case bitc::CAST_SITOFP : return Instruction::SIToFP;
604 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
605 case bitc::CAST_FPEXT : return Instruction::FPExt;
606 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
607 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
608 case bitc::CAST_BITCAST : return Instruction::BitCast;
609 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
613 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
614 bool IsFP = Ty->isFPOrFPVectorTy();
615 // BinOps are only valid for int/fp or vector of int/fp types
616 if (!IsFP && !Ty->isIntOrIntVectorTy())
622 case bitc::BINOP_ADD:
623 return IsFP ? Instruction::FAdd : Instruction::Add;
624 case bitc::BINOP_SUB:
625 return IsFP ? Instruction::FSub : Instruction::Sub;
626 case bitc::BINOP_MUL:
627 return IsFP ? Instruction::FMul : Instruction::Mul;
628 case bitc::BINOP_UDIV:
629 return IsFP ? -1 : Instruction::UDiv;
630 case bitc::BINOP_SDIV:
631 return IsFP ? Instruction::FDiv : Instruction::SDiv;
632 case bitc::BINOP_UREM:
633 return IsFP ? -1 : Instruction::URem;
634 case bitc::BINOP_SREM:
635 return IsFP ? Instruction::FRem : Instruction::SRem;
636 case bitc::BINOP_SHL:
637 return IsFP ? -1 : Instruction::Shl;
638 case bitc::BINOP_LSHR:
639 return IsFP ? -1 : Instruction::LShr;
640 case bitc::BINOP_ASHR:
641 return IsFP ? -1 : Instruction::AShr;
642 case bitc::BINOP_AND:
643 return IsFP ? -1 : Instruction::And;
645 return IsFP ? -1 : Instruction::Or;
646 case bitc::BINOP_XOR:
647 return IsFP ? -1 : Instruction::Xor;
651 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
653 default: return AtomicRMWInst::BAD_BINOP;
654 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
655 case bitc::RMW_ADD: return AtomicRMWInst::Add;
656 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
657 case bitc::RMW_AND: return AtomicRMWInst::And;
658 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
659 case bitc::RMW_OR: return AtomicRMWInst::Or;
660 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
661 case bitc::RMW_MAX: return AtomicRMWInst::Max;
662 case bitc::RMW_MIN: return AtomicRMWInst::Min;
663 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
664 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
668 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
670 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
671 case bitc::ORDERING_UNORDERED: return Unordered;
672 case bitc::ORDERING_MONOTONIC: return Monotonic;
673 case bitc::ORDERING_ACQUIRE: return Acquire;
674 case bitc::ORDERING_RELEASE: return Release;
675 case bitc::ORDERING_ACQREL: return AcquireRelease;
676 default: // Map unknown orderings to sequentially-consistent.
677 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
681 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
683 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
684 default: // Map unknown scopes to cross-thread.
685 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
689 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
691 default: // Map unknown selection kinds to any.
692 case bitc::COMDAT_SELECTION_KIND_ANY:
694 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
695 return Comdat::ExactMatch;
696 case bitc::COMDAT_SELECTION_KIND_LARGEST:
697 return Comdat::Largest;
698 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
699 return Comdat::NoDuplicates;
700 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
701 return Comdat::SameSize;
705 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
707 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
708 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
714 /// @brief A class for maintaining the slot number definition
715 /// as a placeholder for the actual definition for forward constants defs.
716 class ConstantPlaceHolder : public ConstantExpr {
717 void operator=(const ConstantPlaceHolder &) = delete;
719 // allocate space for exactly one operand
720 void *operator new(size_t s) {
721 return User::operator new(s, 1);
723 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
724 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
725 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
728 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
729 static bool classof(const Value *V) {
730 return isa<ConstantExpr>(V) &&
731 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
735 /// Provide fast operand accessors
736 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
740 // FIXME: can we inherit this from ConstantExpr?
742 struct OperandTraits<ConstantPlaceHolder> :
743 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
745 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
749 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
758 WeakVH &OldV = ValuePtrs[Idx];
764 // Handle constants and non-constants (e.g. instrs) differently for
766 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
767 ResolveConstants.push_back(std::make_pair(PHC, Idx));
770 // If there was a forward reference to this value, replace it.
771 Value *PrevVal = OldV;
772 OldV->replaceAllUsesWith(V);
778 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
783 if (Value *V = ValuePtrs[Idx]) {
784 if (Ty != V->getType())
785 report_fatal_error("Type mismatch in constant table!");
786 return cast<Constant>(V);
789 // Create and return a placeholder, which will later be RAUW'd.
790 Constant *C = new ConstantPlaceHolder(Ty, Context);
795 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
796 // Bail out for a clearly invalid value. This would make us call resize(0)
803 if (Value *V = ValuePtrs[Idx]) {
804 // If the types don't match, it's invalid.
805 if (Ty && Ty != V->getType())
810 // No type specified, must be invalid reference.
811 if (!Ty) return nullptr;
813 // Create and return a placeholder, which will later be RAUW'd.
814 Value *V = new Argument(Ty);
819 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
820 /// resolves any forward references. The idea behind this is that we sometimes
821 /// get constants (such as large arrays) which reference *many* forward ref
822 /// constants. Replacing each of these causes a lot of thrashing when
823 /// building/reuniquing the constant. Instead of doing this, we look at all the
824 /// uses and rewrite all the place holders at once for any constant that uses
826 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
827 // Sort the values by-pointer so that they are efficient to look up with a
829 std::sort(ResolveConstants.begin(), ResolveConstants.end());
831 SmallVector<Constant*, 64> NewOps;
833 while (!ResolveConstants.empty()) {
834 Value *RealVal = operator[](ResolveConstants.back().second);
835 Constant *Placeholder = ResolveConstants.back().first;
836 ResolveConstants.pop_back();
838 // Loop over all users of the placeholder, updating them to reference the
839 // new value. If they reference more than one placeholder, update them all
841 while (!Placeholder->use_empty()) {
842 auto UI = Placeholder->user_begin();
845 // If the using object isn't uniqued, just update the operands. This
846 // handles instructions and initializers for global variables.
847 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
848 UI.getUse().set(RealVal);
852 // Otherwise, we have a constant that uses the placeholder. Replace that
853 // constant with a new constant that has *all* placeholder uses updated.
854 Constant *UserC = cast<Constant>(U);
855 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
858 if (!isa<ConstantPlaceHolder>(*I)) {
859 // Not a placeholder reference.
861 } else if (*I == Placeholder) {
862 // Common case is that it just references this one placeholder.
865 // Otherwise, look up the placeholder in ResolveConstants.
866 ResolveConstantsTy::iterator It =
867 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
868 std::pair<Constant*, unsigned>(cast<Constant>(*I),
870 assert(It != ResolveConstants.end() && It->first == *I);
871 NewOp = operator[](It->second);
874 NewOps.push_back(cast<Constant>(NewOp));
877 // Make the new constant.
879 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
880 NewC = ConstantArray::get(UserCA->getType(), NewOps);
881 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
882 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
883 } else if (isa<ConstantVector>(UserC)) {
884 NewC = ConstantVector::get(NewOps);
886 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
887 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
890 UserC->replaceAllUsesWith(NewC);
891 UserC->destroyConstant();
895 // Update all ValueHandles, they should be the only users at this point.
896 Placeholder->replaceAllUsesWith(RealVal);
901 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
910 TrackingMDRef &OldMD = MDValuePtrs[Idx];
916 // If there was a forward reference to this value, replace it.
917 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
918 PrevMD->replaceAllUsesWith(MD);
922 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
926 if (Metadata *MD = MDValuePtrs[Idx])
929 // Track forward refs to be resolved later.
931 MinFwdRef = std::min(MinFwdRef, Idx);
932 MaxFwdRef = std::max(MaxFwdRef, Idx);
935 MinFwdRef = MaxFwdRef = Idx;
939 // Create and return a placeholder, which will later be RAUW'd.
940 Metadata *MD = MDNode::getTemporary(Context, None).release();
941 MDValuePtrs[Idx].reset(MD);
945 void BitcodeReaderMDValueList::tryToResolveCycles() {
951 // Still forward references... can't resolve cycles.
954 // Resolve any cycles.
955 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
956 auto &MD = MDValuePtrs[I];
957 auto *N = dyn_cast_or_null<MDNode>(MD);
961 assert(!N->isTemporary() && "Unexpected forward reference");
965 // Make sure we return early again until there's another forward ref.
969 Type *BitcodeReader::getTypeByID(unsigned ID) {
970 // The type table size is always specified correctly.
971 if (ID >= TypeList.size())
974 if (Type *Ty = TypeList[ID])
977 // If we have a forward reference, the only possible case is when it is to a
978 // named struct. Just create a placeholder for now.
979 return TypeList[ID] = createIdentifiedStructType(Context);
982 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
984 auto *Ret = StructType::create(Context, Name);
985 IdentifiedStructTypes.push_back(Ret);
989 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
990 auto *Ret = StructType::create(Context);
991 IdentifiedStructTypes.push_back(Ret);
996 //===----------------------------------------------------------------------===//
997 // Functions for parsing blocks from the bitcode file
998 //===----------------------------------------------------------------------===//
1001 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1002 /// been decoded from the given integer. This function must stay in sync with
1003 /// 'encodeLLVMAttributesForBitcode'.
1004 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1005 uint64_t EncodedAttrs) {
1006 // FIXME: Remove in 4.0.
1008 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1009 // the bits above 31 down by 11 bits.
1010 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1011 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1012 "Alignment must be a power of two.");
1015 B.addAlignmentAttr(Alignment);
1016 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1017 (EncodedAttrs & 0xffff));
1020 std::error_code BitcodeReader::ParseAttributeBlock() {
1021 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1022 return Error("Invalid record");
1024 if (!MAttributes.empty())
1025 return Error("Invalid multiple blocks");
1027 SmallVector<uint64_t, 64> Record;
1029 SmallVector<AttributeSet, 8> Attrs;
1031 // Read all the records.
1033 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1035 switch (Entry.Kind) {
1036 case BitstreamEntry::SubBlock: // Handled for us already.
1037 case BitstreamEntry::Error:
1038 return Error("Malformed block");
1039 case BitstreamEntry::EndBlock:
1040 return std::error_code();
1041 case BitstreamEntry::Record:
1042 // The interesting case.
1048 switch (Stream.readRecord(Entry.ID, Record)) {
1049 default: // Default behavior: ignore.
1051 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1052 // FIXME: Remove in 4.0.
1053 if (Record.size() & 1)
1054 return Error("Invalid record");
1056 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1058 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1059 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1062 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1066 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1067 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1068 Attrs.push_back(MAttributeGroups[Record[i]]);
1070 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1078 // Returns Attribute::None on unrecognized codes.
1079 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1082 return Attribute::None;
1083 case bitc::ATTR_KIND_ALIGNMENT:
1084 return Attribute::Alignment;
1085 case bitc::ATTR_KIND_ALWAYS_INLINE:
1086 return Attribute::AlwaysInline;
1087 case bitc::ATTR_KIND_BUILTIN:
1088 return Attribute::Builtin;
1089 case bitc::ATTR_KIND_BY_VAL:
1090 return Attribute::ByVal;
1091 case bitc::ATTR_KIND_IN_ALLOCA:
1092 return Attribute::InAlloca;
1093 case bitc::ATTR_KIND_COLD:
1094 return Attribute::Cold;
1095 case bitc::ATTR_KIND_CONVERGENT:
1096 return Attribute::Convergent;
1097 case bitc::ATTR_KIND_INLINE_HINT:
1098 return Attribute::InlineHint;
1099 case bitc::ATTR_KIND_IN_REG:
1100 return Attribute::InReg;
1101 case bitc::ATTR_KIND_JUMP_TABLE:
1102 return Attribute::JumpTable;
1103 case bitc::ATTR_KIND_MIN_SIZE:
1104 return Attribute::MinSize;
1105 case bitc::ATTR_KIND_NAKED:
1106 return Attribute::Naked;
1107 case bitc::ATTR_KIND_NEST:
1108 return Attribute::Nest;
1109 case bitc::ATTR_KIND_NO_ALIAS:
1110 return Attribute::NoAlias;
1111 case bitc::ATTR_KIND_NO_BUILTIN:
1112 return Attribute::NoBuiltin;
1113 case bitc::ATTR_KIND_NO_CAPTURE:
1114 return Attribute::NoCapture;
1115 case bitc::ATTR_KIND_NO_DUPLICATE:
1116 return Attribute::NoDuplicate;
1117 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1118 return Attribute::NoImplicitFloat;
1119 case bitc::ATTR_KIND_NO_INLINE:
1120 return Attribute::NoInline;
1121 case bitc::ATTR_KIND_NON_LAZY_BIND:
1122 return Attribute::NonLazyBind;
1123 case bitc::ATTR_KIND_NON_NULL:
1124 return Attribute::NonNull;
1125 case bitc::ATTR_KIND_DEREFERENCEABLE:
1126 return Attribute::Dereferenceable;
1127 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1128 return Attribute::DereferenceableOrNull;
1129 case bitc::ATTR_KIND_NO_RED_ZONE:
1130 return Attribute::NoRedZone;
1131 case bitc::ATTR_KIND_NO_RETURN:
1132 return Attribute::NoReturn;
1133 case bitc::ATTR_KIND_NO_UNWIND:
1134 return Attribute::NoUnwind;
1135 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1136 return Attribute::OptimizeForSize;
1137 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1138 return Attribute::OptimizeNone;
1139 case bitc::ATTR_KIND_READ_NONE:
1140 return Attribute::ReadNone;
1141 case bitc::ATTR_KIND_READ_ONLY:
1142 return Attribute::ReadOnly;
1143 case bitc::ATTR_KIND_RETURNED:
1144 return Attribute::Returned;
1145 case bitc::ATTR_KIND_RETURNS_TWICE:
1146 return Attribute::ReturnsTwice;
1147 case bitc::ATTR_KIND_S_EXT:
1148 return Attribute::SExt;
1149 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1150 return Attribute::StackAlignment;
1151 case bitc::ATTR_KIND_STACK_PROTECT:
1152 return Attribute::StackProtect;
1153 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1154 return Attribute::StackProtectReq;
1155 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1156 return Attribute::StackProtectStrong;
1157 case bitc::ATTR_KIND_STRUCT_RET:
1158 return Attribute::StructRet;
1159 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1160 return Attribute::SanitizeAddress;
1161 case bitc::ATTR_KIND_SANITIZE_THREAD:
1162 return Attribute::SanitizeThread;
1163 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1164 return Attribute::SanitizeMemory;
1165 case bitc::ATTR_KIND_UW_TABLE:
1166 return Attribute::UWTable;
1167 case bitc::ATTR_KIND_Z_EXT:
1168 return Attribute::ZExt;
1172 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1173 unsigned &Alignment) {
1174 // Note: Alignment in bitcode files is incremented by 1, so that zero
1175 // can be used for default alignment.
1176 if (Exponent > Value::MaxAlignmentExponent + 1)
1177 return Error("Invalid alignment value");
1178 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1179 return std::error_code();
1182 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1183 Attribute::AttrKind *Kind) {
1184 *Kind = GetAttrFromCode(Code);
1185 if (*Kind == Attribute::None)
1186 return Error(BitcodeError::CorruptedBitcode,
1187 "Unknown attribute kind (" + Twine(Code) + ")");
1188 return std::error_code();
1191 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
1192 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1193 return Error("Invalid record");
1195 if (!MAttributeGroups.empty())
1196 return Error("Invalid multiple blocks");
1198 SmallVector<uint64_t, 64> Record;
1200 // Read all the records.
1202 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1204 switch (Entry.Kind) {
1205 case BitstreamEntry::SubBlock: // Handled for us already.
1206 case BitstreamEntry::Error:
1207 return Error("Malformed block");
1208 case BitstreamEntry::EndBlock:
1209 return std::error_code();
1210 case BitstreamEntry::Record:
1211 // The interesting case.
1217 switch (Stream.readRecord(Entry.ID, Record)) {
1218 default: // Default behavior: ignore.
1220 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1221 if (Record.size() < 3)
1222 return Error("Invalid record");
1224 uint64_t GrpID = Record[0];
1225 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1228 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1229 if (Record[i] == 0) { // Enum attribute
1230 Attribute::AttrKind Kind;
1231 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1234 B.addAttribute(Kind);
1235 } else if (Record[i] == 1) { // Integer attribute
1236 Attribute::AttrKind Kind;
1237 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1239 if (Kind == Attribute::Alignment)
1240 B.addAlignmentAttr(Record[++i]);
1241 else if (Kind == Attribute::StackAlignment)
1242 B.addStackAlignmentAttr(Record[++i]);
1243 else if (Kind == Attribute::Dereferenceable)
1244 B.addDereferenceableAttr(Record[++i]);
1245 else if (Kind == Attribute::DereferenceableOrNull)
1246 B.addDereferenceableOrNullAttr(Record[++i]);
1247 } else { // String attribute
1248 assert((Record[i] == 3 || Record[i] == 4) &&
1249 "Invalid attribute group entry");
1250 bool HasValue = (Record[i++] == 4);
1251 SmallString<64> KindStr;
1252 SmallString<64> ValStr;
1254 while (Record[i] != 0 && i != e)
1255 KindStr += Record[i++];
1256 assert(Record[i] == 0 && "Kind string not null terminated");
1259 // Has a value associated with it.
1260 ++i; // Skip the '0' that terminates the "kind" string.
1261 while (Record[i] != 0 && i != e)
1262 ValStr += Record[i++];
1263 assert(Record[i] == 0 && "Value string not null terminated");
1266 B.addAttribute(KindStr.str(), ValStr.str());
1270 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1277 std::error_code BitcodeReader::ParseTypeTable() {
1278 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1279 return Error("Invalid record");
1281 return ParseTypeTableBody();
1284 std::error_code BitcodeReader::ParseTypeTableBody() {
1285 if (!TypeList.empty())
1286 return Error("Invalid multiple blocks");
1288 SmallVector<uint64_t, 64> Record;
1289 unsigned NumRecords = 0;
1291 SmallString<64> TypeName;
1293 // Read all the records for this type table.
1295 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1297 switch (Entry.Kind) {
1298 case BitstreamEntry::SubBlock: // Handled for us already.
1299 case BitstreamEntry::Error:
1300 return Error("Malformed block");
1301 case BitstreamEntry::EndBlock:
1302 if (NumRecords != TypeList.size())
1303 return Error("Malformed block");
1304 return std::error_code();
1305 case BitstreamEntry::Record:
1306 // The interesting case.
1312 Type *ResultTy = nullptr;
1313 switch (Stream.readRecord(Entry.ID, Record)) {
1315 return Error("Invalid value");
1316 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1317 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1318 // type list. This allows us to reserve space.
1319 if (Record.size() < 1)
1320 return Error("Invalid record");
1321 TypeList.resize(Record[0]);
1323 case bitc::TYPE_CODE_VOID: // VOID
1324 ResultTy = Type::getVoidTy(Context);
1326 case bitc::TYPE_CODE_HALF: // HALF
1327 ResultTy = Type::getHalfTy(Context);
1329 case bitc::TYPE_CODE_FLOAT: // FLOAT
1330 ResultTy = Type::getFloatTy(Context);
1332 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1333 ResultTy = Type::getDoubleTy(Context);
1335 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1336 ResultTy = Type::getX86_FP80Ty(Context);
1338 case bitc::TYPE_CODE_FP128: // FP128
1339 ResultTy = Type::getFP128Ty(Context);
1341 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1342 ResultTy = Type::getPPC_FP128Ty(Context);
1344 case bitc::TYPE_CODE_LABEL: // LABEL
1345 ResultTy = Type::getLabelTy(Context);
1347 case bitc::TYPE_CODE_METADATA: // METADATA
1348 ResultTy = Type::getMetadataTy(Context);
1350 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1351 ResultTy = Type::getX86_MMXTy(Context);
1353 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1354 if (Record.size() < 1)
1355 return Error("Invalid record");
1357 uint64_t NumBits = Record[0];
1358 if (NumBits < IntegerType::MIN_INT_BITS ||
1359 NumBits > IntegerType::MAX_INT_BITS)
1360 return Error("Bitwidth for integer type out of range");
1361 ResultTy = IntegerType::get(Context, NumBits);
1364 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1365 // [pointee type, address space]
1366 if (Record.size() < 1)
1367 return Error("Invalid record");
1368 unsigned AddressSpace = 0;
1369 if (Record.size() == 2)
1370 AddressSpace = Record[1];
1371 ResultTy = getTypeByID(Record[0]);
1373 !PointerType::isValidElementType(ResultTy))
1374 return Error("Invalid type");
1375 ResultTy = PointerType::get(ResultTy, AddressSpace);
1378 case bitc::TYPE_CODE_FUNCTION_OLD: {
1379 // FIXME: attrid is dead, remove it in LLVM 4.0
1380 // FUNCTION: [vararg, attrid, retty, paramty x N]
1381 if (Record.size() < 3)
1382 return Error("Invalid record");
1383 SmallVector<Type*, 8> ArgTys;
1384 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1385 if (Type *T = getTypeByID(Record[i]))
1386 ArgTys.push_back(T);
1391 ResultTy = getTypeByID(Record[2]);
1392 if (!ResultTy || ArgTys.size() < Record.size()-3)
1393 return Error("Invalid type");
1395 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1398 case bitc::TYPE_CODE_FUNCTION: {
1399 // FUNCTION: [vararg, retty, paramty x N]
1400 if (Record.size() < 2)
1401 return Error("Invalid record");
1402 SmallVector<Type*, 8> ArgTys;
1403 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1404 if (Type *T = getTypeByID(Record[i])) {
1405 if (!FunctionType::isValidArgumentType(T))
1406 return Error("Invalid function argument type");
1407 ArgTys.push_back(T);
1413 ResultTy = getTypeByID(Record[1]);
1414 if (!ResultTy || ArgTys.size() < Record.size()-2)
1415 return Error("Invalid type");
1417 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1420 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1421 if (Record.size() < 1)
1422 return Error("Invalid record");
1423 SmallVector<Type*, 8> EltTys;
1424 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1425 if (Type *T = getTypeByID(Record[i]))
1426 EltTys.push_back(T);
1430 if (EltTys.size() != Record.size()-1)
1431 return Error("Invalid type");
1432 ResultTy = StructType::get(Context, EltTys, Record[0]);
1435 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1436 if (ConvertToString(Record, 0, TypeName))
1437 return Error("Invalid record");
1440 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1441 if (Record.size() < 1)
1442 return Error("Invalid record");
1444 if (NumRecords >= TypeList.size())
1445 return Error("Invalid TYPE table");
1447 // Check to see if this was forward referenced, if so fill in the temp.
1448 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1450 Res->setName(TypeName);
1451 TypeList[NumRecords] = nullptr;
1452 } else // Otherwise, create a new struct.
1453 Res = createIdentifiedStructType(Context, TypeName);
1456 SmallVector<Type*, 8> EltTys;
1457 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1458 if (Type *T = getTypeByID(Record[i]))
1459 EltTys.push_back(T);
1463 if (EltTys.size() != Record.size()-1)
1464 return Error("Invalid record");
1465 Res->setBody(EltTys, Record[0]);
1469 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1470 if (Record.size() != 1)
1471 return Error("Invalid record");
1473 if (NumRecords >= TypeList.size())
1474 return Error("Invalid TYPE table");
1476 // Check to see if this was forward referenced, if so fill in the temp.
1477 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1479 Res->setName(TypeName);
1480 TypeList[NumRecords] = nullptr;
1481 } else // Otherwise, create a new struct with no body.
1482 Res = createIdentifiedStructType(Context, TypeName);
1487 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1488 if (Record.size() < 2)
1489 return Error("Invalid record");
1490 ResultTy = getTypeByID(Record[1]);
1491 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1492 return Error("Invalid type");
1493 ResultTy = ArrayType::get(ResultTy, Record[0]);
1495 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1496 if (Record.size() < 2)
1497 return Error("Invalid record");
1499 return Error("Invalid vector length");
1500 ResultTy = getTypeByID(Record[1]);
1501 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1502 return Error("Invalid type");
1503 ResultTy = VectorType::get(ResultTy, Record[0]);
1507 if (NumRecords >= TypeList.size())
1508 return Error("Invalid TYPE table");
1509 if (TypeList[NumRecords])
1511 "Invalid TYPE table: Only named structs can be forward referenced");
1512 assert(ResultTy && "Didn't read a type?");
1513 TypeList[NumRecords++] = ResultTy;
1517 std::error_code BitcodeReader::ParseValueSymbolTable() {
1518 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1519 return Error("Invalid record");
1521 SmallVector<uint64_t, 64> Record;
1523 Triple TT(TheModule->getTargetTriple());
1525 // Read all the records for this value table.
1526 SmallString<128> ValueName;
1528 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1530 switch (Entry.Kind) {
1531 case BitstreamEntry::SubBlock: // Handled for us already.
1532 case BitstreamEntry::Error:
1533 return Error("Malformed block");
1534 case BitstreamEntry::EndBlock:
1535 return std::error_code();
1536 case BitstreamEntry::Record:
1537 // The interesting case.
1543 switch (Stream.readRecord(Entry.ID, Record)) {
1544 default: // Default behavior: unknown type.
1546 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1547 if (ConvertToString(Record, 1, ValueName))
1548 return Error("Invalid record");
1549 unsigned ValueID = Record[0];
1550 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1551 return Error("Invalid record");
1552 Value *V = ValueList[ValueID];
1554 V->setName(StringRef(ValueName.data(), ValueName.size()));
1555 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1556 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1557 if (TT.isOSBinFormatMachO())
1558 GO->setComdat(nullptr);
1560 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1566 case bitc::VST_CODE_BBENTRY: {
1567 if (ConvertToString(Record, 1, ValueName))
1568 return Error("Invalid record");
1569 BasicBlock *BB = getBasicBlock(Record[0]);
1571 return Error("Invalid record");
1573 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1581 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1583 std::error_code BitcodeReader::ParseMetadata() {
1584 IsMetadataMaterialized = true;
1585 unsigned NextMDValueNo = MDValueList.size();
1587 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1588 return Error("Invalid record");
1590 SmallVector<uint64_t, 64> Record;
1593 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1594 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1596 return getMD(ID - 1);
1599 auto getMDString = [&](unsigned ID) -> MDString *{
1600 // This requires that the ID is not really a forward reference. In
1601 // particular, the MDString must already have been resolved.
1602 return cast_or_null<MDString>(getMDOrNull(ID));
1605 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1606 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1608 // Read all the records.
1610 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1612 switch (Entry.Kind) {
1613 case BitstreamEntry::SubBlock: // Handled for us already.
1614 case BitstreamEntry::Error:
1615 return Error("Malformed block");
1616 case BitstreamEntry::EndBlock:
1617 MDValueList.tryToResolveCycles();
1618 return std::error_code();
1619 case BitstreamEntry::Record:
1620 // The interesting case.
1626 unsigned Code = Stream.readRecord(Entry.ID, Record);
1627 bool IsDistinct = false;
1629 default: // Default behavior: ignore.
1631 case bitc::METADATA_NAME: {
1632 // Read name of the named metadata.
1633 SmallString<8> Name(Record.begin(), Record.end());
1635 Code = Stream.ReadCode();
1637 unsigned NextBitCode = Stream.readRecord(Code, Record);
1638 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1639 return Error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1641 // Read named metadata elements.
1642 unsigned Size = Record.size();
1643 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1644 for (unsigned i = 0; i != Size; ++i) {
1645 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1647 return Error("Invalid record");
1648 NMD->addOperand(MD);
1652 case bitc::METADATA_OLD_FN_NODE: {
1653 // FIXME: Remove in 4.0.
1654 // This is a LocalAsMetadata record, the only type of function-local
1656 if (Record.size() % 2 == 1)
1657 return Error("Invalid record");
1659 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1660 // to be legal, but there's no upgrade path.
1661 auto dropRecord = [&] {
1662 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1664 if (Record.size() != 2) {
1669 Type *Ty = getTypeByID(Record[0]);
1670 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1675 MDValueList.AssignValue(
1676 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1680 case bitc::METADATA_OLD_NODE: {
1681 // FIXME: Remove in 4.0.
1682 if (Record.size() % 2 == 1)
1683 return Error("Invalid record");
1685 unsigned Size = Record.size();
1686 SmallVector<Metadata *, 8> Elts;
1687 for (unsigned i = 0; i != Size; i += 2) {
1688 Type *Ty = getTypeByID(Record[i]);
1690 return Error("Invalid record");
1691 if (Ty->isMetadataTy())
1692 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1693 else if (!Ty->isVoidTy()) {
1695 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1696 assert(isa<ConstantAsMetadata>(MD) &&
1697 "Expected non-function-local metadata");
1700 Elts.push_back(nullptr);
1702 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1705 case bitc::METADATA_VALUE: {
1706 if (Record.size() != 2)
1707 return Error("Invalid record");
1709 Type *Ty = getTypeByID(Record[0]);
1710 if (Ty->isMetadataTy() || Ty->isVoidTy())
1711 return Error("Invalid record");
1713 MDValueList.AssignValue(
1714 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1718 case bitc::METADATA_DISTINCT_NODE:
1721 case bitc::METADATA_NODE: {
1722 SmallVector<Metadata *, 8> Elts;
1723 Elts.reserve(Record.size());
1724 for (unsigned ID : Record)
1725 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1726 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1727 : MDNode::get(Context, Elts),
1731 case bitc::METADATA_LOCATION: {
1732 if (Record.size() != 5)
1733 return Error("Invalid record");
1735 unsigned Line = Record[1];
1736 unsigned Column = Record[2];
1737 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1738 Metadata *InlinedAt =
1739 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1740 MDValueList.AssignValue(
1741 GET_OR_DISTINCT(DILocation, Record[0],
1742 (Context, Line, Column, Scope, InlinedAt)),
1746 case bitc::METADATA_GENERIC_DEBUG: {
1747 if (Record.size() < 4)
1748 return Error("Invalid record");
1750 unsigned Tag = Record[1];
1751 unsigned Version = Record[2];
1753 if (Tag >= 1u << 16 || Version != 0)
1754 return Error("Invalid record");
1756 auto *Header = getMDString(Record[3]);
1757 SmallVector<Metadata *, 8> DwarfOps;
1758 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1759 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1761 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1762 (Context, Tag, Header, DwarfOps)),
1766 case bitc::METADATA_SUBRANGE: {
1767 if (Record.size() != 3)
1768 return Error("Invalid record");
1770 MDValueList.AssignValue(
1771 GET_OR_DISTINCT(DISubrange, Record[0],
1772 (Context, Record[1], unrotateSign(Record[2]))),
1776 case bitc::METADATA_ENUMERATOR: {
1777 if (Record.size() != 3)
1778 return Error("Invalid record");
1780 MDValueList.AssignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1781 (Context, unrotateSign(Record[1]),
1782 getMDString(Record[2]))),
1786 case bitc::METADATA_BASIC_TYPE: {
1787 if (Record.size() != 6)
1788 return Error("Invalid record");
1790 MDValueList.AssignValue(
1791 GET_OR_DISTINCT(DIBasicType, Record[0],
1792 (Context, Record[1], getMDString(Record[2]),
1793 Record[3], Record[4], Record[5])),
1797 case bitc::METADATA_DERIVED_TYPE: {
1798 if (Record.size() != 12)
1799 return Error("Invalid record");
1801 MDValueList.AssignValue(
1802 GET_OR_DISTINCT(DIDerivedType, Record[0],
1803 (Context, Record[1], getMDString(Record[2]),
1804 getMDOrNull(Record[3]), Record[4],
1805 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1806 Record[7], Record[8], Record[9], Record[10],
1807 getMDOrNull(Record[11]))),
1811 case bitc::METADATA_COMPOSITE_TYPE: {
1812 if (Record.size() != 16)
1813 return Error("Invalid record");
1815 MDValueList.AssignValue(
1816 GET_OR_DISTINCT(DICompositeType, Record[0],
1817 (Context, Record[1], getMDString(Record[2]),
1818 getMDOrNull(Record[3]), Record[4],
1819 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1820 Record[7], Record[8], Record[9], Record[10],
1821 getMDOrNull(Record[11]), Record[12],
1822 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1823 getMDString(Record[15]))),
1827 case bitc::METADATA_SUBROUTINE_TYPE: {
1828 if (Record.size() != 3)
1829 return Error("Invalid record");
1831 MDValueList.AssignValue(
1832 GET_OR_DISTINCT(DISubroutineType, Record[0],
1833 (Context, Record[1], getMDOrNull(Record[2]))),
1837 case bitc::METADATA_FILE: {
1838 if (Record.size() != 3)
1839 return Error("Invalid record");
1841 MDValueList.AssignValue(
1842 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1843 getMDString(Record[2]))),
1847 case bitc::METADATA_COMPILE_UNIT: {
1848 if (Record.size() < 14 || Record.size() > 15)
1849 return Error("Invalid record");
1851 MDValueList.AssignValue(
1852 GET_OR_DISTINCT(DICompileUnit, Record[0],
1853 (Context, Record[1], getMDOrNull(Record[2]),
1854 getMDString(Record[3]), Record[4],
1855 getMDString(Record[5]), Record[6],
1856 getMDString(Record[7]), Record[8],
1857 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1858 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1859 getMDOrNull(Record[13]),
1860 Record.size() == 14 ? 0 : Record[14])),
1864 case bitc::METADATA_SUBPROGRAM: {
1865 if (Record.size() != 19)
1866 return Error("Invalid record");
1868 MDValueList.AssignValue(
1870 DISubprogram, Record[0],
1871 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1872 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1873 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1874 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1875 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1876 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1880 case bitc::METADATA_LEXICAL_BLOCK: {
1881 if (Record.size() != 5)
1882 return Error("Invalid record");
1884 MDValueList.AssignValue(
1885 GET_OR_DISTINCT(DILexicalBlock, Record[0],
1886 (Context, getMDOrNull(Record[1]),
1887 getMDOrNull(Record[2]), Record[3], Record[4])),
1891 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1892 if (Record.size() != 4)
1893 return Error("Invalid record");
1895 MDValueList.AssignValue(
1896 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1897 (Context, getMDOrNull(Record[1]),
1898 getMDOrNull(Record[2]), Record[3])),
1902 case bitc::METADATA_NAMESPACE: {
1903 if (Record.size() != 5)
1904 return Error("Invalid record");
1906 MDValueList.AssignValue(
1907 GET_OR_DISTINCT(DINamespace, Record[0],
1908 (Context, getMDOrNull(Record[1]),
1909 getMDOrNull(Record[2]), getMDString(Record[3]),
1914 case bitc::METADATA_TEMPLATE_TYPE: {
1915 if (Record.size() != 3)
1916 return Error("Invalid record");
1918 MDValueList.AssignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1920 (Context, getMDString(Record[1]),
1921 getMDOrNull(Record[2]))),
1925 case bitc::METADATA_TEMPLATE_VALUE: {
1926 if (Record.size() != 5)
1927 return Error("Invalid record");
1929 MDValueList.AssignValue(
1930 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1931 (Context, Record[1], getMDString(Record[2]),
1932 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1936 case bitc::METADATA_GLOBAL_VAR: {
1937 if (Record.size() != 11)
1938 return Error("Invalid record");
1940 MDValueList.AssignValue(
1941 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1942 (Context, getMDOrNull(Record[1]),
1943 getMDString(Record[2]), getMDString(Record[3]),
1944 getMDOrNull(Record[4]), Record[5],
1945 getMDOrNull(Record[6]), Record[7], Record[8],
1946 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1950 case bitc::METADATA_LOCAL_VAR: {
1951 // 10th field is for the obseleted 'inlinedAt:' field.
1952 if (Record.size() != 9 && Record.size() != 10)
1953 return Error("Invalid record");
1955 MDValueList.AssignValue(
1956 GET_OR_DISTINCT(DILocalVariable, Record[0],
1957 (Context, Record[1], getMDOrNull(Record[2]),
1958 getMDString(Record[3]), getMDOrNull(Record[4]),
1959 Record[5], getMDOrNull(Record[6]), Record[7],
1964 case bitc::METADATA_EXPRESSION: {
1965 if (Record.size() < 1)
1966 return Error("Invalid record");
1968 MDValueList.AssignValue(
1969 GET_OR_DISTINCT(DIExpression, Record[0],
1970 (Context, makeArrayRef(Record).slice(1))),
1974 case bitc::METADATA_OBJC_PROPERTY: {
1975 if (Record.size() != 8)
1976 return Error("Invalid record");
1978 MDValueList.AssignValue(
1979 GET_OR_DISTINCT(DIObjCProperty, Record[0],
1980 (Context, getMDString(Record[1]),
1981 getMDOrNull(Record[2]), Record[3],
1982 getMDString(Record[4]), getMDString(Record[5]),
1983 Record[6], getMDOrNull(Record[7]))),
1987 case bitc::METADATA_IMPORTED_ENTITY: {
1988 if (Record.size() != 6)
1989 return Error("Invalid record");
1991 MDValueList.AssignValue(
1992 GET_OR_DISTINCT(DIImportedEntity, Record[0],
1993 (Context, Record[1], getMDOrNull(Record[2]),
1994 getMDOrNull(Record[3]), Record[4],
1995 getMDString(Record[5]))),
1999 case bitc::METADATA_STRING: {
2000 std::string String(Record.begin(), Record.end());
2001 llvm::UpgradeMDStringConstant(String);
2002 Metadata *MD = MDString::get(Context, String);
2003 MDValueList.AssignValue(MD, NextMDValueNo++);
2006 case bitc::METADATA_KIND: {
2007 if (Record.size() < 2)
2008 return Error("Invalid record");
2010 unsigned Kind = Record[0];
2011 SmallString<8> Name(Record.begin()+1, Record.end());
2013 unsigned NewKind = TheModule->getMDKindID(Name.str());
2014 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2015 return Error("Conflicting METADATA_KIND records");
2020 #undef GET_OR_DISTINCT
2023 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
2024 /// the LSB for dense VBR encoding.
2025 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2030 // There is no such thing as -0 with integers. "-0" really means MININT.
2034 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
2035 /// values and aliases that we can.
2036 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
2037 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2038 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2039 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2040 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2042 GlobalInitWorklist.swap(GlobalInits);
2043 AliasInitWorklist.swap(AliasInits);
2044 FunctionPrefixWorklist.swap(FunctionPrefixes);
2045 FunctionPrologueWorklist.swap(FunctionPrologues);
2047 while (!GlobalInitWorklist.empty()) {
2048 unsigned ValID = GlobalInitWorklist.back().second;
2049 if (ValID >= ValueList.size()) {
2050 // Not ready to resolve this yet, it requires something later in the file.
2051 GlobalInits.push_back(GlobalInitWorklist.back());
2053 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2054 GlobalInitWorklist.back().first->setInitializer(C);
2056 return Error("Expected a constant");
2058 GlobalInitWorklist.pop_back();
2061 while (!AliasInitWorklist.empty()) {
2062 unsigned ValID = AliasInitWorklist.back().second;
2063 if (ValID >= ValueList.size()) {
2064 AliasInits.push_back(AliasInitWorklist.back());
2066 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2068 return Error("Expected a constant");
2069 GlobalAlias *Alias = AliasInitWorklist.back().first;
2070 if (C->getType() != Alias->getType())
2071 return Error("Alias and aliasee types don't match");
2072 Alias->setAliasee(C);
2074 AliasInitWorklist.pop_back();
2077 while (!FunctionPrefixWorklist.empty()) {
2078 unsigned ValID = FunctionPrefixWorklist.back().second;
2079 if (ValID >= ValueList.size()) {
2080 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2082 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2083 FunctionPrefixWorklist.back().first->setPrefixData(C);
2085 return Error("Expected a constant");
2087 FunctionPrefixWorklist.pop_back();
2090 while (!FunctionPrologueWorklist.empty()) {
2091 unsigned ValID = FunctionPrologueWorklist.back().second;
2092 if (ValID >= ValueList.size()) {
2093 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2095 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2096 FunctionPrologueWorklist.back().first->setPrologueData(C);
2098 return Error("Expected a constant");
2100 FunctionPrologueWorklist.pop_back();
2103 return std::error_code();
2106 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2107 SmallVector<uint64_t, 8> Words(Vals.size());
2108 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2109 BitcodeReader::decodeSignRotatedValue);
2111 return APInt(TypeBits, Words);
2114 std::error_code BitcodeReader::ParseConstants() {
2115 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2116 return Error("Invalid record");
2118 SmallVector<uint64_t, 64> Record;
2120 // Read all the records for this value table.
2121 Type *CurTy = Type::getInt32Ty(Context);
2122 unsigned NextCstNo = ValueList.size();
2124 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2126 switch (Entry.Kind) {
2127 case BitstreamEntry::SubBlock: // Handled for us already.
2128 case BitstreamEntry::Error:
2129 return Error("Malformed block");
2130 case BitstreamEntry::EndBlock:
2131 if (NextCstNo != ValueList.size())
2132 return Error("Invalid ronstant reference");
2134 // Once all the constants have been read, go through and resolve forward
2136 ValueList.ResolveConstantForwardRefs();
2137 return std::error_code();
2138 case BitstreamEntry::Record:
2139 // The interesting case.
2146 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2148 default: // Default behavior: unknown constant
2149 case bitc::CST_CODE_UNDEF: // UNDEF
2150 V = UndefValue::get(CurTy);
2152 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2154 return Error("Invalid record");
2155 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2156 return Error("Invalid record");
2157 CurTy = TypeList[Record[0]];
2158 continue; // Skip the ValueList manipulation.
2159 case bitc::CST_CODE_NULL: // NULL
2160 V = Constant::getNullValue(CurTy);
2162 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2163 if (!CurTy->isIntegerTy() || Record.empty())
2164 return Error("Invalid record");
2165 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2167 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2168 if (!CurTy->isIntegerTy() || Record.empty())
2169 return Error("Invalid record");
2171 APInt VInt = ReadWideAPInt(Record,
2172 cast<IntegerType>(CurTy)->getBitWidth());
2173 V = ConstantInt::get(Context, VInt);
2177 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2179 return Error("Invalid record");
2180 if (CurTy->isHalfTy())
2181 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2182 APInt(16, (uint16_t)Record[0])));
2183 else if (CurTy->isFloatTy())
2184 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2185 APInt(32, (uint32_t)Record[0])));
2186 else if (CurTy->isDoubleTy())
2187 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2188 APInt(64, Record[0])));
2189 else if (CurTy->isX86_FP80Ty()) {
2190 // Bits are not stored the same way as a normal i80 APInt, compensate.
2191 uint64_t Rearrange[2];
2192 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2193 Rearrange[1] = Record[0] >> 48;
2194 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2195 APInt(80, Rearrange)));
2196 } else if (CurTy->isFP128Ty())
2197 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2198 APInt(128, Record)));
2199 else if (CurTy->isPPC_FP128Ty())
2200 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2201 APInt(128, Record)));
2203 V = UndefValue::get(CurTy);
2207 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2209 return Error("Invalid record");
2211 unsigned Size = Record.size();
2212 SmallVector<Constant*, 16> Elts;
2214 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2215 for (unsigned i = 0; i != Size; ++i)
2216 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2217 STy->getElementType(i)));
2218 V = ConstantStruct::get(STy, Elts);
2219 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2220 Type *EltTy = ATy->getElementType();
2221 for (unsigned i = 0; i != Size; ++i)
2222 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2223 V = ConstantArray::get(ATy, Elts);
2224 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2225 Type *EltTy = VTy->getElementType();
2226 for (unsigned i = 0; i != Size; ++i)
2227 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2228 V = ConstantVector::get(Elts);
2230 V = UndefValue::get(CurTy);
2234 case bitc::CST_CODE_STRING: // STRING: [values]
2235 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2237 return Error("Invalid record");
2239 SmallString<16> Elts(Record.begin(), Record.end());
2240 V = ConstantDataArray::getString(Context, Elts,
2241 BitCode == bitc::CST_CODE_CSTRING);
2244 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2246 return Error("Invalid record");
2248 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2249 unsigned Size = Record.size();
2251 if (EltTy->isIntegerTy(8)) {
2252 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2253 if (isa<VectorType>(CurTy))
2254 V = ConstantDataVector::get(Context, Elts);
2256 V = ConstantDataArray::get(Context, Elts);
2257 } else if (EltTy->isIntegerTy(16)) {
2258 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2259 if (isa<VectorType>(CurTy))
2260 V = ConstantDataVector::get(Context, Elts);
2262 V = ConstantDataArray::get(Context, Elts);
2263 } else if (EltTy->isIntegerTy(32)) {
2264 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2265 if (isa<VectorType>(CurTy))
2266 V = ConstantDataVector::get(Context, Elts);
2268 V = ConstantDataArray::get(Context, Elts);
2269 } else if (EltTy->isIntegerTy(64)) {
2270 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2271 if (isa<VectorType>(CurTy))
2272 V = ConstantDataVector::get(Context, Elts);
2274 V = ConstantDataArray::get(Context, Elts);
2275 } else if (EltTy->isFloatTy()) {
2276 SmallVector<float, 16> Elts(Size);
2277 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2278 if (isa<VectorType>(CurTy))
2279 V = ConstantDataVector::get(Context, Elts);
2281 V = ConstantDataArray::get(Context, Elts);
2282 } else if (EltTy->isDoubleTy()) {
2283 SmallVector<double, 16> Elts(Size);
2284 std::transform(Record.begin(), Record.end(), Elts.begin(),
2286 if (isa<VectorType>(CurTy))
2287 V = ConstantDataVector::get(Context, Elts);
2289 V = ConstantDataArray::get(Context, Elts);
2291 return Error("Invalid type for value");
2296 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2297 if (Record.size() < 3)
2298 return Error("Invalid record");
2299 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2301 V = UndefValue::get(CurTy); // Unknown binop.
2303 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2304 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2306 if (Record.size() >= 4) {
2307 if (Opc == Instruction::Add ||
2308 Opc == Instruction::Sub ||
2309 Opc == Instruction::Mul ||
2310 Opc == Instruction::Shl) {
2311 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2312 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2313 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2314 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2315 } else if (Opc == Instruction::SDiv ||
2316 Opc == Instruction::UDiv ||
2317 Opc == Instruction::LShr ||
2318 Opc == Instruction::AShr) {
2319 if (Record[3] & (1 << bitc::PEO_EXACT))
2320 Flags |= SDivOperator::IsExact;
2323 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2327 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2328 if (Record.size() < 3)
2329 return Error("Invalid record");
2330 int Opc = GetDecodedCastOpcode(Record[0]);
2332 V = UndefValue::get(CurTy); // Unknown cast.
2334 Type *OpTy = getTypeByID(Record[1]);
2336 return Error("Invalid record");
2337 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2338 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2339 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2343 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2344 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2346 Type *PointeeType = nullptr;
2347 if (Record.size() % 2)
2348 PointeeType = getTypeByID(Record[OpNum++]);
2349 SmallVector<Constant*, 16> Elts;
2350 while (OpNum != Record.size()) {
2351 Type *ElTy = getTypeByID(Record[OpNum++]);
2353 return Error("Invalid record");
2354 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2359 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2361 return Error("Explicit gep operator type does not match pointee type "
2362 "of pointer operand");
2364 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2365 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2367 bitc::CST_CODE_CE_INBOUNDS_GEP);
2370 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2371 if (Record.size() < 3)
2372 return Error("Invalid record");
2374 Type *SelectorTy = Type::getInt1Ty(Context);
2376 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2377 // vector. Otherwise, it must be a single bit.
2378 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2379 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2380 VTy->getNumElements());
2382 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2384 ValueList.getConstantFwdRef(Record[1],CurTy),
2385 ValueList.getConstantFwdRef(Record[2],CurTy));
2388 case bitc::CST_CODE_CE_EXTRACTELT
2389 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2390 if (Record.size() < 3)
2391 return Error("Invalid record");
2393 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2395 return Error("Invalid record");
2396 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2397 Constant *Op1 = nullptr;
2398 if (Record.size() == 4) {
2399 Type *IdxTy = getTypeByID(Record[2]);
2401 return Error("Invalid record");
2402 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2403 } else // TODO: Remove with llvm 4.0
2404 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2406 return Error("Invalid record");
2407 V = ConstantExpr::getExtractElement(Op0, Op1);
2410 case bitc::CST_CODE_CE_INSERTELT
2411 : { // CE_INSERTELT: [opval, opval, opty, opval]
2412 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2413 if (Record.size() < 3 || !OpTy)
2414 return Error("Invalid record");
2415 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2416 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2417 OpTy->getElementType());
2418 Constant *Op2 = nullptr;
2419 if (Record.size() == 4) {
2420 Type *IdxTy = getTypeByID(Record[2]);
2422 return Error("Invalid record");
2423 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2424 } else // TODO: Remove with llvm 4.0
2425 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2427 return Error("Invalid record");
2428 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2431 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, 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], OpTy);
2437 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2438 OpTy->getNumElements());
2439 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2440 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2443 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2444 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2446 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2447 if (Record.size() < 4 || !RTy || !OpTy)
2448 return Error("Invalid record");
2449 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2450 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2451 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2452 RTy->getNumElements());
2453 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2454 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2457 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2458 if (Record.size() < 4)
2459 return Error("Invalid record");
2460 Type *OpTy = getTypeByID(Record[0]);
2462 return Error("Invalid record");
2463 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2464 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2466 if (OpTy->isFPOrFPVectorTy())
2467 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2469 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2472 // This maintains backward compatibility, pre-asm dialect keywords.
2473 // FIXME: Remove with the 4.0 release.
2474 case bitc::CST_CODE_INLINEASM_OLD: {
2475 if (Record.size() < 2)
2476 return Error("Invalid record");
2477 std::string AsmStr, ConstrStr;
2478 bool HasSideEffects = Record[0] & 1;
2479 bool IsAlignStack = Record[0] >> 1;
2480 unsigned AsmStrSize = Record[1];
2481 if (2+AsmStrSize >= Record.size())
2482 return Error("Invalid record");
2483 unsigned ConstStrSize = Record[2+AsmStrSize];
2484 if (3+AsmStrSize+ConstStrSize > Record.size())
2485 return Error("Invalid record");
2487 for (unsigned i = 0; i != AsmStrSize; ++i)
2488 AsmStr += (char)Record[2+i];
2489 for (unsigned i = 0; i != ConstStrSize; ++i)
2490 ConstrStr += (char)Record[3+AsmStrSize+i];
2491 PointerType *PTy = cast<PointerType>(CurTy);
2492 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2493 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2496 // This version adds support for the asm dialect keywords (e.g.,
2498 case bitc::CST_CODE_INLINEASM: {
2499 if (Record.size() < 2)
2500 return Error("Invalid record");
2501 std::string AsmStr, ConstrStr;
2502 bool HasSideEffects = Record[0] & 1;
2503 bool IsAlignStack = (Record[0] >> 1) & 1;
2504 unsigned AsmDialect = Record[0] >> 2;
2505 unsigned AsmStrSize = Record[1];
2506 if (2+AsmStrSize >= Record.size())
2507 return Error("Invalid record");
2508 unsigned ConstStrSize = Record[2+AsmStrSize];
2509 if (3+AsmStrSize+ConstStrSize > Record.size())
2510 return Error("Invalid record");
2512 for (unsigned i = 0; i != AsmStrSize; ++i)
2513 AsmStr += (char)Record[2+i];
2514 for (unsigned i = 0; i != ConstStrSize; ++i)
2515 ConstrStr += (char)Record[3+AsmStrSize+i];
2516 PointerType *PTy = cast<PointerType>(CurTy);
2517 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2518 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2519 InlineAsm::AsmDialect(AsmDialect));
2522 case bitc::CST_CODE_BLOCKADDRESS:{
2523 if (Record.size() < 3)
2524 return Error("Invalid record");
2525 Type *FnTy = getTypeByID(Record[0]);
2527 return Error("Invalid record");
2529 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2531 return Error("Invalid record");
2533 // Don't let Fn get dematerialized.
2534 BlockAddressesTaken.insert(Fn);
2536 // If the function is already parsed we can insert the block address right
2539 unsigned BBID = Record[2];
2541 // Invalid reference to entry block.
2542 return Error("Invalid ID");
2544 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2545 for (size_t I = 0, E = BBID; I != E; ++I) {
2547 return Error("Invalid ID");
2552 // Otherwise insert a placeholder and remember it so it can be inserted
2553 // when the function is parsed.
2554 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2556 BasicBlockFwdRefQueue.push_back(Fn);
2557 if (FwdBBs.size() < BBID + 1)
2558 FwdBBs.resize(BBID + 1);
2560 FwdBBs[BBID] = BasicBlock::Create(Context);
2563 V = BlockAddress::get(Fn, BB);
2568 ValueList.AssignValue(V, NextCstNo);
2573 std::error_code BitcodeReader::ParseUseLists() {
2574 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2575 return Error("Invalid record");
2577 // Read all the records.
2578 SmallVector<uint64_t, 64> Record;
2580 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2582 switch (Entry.Kind) {
2583 case BitstreamEntry::SubBlock: // Handled for us already.
2584 case BitstreamEntry::Error:
2585 return Error("Malformed block");
2586 case BitstreamEntry::EndBlock:
2587 return std::error_code();
2588 case BitstreamEntry::Record:
2589 // The interesting case.
2593 // Read a use list record.
2596 switch (Stream.readRecord(Entry.ID, Record)) {
2597 default: // Default behavior: unknown type.
2599 case bitc::USELIST_CODE_BB:
2602 case bitc::USELIST_CODE_DEFAULT: {
2603 unsigned RecordLength = Record.size();
2604 if (RecordLength < 3)
2605 // Records should have at least an ID and two indexes.
2606 return Error("Invalid record");
2607 unsigned ID = Record.back();
2612 assert(ID < FunctionBBs.size() && "Basic block not found");
2613 V = FunctionBBs[ID];
2616 unsigned NumUses = 0;
2617 SmallDenseMap<const Use *, unsigned, 16> Order;
2618 for (const Use &U : V->uses()) {
2619 if (++NumUses > Record.size())
2621 Order[&U] = Record[NumUses - 1];
2623 if (Order.size() != Record.size() || NumUses > Record.size())
2624 // Mismatches can happen if the functions are being materialized lazily
2625 // (out-of-order), or a value has been upgraded.
2628 V->sortUseList([&](const Use &L, const Use &R) {
2629 return Order.lookup(&L) < Order.lookup(&R);
2637 /// When we see the block for metadata, remember where it is and then skip it.
2638 /// This lets us lazily deserialize the metadata.
2639 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2640 // Save the current stream state.
2641 uint64_t CurBit = Stream.GetCurrentBitNo();
2642 DeferredMetadataInfo.push_back(CurBit);
2644 // Skip over the block for now.
2645 if (Stream.SkipBlock())
2646 return Error("Invalid record");
2647 return std::error_code();
2650 std::error_code BitcodeReader::materializeMetadata() {
2651 for (uint64_t BitPos : DeferredMetadataInfo) {
2652 // Move the bit stream to the saved position.
2653 Stream.JumpToBit(BitPos);
2654 if (std::error_code EC = ParseMetadata())
2657 DeferredMetadataInfo.clear();
2658 return std::error_code();
2661 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2663 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2664 /// remember where it is and then skip it. This lets us lazily deserialize the
2666 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2667 // Get the function we are talking about.
2668 if (FunctionsWithBodies.empty())
2669 return Error("Insufficient function protos");
2671 Function *Fn = FunctionsWithBodies.back();
2672 FunctionsWithBodies.pop_back();
2674 // Save the current stream state.
2675 uint64_t CurBit = Stream.GetCurrentBitNo();
2676 DeferredFunctionInfo[Fn] = CurBit;
2678 // Skip over the function block for now.
2679 if (Stream.SkipBlock())
2680 return Error("Invalid record");
2681 return std::error_code();
2684 std::error_code BitcodeReader::GlobalCleanup() {
2685 // Patch the initializers for globals and aliases up.
2686 ResolveGlobalAndAliasInits();
2687 if (!GlobalInits.empty() || !AliasInits.empty())
2688 return Error("Malformed global initializer set");
2690 // Look for intrinsic functions which need to be upgraded at some point
2691 for (Function &F : *TheModule) {
2693 if (UpgradeIntrinsicFunction(&F, NewFn))
2694 UpgradedIntrinsics.push_back(std::make_pair(&F, NewFn));
2697 // Look for global variables which need to be renamed.
2698 for (GlobalVariable &GV : TheModule->globals())
2699 UpgradeGlobalVariable(&GV);
2701 // Force deallocation of memory for these vectors to favor the client that
2702 // want lazy deserialization.
2703 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2704 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2705 return std::error_code();
2708 std::error_code BitcodeReader::ParseModule(bool Resume,
2709 bool ShouldLazyLoadMetadata) {
2711 Stream.JumpToBit(NextUnreadBit);
2712 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2713 return Error("Invalid record");
2715 SmallVector<uint64_t, 64> Record;
2716 std::vector<std::string> SectionTable;
2717 std::vector<std::string> GCTable;
2719 // Read all the records for this module.
2721 BitstreamEntry Entry = Stream.advance();
2723 switch (Entry.Kind) {
2724 case BitstreamEntry::Error:
2725 return Error("Malformed block");
2726 case BitstreamEntry::EndBlock:
2727 return GlobalCleanup();
2729 case BitstreamEntry::SubBlock:
2731 default: // Skip unknown content.
2732 if (Stream.SkipBlock())
2733 return Error("Invalid record");
2735 case bitc::BLOCKINFO_BLOCK_ID:
2736 if (Stream.ReadBlockInfoBlock())
2737 return Error("Malformed block");
2739 case bitc::PARAMATTR_BLOCK_ID:
2740 if (std::error_code EC = ParseAttributeBlock())
2743 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2744 if (std::error_code EC = ParseAttributeGroupBlock())
2747 case bitc::TYPE_BLOCK_ID_NEW:
2748 if (std::error_code EC = ParseTypeTable())
2751 case bitc::VALUE_SYMTAB_BLOCK_ID:
2752 if (std::error_code EC = ParseValueSymbolTable())
2754 SeenValueSymbolTable = true;
2756 case bitc::CONSTANTS_BLOCK_ID:
2757 if (std::error_code EC = ParseConstants())
2759 if (std::error_code EC = ResolveGlobalAndAliasInits())
2762 case bitc::METADATA_BLOCK_ID:
2763 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2764 if (std::error_code EC = rememberAndSkipMetadata())
2768 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2769 if (std::error_code EC = ParseMetadata())
2772 case bitc::FUNCTION_BLOCK_ID:
2773 // If this is the first function body we've seen, reverse the
2774 // FunctionsWithBodies list.
2775 if (!SeenFirstFunctionBody) {
2776 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2777 if (std::error_code EC = GlobalCleanup())
2779 SeenFirstFunctionBody = true;
2782 if (std::error_code EC = RememberAndSkipFunctionBody())
2784 // For streaming bitcode, suspend parsing when we reach the function
2785 // bodies. Subsequent materialization calls will resume it when
2786 // necessary. For streaming, the function bodies must be at the end of
2787 // the bitcode. If the bitcode file is old, the symbol table will be
2788 // at the end instead and will not have been seen yet. In this case,
2789 // just finish the parse now.
2790 if (Streamer && SeenValueSymbolTable) {
2791 NextUnreadBit = Stream.GetCurrentBitNo();
2792 return std::error_code();
2795 case bitc::USELIST_BLOCK_ID:
2796 if (std::error_code EC = ParseUseLists())
2802 case BitstreamEntry::Record:
2803 // The interesting case.
2809 switch (Stream.readRecord(Entry.ID, Record)) {
2810 default: break; // Default behavior, ignore unknown content.
2811 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2812 if (Record.size() < 1)
2813 return Error("Invalid record");
2814 // Only version #0 and #1 are supported so far.
2815 unsigned module_version = Record[0];
2816 switch (module_version) {
2818 return Error("Invalid value");
2820 UseRelativeIDs = false;
2823 UseRelativeIDs = true;
2828 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2830 if (ConvertToString(Record, 0, S))
2831 return Error("Invalid record");
2832 TheModule->setTargetTriple(S);
2835 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2837 if (ConvertToString(Record, 0, S))
2838 return Error("Invalid record");
2839 TheModule->setDataLayout(S);
2842 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2844 if (ConvertToString(Record, 0, S))
2845 return Error("Invalid record");
2846 TheModule->setModuleInlineAsm(S);
2849 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2850 // FIXME: Remove in 4.0.
2852 if (ConvertToString(Record, 0, S))
2853 return Error("Invalid record");
2857 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2859 if (ConvertToString(Record, 0, S))
2860 return Error("Invalid record");
2861 SectionTable.push_back(S);
2864 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2866 if (ConvertToString(Record, 0, S))
2867 return Error("Invalid record");
2868 GCTable.push_back(S);
2871 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2872 if (Record.size() < 2)
2873 return Error("Invalid record");
2874 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2875 unsigned ComdatNameSize = Record[1];
2876 std::string ComdatName;
2877 ComdatName.reserve(ComdatNameSize);
2878 for (unsigned i = 0; i != ComdatNameSize; ++i)
2879 ComdatName += (char)Record[2 + i];
2880 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2881 C->setSelectionKind(SK);
2882 ComdatList.push_back(C);
2885 // GLOBALVAR: [pointer type, isconst, initid,
2886 // linkage, alignment, section, visibility, threadlocal,
2887 // unnamed_addr, externally_initialized, dllstorageclass,
2889 case bitc::MODULE_CODE_GLOBALVAR: {
2890 if (Record.size() < 6)
2891 return Error("Invalid record");
2892 Type *Ty = getTypeByID(Record[0]);
2894 return Error("Invalid record");
2895 bool isConstant = Record[1] & 1;
2896 bool explicitType = Record[1] & 2;
2897 unsigned AddressSpace;
2899 AddressSpace = Record[1] >> 2;
2901 if (!Ty->isPointerTy())
2902 return Error("Invalid type for value");
2903 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2904 Ty = cast<PointerType>(Ty)->getElementType();
2907 uint64_t RawLinkage = Record[3];
2908 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2910 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2912 std::string Section;
2914 if (Record[5]-1 >= SectionTable.size())
2915 return Error("Invalid ID");
2916 Section = SectionTable[Record[5]-1];
2918 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2919 // Local linkage must have default visibility.
2920 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2921 // FIXME: Change to an error if non-default in 4.0.
2922 Visibility = GetDecodedVisibility(Record[6]);
2924 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2925 if (Record.size() > 7)
2926 TLM = GetDecodedThreadLocalMode(Record[7]);
2928 bool UnnamedAddr = false;
2929 if (Record.size() > 8)
2930 UnnamedAddr = Record[8];
2932 bool ExternallyInitialized = false;
2933 if (Record.size() > 9)
2934 ExternallyInitialized = Record[9];
2936 GlobalVariable *NewGV =
2937 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2938 TLM, AddressSpace, ExternallyInitialized);
2939 NewGV->setAlignment(Alignment);
2940 if (!Section.empty())
2941 NewGV->setSection(Section);
2942 NewGV->setVisibility(Visibility);
2943 NewGV->setUnnamedAddr(UnnamedAddr);
2945 if (Record.size() > 10)
2946 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2948 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2950 ValueList.push_back(NewGV);
2952 // Remember which value to use for the global initializer.
2953 if (unsigned InitID = Record[2])
2954 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2956 if (Record.size() > 11) {
2957 if (unsigned ComdatID = Record[11]) {
2958 if (ComdatID > ComdatList.size())
2959 return Error("Invalid global variable comdat ID");
2960 NewGV->setComdat(ComdatList[ComdatID - 1]);
2962 } else if (hasImplicitComdat(RawLinkage)) {
2963 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2967 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2968 // alignment, section, visibility, gc, unnamed_addr,
2969 // prologuedata, dllstorageclass, comdat, prefixdata]
2970 case bitc::MODULE_CODE_FUNCTION: {
2971 if (Record.size() < 8)
2972 return Error("Invalid record");
2973 Type *Ty = getTypeByID(Record[0]);
2975 return Error("Invalid record");
2976 if (auto *PTy = dyn_cast<PointerType>(Ty))
2977 Ty = PTy->getElementType();
2978 auto *FTy = dyn_cast<FunctionType>(Ty);
2980 return Error("Invalid type for value");
2982 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2985 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2986 bool isProto = Record[2];
2987 uint64_t RawLinkage = Record[3];
2988 Func->setLinkage(getDecodedLinkage(RawLinkage));
2989 Func->setAttributes(getAttributes(Record[4]));
2992 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2994 Func->setAlignment(Alignment);
2996 if (Record[6]-1 >= SectionTable.size())
2997 return Error("Invalid ID");
2998 Func->setSection(SectionTable[Record[6]-1]);
3000 // Local linkage must have default visibility.
3001 if (!Func->hasLocalLinkage())
3002 // FIXME: Change to an error if non-default in 4.0.
3003 Func->setVisibility(GetDecodedVisibility(Record[7]));
3004 if (Record.size() > 8 && Record[8]) {
3005 if (Record[8]-1 >= GCTable.size())
3006 return Error("Invalid ID");
3007 Func->setGC(GCTable[Record[8]-1].c_str());
3009 bool UnnamedAddr = false;
3010 if (Record.size() > 9)
3011 UnnamedAddr = Record[9];
3012 Func->setUnnamedAddr(UnnamedAddr);
3013 if (Record.size() > 10 && Record[10] != 0)
3014 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3016 if (Record.size() > 11)
3017 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
3019 UpgradeDLLImportExportLinkage(Func, RawLinkage);
3021 if (Record.size() > 12) {
3022 if (unsigned ComdatID = Record[12]) {
3023 if (ComdatID > ComdatList.size())
3024 return Error("Invalid function comdat ID");
3025 Func->setComdat(ComdatList[ComdatID - 1]);
3027 } else if (hasImplicitComdat(RawLinkage)) {
3028 Func->setComdat(reinterpret_cast<Comdat *>(1));
3031 if (Record.size() > 13 && Record[13] != 0)
3032 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3034 ValueList.push_back(Func);
3036 // If this is a function with a body, remember the prototype we are
3037 // creating now, so that we can match up the body with them later.
3039 Func->setIsMaterializable(true);
3040 FunctionsWithBodies.push_back(Func);
3042 DeferredFunctionInfo[Func] = 0;
3046 // ALIAS: [alias type, aliasee val#, linkage]
3047 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3048 case bitc::MODULE_CODE_ALIAS: {
3049 if (Record.size() < 3)
3050 return Error("Invalid record");
3051 Type *Ty = getTypeByID(Record[0]);
3053 return Error("Invalid record");
3054 auto *PTy = dyn_cast<PointerType>(Ty);
3056 return Error("Invalid type for value");
3059 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3060 // Old bitcode files didn't have visibility field.
3061 // Local linkage must have default visibility.
3062 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3063 // FIXME: Change to an error if non-default in 4.0.
3064 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3065 if (Record.size() > 4)
3066 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3068 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3069 if (Record.size() > 5)
3070 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3071 if (Record.size() > 6)
3072 NewGA->setUnnamedAddr(Record[6]);
3073 ValueList.push_back(NewGA);
3074 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3077 /// MODULE_CODE_PURGEVALS: [numvals]
3078 case bitc::MODULE_CODE_PURGEVALS:
3079 // Trim down the value list to the specified size.
3080 if (Record.size() < 1 || Record[0] > ValueList.size())
3081 return Error("Invalid record");
3082 ValueList.shrinkTo(Record[0]);
3089 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3090 bool ShouldLazyLoadMetadata) {
3091 TheModule = nullptr;
3093 if (std::error_code EC = InitStream())
3096 // Sniff for the signature.
3097 if (Stream.Read(8) != 'B' ||
3098 Stream.Read(8) != 'C' ||
3099 Stream.Read(4) != 0x0 ||
3100 Stream.Read(4) != 0xC ||
3101 Stream.Read(4) != 0xE ||
3102 Stream.Read(4) != 0xD)
3103 return Error("Invalid bitcode signature");
3105 // We expect a number of well-defined blocks, though we don't necessarily
3106 // need to understand them all.
3108 if (Stream.AtEndOfStream()) {
3110 return std::error_code();
3111 // We didn't really read a proper Module.
3112 return Error("Malformed IR file");
3115 BitstreamEntry Entry =
3116 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3118 switch (Entry.Kind) {
3119 case BitstreamEntry::Error:
3120 return Error("Malformed block");
3121 case BitstreamEntry::EndBlock:
3122 return std::error_code();
3124 case BitstreamEntry::SubBlock:
3126 case bitc::BLOCKINFO_BLOCK_ID:
3127 if (Stream.ReadBlockInfoBlock())
3128 return Error("Malformed block");
3130 case bitc::MODULE_BLOCK_ID:
3131 // Reject multiple MODULE_BLOCK's in a single bitstream.
3133 return Error("Invalid multiple blocks");
3135 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3138 return std::error_code();
3141 if (Stream.SkipBlock())
3142 return Error("Invalid record");
3146 case BitstreamEntry::Record:
3147 // There should be no records in the top-level of blocks.
3149 // The ranlib in Xcode 4 will align archive members by appending newlines
3150 // to the end of them. If this file size is a multiple of 4 but not 8, we
3151 // have to read and ignore these final 4 bytes :-(
3152 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3153 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3154 Stream.AtEndOfStream())
3155 return std::error_code();
3157 return Error("Invalid record");
3162 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3163 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3164 return Error("Invalid record");
3166 SmallVector<uint64_t, 64> Record;
3169 // Read all the records for this module.
3171 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3173 switch (Entry.Kind) {
3174 case BitstreamEntry::SubBlock: // Handled for us already.
3175 case BitstreamEntry::Error:
3176 return Error("Malformed block");
3177 case BitstreamEntry::EndBlock:
3179 case BitstreamEntry::Record:
3180 // The interesting case.
3185 switch (Stream.readRecord(Entry.ID, Record)) {
3186 default: break; // Default behavior, ignore unknown content.
3187 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3189 if (ConvertToString(Record, 0, S))
3190 return Error("Invalid record");
3197 llvm_unreachable("Exit infinite loop");
3200 ErrorOr<std::string> BitcodeReader::parseTriple() {
3201 if (std::error_code EC = InitStream())
3204 // Sniff for the signature.
3205 if (Stream.Read(8) != 'B' ||
3206 Stream.Read(8) != 'C' ||
3207 Stream.Read(4) != 0x0 ||
3208 Stream.Read(4) != 0xC ||
3209 Stream.Read(4) != 0xE ||
3210 Stream.Read(4) != 0xD)
3211 return Error("Invalid bitcode signature");
3213 // We expect a number of well-defined blocks, though we don't necessarily
3214 // need to understand them all.
3216 BitstreamEntry Entry = Stream.advance();
3218 switch (Entry.Kind) {
3219 case BitstreamEntry::Error:
3220 return Error("Malformed block");
3221 case BitstreamEntry::EndBlock:
3222 return std::error_code();
3224 case BitstreamEntry::SubBlock:
3225 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3226 return parseModuleTriple();
3228 // Ignore other sub-blocks.
3229 if (Stream.SkipBlock())
3230 return Error("Malformed block");
3233 case BitstreamEntry::Record:
3234 Stream.skipRecord(Entry.ID);
3240 /// ParseMetadataAttachment - Parse metadata attachments.
3241 std::error_code BitcodeReader::ParseMetadataAttachment(Function &F) {
3242 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3243 return Error("Invalid record");
3245 SmallVector<uint64_t, 64> Record;
3247 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3249 switch (Entry.Kind) {
3250 case BitstreamEntry::SubBlock: // Handled for us already.
3251 case BitstreamEntry::Error:
3252 return Error("Malformed block");
3253 case BitstreamEntry::EndBlock:
3254 return std::error_code();
3255 case BitstreamEntry::Record:
3256 // The interesting case.
3260 // Read a metadata attachment record.
3262 switch (Stream.readRecord(Entry.ID, Record)) {
3263 default: // Default behavior: ignore.
3265 case bitc::METADATA_ATTACHMENT: {
3266 unsigned RecordLength = Record.size();
3268 return Error("Invalid record");
3269 if (RecordLength % 2 == 0) {
3270 // A function attachment.
3271 for (unsigned I = 0; I != RecordLength; I += 2) {
3272 auto K = MDKindMap.find(Record[I]);
3273 if (K == MDKindMap.end())
3274 return Error("Invalid ID");
3275 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3276 F.setMetadata(K->second, cast<MDNode>(MD));
3281 // An instruction attachment.
3282 Instruction *Inst = InstructionList[Record[0]];
3283 for (unsigned i = 1; i != RecordLength; i = i+2) {
3284 unsigned Kind = Record[i];
3285 DenseMap<unsigned, unsigned>::iterator I =
3286 MDKindMap.find(Kind);
3287 if (I == MDKindMap.end())
3288 return Error("Invalid ID");
3289 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3290 if (isa<LocalAsMetadata>(Node))
3291 // Drop the attachment. This used to be legal, but there's no
3294 Inst->setMetadata(I->second, cast<MDNode>(Node));
3295 if (I->second == LLVMContext::MD_tbaa)
3296 InstsWithTBAATag.push_back(Inst);
3304 static std::error_code TypeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3305 Type *ValType, Type *PtrType) {
3306 if (!isa<PointerType>(PtrType))
3307 return Error(DH, "Load/Store operand is not a pointer type");
3308 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3310 if (ValType && ValType != ElemType)
3311 return Error(DH, "Explicit load/store type does not match pointee type of "
3313 if (!PointerType::isLoadableOrStorableType(ElemType))
3314 return Error(DH, "Cannot load/store from pointer");
3315 return std::error_code();
3318 /// ParseFunctionBody - Lazily parse the specified function body block.
3319 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3320 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3321 return Error("Invalid record");
3323 InstructionList.clear();
3324 unsigned ModuleValueListSize = ValueList.size();
3325 unsigned ModuleMDValueListSize = MDValueList.size();
3327 // Add all the function arguments to the value table.
3328 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3329 ValueList.push_back(I);
3331 unsigned NextValueNo = ValueList.size();
3332 BasicBlock *CurBB = nullptr;
3333 unsigned CurBBNo = 0;
3336 auto getLastInstruction = [&]() -> Instruction * {
3337 if (CurBB && !CurBB->empty())
3338 return &CurBB->back();
3339 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3340 !FunctionBBs[CurBBNo - 1]->empty())
3341 return &FunctionBBs[CurBBNo - 1]->back();
3345 // Read all the records.
3346 SmallVector<uint64_t, 64> Record;
3348 BitstreamEntry Entry = Stream.advance();
3350 switch (Entry.Kind) {
3351 case BitstreamEntry::Error:
3352 return Error("Malformed block");
3353 case BitstreamEntry::EndBlock:
3354 goto OutOfRecordLoop;
3356 case BitstreamEntry::SubBlock:
3358 default: // Skip unknown content.
3359 if (Stream.SkipBlock())
3360 return Error("Invalid record");
3362 case bitc::CONSTANTS_BLOCK_ID:
3363 if (std::error_code EC = ParseConstants())
3365 NextValueNo = ValueList.size();
3367 case bitc::VALUE_SYMTAB_BLOCK_ID:
3368 if (std::error_code EC = ParseValueSymbolTable())
3371 case bitc::METADATA_ATTACHMENT_ID:
3372 if (std::error_code EC = ParseMetadataAttachment(*F))
3375 case bitc::METADATA_BLOCK_ID:
3376 if (std::error_code EC = ParseMetadata())
3379 case bitc::USELIST_BLOCK_ID:
3380 if (std::error_code EC = ParseUseLists())
3386 case BitstreamEntry::Record:
3387 // The interesting case.
3393 Instruction *I = nullptr;
3394 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3396 default: // Default behavior: reject
3397 return Error("Invalid value");
3398 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3399 if (Record.size() < 1 || Record[0] == 0)
3400 return Error("Invalid record");
3401 // Create all the basic blocks for the function.
3402 FunctionBBs.resize(Record[0]);
3404 // See if anything took the address of blocks in this function.
3405 auto BBFRI = BasicBlockFwdRefs.find(F);
3406 if (BBFRI == BasicBlockFwdRefs.end()) {
3407 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3408 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3410 auto &BBRefs = BBFRI->second;
3411 // Check for invalid basic block references.
3412 if (BBRefs.size() > FunctionBBs.size())
3413 return Error("Invalid ID");
3414 assert(!BBRefs.empty() && "Unexpected empty array");
3415 assert(!BBRefs.front() && "Invalid reference to entry block");
3416 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3418 if (I < RE && BBRefs[I]) {
3419 BBRefs[I]->insertInto(F);
3420 FunctionBBs[I] = BBRefs[I];
3422 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3425 // Erase from the table.
3426 BasicBlockFwdRefs.erase(BBFRI);
3429 CurBB = FunctionBBs[0];
3433 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3434 // This record indicates that the last instruction is at the same
3435 // location as the previous instruction with a location.
3436 I = getLastInstruction();
3439 return Error("Invalid record");
3440 I->setDebugLoc(LastLoc);
3444 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3445 I = getLastInstruction();
3446 if (!I || Record.size() < 4)
3447 return Error("Invalid record");
3449 unsigned Line = Record[0], Col = Record[1];
3450 unsigned ScopeID = Record[2], IAID = Record[3];
3452 MDNode *Scope = nullptr, *IA = nullptr;
3453 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3454 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3455 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3456 I->setDebugLoc(LastLoc);
3461 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3464 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3465 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3466 OpNum+1 > Record.size())
3467 return Error("Invalid record");
3469 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3471 return Error("Invalid record");
3472 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3473 InstructionList.push_back(I);
3474 if (OpNum < Record.size()) {
3475 if (Opc == Instruction::Add ||
3476 Opc == Instruction::Sub ||
3477 Opc == Instruction::Mul ||
3478 Opc == Instruction::Shl) {
3479 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3480 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3481 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3482 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3483 } else if (Opc == Instruction::SDiv ||
3484 Opc == Instruction::UDiv ||
3485 Opc == Instruction::LShr ||
3486 Opc == Instruction::AShr) {
3487 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3488 cast<BinaryOperator>(I)->setIsExact(true);
3489 } else if (isa<FPMathOperator>(I)) {
3491 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3492 FMF.setUnsafeAlgebra();
3493 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3495 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3497 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3498 FMF.setNoSignedZeros();
3499 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3500 FMF.setAllowReciprocal();
3502 I->setFastMathFlags(FMF);
3508 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3511 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3512 OpNum+2 != Record.size())
3513 return Error("Invalid record");
3515 Type *ResTy = getTypeByID(Record[OpNum]);
3516 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3517 if (Opc == -1 || !ResTy)
3518 return Error("Invalid record");
3519 Instruction *Temp = nullptr;
3520 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3522 InstructionList.push_back(Temp);
3523 CurBB->getInstList().push_back(Temp);
3526 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3528 InstructionList.push_back(I);
3531 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3532 case bitc::FUNC_CODE_INST_GEP_OLD:
3533 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3539 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3540 InBounds = Record[OpNum++];
3541 Ty = getTypeByID(Record[OpNum++]);
3543 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3548 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3549 return Error("Invalid record");
3552 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3555 cast<SequentialType>(BasePtr->getType()->getScalarType())
3558 "Explicit gep type does not match pointee type of pointer operand");
3560 SmallVector<Value*, 16> GEPIdx;
3561 while (OpNum != Record.size()) {
3563 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3564 return Error("Invalid record");
3565 GEPIdx.push_back(Op);
3568 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3570 InstructionList.push_back(I);
3572 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3576 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3577 // EXTRACTVAL: [opty, opval, n x indices]
3580 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3581 return Error("Invalid record");
3583 unsigned RecSize = Record.size();
3584 if (OpNum == RecSize)
3585 return Error("EXTRACTVAL: Invalid instruction with 0 indices");
3587 SmallVector<unsigned, 4> EXTRACTVALIdx;
3588 Type *CurTy = Agg->getType();
3589 for (; OpNum != RecSize; ++OpNum) {
3590 bool IsArray = CurTy->isArrayTy();
3591 bool IsStruct = CurTy->isStructTy();
3592 uint64_t Index = Record[OpNum];
3594 if (!IsStruct && !IsArray)
3595 return Error("EXTRACTVAL: Invalid type");
3596 if ((unsigned)Index != Index)
3597 return Error("Invalid value");
3598 if (IsStruct && Index >= CurTy->subtypes().size())
3599 return Error("EXTRACTVAL: Invalid struct index");
3600 if (IsArray && Index >= CurTy->getArrayNumElements())
3601 return Error("EXTRACTVAL: Invalid array index");
3602 EXTRACTVALIdx.push_back((unsigned)Index);
3605 CurTy = CurTy->subtypes()[Index];
3607 CurTy = CurTy->subtypes()[0];
3610 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3611 InstructionList.push_back(I);
3615 case bitc::FUNC_CODE_INST_INSERTVAL: {
3616 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3619 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3620 return Error("Invalid record");
3622 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3623 return Error("Invalid record");
3625 unsigned RecSize = Record.size();
3626 if (OpNum == RecSize)
3627 return Error("INSERTVAL: Invalid instruction with 0 indices");
3629 SmallVector<unsigned, 4> INSERTVALIdx;
3630 Type *CurTy = Agg->getType();
3631 for (; OpNum != RecSize; ++OpNum) {
3632 bool IsArray = CurTy->isArrayTy();
3633 bool IsStruct = CurTy->isStructTy();
3634 uint64_t Index = Record[OpNum];
3636 if (!IsStruct && !IsArray)
3637 return Error("INSERTVAL: Invalid type");
3638 if ((unsigned)Index != Index)
3639 return Error("Invalid value");
3640 if (IsStruct && Index >= CurTy->subtypes().size())
3641 return Error("INSERTVAL: Invalid struct index");
3642 if (IsArray && Index >= CurTy->getArrayNumElements())
3643 return Error("INSERTVAL: Invalid array index");
3645 INSERTVALIdx.push_back((unsigned)Index);
3647 CurTy = CurTy->subtypes()[Index];
3649 CurTy = CurTy->subtypes()[0];
3652 if (CurTy != Val->getType())
3653 return Error("Inserted value type doesn't match aggregate type");
3655 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3656 InstructionList.push_back(I);
3660 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3661 // obsolete form of select
3662 // handles select i1 ... in old bitcode
3664 Value *TrueVal, *FalseVal, *Cond;
3665 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3666 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3667 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3668 return Error("Invalid record");
3670 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3671 InstructionList.push_back(I);
3675 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3676 // new form of select
3677 // handles select i1 or select [N x i1]
3679 Value *TrueVal, *FalseVal, *Cond;
3680 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3681 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3682 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3683 return Error("Invalid record");
3685 // select condition can be either i1 or [N x i1]
3686 if (VectorType* vector_type =
3687 dyn_cast<VectorType>(Cond->getType())) {
3689 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3690 return Error("Invalid type for value");
3693 if (Cond->getType() != Type::getInt1Ty(Context))
3694 return Error("Invalid type for value");
3697 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3698 InstructionList.push_back(I);
3702 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3705 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3706 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3707 return Error("Invalid record");
3708 if (!Vec->getType()->isVectorTy())
3709 return Error("Invalid type for value");
3710 I = ExtractElementInst::Create(Vec, Idx);
3711 InstructionList.push_back(I);
3715 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3717 Value *Vec, *Elt, *Idx;
3718 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3719 return Error("Invalid record");
3720 if (!Vec->getType()->isVectorTy())
3721 return Error("Invalid type for value");
3722 if (popValue(Record, OpNum, NextValueNo,
3723 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3724 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3725 return Error("Invalid record");
3726 I = InsertElementInst::Create(Vec, Elt, Idx);
3727 InstructionList.push_back(I);
3731 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3733 Value *Vec1, *Vec2, *Mask;
3734 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3735 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3736 return Error("Invalid record");
3738 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3739 return Error("Invalid record");
3740 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3741 return Error("Invalid type for value");
3742 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3743 InstructionList.push_back(I);
3747 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3748 // Old form of ICmp/FCmp returning bool
3749 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3750 // both legal on vectors but had different behaviour.
3751 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3752 // FCmp/ICmp returning bool or vector of bool
3756 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3757 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3758 OpNum+1 != Record.size())
3759 return Error("Invalid record");
3761 if (LHS->getType()->isFPOrFPVectorTy())
3762 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3764 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3765 InstructionList.push_back(I);
3769 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3771 unsigned Size = Record.size();
3773 I = ReturnInst::Create(Context);
3774 InstructionList.push_back(I);
3779 Value *Op = nullptr;
3780 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3781 return Error("Invalid record");
3782 if (OpNum != Record.size())
3783 return Error("Invalid record");
3785 I = ReturnInst::Create(Context, Op);
3786 InstructionList.push_back(I);
3789 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3790 if (Record.size() != 1 && Record.size() != 3)
3791 return Error("Invalid record");
3792 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3794 return Error("Invalid record");
3796 if (Record.size() == 1) {
3797 I = BranchInst::Create(TrueDest);
3798 InstructionList.push_back(I);
3801 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3802 Value *Cond = getValue(Record, 2, NextValueNo,
3803 Type::getInt1Ty(Context));
3804 if (!FalseDest || !Cond)
3805 return Error("Invalid record");
3806 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3807 InstructionList.push_back(I);
3811 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3813 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3814 // "New" SwitchInst format with case ranges. The changes to write this
3815 // format were reverted but we still recognize bitcode that uses it.
3816 // Hopefully someday we will have support for case ranges and can use
3817 // this format again.
3819 Type *OpTy = getTypeByID(Record[1]);
3820 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3822 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3823 BasicBlock *Default = getBasicBlock(Record[3]);
3824 if (!OpTy || !Cond || !Default)
3825 return Error("Invalid record");
3827 unsigned NumCases = Record[4];
3829 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3830 InstructionList.push_back(SI);
3832 unsigned CurIdx = 5;
3833 for (unsigned i = 0; i != NumCases; ++i) {
3834 SmallVector<ConstantInt*, 1> CaseVals;
3835 unsigned NumItems = Record[CurIdx++];
3836 for (unsigned ci = 0; ci != NumItems; ++ci) {
3837 bool isSingleNumber = Record[CurIdx++];
3840 unsigned ActiveWords = 1;
3841 if (ValueBitWidth > 64)
3842 ActiveWords = Record[CurIdx++];
3843 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3845 CurIdx += ActiveWords;
3847 if (!isSingleNumber) {
3849 if (ValueBitWidth > 64)
3850 ActiveWords = Record[CurIdx++];
3852 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3854 CurIdx += ActiveWords;
3856 // FIXME: It is not clear whether values in the range should be
3857 // compared as signed or unsigned values. The partially
3858 // implemented changes that used this format in the past used
3859 // unsigned comparisons.
3860 for ( ; Low.ule(High); ++Low)
3861 CaseVals.push_back(ConstantInt::get(Context, Low));
3863 CaseVals.push_back(ConstantInt::get(Context, Low));
3865 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3866 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3867 cve = CaseVals.end(); cvi != cve; ++cvi)
3868 SI->addCase(*cvi, DestBB);
3874 // Old SwitchInst format without case ranges.
3876 if (Record.size() < 3 || (Record.size() & 1) == 0)
3877 return Error("Invalid record");
3878 Type *OpTy = getTypeByID(Record[0]);
3879 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3880 BasicBlock *Default = getBasicBlock(Record[2]);
3881 if (!OpTy || !Cond || !Default)
3882 return Error("Invalid record");
3883 unsigned NumCases = (Record.size()-3)/2;
3884 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3885 InstructionList.push_back(SI);
3886 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3887 ConstantInt *CaseVal =
3888 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3889 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3890 if (!CaseVal || !DestBB) {
3892 return Error("Invalid record");
3894 SI->addCase(CaseVal, DestBB);
3899 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3900 if (Record.size() < 2)
3901 return Error("Invalid record");
3902 Type *OpTy = getTypeByID(Record[0]);
3903 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3904 if (!OpTy || !Address)
3905 return Error("Invalid record");
3906 unsigned NumDests = Record.size()-2;
3907 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3908 InstructionList.push_back(IBI);
3909 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3910 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3911 IBI->addDestination(DestBB);
3914 return Error("Invalid record");
3921 case bitc::FUNC_CODE_INST_INVOKE: {
3922 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3923 if (Record.size() < 4)
3924 return Error("Invalid record");
3926 AttributeSet PAL = getAttributes(Record[OpNum++]);
3927 unsigned CCInfo = Record[OpNum++];
3928 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3929 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3931 FunctionType *FTy = nullptr;
3932 if (CCInfo >> 13 & 1 &&
3933 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3934 return Error("Explicit invoke type is not a function type");
3937 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3938 return Error("Invalid record");
3940 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3942 return Error("Callee is not a pointer");
3944 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3946 return Error("Callee is not of pointer to function type");
3947 } else if (CalleeTy->getElementType() != FTy)
3948 return Error("Explicit invoke type does not match pointee type of "
3950 if (Record.size() < FTy->getNumParams() + OpNum)
3951 return Error("Insufficient operands to call");
3953 SmallVector<Value*, 16> Ops;
3954 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3955 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3956 FTy->getParamType(i)));
3958 return Error("Invalid record");
3961 if (!FTy->isVarArg()) {
3962 if (Record.size() != OpNum)
3963 return Error("Invalid record");
3965 // Read type/value pairs for varargs params.
3966 while (OpNum != Record.size()) {
3968 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3969 return Error("Invalid record");
3974 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3975 InstructionList.push_back(I);
3977 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
3978 cast<InvokeInst>(I)->setAttributes(PAL);
3981 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3983 Value *Val = nullptr;
3984 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3985 return Error("Invalid record");
3986 I = ResumeInst::Create(Val);
3987 InstructionList.push_back(I);
3990 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3991 I = new UnreachableInst(Context);
3992 InstructionList.push_back(I);
3994 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3995 if (Record.size() < 1 || ((Record.size()-1)&1))
3996 return Error("Invalid record");
3997 Type *Ty = getTypeByID(Record[0]);
3999 return Error("Invalid record");
4001 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4002 InstructionList.push_back(PN);
4004 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4006 // With the new function encoding, it is possible that operands have
4007 // negative IDs (for forward references). Use a signed VBR
4008 // representation to keep the encoding small.
4010 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4012 V = getValue(Record, 1+i, NextValueNo, Ty);
4013 BasicBlock *BB = getBasicBlock(Record[2+i]);
4015 return Error("Invalid record");
4016 PN->addIncoming(V, BB);
4022 case bitc::FUNC_CODE_INST_LANDINGPAD: {
4023 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4025 if (Record.size() < 4)
4026 return Error("Invalid record");
4027 Type *Ty = getTypeByID(Record[Idx++]);
4029 return Error("Invalid record");
4030 Value *PersFn = nullptr;
4031 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4032 return Error("Invalid record");
4034 bool IsCleanup = !!Record[Idx++];
4035 unsigned NumClauses = Record[Idx++];
4036 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
4037 LP->setCleanup(IsCleanup);
4038 for (unsigned J = 0; J != NumClauses; ++J) {
4039 LandingPadInst::ClauseType CT =
4040 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4043 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4045 return Error("Invalid record");
4048 assert((CT != LandingPadInst::Catch ||
4049 !isa<ArrayType>(Val->getType())) &&
4050 "Catch clause has a invalid type!");
4051 assert((CT != LandingPadInst::Filter ||
4052 isa<ArrayType>(Val->getType())) &&
4053 "Filter clause has invalid type!");
4054 LP->addClause(cast<Constant>(Val));
4058 InstructionList.push_back(I);
4062 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4063 if (Record.size() != 4)
4064 return Error("Invalid record");
4065 uint64_t AlignRecord = Record[3];
4066 const uint64_t InAllocaMask = uint64_t(1) << 5;
4067 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4068 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4069 bool InAlloca = AlignRecord & InAllocaMask;
4070 Type *Ty = getTypeByID(Record[0]);
4071 if ((AlignRecord & ExplicitTypeMask) == 0) {
4072 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4074 return Error("Old-style alloca with a non-pointer type");
4075 Ty = PTy->getElementType();
4077 Type *OpTy = getTypeByID(Record[1]);
4078 Value *Size = getFnValueByID(Record[2], OpTy);
4080 if (std::error_code EC =
4081 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4085 return Error("Invalid record");
4086 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4087 AI->setUsedWithInAlloca(InAlloca);
4089 InstructionList.push_back(I);
4092 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4095 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4096 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4097 return Error("Invalid record");
4100 if (OpNum + 3 == Record.size())
4101 Ty = getTypeByID(Record[OpNum++]);
4102 if (std::error_code EC =
4103 TypeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4106 Ty = cast<PointerType>(Op->getType())->getElementType();
4109 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4111 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4113 InstructionList.push_back(I);
4116 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4117 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4120 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4121 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4122 return Error("Invalid record");
4125 if (OpNum + 5 == Record.size())
4126 Ty = getTypeByID(Record[OpNum++]);
4127 if (std::error_code EC =
4128 TypeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4131 Ty = cast<PointerType>(Op->getType())->getElementType();
4133 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4134 if (Ordering == NotAtomic || Ordering == Release ||
4135 Ordering == AcquireRelease)
4136 return Error("Invalid record");
4137 if (Ordering != NotAtomic && Record[OpNum] == 0)
4138 return Error("Invalid record");
4139 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4142 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4144 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4146 InstructionList.push_back(I);
4149 case bitc::FUNC_CODE_INST_STORE:
4150 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4153 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4154 (BitCode == bitc::FUNC_CODE_INST_STORE
4155 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4156 : popValue(Record, OpNum, NextValueNo,
4157 cast<PointerType>(Ptr->getType())->getElementType(),
4159 OpNum + 2 != Record.size())
4160 return Error("Invalid record");
4162 if (std::error_code EC = TypeCheckLoadStoreInst(
4163 DiagnosticHandler, Val->getType(), Ptr->getType()))
4166 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4168 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4169 InstructionList.push_back(I);
4172 case bitc::FUNC_CODE_INST_STOREATOMIC:
4173 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4174 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4177 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4178 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4179 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4180 : popValue(Record, OpNum, NextValueNo,
4181 cast<PointerType>(Ptr->getType())->getElementType(),
4183 OpNum + 4 != Record.size())
4184 return Error("Invalid record");
4186 if (std::error_code EC = TypeCheckLoadStoreInst(
4187 DiagnosticHandler, Val->getType(), Ptr->getType()))
4189 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4190 if (Ordering == NotAtomic || Ordering == Acquire ||
4191 Ordering == AcquireRelease)
4192 return Error("Invalid record");
4193 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4194 if (Ordering != NotAtomic && Record[OpNum] == 0)
4195 return Error("Invalid record");
4198 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4200 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4201 InstructionList.push_back(I);
4204 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4205 case bitc::FUNC_CODE_INST_CMPXCHG: {
4206 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4207 // failureordering?, isweak?]
4209 Value *Ptr, *Cmp, *New;
4210 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4211 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4212 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4213 : popValue(Record, OpNum, NextValueNo,
4214 cast<PointerType>(Ptr->getType())->getElementType(),
4216 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4217 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4218 return Error("Invalid record");
4219 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4220 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4221 return Error("Invalid record");
4222 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4224 if (std::error_code EC = TypeCheckLoadStoreInst(
4225 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4227 AtomicOrdering FailureOrdering;
4228 if (Record.size() < 7)
4230 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4232 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4234 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4236 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4238 if (Record.size() < 8) {
4239 // Before weak cmpxchgs existed, the instruction simply returned the
4240 // value loaded from memory, so bitcode files from that era will be
4241 // expecting the first component of a modern cmpxchg.
4242 CurBB->getInstList().push_back(I);
4243 I = ExtractValueInst::Create(I, 0);
4245 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4248 InstructionList.push_back(I);
4251 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4252 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4255 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4256 popValue(Record, OpNum, NextValueNo,
4257 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4258 OpNum+4 != Record.size())
4259 return Error("Invalid record");
4260 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4261 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4262 Operation > AtomicRMWInst::LAST_BINOP)
4263 return Error("Invalid record");
4264 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4265 if (Ordering == NotAtomic || Ordering == Unordered)
4266 return Error("Invalid record");
4267 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4268 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4269 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4270 InstructionList.push_back(I);
4273 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4274 if (2 != Record.size())
4275 return Error("Invalid record");
4276 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4277 if (Ordering == NotAtomic || Ordering == Unordered ||
4278 Ordering == Monotonic)
4279 return Error("Invalid record");
4280 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4281 I = new FenceInst(Context, Ordering, SynchScope);
4282 InstructionList.push_back(I);
4285 case bitc::FUNC_CODE_INST_CALL: {
4286 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4287 if (Record.size() < 3)
4288 return Error("Invalid record");
4291 AttributeSet PAL = getAttributes(Record[OpNum++]);
4292 unsigned CCInfo = Record[OpNum++];
4294 FunctionType *FTy = nullptr;
4295 if (CCInfo >> 15 & 1 &&
4296 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4297 return Error("Explicit call type is not a function type");
4300 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4301 return Error("Invalid record");
4303 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4305 return Error("Callee is not a pointer type");
4307 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4309 return Error("Callee is not of pointer to function type");
4310 } else if (OpTy->getElementType() != FTy)
4311 return Error("Explicit call type does not match pointee type of "
4313 if (Record.size() < FTy->getNumParams() + OpNum)
4314 return Error("Insufficient operands to call");
4316 SmallVector<Value*, 16> Args;
4317 // Read the fixed params.
4318 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4319 if (FTy->getParamType(i)->isLabelTy())
4320 Args.push_back(getBasicBlock(Record[OpNum]));
4322 Args.push_back(getValue(Record, OpNum, NextValueNo,
4323 FTy->getParamType(i)));
4325 return Error("Invalid record");
4328 // Read type/value pairs for varargs params.
4329 if (!FTy->isVarArg()) {
4330 if (OpNum != Record.size())
4331 return Error("Invalid record");
4333 while (OpNum != Record.size()) {
4335 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4336 return Error("Invalid record");
4341 I = CallInst::Create(FTy, Callee, Args);
4342 InstructionList.push_back(I);
4343 cast<CallInst>(I)->setCallingConv(
4344 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4345 CallInst::TailCallKind TCK = CallInst::TCK_None;
4347 TCK = CallInst::TCK_Tail;
4348 if (CCInfo & (1 << 14))
4349 TCK = CallInst::TCK_MustTail;
4350 cast<CallInst>(I)->setTailCallKind(TCK);
4351 cast<CallInst>(I)->setAttributes(PAL);
4354 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4355 if (Record.size() < 3)
4356 return Error("Invalid record");
4357 Type *OpTy = getTypeByID(Record[0]);
4358 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4359 Type *ResTy = getTypeByID(Record[2]);
4360 if (!OpTy || !Op || !ResTy)
4361 return Error("Invalid record");
4362 I = new VAArgInst(Op, ResTy);
4363 InstructionList.push_back(I);
4368 // Add instruction to end of current BB. If there is no current BB, reject
4372 return Error("Invalid instruction with no BB");
4374 CurBB->getInstList().push_back(I);
4376 // If this was a terminator instruction, move to the next block.
4377 if (isa<TerminatorInst>(I)) {
4379 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4382 // Non-void values get registered in the value table for future use.
4383 if (I && !I->getType()->isVoidTy())
4384 ValueList.AssignValue(I, NextValueNo++);
4389 // Check the function list for unresolved values.
4390 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4391 if (!A->getParent()) {
4392 // We found at least one unresolved value. Nuke them all to avoid leaks.
4393 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4394 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4395 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4399 return Error("Never resolved value found in function");
4403 // FIXME: Check for unresolved forward-declared metadata references
4404 // and clean up leaks.
4406 // Trim the value list down to the size it was before we parsed this function.
4407 ValueList.shrinkTo(ModuleValueListSize);
4408 MDValueList.shrinkTo(ModuleMDValueListSize);
4409 std::vector<BasicBlock*>().swap(FunctionBBs);
4410 return std::error_code();
4413 /// Find the function body in the bitcode stream
4414 std::error_code BitcodeReader::FindFunctionInStream(
4416 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4417 while (DeferredFunctionInfoIterator->second == 0) {
4418 if (Stream.AtEndOfStream())
4419 return Error("Could not find function in stream");
4420 // ParseModule will parse the next body in the stream and set its
4421 // position in the DeferredFunctionInfo map.
4422 if (std::error_code EC = ParseModule(true))
4425 return std::error_code();
4428 //===----------------------------------------------------------------------===//
4429 // GVMaterializer implementation
4430 //===----------------------------------------------------------------------===//
4432 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4434 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4435 if (std::error_code EC = materializeMetadata())
4438 Function *F = dyn_cast<Function>(GV);
4439 // If it's not a function or is already material, ignore the request.
4440 if (!F || !F->isMaterializable())
4441 return std::error_code();
4443 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4444 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4445 // If its position is recorded as 0, its body is somewhere in the stream
4446 // but we haven't seen it yet.
4447 if (DFII->second == 0 && Streamer)
4448 if (std::error_code EC = FindFunctionInStream(F, DFII))
4451 // Move the bit stream to the saved position of the deferred function body.
4452 Stream.JumpToBit(DFII->second);
4454 if (std::error_code EC = ParseFunctionBody(F))
4456 F->setIsMaterializable(false);
4461 // Upgrade any old intrinsic calls in the function.
4462 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4463 E = UpgradedIntrinsics.end(); I != E; ++I) {
4464 if (I->first != I->second) {
4465 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4467 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4468 UpgradeIntrinsicCall(CI, I->second);
4473 // Bring in any functions that this function forward-referenced via
4475 return materializeForwardReferencedFunctions();
4478 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4479 const Function *F = dyn_cast<Function>(GV);
4480 if (!F || F->isDeclaration())
4483 // Dematerializing F would leave dangling references that wouldn't be
4484 // reconnected on re-materialization.
4485 if (BlockAddressesTaken.count(F))
4488 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4491 void BitcodeReader::dematerialize(GlobalValue *GV) {
4492 Function *F = dyn_cast<Function>(GV);
4493 // If this function isn't dematerializable, this is a noop.
4494 if (!F || !isDematerializable(F))
4497 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4499 // Just forget the function body, we can remat it later.
4500 F->dropAllReferences();
4501 F->setIsMaterializable(true);
4504 std::error_code BitcodeReader::materializeModule(Module *M) {
4505 assert(M == TheModule &&
4506 "Can only Materialize the Module this BitcodeReader is attached to.");
4508 if (std::error_code EC = materializeMetadata())
4511 // Promise to materialize all forward references.
4512 WillMaterializeAllForwardRefs = true;
4514 // Iterate over the module, deserializing any functions that are still on
4516 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4518 if (std::error_code EC = materialize(F))
4521 // At this point, if there are any function bodies, the current bit is
4522 // pointing to the END_BLOCK record after them. Now make sure the rest
4523 // of the bits in the module have been read.
4527 // Check that all block address forward references got resolved (as we
4529 if (!BasicBlockFwdRefs.empty())
4530 return Error("Never resolved function from blockaddress");
4532 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4533 // delete the old functions to clean up. We can't do this unless the entire
4534 // module is materialized because there could always be another function body
4535 // with calls to the old function.
4536 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4537 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4538 if (I->first != I->second) {
4539 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4541 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4542 UpgradeIntrinsicCall(CI, I->second);
4544 if (!I->first->use_empty())
4545 I->first->replaceAllUsesWith(I->second);
4546 I->first->eraseFromParent();
4549 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4551 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4552 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4554 UpgradeDebugInfo(*M);
4555 return std::error_code();
4558 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4559 return IdentifiedStructTypes;
4562 std::error_code BitcodeReader::InitStream() {
4564 return InitLazyStream();
4565 return InitStreamFromBuffer();
4568 std::error_code BitcodeReader::InitStreamFromBuffer() {
4569 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4570 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4572 if (Buffer->getBufferSize() & 3)
4573 return Error("Invalid bitcode signature");
4575 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4576 // The magic number is 0x0B17C0DE stored in little endian.
4577 if (isBitcodeWrapper(BufPtr, BufEnd))
4578 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4579 return Error("Invalid bitcode wrapper header");
4581 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4582 Stream.init(&*StreamFile);
4584 return std::error_code();
4587 std::error_code BitcodeReader::InitLazyStream() {
4588 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4590 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(Streamer);
4591 StreamingMemoryObject &Bytes = *OwnedBytes;
4592 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4593 Stream.init(&*StreamFile);
4595 unsigned char buf[16];
4596 if (Bytes.readBytes(buf, 16, 0) != 16)
4597 return Error("Invalid bitcode signature");
4599 if (!isBitcode(buf, buf + 16))
4600 return Error("Invalid bitcode signature");
4602 if (isBitcodeWrapper(buf, buf + 4)) {
4603 const unsigned char *bitcodeStart = buf;
4604 const unsigned char *bitcodeEnd = buf + 16;
4605 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4606 Bytes.dropLeadingBytes(bitcodeStart - buf);
4607 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4609 return std::error_code();
4613 class BitcodeErrorCategoryType : public std::error_category {
4614 const char *name() const LLVM_NOEXCEPT override {
4615 return "llvm.bitcode";
4617 std::string message(int IE) const override {
4618 BitcodeError E = static_cast<BitcodeError>(IE);
4620 case BitcodeError::InvalidBitcodeSignature:
4621 return "Invalid bitcode signature";
4622 case BitcodeError::CorruptedBitcode:
4623 return "Corrupted bitcode";
4625 llvm_unreachable("Unknown error type!");
4630 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4632 const std::error_category &llvm::BitcodeErrorCategory() {
4633 return *ErrorCategory;
4636 //===----------------------------------------------------------------------===//
4637 // External interface
4638 //===----------------------------------------------------------------------===//
4640 /// \brief Get a lazy one-at-time loading module from bitcode.
4642 /// This isn't always used in a lazy context. In particular, it's also used by
4643 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4644 /// in forward-referenced functions from block address references.
4646 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4647 /// materialize everything -- in particular, if this isn't truly lazy.
4648 static ErrorOr<Module *>
4649 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4650 LLVMContext &Context, bool WillMaterializeAll,
4651 DiagnosticHandlerFunction DiagnosticHandler,
4652 bool ShouldLazyLoadMetadata = false) {
4653 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4655 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4656 M->setMaterializer(R);
4658 auto cleanupOnError = [&](std::error_code EC) {
4659 R->releaseBuffer(); // Never take ownership on error.
4660 delete M; // Also deletes R.
4664 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4665 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4666 return cleanupOnError(EC);
4668 if (!WillMaterializeAll)
4669 // Resolve forward references from blockaddresses.
4670 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4671 return cleanupOnError(EC);
4673 Buffer.release(); // The BitcodeReader owns it now.
4678 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4679 LLVMContext &Context,
4680 DiagnosticHandlerFunction DiagnosticHandler,
4681 bool ShouldLazyLoadMetadata) {
4682 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4683 DiagnosticHandler, ShouldLazyLoadMetadata);
4686 ErrorOr<std::unique_ptr<Module>>
4687 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4688 LLVMContext &Context,
4689 DiagnosticHandlerFunction DiagnosticHandler) {
4690 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4691 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4692 M->setMaterializer(R);
4693 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4695 return std::move(M);
4699 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4700 DiagnosticHandlerFunction DiagnosticHandler) {
4701 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4702 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4703 std::move(Buf), Context, true, DiagnosticHandler);
4706 Module *M = ModuleOrErr.get();
4707 // Read in the entire module, and destroy the BitcodeReader.
4708 if (std::error_code EC = M->materializeAllPermanently()) {
4713 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4714 // written. We must defer until the Module has been fully materialized.
4720 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4721 DiagnosticHandlerFunction DiagnosticHandler) {
4722 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4723 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4725 ErrorOr<std::string> Triple = R->parseTriple();
4726 if (Triple.getError())
4728 return Triple.get();