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) {
67 ValuePtrs.push_back(V);
71 assert(ResolveConstants.empty() && "Constants not resolved?");
75 Value *operator[](unsigned i) const {
76 assert(i < ValuePtrs.size());
80 Value *back() const { return ValuePtrs.back(); }
81 void pop_back() { ValuePtrs.pop_back(); }
82 bool empty() const { return ValuePtrs.empty(); }
83 void shrinkTo(unsigned N) {
84 assert(N <= size() && "Invalid shrinkTo request!");
88 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
89 Value *getValueFwdRef(unsigned Idx, Type *Ty);
91 void AssignValue(Value *V, unsigned Idx);
93 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
94 /// resolves any forward references.
95 void ResolveConstantForwardRefs();
98 class BitcodeReaderMDValueList {
103 std::vector<TrackingMDRef> MDValuePtrs;
105 LLVMContext &Context;
107 BitcodeReaderMDValueList(LLVMContext &C)
108 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
110 // vector compatibility methods
111 unsigned size() const { return MDValuePtrs.size(); }
112 void resize(unsigned N) { MDValuePtrs.resize(N); }
113 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
114 void clear() { MDValuePtrs.clear(); }
115 Metadata *back() const { return MDValuePtrs.back(); }
116 void pop_back() { MDValuePtrs.pop_back(); }
117 bool empty() const { return MDValuePtrs.empty(); }
119 Metadata *operator[](unsigned i) const {
120 assert(i < MDValuePtrs.size());
121 return MDValuePtrs[i];
124 void shrinkTo(unsigned N) {
125 assert(N <= size() && "Invalid shrinkTo request!");
126 MDValuePtrs.resize(N);
129 Metadata *getValueFwdRef(unsigned Idx);
130 void AssignValue(Metadata *MD, unsigned Idx);
131 void tryToResolveCycles();
134 class BitcodeReader : public GVMaterializer {
135 LLVMContext &Context;
136 DiagnosticHandlerFunction DiagnosticHandler;
138 std::unique_ptr<MemoryBuffer> Buffer;
139 std::unique_ptr<BitstreamReader> StreamFile;
140 BitstreamCursor Stream;
141 DataStreamer *LazyStreamer;
142 uint64_t NextUnreadBit;
143 bool SeenValueSymbolTable;
145 std::vector<Type*> TypeList;
146 BitcodeReaderValueList ValueList;
147 BitcodeReaderMDValueList MDValueList;
148 std::vector<Comdat *> ComdatList;
149 SmallVector<Instruction *, 64> InstructionList;
151 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
152 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
153 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
154 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
156 SmallVector<Instruction*, 64> InstsWithTBAATag;
158 /// MAttributes - The set of attributes by index. Index zero in the
159 /// file is for null, and is thus not represented here. As such all indices
161 std::vector<AttributeSet> MAttributes;
163 /// \brief The set of attribute groups.
164 std::map<unsigned, AttributeSet> MAttributeGroups;
166 /// FunctionBBs - While parsing a function body, this is a list of the basic
167 /// blocks for the function.
168 std::vector<BasicBlock*> FunctionBBs;
170 // When reading the module header, this list is populated with functions that
171 // have bodies later in the file.
172 std::vector<Function*> FunctionsWithBodies;
174 // When intrinsic functions are encountered which require upgrading they are
175 // stored here with their replacement function.
176 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
177 UpgradedIntrinsicMap UpgradedIntrinsics;
179 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
180 DenseMap<unsigned, unsigned> MDKindMap;
182 // Several operations happen after the module header has been read, but
183 // before function bodies are processed. This keeps track of whether
184 // we've done this yet.
185 bool SeenFirstFunctionBody;
187 /// DeferredFunctionInfo - When function bodies are initially scanned, this
188 /// map contains info about where to find deferred function body in the
190 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
192 /// When Metadata block is initially scanned when parsing the module, we may
193 /// choose to defer parsing of the metadata. This vector contains info about
194 /// which Metadata blocks are deferred.
195 std::vector<uint64_t> DeferredMetadataInfo;
197 /// These are basic blocks forward-referenced by block addresses. They are
198 /// inserted lazily into functions when they're loaded. The basic block ID is
199 /// its index into the vector.
200 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
201 std::deque<Function *> BasicBlockFwdRefQueue;
203 /// UseRelativeIDs - Indicates that we are using a new encoding for
204 /// instruction operands where most operands in the current
205 /// FUNCTION_BLOCK are encoded relative to the instruction number,
206 /// for a more compact encoding. Some instruction operands are not
207 /// relative to the instruction ID: basic block numbers, and types.
208 /// Once the old style function blocks have been phased out, we would
209 /// not need this flag.
212 /// True if all functions will be materialized, negating the need to process
213 /// (e.g.) blockaddress forward references.
214 bool WillMaterializeAllForwardRefs;
216 /// Functions that have block addresses taken. This is usually empty.
217 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
219 /// True if any Metadata block has been materialized.
220 bool IsMetadataMaterialized;
222 bool StripDebugInfo = false;
225 std::error_code Error(BitcodeError E, const Twine &Message);
226 std::error_code Error(BitcodeError E);
227 std::error_code Error(const Twine &Message);
229 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
230 DiagnosticHandlerFunction DiagnosticHandler);
231 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
232 DiagnosticHandlerFunction DiagnosticHandler);
233 ~BitcodeReader() override { FreeState(); }
235 std::error_code materializeForwardReferencedFunctions();
239 void releaseBuffer();
241 bool isDematerializable(const GlobalValue *GV) const override;
242 std::error_code materialize(GlobalValue *GV) override;
243 std::error_code materializeModule(Module *M) override;
244 std::vector<StructType *> getIdentifiedStructTypes() const override;
245 void dematerialize(GlobalValue *GV) override;
247 /// @brief Main interface to parsing a bitcode buffer.
248 /// @returns true if an error occurred.
249 std::error_code ParseBitcodeInto(Module *M,
250 bool ShouldLazyLoadMetadata = false);
252 /// @brief Cheap mechanism to just extract module triple
253 /// @returns true if an error occurred.
254 ErrorOr<std::string> parseTriple();
256 static uint64_t decodeSignRotatedValue(uint64_t V);
258 /// Materialize any deferred Metadata block.
259 std::error_code materializeMetadata() override;
261 void setStripDebugInfo() override;
264 std::vector<StructType *> IdentifiedStructTypes;
265 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
266 StructType *createIdentifiedStructType(LLVMContext &Context);
268 Type *getTypeByID(unsigned ID);
269 Value *getFnValueByID(unsigned ID, Type *Ty) {
270 if (Ty && Ty->isMetadataTy())
271 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
272 return ValueList.getValueFwdRef(ID, Ty);
274 Metadata *getFnMetadataByID(unsigned ID) {
275 return MDValueList.getValueFwdRef(ID);
277 BasicBlock *getBasicBlock(unsigned ID) const {
278 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
279 return FunctionBBs[ID];
281 AttributeSet getAttributes(unsigned i) const {
282 if (i-1 < MAttributes.size())
283 return MAttributes[i-1];
284 return AttributeSet();
287 /// getValueTypePair - Read a value/type pair out of the specified record from
288 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
289 /// Return true on failure.
290 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
291 unsigned InstNum, Value *&ResVal) {
292 if (Slot == Record.size()) return true;
293 unsigned ValNo = (unsigned)Record[Slot++];
294 // Adjust the ValNo, if it was encoded relative to the InstNum.
296 ValNo = InstNum - ValNo;
297 if (ValNo < InstNum) {
298 // If this is not a forward reference, just return the value we already
300 ResVal = getFnValueByID(ValNo, nullptr);
301 return ResVal == nullptr;
303 if (Slot == Record.size())
306 unsigned TypeNo = (unsigned)Record[Slot++];
307 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
308 return ResVal == nullptr;
311 /// popValue - Read a value out of the specified record from slot 'Slot'.
312 /// Increment Slot past the number of slots used by the value in the record.
313 /// Return true if there is an error.
314 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
315 unsigned InstNum, Type *Ty, Value *&ResVal) {
316 if (getValue(Record, Slot, InstNum, Ty, ResVal))
318 // All values currently take a single record slot.
323 /// getValue -- Like popValue, but does not increment the Slot number.
324 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
325 unsigned InstNum, Type *Ty, Value *&ResVal) {
326 ResVal = getValue(Record, Slot, InstNum, Ty);
327 return ResVal == nullptr;
330 /// getValue -- Version of getValue that returns ResVal directly,
331 /// or 0 if there is an error.
332 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
333 unsigned InstNum, Type *Ty) {
334 if (Slot == Record.size()) return nullptr;
335 unsigned ValNo = (unsigned)Record[Slot];
336 // Adjust the ValNo, if it was encoded relative to the InstNum.
338 ValNo = InstNum - ValNo;
339 return getFnValueByID(ValNo, Ty);
342 /// getValueSigned -- Like getValue, but decodes signed VBRs.
343 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
344 unsigned InstNum, Type *Ty) {
345 if (Slot == Record.size()) return nullptr;
346 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
347 // Adjust the ValNo, if it was encoded relative to the InstNum.
349 ValNo = InstNum - ValNo;
350 return getFnValueByID(ValNo, Ty);
353 /// Converts alignment exponent (i.e. power of two (or zero)) to the
354 /// corresponding alignment to use. If alignment is too large, returns
355 /// a corresponding error code.
356 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
357 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
358 std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
359 std::error_code ParseAttributeBlock();
360 std::error_code ParseAttributeGroupBlock();
361 std::error_code ParseTypeTable();
362 std::error_code ParseTypeTableBody();
364 std::error_code ParseValueSymbolTable();
365 std::error_code ParseConstants();
366 std::error_code RememberAndSkipFunctionBody();
367 /// Save the positions of the Metadata blocks and skip parsing the blocks.
368 std::error_code rememberAndSkipMetadata();
369 std::error_code ParseFunctionBody(Function *F);
370 std::error_code GlobalCleanup();
371 std::error_code ResolveGlobalAndAliasInits();
372 std::error_code ParseMetadata();
373 std::error_code ParseMetadataAttachment(Function &F);
374 ErrorOr<std::string> parseModuleTriple();
375 std::error_code ParseUseLists();
376 std::error_code InitStream();
377 std::error_code InitStreamFromBuffer();
378 std::error_code InitLazyStream();
379 std::error_code FindFunctionInStream(
381 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
385 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
386 DiagnosticSeverity Severity,
388 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
390 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
392 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
393 std::error_code EC, const Twine &Message) {
394 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
395 DiagnosticHandler(DI);
399 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
400 std::error_code EC) {
401 return Error(DiagnosticHandler, EC, EC.message());
404 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
405 const Twine &Message) {
406 return Error(DiagnosticHandler,
407 make_error_code(BitcodeError::CorruptedBitcode), Message);
410 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
411 return ::Error(DiagnosticHandler, make_error_code(E), Message);
414 std::error_code BitcodeReader::Error(const Twine &Message) {
415 return ::Error(DiagnosticHandler,
416 make_error_code(BitcodeError::CorruptedBitcode), Message);
419 std::error_code BitcodeReader::Error(BitcodeError E) {
420 return ::Error(DiagnosticHandler, make_error_code(E));
423 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
427 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
430 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
431 DiagnosticHandlerFunction DiagnosticHandler)
432 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
433 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
434 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
435 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
436 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
438 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
439 DiagnosticHandlerFunction DiagnosticHandler)
440 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
441 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
442 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
443 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
444 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
446 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
447 if (WillMaterializeAllForwardRefs)
448 return std::error_code();
450 // Prevent recursion.
451 WillMaterializeAllForwardRefs = true;
453 while (!BasicBlockFwdRefQueue.empty()) {
454 Function *F = BasicBlockFwdRefQueue.front();
455 BasicBlockFwdRefQueue.pop_front();
456 assert(F && "Expected valid function");
457 if (!BasicBlockFwdRefs.count(F))
458 // Already materialized.
461 // Check for a function that isn't materializable to prevent an infinite
462 // loop. When parsing a blockaddress stored in a global variable, there
463 // isn't a trivial way to check if a function will have a body without a
464 // linear search through FunctionsWithBodies, so just check it here.
465 if (!F->isMaterializable())
466 return Error("Never resolved function from blockaddress");
468 // Try to materialize F.
469 if (std::error_code EC = materialize(F))
472 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
475 WillMaterializeAllForwardRefs = false;
476 return std::error_code();
479 void BitcodeReader::FreeState() {
481 std::vector<Type*>().swap(TypeList);
484 std::vector<Comdat *>().swap(ComdatList);
486 std::vector<AttributeSet>().swap(MAttributes);
487 std::vector<BasicBlock*>().swap(FunctionBBs);
488 std::vector<Function*>().swap(FunctionsWithBodies);
489 DeferredFunctionInfo.clear();
490 DeferredMetadataInfo.clear();
493 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
494 BasicBlockFwdRefQueue.clear();
497 //===----------------------------------------------------------------------===//
498 // Helper functions to implement forward reference resolution, etc.
499 //===----------------------------------------------------------------------===//
501 /// ConvertToString - Convert a string from a record into an std::string, return
503 template<typename StrTy>
504 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
506 if (Idx > Record.size())
509 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
510 Result += (char)Record[i];
514 static bool hasImplicitComdat(size_t Val) {
518 case 1: // Old WeakAnyLinkage
519 case 4: // Old LinkOnceAnyLinkage
520 case 10: // Old WeakODRLinkage
521 case 11: // Old LinkOnceODRLinkage
526 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
528 default: // Map unknown/new linkages to external
530 return GlobalValue::ExternalLinkage;
532 return GlobalValue::AppendingLinkage;
534 return GlobalValue::InternalLinkage;
536 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
538 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
540 return GlobalValue::ExternalWeakLinkage;
542 return GlobalValue::CommonLinkage;
544 return GlobalValue::PrivateLinkage;
546 return GlobalValue::AvailableExternallyLinkage;
548 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
550 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
552 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
553 case 1: // Old value with implicit comdat.
555 return GlobalValue::WeakAnyLinkage;
556 case 10: // Old value with implicit comdat.
558 return GlobalValue::WeakODRLinkage;
559 case 4: // Old value with implicit comdat.
561 return GlobalValue::LinkOnceAnyLinkage;
562 case 11: // Old value with implicit comdat.
564 return GlobalValue::LinkOnceODRLinkage;
568 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
570 default: // Map unknown visibilities to default.
571 case 0: return GlobalValue::DefaultVisibility;
572 case 1: return GlobalValue::HiddenVisibility;
573 case 2: return GlobalValue::ProtectedVisibility;
577 static GlobalValue::DLLStorageClassTypes
578 GetDecodedDLLStorageClass(unsigned Val) {
580 default: // Map unknown values to default.
581 case 0: return GlobalValue::DefaultStorageClass;
582 case 1: return GlobalValue::DLLImportStorageClass;
583 case 2: return GlobalValue::DLLExportStorageClass;
587 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
589 case 0: return GlobalVariable::NotThreadLocal;
590 default: // Map unknown non-zero value to general dynamic.
591 case 1: return GlobalVariable::GeneralDynamicTLSModel;
592 case 2: return GlobalVariable::LocalDynamicTLSModel;
593 case 3: return GlobalVariable::InitialExecTLSModel;
594 case 4: return GlobalVariable::LocalExecTLSModel;
598 static int GetDecodedCastOpcode(unsigned Val) {
601 case bitc::CAST_TRUNC : return Instruction::Trunc;
602 case bitc::CAST_ZEXT : return Instruction::ZExt;
603 case bitc::CAST_SEXT : return Instruction::SExt;
604 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
605 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
606 case bitc::CAST_UITOFP : return Instruction::UIToFP;
607 case bitc::CAST_SITOFP : return Instruction::SIToFP;
608 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
609 case bitc::CAST_FPEXT : return Instruction::FPExt;
610 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
611 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
612 case bitc::CAST_BITCAST : return Instruction::BitCast;
613 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
617 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
618 bool IsFP = Ty->isFPOrFPVectorTy();
619 // BinOps are only valid for int/fp or vector of int/fp types
620 if (!IsFP && !Ty->isIntOrIntVectorTy())
626 case bitc::BINOP_ADD:
627 return IsFP ? Instruction::FAdd : Instruction::Add;
628 case bitc::BINOP_SUB:
629 return IsFP ? Instruction::FSub : Instruction::Sub;
630 case bitc::BINOP_MUL:
631 return IsFP ? Instruction::FMul : Instruction::Mul;
632 case bitc::BINOP_UDIV:
633 return IsFP ? -1 : Instruction::UDiv;
634 case bitc::BINOP_SDIV:
635 return IsFP ? Instruction::FDiv : Instruction::SDiv;
636 case bitc::BINOP_UREM:
637 return IsFP ? -1 : Instruction::URem;
638 case bitc::BINOP_SREM:
639 return IsFP ? Instruction::FRem : Instruction::SRem;
640 case bitc::BINOP_SHL:
641 return IsFP ? -1 : Instruction::Shl;
642 case bitc::BINOP_LSHR:
643 return IsFP ? -1 : Instruction::LShr;
644 case bitc::BINOP_ASHR:
645 return IsFP ? -1 : Instruction::AShr;
646 case bitc::BINOP_AND:
647 return IsFP ? -1 : Instruction::And;
649 return IsFP ? -1 : Instruction::Or;
650 case bitc::BINOP_XOR:
651 return IsFP ? -1 : Instruction::Xor;
655 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
657 default: return AtomicRMWInst::BAD_BINOP;
658 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
659 case bitc::RMW_ADD: return AtomicRMWInst::Add;
660 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
661 case bitc::RMW_AND: return AtomicRMWInst::And;
662 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
663 case bitc::RMW_OR: return AtomicRMWInst::Or;
664 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
665 case bitc::RMW_MAX: return AtomicRMWInst::Max;
666 case bitc::RMW_MIN: return AtomicRMWInst::Min;
667 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
668 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
672 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
674 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
675 case bitc::ORDERING_UNORDERED: return Unordered;
676 case bitc::ORDERING_MONOTONIC: return Monotonic;
677 case bitc::ORDERING_ACQUIRE: return Acquire;
678 case bitc::ORDERING_RELEASE: return Release;
679 case bitc::ORDERING_ACQREL: return AcquireRelease;
680 default: // Map unknown orderings to sequentially-consistent.
681 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
685 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
687 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
688 default: // Map unknown scopes to cross-thread.
689 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
693 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
695 default: // Map unknown selection kinds to any.
696 case bitc::COMDAT_SELECTION_KIND_ANY:
698 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
699 return Comdat::ExactMatch;
700 case bitc::COMDAT_SELECTION_KIND_LARGEST:
701 return Comdat::Largest;
702 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
703 return Comdat::NoDuplicates;
704 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
705 return Comdat::SameSize;
709 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
711 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
712 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
718 /// @brief A class for maintaining the slot number definition
719 /// as a placeholder for the actual definition for forward constants defs.
720 class ConstantPlaceHolder : public ConstantExpr {
721 void operator=(const ConstantPlaceHolder &) = delete;
723 // allocate space for exactly one operand
724 void *operator new(size_t s) {
725 return User::operator new(s, 1);
727 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
728 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
729 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
732 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
733 static bool classof(const Value *V) {
734 return isa<ConstantExpr>(V) &&
735 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
739 /// Provide fast operand accessors
740 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
744 // FIXME: can we inherit this from ConstantExpr?
746 struct OperandTraits<ConstantPlaceHolder> :
747 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
749 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
753 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
762 WeakVH &OldV = ValuePtrs[Idx];
768 // Handle constants and non-constants (e.g. instrs) differently for
770 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
771 ResolveConstants.push_back(std::make_pair(PHC, Idx));
774 // If there was a forward reference to this value, replace it.
775 Value *PrevVal = OldV;
776 OldV->replaceAllUsesWith(V);
782 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
787 if (Value *V = ValuePtrs[Idx]) {
788 assert(Ty == V->getType() && "Type mismatch in constant table!");
789 return cast<Constant>(V);
792 // Create and return a placeholder, which will later be RAUW'd.
793 Constant *C = new ConstantPlaceHolder(Ty, Context);
798 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
799 // Bail out for a clearly invalid value. This would make us call resize(0)
806 if (Value *V = ValuePtrs[Idx]) {
807 // If the types don't match, it's invalid.
808 if (Ty && Ty != V->getType())
813 // No type specified, must be invalid reference.
814 if (!Ty) return nullptr;
816 // Create and return a placeholder, which will later be RAUW'd.
817 Value *V = new Argument(Ty);
822 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
823 /// resolves any forward references. The idea behind this is that we sometimes
824 /// get constants (such as large arrays) which reference *many* forward ref
825 /// constants. Replacing each of these causes a lot of thrashing when
826 /// building/reuniquing the constant. Instead of doing this, we look at all the
827 /// uses and rewrite all the place holders at once for any constant that uses
829 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
830 // Sort the values by-pointer so that they are efficient to look up with a
832 std::sort(ResolveConstants.begin(), ResolveConstants.end());
834 SmallVector<Constant*, 64> NewOps;
836 while (!ResolveConstants.empty()) {
837 Value *RealVal = operator[](ResolveConstants.back().second);
838 Constant *Placeholder = ResolveConstants.back().first;
839 ResolveConstants.pop_back();
841 // Loop over all users of the placeholder, updating them to reference the
842 // new value. If they reference more than one placeholder, update them all
844 while (!Placeholder->use_empty()) {
845 auto UI = Placeholder->user_begin();
848 // If the using object isn't uniqued, just update the operands. This
849 // handles instructions and initializers for global variables.
850 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
851 UI.getUse().set(RealVal);
855 // Otherwise, we have a constant that uses the placeholder. Replace that
856 // constant with a new constant that has *all* placeholder uses updated.
857 Constant *UserC = cast<Constant>(U);
858 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
861 if (!isa<ConstantPlaceHolder>(*I)) {
862 // Not a placeholder reference.
864 } else if (*I == Placeholder) {
865 // Common case is that it just references this one placeholder.
868 // Otherwise, look up the placeholder in ResolveConstants.
869 ResolveConstantsTy::iterator It =
870 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
871 std::pair<Constant*, unsigned>(cast<Constant>(*I),
873 assert(It != ResolveConstants.end() && It->first == *I);
874 NewOp = operator[](It->second);
877 NewOps.push_back(cast<Constant>(NewOp));
880 // Make the new constant.
882 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
883 NewC = ConstantArray::get(UserCA->getType(), NewOps);
884 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
885 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
886 } else if (isa<ConstantVector>(UserC)) {
887 NewC = ConstantVector::get(NewOps);
889 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
890 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
893 UserC->replaceAllUsesWith(NewC);
894 UserC->destroyConstant();
898 // Update all ValueHandles, they should be the only users at this point.
899 Placeholder->replaceAllUsesWith(RealVal);
904 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
913 TrackingMDRef &OldMD = MDValuePtrs[Idx];
919 // If there was a forward reference to this value, replace it.
920 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
921 PrevMD->replaceAllUsesWith(MD);
925 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
929 if (Metadata *MD = MDValuePtrs[Idx])
932 // Track forward refs to be resolved later.
934 MinFwdRef = std::min(MinFwdRef, Idx);
935 MaxFwdRef = std::max(MaxFwdRef, Idx);
938 MinFwdRef = MaxFwdRef = Idx;
942 // Create and return a placeholder, which will later be RAUW'd.
943 Metadata *MD = MDNode::getTemporary(Context, None).release();
944 MDValuePtrs[Idx].reset(MD);
948 void BitcodeReaderMDValueList::tryToResolveCycles() {
954 // Still forward references... can't resolve cycles.
957 // Resolve any cycles.
958 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
959 auto &MD = MDValuePtrs[I];
960 auto *N = dyn_cast_or_null<MDNode>(MD);
964 assert(!N->isTemporary() && "Unexpected forward reference");
968 // Make sure we return early again until there's another forward ref.
972 Type *BitcodeReader::getTypeByID(unsigned ID) {
973 // The type table size is always specified correctly.
974 if (ID >= TypeList.size())
977 if (Type *Ty = TypeList[ID])
980 // If we have a forward reference, the only possible case is when it is to a
981 // named struct. Just create a placeholder for now.
982 return TypeList[ID] = createIdentifiedStructType(Context);
985 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
987 auto *Ret = StructType::create(Context, Name);
988 IdentifiedStructTypes.push_back(Ret);
992 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
993 auto *Ret = StructType::create(Context);
994 IdentifiedStructTypes.push_back(Ret);
999 //===----------------------------------------------------------------------===//
1000 // Functions for parsing blocks from the bitcode file
1001 //===----------------------------------------------------------------------===//
1004 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1005 /// been decoded from the given integer. This function must stay in sync with
1006 /// 'encodeLLVMAttributesForBitcode'.
1007 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1008 uint64_t EncodedAttrs) {
1009 // FIXME: Remove in 4.0.
1011 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1012 // the bits above 31 down by 11 bits.
1013 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1014 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1015 "Alignment must be a power of two.");
1018 B.addAlignmentAttr(Alignment);
1019 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1020 (EncodedAttrs & 0xffff));
1023 std::error_code BitcodeReader::ParseAttributeBlock() {
1024 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1025 return Error("Invalid record");
1027 if (!MAttributes.empty())
1028 return Error("Invalid multiple blocks");
1030 SmallVector<uint64_t, 64> Record;
1032 SmallVector<AttributeSet, 8> Attrs;
1034 // Read all the records.
1036 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1038 switch (Entry.Kind) {
1039 case BitstreamEntry::SubBlock: // Handled for us already.
1040 case BitstreamEntry::Error:
1041 return Error("Malformed block");
1042 case BitstreamEntry::EndBlock:
1043 return std::error_code();
1044 case BitstreamEntry::Record:
1045 // The interesting case.
1051 switch (Stream.readRecord(Entry.ID, Record)) {
1052 default: // Default behavior: ignore.
1054 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1055 // FIXME: Remove in 4.0.
1056 if (Record.size() & 1)
1057 return Error("Invalid record");
1059 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1061 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1062 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1065 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1069 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1070 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1071 Attrs.push_back(MAttributeGroups[Record[i]]);
1073 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1081 // Returns Attribute::None on unrecognized codes.
1082 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1085 return Attribute::None;
1086 case bitc::ATTR_KIND_ALIGNMENT:
1087 return Attribute::Alignment;
1088 case bitc::ATTR_KIND_ALWAYS_INLINE:
1089 return Attribute::AlwaysInline;
1090 case bitc::ATTR_KIND_BUILTIN:
1091 return Attribute::Builtin;
1092 case bitc::ATTR_KIND_BY_VAL:
1093 return Attribute::ByVal;
1094 case bitc::ATTR_KIND_IN_ALLOCA:
1095 return Attribute::InAlloca;
1096 case bitc::ATTR_KIND_COLD:
1097 return Attribute::Cold;
1098 case bitc::ATTR_KIND_INLINE_HINT:
1099 return Attribute::InlineHint;
1100 case bitc::ATTR_KIND_IN_REG:
1101 return Attribute::InReg;
1102 case bitc::ATTR_KIND_JUMP_TABLE:
1103 return Attribute::JumpTable;
1104 case bitc::ATTR_KIND_MIN_SIZE:
1105 return Attribute::MinSize;
1106 case bitc::ATTR_KIND_NAKED:
1107 return Attribute::Naked;
1108 case bitc::ATTR_KIND_NEST:
1109 return Attribute::Nest;
1110 case bitc::ATTR_KIND_NO_ALIAS:
1111 return Attribute::NoAlias;
1112 case bitc::ATTR_KIND_NO_BUILTIN:
1113 return Attribute::NoBuiltin;
1114 case bitc::ATTR_KIND_NO_CAPTURE:
1115 return Attribute::NoCapture;
1116 case bitc::ATTR_KIND_NO_DUPLICATE:
1117 return Attribute::NoDuplicate;
1118 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1119 return Attribute::NoImplicitFloat;
1120 case bitc::ATTR_KIND_NO_INLINE:
1121 return Attribute::NoInline;
1122 case bitc::ATTR_KIND_NON_LAZY_BIND:
1123 return Attribute::NonLazyBind;
1124 case bitc::ATTR_KIND_NON_NULL:
1125 return Attribute::NonNull;
1126 case bitc::ATTR_KIND_DEREFERENCEABLE:
1127 return Attribute::Dereferenceable;
1128 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1129 return Attribute::DereferenceableOrNull;
1130 case bitc::ATTR_KIND_NO_RED_ZONE:
1131 return Attribute::NoRedZone;
1132 case bitc::ATTR_KIND_NO_RETURN:
1133 return Attribute::NoReturn;
1134 case bitc::ATTR_KIND_NO_UNWIND:
1135 return Attribute::NoUnwind;
1136 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1137 return Attribute::OptimizeForSize;
1138 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1139 return Attribute::OptimizeNone;
1140 case bitc::ATTR_KIND_READ_NONE:
1141 return Attribute::ReadNone;
1142 case bitc::ATTR_KIND_READ_ONLY:
1143 return Attribute::ReadOnly;
1144 case bitc::ATTR_KIND_RETURNED:
1145 return Attribute::Returned;
1146 case bitc::ATTR_KIND_RETURNS_TWICE:
1147 return Attribute::ReturnsTwice;
1148 case bitc::ATTR_KIND_S_EXT:
1149 return Attribute::SExt;
1150 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1151 return Attribute::StackAlignment;
1152 case bitc::ATTR_KIND_STACK_PROTECT:
1153 return Attribute::StackProtect;
1154 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1155 return Attribute::StackProtectReq;
1156 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1157 return Attribute::StackProtectStrong;
1158 case bitc::ATTR_KIND_STRUCT_RET:
1159 return Attribute::StructRet;
1160 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1161 return Attribute::SanitizeAddress;
1162 case bitc::ATTR_KIND_SANITIZE_THREAD:
1163 return Attribute::SanitizeThread;
1164 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1165 return Attribute::SanitizeMemory;
1166 case bitc::ATTR_KIND_UW_TABLE:
1167 return Attribute::UWTable;
1168 case bitc::ATTR_KIND_Z_EXT:
1169 return Attribute::ZExt;
1173 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1174 unsigned &Alignment) {
1175 // Note: Alignment in bitcode files is incremented by 1, so that zero
1176 // can be used for default alignment.
1177 if (Exponent > Value::MaxAlignmentExponent + 1)
1178 return Error("Invalid alignment value");
1179 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1180 return std::error_code();
1183 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1184 Attribute::AttrKind *Kind) {
1185 *Kind = GetAttrFromCode(Code);
1186 if (*Kind == Attribute::None)
1187 return Error(BitcodeError::CorruptedBitcode,
1188 "Unknown attribute kind (" + Twine(Code) + ")");
1189 return std::error_code();
1192 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
1193 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1194 return Error("Invalid record");
1196 if (!MAttributeGroups.empty())
1197 return Error("Invalid multiple blocks");
1199 SmallVector<uint64_t, 64> Record;
1201 // Read all the records.
1203 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1205 switch (Entry.Kind) {
1206 case BitstreamEntry::SubBlock: // Handled for us already.
1207 case BitstreamEntry::Error:
1208 return Error("Malformed block");
1209 case BitstreamEntry::EndBlock:
1210 return std::error_code();
1211 case BitstreamEntry::Record:
1212 // The interesting case.
1218 switch (Stream.readRecord(Entry.ID, Record)) {
1219 default: // Default behavior: ignore.
1221 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1222 if (Record.size() < 3)
1223 return Error("Invalid record");
1225 uint64_t GrpID = Record[0];
1226 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1229 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1230 if (Record[i] == 0) { // Enum attribute
1231 Attribute::AttrKind Kind;
1232 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1235 B.addAttribute(Kind);
1236 } else if (Record[i] == 1) { // Integer attribute
1237 Attribute::AttrKind Kind;
1238 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1240 if (Kind == Attribute::Alignment)
1241 B.addAlignmentAttr(Record[++i]);
1242 else if (Kind == Attribute::StackAlignment)
1243 B.addStackAlignmentAttr(Record[++i]);
1244 else if (Kind == Attribute::Dereferenceable)
1245 B.addDereferenceableAttr(Record[++i]);
1246 else if (Kind == Attribute::DereferenceableOrNull)
1247 B.addDereferenceableOrNullAttr(Record[++i]);
1248 } else { // String attribute
1249 assert((Record[i] == 3 || Record[i] == 4) &&
1250 "Invalid attribute group entry");
1251 bool HasValue = (Record[i++] == 4);
1252 SmallString<64> KindStr;
1253 SmallString<64> ValStr;
1255 while (Record[i] != 0 && i != e)
1256 KindStr += Record[i++];
1257 assert(Record[i] == 0 && "Kind string not null terminated");
1260 // Has a value associated with it.
1261 ++i; // Skip the '0' that terminates the "kind" string.
1262 while (Record[i] != 0 && i != e)
1263 ValStr += Record[i++];
1264 assert(Record[i] == 0 && "Value string not null terminated");
1267 B.addAttribute(KindStr.str(), ValStr.str());
1271 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1278 std::error_code BitcodeReader::ParseTypeTable() {
1279 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1280 return Error("Invalid record");
1282 return ParseTypeTableBody();
1285 std::error_code BitcodeReader::ParseTypeTableBody() {
1286 if (!TypeList.empty())
1287 return Error("Invalid multiple blocks");
1289 SmallVector<uint64_t, 64> Record;
1290 unsigned NumRecords = 0;
1292 SmallString<64> TypeName;
1294 // Read all the records for this type table.
1296 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1298 switch (Entry.Kind) {
1299 case BitstreamEntry::SubBlock: // Handled for us already.
1300 case BitstreamEntry::Error:
1301 return Error("Malformed block");
1302 case BitstreamEntry::EndBlock:
1303 if (NumRecords != TypeList.size())
1304 return Error("Malformed block");
1305 return std::error_code();
1306 case BitstreamEntry::Record:
1307 // The interesting case.
1313 Type *ResultTy = nullptr;
1314 switch (Stream.readRecord(Entry.ID, Record)) {
1316 return Error("Invalid value");
1317 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1318 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1319 // type list. This allows us to reserve space.
1320 if (Record.size() < 1)
1321 return Error("Invalid record");
1322 TypeList.resize(Record[0]);
1324 case bitc::TYPE_CODE_VOID: // VOID
1325 ResultTy = Type::getVoidTy(Context);
1327 case bitc::TYPE_CODE_HALF: // HALF
1328 ResultTy = Type::getHalfTy(Context);
1330 case bitc::TYPE_CODE_FLOAT: // FLOAT
1331 ResultTy = Type::getFloatTy(Context);
1333 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1334 ResultTy = Type::getDoubleTy(Context);
1336 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1337 ResultTy = Type::getX86_FP80Ty(Context);
1339 case bitc::TYPE_CODE_FP128: // FP128
1340 ResultTy = Type::getFP128Ty(Context);
1342 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1343 ResultTy = Type::getPPC_FP128Ty(Context);
1345 case bitc::TYPE_CODE_LABEL: // LABEL
1346 ResultTy = Type::getLabelTy(Context);
1348 case bitc::TYPE_CODE_METADATA: // METADATA
1349 ResultTy = Type::getMetadataTy(Context);
1351 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1352 ResultTy = Type::getX86_MMXTy(Context);
1354 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1355 if (Record.size() < 1)
1356 return Error("Invalid record");
1358 uint64_t NumBits = Record[0];
1359 if (NumBits < IntegerType::MIN_INT_BITS ||
1360 NumBits > IntegerType::MAX_INT_BITS)
1361 return Error("Bitwidth for integer type out of range");
1362 ResultTy = IntegerType::get(Context, NumBits);
1365 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1366 // [pointee type, address space]
1367 if (Record.size() < 1)
1368 return Error("Invalid record");
1369 unsigned AddressSpace = 0;
1370 if (Record.size() == 2)
1371 AddressSpace = Record[1];
1372 ResultTy = getTypeByID(Record[0]);
1374 !PointerType::isValidElementType(ResultTy))
1375 return Error("Invalid type");
1376 ResultTy = PointerType::get(ResultTy, AddressSpace);
1379 case bitc::TYPE_CODE_FUNCTION_OLD: {
1380 // FIXME: attrid is dead, remove it in LLVM 4.0
1381 // FUNCTION: [vararg, attrid, retty, paramty x N]
1382 if (Record.size() < 3)
1383 return Error("Invalid record");
1384 SmallVector<Type*, 8> ArgTys;
1385 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1386 if (Type *T = getTypeByID(Record[i]))
1387 ArgTys.push_back(T);
1392 ResultTy = getTypeByID(Record[2]);
1393 if (!ResultTy || ArgTys.size() < Record.size()-3)
1394 return Error("Invalid type");
1396 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1399 case bitc::TYPE_CODE_FUNCTION: {
1400 // FUNCTION: [vararg, retty, paramty x N]
1401 if (Record.size() < 2)
1402 return Error("Invalid record");
1403 SmallVector<Type*, 8> ArgTys;
1404 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1405 if (Type *T = getTypeByID(Record[i])) {
1406 if (!FunctionType::isValidArgumentType(T))
1407 return Error("Invalid function argument type");
1408 ArgTys.push_back(T);
1414 ResultTy = getTypeByID(Record[1]);
1415 if (!ResultTy || ArgTys.size() < Record.size()-2)
1416 return Error("Invalid type");
1418 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1421 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1422 if (Record.size() < 1)
1423 return Error("Invalid record");
1424 SmallVector<Type*, 8> EltTys;
1425 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1426 if (Type *T = getTypeByID(Record[i]))
1427 EltTys.push_back(T);
1431 if (EltTys.size() != Record.size()-1)
1432 return Error("Invalid type");
1433 ResultTy = StructType::get(Context, EltTys, Record[0]);
1436 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1437 if (ConvertToString(Record, 0, TypeName))
1438 return Error("Invalid record");
1441 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1442 if (Record.size() < 1)
1443 return Error("Invalid record");
1445 if (NumRecords >= TypeList.size())
1446 return Error("Invalid TYPE table");
1448 // Check to see if this was forward referenced, if so fill in the temp.
1449 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1451 Res->setName(TypeName);
1452 TypeList[NumRecords] = nullptr;
1453 } else // Otherwise, create a new struct.
1454 Res = createIdentifiedStructType(Context, TypeName);
1457 SmallVector<Type*, 8> EltTys;
1458 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1459 if (Type *T = getTypeByID(Record[i]))
1460 EltTys.push_back(T);
1464 if (EltTys.size() != Record.size()-1)
1465 return Error("Invalid record");
1466 Res->setBody(EltTys, Record[0]);
1470 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1471 if (Record.size() != 1)
1472 return Error("Invalid record");
1474 if (NumRecords >= TypeList.size())
1475 return Error("Invalid TYPE table");
1477 // Check to see if this was forward referenced, if so fill in the temp.
1478 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1480 Res->setName(TypeName);
1481 TypeList[NumRecords] = nullptr;
1482 } else // Otherwise, create a new struct with no body.
1483 Res = createIdentifiedStructType(Context, TypeName);
1488 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1489 if (Record.size() < 2)
1490 return Error("Invalid record");
1491 ResultTy = getTypeByID(Record[1]);
1492 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1493 return Error("Invalid type");
1494 ResultTy = ArrayType::get(ResultTy, Record[0]);
1496 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1497 if (Record.size() < 2)
1498 return Error("Invalid record");
1499 ResultTy = getTypeByID(Record[1]);
1500 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1501 return Error("Invalid type");
1502 ResultTy = VectorType::get(ResultTy, Record[0]);
1506 if (NumRecords >= TypeList.size())
1507 return Error("Invalid TYPE table");
1508 if (TypeList[NumRecords])
1510 "Invalid TYPE table: Only named structs can be forward referenced");
1511 assert(ResultTy && "Didn't read a type?");
1512 TypeList[NumRecords++] = ResultTy;
1516 std::error_code BitcodeReader::ParseValueSymbolTable() {
1517 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1518 return Error("Invalid record");
1520 SmallVector<uint64_t, 64> Record;
1522 Triple TT(TheModule->getTargetTriple());
1524 // Read all the records for this value table.
1525 SmallString<128> ValueName;
1527 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1529 switch (Entry.Kind) {
1530 case BitstreamEntry::SubBlock: // Handled for us already.
1531 case BitstreamEntry::Error:
1532 return Error("Malformed block");
1533 case BitstreamEntry::EndBlock:
1534 return std::error_code();
1535 case BitstreamEntry::Record:
1536 // The interesting case.
1542 switch (Stream.readRecord(Entry.ID, Record)) {
1543 default: // Default behavior: unknown type.
1545 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1546 if (ConvertToString(Record, 1, ValueName))
1547 return Error("Invalid record");
1548 unsigned ValueID = Record[0];
1549 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1550 return Error("Invalid record");
1551 Value *V = ValueList[ValueID];
1553 V->setName(StringRef(ValueName.data(), ValueName.size()));
1554 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1555 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1556 if (TT.isOSBinFormatMachO())
1557 GO->setComdat(nullptr);
1559 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1565 case bitc::VST_CODE_BBENTRY: {
1566 if (ConvertToString(Record, 1, ValueName))
1567 return Error("Invalid record");
1568 BasicBlock *BB = getBasicBlock(Record[0]);
1570 return Error("Invalid record");
1572 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1580 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1582 std::error_code BitcodeReader::ParseMetadata() {
1583 IsMetadataMaterialized = true;
1584 unsigned NextMDValueNo = MDValueList.size();
1586 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1587 return Error("Invalid record");
1589 SmallVector<uint64_t, 64> Record;
1592 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1593 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1595 return getMD(ID - 1);
1598 auto getMDString = [&](unsigned ID) -> MDString *{
1599 // This requires that the ID is not really a forward reference. In
1600 // particular, the MDString must already have been resolved.
1601 return cast_or_null<MDString>(getMDOrNull(ID));
1604 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1605 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1607 // Read all the records.
1609 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1611 switch (Entry.Kind) {
1612 case BitstreamEntry::SubBlock: // Handled for us already.
1613 case BitstreamEntry::Error:
1614 return Error("Malformed block");
1615 case BitstreamEntry::EndBlock:
1616 MDValueList.tryToResolveCycles();
1617 return std::error_code();
1618 case BitstreamEntry::Record:
1619 // The interesting case.
1625 unsigned Code = Stream.readRecord(Entry.ID, Record);
1626 bool IsDistinct = false;
1628 default: // Default behavior: ignore.
1630 case bitc::METADATA_NAME: {
1631 // Read name of the named metadata.
1632 SmallString<8> Name(Record.begin(), Record.end());
1634 Code = Stream.ReadCode();
1636 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1637 unsigned NextBitCode = Stream.readRecord(Code, Record);
1638 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1640 // Read named metadata elements.
1641 unsigned Size = Record.size();
1642 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1643 for (unsigned i = 0; i != Size; ++i) {
1644 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1646 return Error("Invalid record");
1647 NMD->addOperand(MD);
1651 case bitc::METADATA_OLD_FN_NODE: {
1652 // FIXME: Remove in 4.0.
1653 // This is a LocalAsMetadata record, the only type of function-local
1655 if (Record.size() % 2 == 1)
1656 return Error("Invalid record");
1658 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1659 // to be legal, but there's no upgrade path.
1660 auto dropRecord = [&] {
1661 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1663 if (Record.size() != 2) {
1668 Type *Ty = getTypeByID(Record[0]);
1669 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1674 MDValueList.AssignValue(
1675 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1679 case bitc::METADATA_OLD_NODE: {
1680 // FIXME: Remove in 4.0.
1681 if (Record.size() % 2 == 1)
1682 return Error("Invalid record");
1684 unsigned Size = Record.size();
1685 SmallVector<Metadata *, 8> Elts;
1686 for (unsigned i = 0; i != Size; i += 2) {
1687 Type *Ty = getTypeByID(Record[i]);
1689 return Error("Invalid record");
1690 if (Ty->isMetadataTy())
1691 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1692 else if (!Ty->isVoidTy()) {
1694 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1695 assert(isa<ConstantAsMetadata>(MD) &&
1696 "Expected non-function-local metadata");
1699 Elts.push_back(nullptr);
1701 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1704 case bitc::METADATA_VALUE: {
1705 if (Record.size() != 2)
1706 return Error("Invalid record");
1708 Type *Ty = getTypeByID(Record[0]);
1709 if (Ty->isMetadataTy() || Ty->isVoidTy())
1710 return Error("Invalid record");
1712 MDValueList.AssignValue(
1713 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1717 case bitc::METADATA_DISTINCT_NODE:
1720 case bitc::METADATA_NODE: {
1721 SmallVector<Metadata *, 8> Elts;
1722 Elts.reserve(Record.size());
1723 for (unsigned ID : Record)
1724 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1725 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1726 : MDNode::get(Context, Elts),
1730 case bitc::METADATA_LOCATION: {
1731 if (Record.size() != 5)
1732 return Error("Invalid record");
1734 unsigned Line = Record[1];
1735 unsigned Column = Record[2];
1736 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1737 Metadata *InlinedAt =
1738 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1739 MDValueList.AssignValue(
1740 GET_OR_DISTINCT(DILocation, Record[0],
1741 (Context, Line, Column, Scope, InlinedAt)),
1745 case bitc::METADATA_GENERIC_DEBUG: {
1746 if (Record.size() < 4)
1747 return Error("Invalid record");
1749 unsigned Tag = Record[1];
1750 unsigned Version = Record[2];
1752 if (Tag >= 1u << 16 || Version != 0)
1753 return Error("Invalid record");
1755 auto *Header = getMDString(Record[3]);
1756 SmallVector<Metadata *, 8> DwarfOps;
1757 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1758 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1760 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1761 (Context, Tag, Header, DwarfOps)),
1765 case bitc::METADATA_SUBRANGE: {
1766 if (Record.size() != 3)
1767 return Error("Invalid record");
1769 MDValueList.AssignValue(
1770 GET_OR_DISTINCT(DISubrange, Record[0],
1771 (Context, Record[1], unrotateSign(Record[2]))),
1775 case bitc::METADATA_ENUMERATOR: {
1776 if (Record.size() != 3)
1777 return Error("Invalid record");
1779 MDValueList.AssignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1780 (Context, unrotateSign(Record[1]),
1781 getMDString(Record[2]))),
1785 case bitc::METADATA_BASIC_TYPE: {
1786 if (Record.size() != 6)
1787 return Error("Invalid record");
1789 MDValueList.AssignValue(
1790 GET_OR_DISTINCT(DIBasicType, Record[0],
1791 (Context, Record[1], getMDString(Record[2]),
1792 Record[3], Record[4], Record[5])),
1796 case bitc::METADATA_DERIVED_TYPE: {
1797 if (Record.size() != 12)
1798 return Error("Invalid record");
1800 MDValueList.AssignValue(
1801 GET_OR_DISTINCT(DIDerivedType, Record[0],
1802 (Context, Record[1], getMDString(Record[2]),
1803 getMDOrNull(Record[3]), Record[4],
1804 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1805 Record[7], Record[8], Record[9], Record[10],
1806 getMDOrNull(Record[11]))),
1810 case bitc::METADATA_COMPOSITE_TYPE: {
1811 if (Record.size() != 16)
1812 return Error("Invalid record");
1814 MDValueList.AssignValue(
1815 GET_OR_DISTINCT(DICompositeType, Record[0],
1816 (Context, Record[1], getMDString(Record[2]),
1817 getMDOrNull(Record[3]), Record[4],
1818 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1819 Record[7], Record[8], Record[9], Record[10],
1820 getMDOrNull(Record[11]), Record[12],
1821 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1822 getMDString(Record[15]))),
1826 case bitc::METADATA_SUBROUTINE_TYPE: {
1827 if (Record.size() != 3)
1828 return Error("Invalid record");
1830 MDValueList.AssignValue(
1831 GET_OR_DISTINCT(DISubroutineType, Record[0],
1832 (Context, Record[1], getMDOrNull(Record[2]))),
1836 case bitc::METADATA_FILE: {
1837 if (Record.size() != 3)
1838 return Error("Invalid record");
1840 MDValueList.AssignValue(
1841 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1842 getMDString(Record[2]))),
1846 case bitc::METADATA_COMPILE_UNIT: {
1847 if (Record.size() != 14)
1848 return Error("Invalid record");
1850 MDValueList.AssignValue(
1851 GET_OR_DISTINCT(DICompileUnit, Record[0],
1852 (Context, Record[1], getMDOrNull(Record[2]),
1853 getMDString(Record[3]), Record[4],
1854 getMDString(Record[5]), Record[6],
1855 getMDString(Record[7]), Record[8],
1856 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1857 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1858 getMDOrNull(Record[13]))),
1862 case bitc::METADATA_SUBPROGRAM: {
1863 if (Record.size() != 19)
1864 return Error("Invalid record");
1866 MDValueList.AssignValue(
1868 DISubprogram, Record[0],
1869 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1870 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1871 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1872 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1873 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1874 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1878 case bitc::METADATA_LEXICAL_BLOCK: {
1879 if (Record.size() != 5)
1880 return Error("Invalid record");
1882 MDValueList.AssignValue(
1883 GET_OR_DISTINCT(DILexicalBlock, Record[0],
1884 (Context, getMDOrNull(Record[1]),
1885 getMDOrNull(Record[2]), Record[3], Record[4])),
1889 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1890 if (Record.size() != 4)
1891 return Error("Invalid record");
1893 MDValueList.AssignValue(
1894 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1895 (Context, getMDOrNull(Record[1]),
1896 getMDOrNull(Record[2]), Record[3])),
1900 case bitc::METADATA_NAMESPACE: {
1901 if (Record.size() != 5)
1902 return Error("Invalid record");
1904 MDValueList.AssignValue(
1905 GET_OR_DISTINCT(DINamespace, Record[0],
1906 (Context, getMDOrNull(Record[1]),
1907 getMDOrNull(Record[2]), getMDString(Record[3]),
1912 case bitc::METADATA_TEMPLATE_TYPE: {
1913 if (Record.size() != 3)
1914 return Error("Invalid record");
1916 MDValueList.AssignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1918 (Context, getMDString(Record[1]),
1919 getMDOrNull(Record[2]))),
1923 case bitc::METADATA_TEMPLATE_VALUE: {
1924 if (Record.size() != 5)
1925 return Error("Invalid record");
1927 MDValueList.AssignValue(
1928 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1929 (Context, Record[1], getMDString(Record[2]),
1930 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1934 case bitc::METADATA_GLOBAL_VAR: {
1935 if (Record.size() != 11)
1936 return Error("Invalid record");
1938 MDValueList.AssignValue(
1939 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1940 (Context, getMDOrNull(Record[1]),
1941 getMDString(Record[2]), getMDString(Record[3]),
1942 getMDOrNull(Record[4]), Record[5],
1943 getMDOrNull(Record[6]), Record[7], Record[8],
1944 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1948 case bitc::METADATA_LOCAL_VAR: {
1949 // 10th field is for the obseleted 'inlinedAt:' field.
1950 if (Record.size() != 9 && Record.size() != 10)
1951 return Error("Invalid record");
1953 MDValueList.AssignValue(
1954 GET_OR_DISTINCT(DILocalVariable, Record[0],
1955 (Context, Record[1], getMDOrNull(Record[2]),
1956 getMDString(Record[3]), getMDOrNull(Record[4]),
1957 Record[5], getMDOrNull(Record[6]), Record[7],
1962 case bitc::METADATA_EXPRESSION: {
1963 if (Record.size() < 1)
1964 return Error("Invalid record");
1966 MDValueList.AssignValue(
1967 GET_OR_DISTINCT(DIExpression, Record[0],
1968 (Context, makeArrayRef(Record).slice(1))),
1972 case bitc::METADATA_OBJC_PROPERTY: {
1973 if (Record.size() != 8)
1974 return Error("Invalid record");
1976 MDValueList.AssignValue(
1977 GET_OR_DISTINCT(DIObjCProperty, Record[0],
1978 (Context, getMDString(Record[1]),
1979 getMDOrNull(Record[2]), Record[3],
1980 getMDString(Record[4]), getMDString(Record[5]),
1981 Record[6], getMDOrNull(Record[7]))),
1985 case bitc::METADATA_IMPORTED_ENTITY: {
1986 if (Record.size() != 6)
1987 return Error("Invalid record");
1989 MDValueList.AssignValue(
1990 GET_OR_DISTINCT(DIImportedEntity, Record[0],
1991 (Context, Record[1], getMDOrNull(Record[2]),
1992 getMDOrNull(Record[3]), Record[4],
1993 getMDString(Record[5]))),
1997 case bitc::METADATA_STRING: {
1998 std::string String(Record.begin(), Record.end());
1999 llvm::UpgradeMDStringConstant(String);
2000 Metadata *MD = MDString::get(Context, String);
2001 MDValueList.AssignValue(MD, NextMDValueNo++);
2004 case bitc::METADATA_KIND: {
2005 if (Record.size() < 2)
2006 return Error("Invalid record");
2008 unsigned Kind = Record[0];
2009 SmallString<8> Name(Record.begin()+1, Record.end());
2011 unsigned NewKind = TheModule->getMDKindID(Name.str());
2012 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2013 return Error("Conflicting METADATA_KIND records");
2018 #undef GET_OR_DISTINCT
2021 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
2022 /// the LSB for dense VBR encoding.
2023 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2028 // There is no such thing as -0 with integers. "-0" really means MININT.
2032 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
2033 /// values and aliases that we can.
2034 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
2035 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2036 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2037 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2038 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2040 GlobalInitWorklist.swap(GlobalInits);
2041 AliasInitWorklist.swap(AliasInits);
2042 FunctionPrefixWorklist.swap(FunctionPrefixes);
2043 FunctionPrologueWorklist.swap(FunctionPrologues);
2045 while (!GlobalInitWorklist.empty()) {
2046 unsigned ValID = GlobalInitWorklist.back().second;
2047 if (ValID >= ValueList.size()) {
2048 // Not ready to resolve this yet, it requires something later in the file.
2049 GlobalInits.push_back(GlobalInitWorklist.back());
2051 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2052 GlobalInitWorklist.back().first->setInitializer(C);
2054 return Error("Expected a constant");
2056 GlobalInitWorklist.pop_back();
2059 while (!AliasInitWorklist.empty()) {
2060 unsigned ValID = AliasInitWorklist.back().second;
2061 if (ValID >= ValueList.size()) {
2062 AliasInits.push_back(AliasInitWorklist.back());
2064 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2065 AliasInitWorklist.back().first->setAliasee(C);
2067 return Error("Expected a constant");
2069 AliasInitWorklist.pop_back();
2072 while (!FunctionPrefixWorklist.empty()) {
2073 unsigned ValID = FunctionPrefixWorklist.back().second;
2074 if (ValID >= ValueList.size()) {
2075 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2077 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2078 FunctionPrefixWorklist.back().first->setPrefixData(C);
2080 return Error("Expected a constant");
2082 FunctionPrefixWorklist.pop_back();
2085 while (!FunctionPrologueWorklist.empty()) {
2086 unsigned ValID = FunctionPrologueWorklist.back().second;
2087 if (ValID >= ValueList.size()) {
2088 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2090 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2091 FunctionPrologueWorklist.back().first->setPrologueData(C);
2093 return Error("Expected a constant");
2095 FunctionPrologueWorklist.pop_back();
2098 return std::error_code();
2101 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2102 SmallVector<uint64_t, 8> Words(Vals.size());
2103 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2104 BitcodeReader::decodeSignRotatedValue);
2106 return APInt(TypeBits, Words);
2109 std::error_code BitcodeReader::ParseConstants() {
2110 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2111 return Error("Invalid record");
2113 SmallVector<uint64_t, 64> Record;
2115 // Read all the records for this value table.
2116 Type *CurTy = Type::getInt32Ty(Context);
2117 unsigned NextCstNo = ValueList.size();
2119 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2121 switch (Entry.Kind) {
2122 case BitstreamEntry::SubBlock: // Handled for us already.
2123 case BitstreamEntry::Error:
2124 return Error("Malformed block");
2125 case BitstreamEntry::EndBlock:
2126 if (NextCstNo != ValueList.size())
2127 return Error("Invalid ronstant reference");
2129 // Once all the constants have been read, go through and resolve forward
2131 ValueList.ResolveConstantForwardRefs();
2132 return std::error_code();
2133 case BitstreamEntry::Record:
2134 // The interesting case.
2141 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2143 default: // Default behavior: unknown constant
2144 case bitc::CST_CODE_UNDEF: // UNDEF
2145 V = UndefValue::get(CurTy);
2147 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2149 return Error("Invalid record");
2150 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2151 return Error("Invalid record");
2152 CurTy = TypeList[Record[0]];
2153 continue; // Skip the ValueList manipulation.
2154 case bitc::CST_CODE_NULL: // NULL
2155 V = Constant::getNullValue(CurTy);
2157 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2158 if (!CurTy->isIntegerTy() || Record.empty())
2159 return Error("Invalid record");
2160 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2162 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2163 if (!CurTy->isIntegerTy() || Record.empty())
2164 return Error("Invalid record");
2166 APInt VInt = ReadWideAPInt(Record,
2167 cast<IntegerType>(CurTy)->getBitWidth());
2168 V = ConstantInt::get(Context, VInt);
2172 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2174 return Error("Invalid record");
2175 if (CurTy->isHalfTy())
2176 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2177 APInt(16, (uint16_t)Record[0])));
2178 else if (CurTy->isFloatTy())
2179 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2180 APInt(32, (uint32_t)Record[0])));
2181 else if (CurTy->isDoubleTy())
2182 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2183 APInt(64, Record[0])));
2184 else if (CurTy->isX86_FP80Ty()) {
2185 // Bits are not stored the same way as a normal i80 APInt, compensate.
2186 uint64_t Rearrange[2];
2187 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2188 Rearrange[1] = Record[0] >> 48;
2189 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2190 APInt(80, Rearrange)));
2191 } else if (CurTy->isFP128Ty())
2192 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2193 APInt(128, Record)));
2194 else if (CurTy->isPPC_FP128Ty())
2195 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2196 APInt(128, Record)));
2198 V = UndefValue::get(CurTy);
2202 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2204 return Error("Invalid record");
2206 unsigned Size = Record.size();
2207 SmallVector<Constant*, 16> Elts;
2209 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2210 for (unsigned i = 0; i != Size; ++i)
2211 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2212 STy->getElementType(i)));
2213 V = ConstantStruct::get(STy, Elts);
2214 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2215 Type *EltTy = ATy->getElementType();
2216 for (unsigned i = 0; i != Size; ++i)
2217 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2218 V = ConstantArray::get(ATy, Elts);
2219 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2220 Type *EltTy = VTy->getElementType();
2221 for (unsigned i = 0; i != Size; ++i)
2222 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2223 V = ConstantVector::get(Elts);
2225 V = UndefValue::get(CurTy);
2229 case bitc::CST_CODE_STRING: // STRING: [values]
2230 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2232 return Error("Invalid record");
2234 SmallString<16> Elts(Record.begin(), Record.end());
2235 V = ConstantDataArray::getString(Context, Elts,
2236 BitCode == bitc::CST_CODE_CSTRING);
2239 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2241 return Error("Invalid record");
2243 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2244 unsigned Size = Record.size();
2246 if (EltTy->isIntegerTy(8)) {
2247 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2248 if (isa<VectorType>(CurTy))
2249 V = ConstantDataVector::get(Context, Elts);
2251 V = ConstantDataArray::get(Context, Elts);
2252 } else if (EltTy->isIntegerTy(16)) {
2253 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2254 if (isa<VectorType>(CurTy))
2255 V = ConstantDataVector::get(Context, Elts);
2257 V = ConstantDataArray::get(Context, Elts);
2258 } else if (EltTy->isIntegerTy(32)) {
2259 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2260 if (isa<VectorType>(CurTy))
2261 V = ConstantDataVector::get(Context, Elts);
2263 V = ConstantDataArray::get(Context, Elts);
2264 } else if (EltTy->isIntegerTy(64)) {
2265 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2266 if (isa<VectorType>(CurTy))
2267 V = ConstantDataVector::get(Context, Elts);
2269 V = ConstantDataArray::get(Context, Elts);
2270 } else if (EltTy->isFloatTy()) {
2271 SmallVector<float, 16> Elts(Size);
2272 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2273 if (isa<VectorType>(CurTy))
2274 V = ConstantDataVector::get(Context, Elts);
2276 V = ConstantDataArray::get(Context, Elts);
2277 } else if (EltTy->isDoubleTy()) {
2278 SmallVector<double, 16> Elts(Size);
2279 std::transform(Record.begin(), Record.end(), Elts.begin(),
2281 if (isa<VectorType>(CurTy))
2282 V = ConstantDataVector::get(Context, Elts);
2284 V = ConstantDataArray::get(Context, Elts);
2286 return Error("Invalid type for value");
2291 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2292 if (Record.size() < 3)
2293 return Error("Invalid record");
2294 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2296 V = UndefValue::get(CurTy); // Unknown binop.
2298 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2299 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2301 if (Record.size() >= 4) {
2302 if (Opc == Instruction::Add ||
2303 Opc == Instruction::Sub ||
2304 Opc == Instruction::Mul ||
2305 Opc == Instruction::Shl) {
2306 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2307 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2308 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2309 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2310 } else if (Opc == Instruction::SDiv ||
2311 Opc == Instruction::UDiv ||
2312 Opc == Instruction::LShr ||
2313 Opc == Instruction::AShr) {
2314 if (Record[3] & (1 << bitc::PEO_EXACT))
2315 Flags |= SDivOperator::IsExact;
2318 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2322 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2323 if (Record.size() < 3)
2324 return Error("Invalid record");
2325 int Opc = GetDecodedCastOpcode(Record[0]);
2327 V = UndefValue::get(CurTy); // Unknown cast.
2329 Type *OpTy = getTypeByID(Record[1]);
2331 return Error("Invalid record");
2332 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2333 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2334 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2338 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2339 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2341 Type *PointeeType = nullptr;
2342 if (Record.size() % 2)
2343 PointeeType = getTypeByID(Record[OpNum++]);
2344 SmallVector<Constant*, 16> Elts;
2345 while (OpNum != Record.size()) {
2346 Type *ElTy = getTypeByID(Record[OpNum++]);
2348 return Error("Invalid record");
2349 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2354 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2356 return Error("Explicit gep operator type does not match pointee type "
2357 "of pointer operand");
2359 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2360 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2362 bitc::CST_CODE_CE_INBOUNDS_GEP);
2365 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2366 if (Record.size() < 3)
2367 return Error("Invalid record");
2369 Type *SelectorTy = Type::getInt1Ty(Context);
2371 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2372 // vector. Otherwise, it must be a single bit.
2373 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2374 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2375 VTy->getNumElements());
2377 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2379 ValueList.getConstantFwdRef(Record[1],CurTy),
2380 ValueList.getConstantFwdRef(Record[2],CurTy));
2383 case bitc::CST_CODE_CE_EXTRACTELT
2384 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2385 if (Record.size() < 3)
2386 return Error("Invalid record");
2388 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2390 return Error("Invalid record");
2391 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2392 Constant *Op1 = nullptr;
2393 if (Record.size() == 4) {
2394 Type *IdxTy = getTypeByID(Record[2]);
2396 return Error("Invalid record");
2397 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2398 } else // TODO: Remove with llvm 4.0
2399 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2401 return Error("Invalid record");
2402 V = ConstantExpr::getExtractElement(Op0, Op1);
2405 case bitc::CST_CODE_CE_INSERTELT
2406 : { // CE_INSERTELT: [opval, opval, opty, opval]
2407 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2408 if (Record.size() < 3 || !OpTy)
2409 return Error("Invalid record");
2410 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2411 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2412 OpTy->getElementType());
2413 Constant *Op2 = nullptr;
2414 if (Record.size() == 4) {
2415 Type *IdxTy = getTypeByID(Record[2]);
2417 return Error("Invalid record");
2418 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2419 } else // TODO: Remove with llvm 4.0
2420 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2422 return Error("Invalid record");
2423 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2426 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2427 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2428 if (Record.size() < 3 || !OpTy)
2429 return Error("Invalid record");
2430 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2431 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2432 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2433 OpTy->getNumElements());
2434 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2435 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2438 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2439 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2441 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2442 if (Record.size() < 4 || !RTy || !OpTy)
2443 return Error("Invalid record");
2444 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2445 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2446 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2447 RTy->getNumElements());
2448 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2449 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2452 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2453 if (Record.size() < 4)
2454 return Error("Invalid record");
2455 Type *OpTy = getTypeByID(Record[0]);
2457 return Error("Invalid record");
2458 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2459 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2461 if (OpTy->isFPOrFPVectorTy())
2462 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2464 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2467 // This maintains backward compatibility, pre-asm dialect keywords.
2468 // FIXME: Remove with the 4.0 release.
2469 case bitc::CST_CODE_INLINEASM_OLD: {
2470 if (Record.size() < 2)
2471 return Error("Invalid record");
2472 std::string AsmStr, ConstrStr;
2473 bool HasSideEffects = Record[0] & 1;
2474 bool IsAlignStack = Record[0] >> 1;
2475 unsigned AsmStrSize = Record[1];
2476 if (2+AsmStrSize >= Record.size())
2477 return Error("Invalid record");
2478 unsigned ConstStrSize = Record[2+AsmStrSize];
2479 if (3+AsmStrSize+ConstStrSize > Record.size())
2480 return Error("Invalid record");
2482 for (unsigned i = 0; i != AsmStrSize; ++i)
2483 AsmStr += (char)Record[2+i];
2484 for (unsigned i = 0; i != ConstStrSize; ++i)
2485 ConstrStr += (char)Record[3+AsmStrSize+i];
2486 PointerType *PTy = cast<PointerType>(CurTy);
2487 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2488 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2491 // This version adds support for the asm dialect keywords (e.g.,
2493 case bitc::CST_CODE_INLINEASM: {
2494 if (Record.size() < 2)
2495 return Error("Invalid record");
2496 std::string AsmStr, ConstrStr;
2497 bool HasSideEffects = Record[0] & 1;
2498 bool IsAlignStack = (Record[0] >> 1) & 1;
2499 unsigned AsmDialect = Record[0] >> 2;
2500 unsigned AsmStrSize = Record[1];
2501 if (2+AsmStrSize >= Record.size())
2502 return Error("Invalid record");
2503 unsigned ConstStrSize = Record[2+AsmStrSize];
2504 if (3+AsmStrSize+ConstStrSize > Record.size())
2505 return Error("Invalid record");
2507 for (unsigned i = 0; i != AsmStrSize; ++i)
2508 AsmStr += (char)Record[2+i];
2509 for (unsigned i = 0; i != ConstStrSize; ++i)
2510 ConstrStr += (char)Record[3+AsmStrSize+i];
2511 PointerType *PTy = cast<PointerType>(CurTy);
2512 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2513 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2514 InlineAsm::AsmDialect(AsmDialect));
2517 case bitc::CST_CODE_BLOCKADDRESS:{
2518 if (Record.size() < 3)
2519 return Error("Invalid record");
2520 Type *FnTy = getTypeByID(Record[0]);
2522 return Error("Invalid record");
2524 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2526 return Error("Invalid record");
2528 // Don't let Fn get dematerialized.
2529 BlockAddressesTaken.insert(Fn);
2531 // If the function is already parsed we can insert the block address right
2534 unsigned BBID = Record[2];
2536 // Invalid reference to entry block.
2537 return Error("Invalid ID");
2539 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2540 for (size_t I = 0, E = BBID; I != E; ++I) {
2542 return Error("Invalid ID");
2547 // Otherwise insert a placeholder and remember it so it can be inserted
2548 // when the function is parsed.
2549 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2551 BasicBlockFwdRefQueue.push_back(Fn);
2552 if (FwdBBs.size() < BBID + 1)
2553 FwdBBs.resize(BBID + 1);
2555 FwdBBs[BBID] = BasicBlock::Create(Context);
2558 V = BlockAddress::get(Fn, BB);
2563 ValueList.AssignValue(V, NextCstNo);
2568 std::error_code BitcodeReader::ParseUseLists() {
2569 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2570 return Error("Invalid record");
2572 // Read all the records.
2573 SmallVector<uint64_t, 64> Record;
2575 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2577 switch (Entry.Kind) {
2578 case BitstreamEntry::SubBlock: // Handled for us already.
2579 case BitstreamEntry::Error:
2580 return Error("Malformed block");
2581 case BitstreamEntry::EndBlock:
2582 return std::error_code();
2583 case BitstreamEntry::Record:
2584 // The interesting case.
2588 // Read a use list record.
2591 switch (Stream.readRecord(Entry.ID, Record)) {
2592 default: // Default behavior: unknown type.
2594 case bitc::USELIST_CODE_BB:
2597 case bitc::USELIST_CODE_DEFAULT: {
2598 unsigned RecordLength = Record.size();
2599 if (RecordLength < 3)
2600 // Records should have at least an ID and two indexes.
2601 return Error("Invalid record");
2602 unsigned ID = Record.back();
2607 assert(ID < FunctionBBs.size() && "Basic block not found");
2608 V = FunctionBBs[ID];
2611 unsigned NumUses = 0;
2612 SmallDenseMap<const Use *, unsigned, 16> Order;
2613 for (const Use &U : V->uses()) {
2614 if (++NumUses > Record.size())
2616 Order[&U] = Record[NumUses - 1];
2618 if (Order.size() != Record.size() || NumUses > Record.size())
2619 // Mismatches can happen if the functions are being materialized lazily
2620 // (out-of-order), or a value has been upgraded.
2623 V->sortUseList([&](const Use &L, const Use &R) {
2624 return Order.lookup(&L) < Order.lookup(&R);
2632 /// When we see the block for metadata, remember where it is and then skip it.
2633 /// This lets us lazily deserialize the metadata.
2634 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2635 // Save the current stream state.
2636 uint64_t CurBit = Stream.GetCurrentBitNo();
2637 DeferredMetadataInfo.push_back(CurBit);
2639 // Skip over the block for now.
2640 if (Stream.SkipBlock())
2641 return Error("Invalid record");
2642 return std::error_code();
2645 std::error_code BitcodeReader::materializeMetadata() {
2646 for (uint64_t BitPos : DeferredMetadataInfo) {
2647 // Move the bit stream to the saved position.
2648 Stream.JumpToBit(BitPos);
2649 if (std::error_code EC = ParseMetadata())
2652 DeferredMetadataInfo.clear();
2653 return std::error_code();
2656 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2658 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2659 /// remember where it is and then skip it. This lets us lazily deserialize the
2661 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2662 // Get the function we are talking about.
2663 if (FunctionsWithBodies.empty())
2664 return Error("Insufficient function protos");
2666 Function *Fn = FunctionsWithBodies.back();
2667 FunctionsWithBodies.pop_back();
2669 // Save the current stream state.
2670 uint64_t CurBit = Stream.GetCurrentBitNo();
2671 DeferredFunctionInfo[Fn] = CurBit;
2673 // Skip over the function block for now.
2674 if (Stream.SkipBlock())
2675 return Error("Invalid record");
2676 return std::error_code();
2679 std::error_code BitcodeReader::GlobalCleanup() {
2680 // Patch the initializers for globals and aliases up.
2681 ResolveGlobalAndAliasInits();
2682 if (!GlobalInits.empty() || !AliasInits.empty())
2683 return Error("Malformed global initializer set");
2685 // Look for intrinsic functions which need to be upgraded at some point
2686 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2689 if (UpgradeIntrinsicFunction(FI, NewFn))
2690 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2693 // Look for global variables which need to be renamed.
2694 for (Module::global_iterator
2695 GI = TheModule->global_begin(), GE = TheModule->global_end();
2697 GlobalVariable *GV = GI++;
2698 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 (LazyStreamer && 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 assert(ComdatID <= ComdatList.size());
2959 NewGV->setComdat(ComdatList[ComdatID - 1]);
2961 } else if (hasImplicitComdat(RawLinkage)) {
2962 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2966 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2967 // alignment, section, visibility, gc, unnamed_addr,
2968 // prologuedata, dllstorageclass, comdat, prefixdata]
2969 case bitc::MODULE_CODE_FUNCTION: {
2970 if (Record.size() < 8)
2971 return Error("Invalid record");
2972 Type *Ty = getTypeByID(Record[0]);
2974 return Error("Invalid record");
2975 if (auto *PTy = dyn_cast<PointerType>(Ty))
2976 Ty = PTy->getElementType();
2977 auto *FTy = dyn_cast<FunctionType>(Ty);
2979 return Error("Invalid type for value");
2981 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2984 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2985 bool isProto = Record[2];
2986 uint64_t RawLinkage = Record[3];
2987 Func->setLinkage(getDecodedLinkage(RawLinkage));
2988 Func->setAttributes(getAttributes(Record[4]));
2991 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2993 Func->setAlignment(Alignment);
2995 if (Record[6]-1 >= SectionTable.size())
2996 return Error("Invalid ID");
2997 Func->setSection(SectionTable[Record[6]-1]);
2999 // Local linkage must have default visibility.
3000 if (!Func->hasLocalLinkage())
3001 // FIXME: Change to an error if non-default in 4.0.
3002 Func->setVisibility(GetDecodedVisibility(Record[7]));
3003 if (Record.size() > 8 && Record[8]) {
3004 if (Record[8]-1 >= GCTable.size())
3005 return Error("Invalid ID");
3006 Func->setGC(GCTable[Record[8]-1].c_str());
3008 bool UnnamedAddr = false;
3009 if (Record.size() > 9)
3010 UnnamedAddr = Record[9];
3011 Func->setUnnamedAddr(UnnamedAddr);
3012 if (Record.size() > 10 && Record[10] != 0)
3013 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3015 if (Record.size() > 11)
3016 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
3018 UpgradeDLLImportExportLinkage(Func, RawLinkage);
3020 if (Record.size() > 12) {
3021 if (unsigned ComdatID = Record[12]) {
3022 assert(ComdatID <= ComdatList.size());
3023 Func->setComdat(ComdatList[ComdatID - 1]);
3025 } else if (hasImplicitComdat(RawLinkage)) {
3026 Func->setComdat(reinterpret_cast<Comdat *>(1));
3029 if (Record.size() > 13 && Record[13] != 0)
3030 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3032 ValueList.push_back(Func);
3034 // If this is a function with a body, remember the prototype we are
3035 // creating now, so that we can match up the body with them later.
3037 Func->setIsMaterializable(true);
3038 FunctionsWithBodies.push_back(Func);
3040 DeferredFunctionInfo[Func] = 0;
3044 // ALIAS: [alias type, aliasee val#, linkage]
3045 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3046 case bitc::MODULE_CODE_ALIAS: {
3047 if (Record.size() < 3)
3048 return Error("Invalid record");
3049 Type *Ty = getTypeByID(Record[0]);
3051 return Error("Invalid record");
3052 auto *PTy = dyn_cast<PointerType>(Ty);
3054 return Error("Invalid type for value");
3057 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3058 // Old bitcode files didn't have visibility field.
3059 // Local linkage must have default visibility.
3060 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3061 // FIXME: Change to an error if non-default in 4.0.
3062 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3063 if (Record.size() > 4)
3064 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3066 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3067 if (Record.size() > 5)
3068 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3069 if (Record.size() > 6)
3070 NewGA->setUnnamedAddr(Record[6]);
3071 ValueList.push_back(NewGA);
3072 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3075 /// MODULE_CODE_PURGEVALS: [numvals]
3076 case bitc::MODULE_CODE_PURGEVALS:
3077 // Trim down the value list to the specified size.
3078 if (Record.size() < 1 || Record[0] > ValueList.size())
3079 return Error("Invalid record");
3080 ValueList.shrinkTo(Record[0]);
3087 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3088 bool ShouldLazyLoadMetadata) {
3089 TheModule = nullptr;
3091 if (std::error_code EC = InitStream())
3094 // Sniff for the signature.
3095 if (Stream.Read(8) != 'B' ||
3096 Stream.Read(8) != 'C' ||
3097 Stream.Read(4) != 0x0 ||
3098 Stream.Read(4) != 0xC ||
3099 Stream.Read(4) != 0xE ||
3100 Stream.Read(4) != 0xD)
3101 return Error("Invalid bitcode signature");
3103 // We expect a number of well-defined blocks, though we don't necessarily
3104 // need to understand them all.
3106 if (Stream.AtEndOfStream()) {
3108 return std::error_code();
3109 // We didn't really read a proper Module.
3110 return Error("Malformed IR file");
3113 BitstreamEntry Entry =
3114 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3116 switch (Entry.Kind) {
3117 case BitstreamEntry::Error:
3118 return Error("Malformed block");
3119 case BitstreamEntry::EndBlock:
3120 return std::error_code();
3122 case BitstreamEntry::SubBlock:
3124 case bitc::BLOCKINFO_BLOCK_ID:
3125 if (Stream.ReadBlockInfoBlock())
3126 return Error("Malformed block");
3128 case bitc::MODULE_BLOCK_ID:
3129 // Reject multiple MODULE_BLOCK's in a single bitstream.
3131 return Error("Invalid multiple blocks");
3133 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3136 return std::error_code();
3139 if (Stream.SkipBlock())
3140 return Error("Invalid record");
3144 case BitstreamEntry::Record:
3145 // There should be no records in the top-level of blocks.
3147 // The ranlib in Xcode 4 will align archive members by appending newlines
3148 // to the end of them. If this file size is a multiple of 4 but not 8, we
3149 // have to read and ignore these final 4 bytes :-(
3150 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3151 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3152 Stream.AtEndOfStream())
3153 return std::error_code();
3155 return Error("Invalid record");
3160 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3161 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3162 return Error("Invalid record");
3164 SmallVector<uint64_t, 64> Record;
3167 // Read all the records for this module.
3169 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3171 switch (Entry.Kind) {
3172 case BitstreamEntry::SubBlock: // Handled for us already.
3173 case BitstreamEntry::Error:
3174 return Error("Malformed block");
3175 case BitstreamEntry::EndBlock:
3177 case BitstreamEntry::Record:
3178 // The interesting case.
3183 switch (Stream.readRecord(Entry.ID, Record)) {
3184 default: break; // Default behavior, ignore unknown content.
3185 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3187 if (ConvertToString(Record, 0, S))
3188 return Error("Invalid record");
3195 llvm_unreachable("Exit infinite loop");
3198 ErrorOr<std::string> BitcodeReader::parseTriple() {
3199 if (std::error_code EC = InitStream())
3202 // Sniff for the signature.
3203 if (Stream.Read(8) != 'B' ||
3204 Stream.Read(8) != 'C' ||
3205 Stream.Read(4) != 0x0 ||
3206 Stream.Read(4) != 0xC ||
3207 Stream.Read(4) != 0xE ||
3208 Stream.Read(4) != 0xD)
3209 return Error("Invalid bitcode signature");
3211 // We expect a number of well-defined blocks, though we don't necessarily
3212 // need to understand them all.
3214 BitstreamEntry Entry = Stream.advance();
3216 switch (Entry.Kind) {
3217 case BitstreamEntry::Error:
3218 return Error("Malformed block");
3219 case BitstreamEntry::EndBlock:
3220 return std::error_code();
3222 case BitstreamEntry::SubBlock:
3223 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3224 return parseModuleTriple();
3226 // Ignore other sub-blocks.
3227 if (Stream.SkipBlock())
3228 return Error("Malformed block");
3231 case BitstreamEntry::Record:
3232 Stream.skipRecord(Entry.ID);
3238 /// ParseMetadataAttachment - Parse metadata attachments.
3239 std::error_code BitcodeReader::ParseMetadataAttachment(Function &F) {
3240 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3241 return Error("Invalid record");
3243 SmallVector<uint64_t, 64> Record;
3245 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3247 switch (Entry.Kind) {
3248 case BitstreamEntry::SubBlock: // Handled for us already.
3249 case BitstreamEntry::Error:
3250 return Error("Malformed block");
3251 case BitstreamEntry::EndBlock:
3252 return std::error_code();
3253 case BitstreamEntry::Record:
3254 // The interesting case.
3258 // Read a metadata attachment record.
3260 switch (Stream.readRecord(Entry.ID, Record)) {
3261 default: // Default behavior: ignore.
3263 case bitc::METADATA_ATTACHMENT: {
3264 unsigned RecordLength = Record.size();
3266 return Error("Invalid record");
3267 if (RecordLength % 2 == 0) {
3268 // A function attachment.
3269 for (unsigned I = 0; I != RecordLength; I += 2) {
3270 auto K = MDKindMap.find(Record[I]);
3271 if (K == MDKindMap.end())
3272 return Error("Invalid ID");
3273 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3274 F.setMetadata(K->second, cast<MDNode>(MD));
3279 // An instruction attachment.
3280 Instruction *Inst = InstructionList[Record[0]];
3281 for (unsigned i = 1; i != RecordLength; i = i+2) {
3282 unsigned Kind = Record[i];
3283 DenseMap<unsigned, unsigned>::iterator I =
3284 MDKindMap.find(Kind);
3285 if (I == MDKindMap.end())
3286 return Error("Invalid ID");
3287 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3288 if (isa<LocalAsMetadata>(Node))
3289 // Drop the attachment. This used to be legal, but there's no
3292 Inst->setMetadata(I->second, cast<MDNode>(Node));
3293 if (I->second == LLVMContext::MD_tbaa)
3294 InstsWithTBAATag.push_back(Inst);
3302 static std::error_code TypeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3303 Type *ValType, Type *PtrType) {
3304 if (!isa<PointerType>(PtrType))
3305 return Error(DH, "Load/Store operand is not a pointer type");
3306 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3308 if (ValType && ValType != ElemType)
3309 return Error(DH, "Explicit load/store type does not match pointee type of "
3311 if (!PointerType::isLoadableOrStorableType(ElemType))
3312 return Error(DH, "Cannot load/store from pointer");
3313 return std::error_code();
3316 /// ParseFunctionBody - Lazily parse the specified function body block.
3317 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3318 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3319 return Error("Invalid record");
3321 InstructionList.clear();
3322 unsigned ModuleValueListSize = ValueList.size();
3323 unsigned ModuleMDValueListSize = MDValueList.size();
3325 // Add all the function arguments to the value table.
3326 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3327 ValueList.push_back(I);
3329 unsigned NextValueNo = ValueList.size();
3330 BasicBlock *CurBB = nullptr;
3331 unsigned CurBBNo = 0;
3334 auto getLastInstruction = [&]() -> Instruction * {
3335 if (CurBB && !CurBB->empty())
3336 return &CurBB->back();
3337 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3338 !FunctionBBs[CurBBNo - 1]->empty())
3339 return &FunctionBBs[CurBBNo - 1]->back();
3343 // Read all the records.
3344 SmallVector<uint64_t, 64> Record;
3346 BitstreamEntry Entry = Stream.advance();
3348 switch (Entry.Kind) {
3349 case BitstreamEntry::Error:
3350 return Error("Malformed block");
3351 case BitstreamEntry::EndBlock:
3352 goto OutOfRecordLoop;
3354 case BitstreamEntry::SubBlock:
3356 default: // Skip unknown content.
3357 if (Stream.SkipBlock())
3358 return Error("Invalid record");
3360 case bitc::CONSTANTS_BLOCK_ID:
3361 if (std::error_code EC = ParseConstants())
3363 NextValueNo = ValueList.size();
3365 case bitc::VALUE_SYMTAB_BLOCK_ID:
3366 if (std::error_code EC = ParseValueSymbolTable())
3369 case bitc::METADATA_ATTACHMENT_ID:
3370 if (std::error_code EC = ParseMetadataAttachment(*F))
3373 case bitc::METADATA_BLOCK_ID:
3374 if (std::error_code EC = ParseMetadata())
3377 case bitc::USELIST_BLOCK_ID:
3378 if (std::error_code EC = ParseUseLists())
3384 case BitstreamEntry::Record:
3385 // The interesting case.
3391 Instruction *I = nullptr;
3392 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3394 default: // Default behavior: reject
3395 return Error("Invalid value");
3396 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3397 if (Record.size() < 1 || Record[0] == 0)
3398 return Error("Invalid record");
3399 // Create all the basic blocks for the function.
3400 FunctionBBs.resize(Record[0]);
3402 // See if anything took the address of blocks in this function.
3403 auto BBFRI = BasicBlockFwdRefs.find(F);
3404 if (BBFRI == BasicBlockFwdRefs.end()) {
3405 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3406 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3408 auto &BBRefs = BBFRI->second;
3409 // Check for invalid basic block references.
3410 if (BBRefs.size() > FunctionBBs.size())
3411 return Error("Invalid ID");
3412 assert(!BBRefs.empty() && "Unexpected empty array");
3413 assert(!BBRefs.front() && "Invalid reference to entry block");
3414 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3416 if (I < RE && BBRefs[I]) {
3417 BBRefs[I]->insertInto(F);
3418 FunctionBBs[I] = BBRefs[I];
3420 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3423 // Erase from the table.
3424 BasicBlockFwdRefs.erase(BBFRI);
3427 CurBB = FunctionBBs[0];
3431 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3432 // This record indicates that the last instruction is at the same
3433 // location as the previous instruction with a location.
3434 I = getLastInstruction();
3437 return Error("Invalid record");
3438 I->setDebugLoc(LastLoc);
3442 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3443 I = getLastInstruction();
3444 if (!I || Record.size() < 4)
3445 return Error("Invalid record");
3447 unsigned Line = Record[0], Col = Record[1];
3448 unsigned ScopeID = Record[2], IAID = Record[3];
3450 MDNode *Scope = nullptr, *IA = nullptr;
3451 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3452 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3453 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3454 I->setDebugLoc(LastLoc);
3459 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3462 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3463 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3464 OpNum+1 > Record.size())
3465 return Error("Invalid record");
3467 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3469 return Error("Invalid record");
3470 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3471 InstructionList.push_back(I);
3472 if (OpNum < Record.size()) {
3473 if (Opc == Instruction::Add ||
3474 Opc == Instruction::Sub ||
3475 Opc == Instruction::Mul ||
3476 Opc == Instruction::Shl) {
3477 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3478 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3479 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3480 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3481 } else if (Opc == Instruction::SDiv ||
3482 Opc == Instruction::UDiv ||
3483 Opc == Instruction::LShr ||
3484 Opc == Instruction::AShr) {
3485 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3486 cast<BinaryOperator>(I)->setIsExact(true);
3487 } else if (isa<FPMathOperator>(I)) {
3489 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3490 FMF.setUnsafeAlgebra();
3491 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3493 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3495 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3496 FMF.setNoSignedZeros();
3497 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3498 FMF.setAllowReciprocal();
3500 I->setFastMathFlags(FMF);
3506 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3509 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3510 OpNum+2 != Record.size())
3511 return Error("Invalid record");
3513 Type *ResTy = getTypeByID(Record[OpNum]);
3514 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3515 if (Opc == -1 || !ResTy)
3516 return Error("Invalid record");
3517 Instruction *Temp = nullptr;
3518 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3520 InstructionList.push_back(Temp);
3521 CurBB->getInstList().push_back(Temp);
3524 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3526 InstructionList.push_back(I);
3529 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3530 case bitc::FUNC_CODE_INST_GEP_OLD:
3531 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3537 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3538 InBounds = Record[OpNum++];
3539 Ty = getTypeByID(Record[OpNum++]);
3541 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3546 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3547 return Error("Invalid record");
3550 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3553 cast<SequentialType>(BasePtr->getType()->getScalarType())
3556 "Explicit gep type does not match pointee type of pointer operand");
3558 SmallVector<Value*, 16> GEPIdx;
3559 while (OpNum != Record.size()) {
3561 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3562 return Error("Invalid record");
3563 GEPIdx.push_back(Op);
3566 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3568 InstructionList.push_back(I);
3570 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3574 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3575 // EXTRACTVAL: [opty, opval, n x indices]
3578 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3579 return Error("Invalid record");
3581 unsigned RecSize = Record.size();
3582 if (OpNum == RecSize)
3583 return Error("EXTRACTVAL: Invalid instruction with 0 indices");
3585 SmallVector<unsigned, 4> EXTRACTVALIdx;
3586 Type *CurTy = Agg->getType();
3587 for (; OpNum != RecSize; ++OpNum) {
3588 bool IsArray = CurTy->isArrayTy();
3589 bool IsStruct = CurTy->isStructTy();
3590 uint64_t Index = Record[OpNum];
3592 if (!IsStruct && !IsArray)
3593 return Error("EXTRACTVAL: Invalid type");
3594 if ((unsigned)Index != Index)
3595 return Error("Invalid value");
3596 if (IsStruct && Index >= CurTy->subtypes().size())
3597 return Error("EXTRACTVAL: Invalid struct index");
3598 if (IsArray && Index >= CurTy->getArrayNumElements())
3599 return Error("EXTRACTVAL: Invalid array index");
3600 EXTRACTVALIdx.push_back((unsigned)Index);
3603 CurTy = CurTy->subtypes()[Index];
3605 CurTy = CurTy->subtypes()[0];
3608 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3609 InstructionList.push_back(I);
3613 case bitc::FUNC_CODE_INST_INSERTVAL: {
3614 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3617 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3618 return Error("Invalid record");
3620 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3621 return Error("Invalid record");
3623 unsigned RecSize = Record.size();
3624 if (OpNum == RecSize)
3625 return Error("INSERTVAL: Invalid instruction with 0 indices");
3627 SmallVector<unsigned, 4> INSERTVALIdx;
3628 Type *CurTy = Agg->getType();
3629 for (; OpNum != RecSize; ++OpNum) {
3630 bool IsArray = CurTy->isArrayTy();
3631 bool IsStruct = CurTy->isStructTy();
3632 uint64_t Index = Record[OpNum];
3634 if (!IsStruct && !IsArray)
3635 return Error("INSERTVAL: Invalid type");
3636 if ((unsigned)Index != Index)
3637 return Error("Invalid value");
3638 if (IsStruct && Index >= CurTy->subtypes().size())
3639 return Error("INSERTVAL: Invalid struct index");
3640 if (IsArray && Index >= CurTy->getArrayNumElements())
3641 return Error("INSERTVAL: Invalid array index");
3643 INSERTVALIdx.push_back((unsigned)Index);
3645 CurTy = CurTy->subtypes()[Index];
3647 CurTy = CurTy->subtypes()[0];
3650 if (CurTy != Val->getType())
3651 return Error("Inserted value type doesn't match aggregate type");
3653 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3654 InstructionList.push_back(I);
3658 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3659 // obsolete form of select
3660 // handles select i1 ... in old bitcode
3662 Value *TrueVal, *FalseVal, *Cond;
3663 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3664 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3665 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3666 return Error("Invalid record");
3668 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3669 InstructionList.push_back(I);
3673 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3674 // new form of select
3675 // handles select i1 or select [N x i1]
3677 Value *TrueVal, *FalseVal, *Cond;
3678 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3679 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3680 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3681 return Error("Invalid record");
3683 // select condition can be either i1 or [N x i1]
3684 if (VectorType* vector_type =
3685 dyn_cast<VectorType>(Cond->getType())) {
3687 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3688 return Error("Invalid type for value");
3691 if (Cond->getType() != Type::getInt1Ty(Context))
3692 return Error("Invalid type for value");
3695 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3696 InstructionList.push_back(I);
3700 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3703 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3704 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3705 return Error("Invalid record");
3706 if (!Vec->getType()->isVectorTy())
3707 return Error("Invalid type for value");
3708 I = ExtractElementInst::Create(Vec, Idx);
3709 InstructionList.push_back(I);
3713 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3715 Value *Vec, *Elt, *Idx;
3716 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3717 return Error("Invalid record");
3718 if (!Vec->getType()->isVectorTy())
3719 return Error("Invalid type for value");
3720 if (popValue(Record, OpNum, NextValueNo,
3721 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3722 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3723 return Error("Invalid record");
3724 I = InsertElementInst::Create(Vec, Elt, Idx);
3725 InstructionList.push_back(I);
3729 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3731 Value *Vec1, *Vec2, *Mask;
3732 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3733 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3734 return Error("Invalid record");
3736 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3737 return Error("Invalid record");
3738 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3739 return Error("Invalid type for value");
3740 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3741 InstructionList.push_back(I);
3745 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3746 // Old form of ICmp/FCmp returning bool
3747 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3748 // both legal on vectors but had different behaviour.
3749 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3750 // FCmp/ICmp returning bool or vector of bool
3754 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3755 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3756 OpNum+1 != Record.size())
3757 return Error("Invalid record");
3759 if (LHS->getType()->isFPOrFPVectorTy())
3760 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3762 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3763 InstructionList.push_back(I);
3767 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3769 unsigned Size = Record.size();
3771 I = ReturnInst::Create(Context);
3772 InstructionList.push_back(I);
3777 Value *Op = nullptr;
3778 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3779 return Error("Invalid record");
3780 if (OpNum != Record.size())
3781 return Error("Invalid record");
3783 I = ReturnInst::Create(Context, Op);
3784 InstructionList.push_back(I);
3787 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3788 if (Record.size() != 1 && Record.size() != 3)
3789 return Error("Invalid record");
3790 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3792 return Error("Invalid record");
3794 if (Record.size() == 1) {
3795 I = BranchInst::Create(TrueDest);
3796 InstructionList.push_back(I);
3799 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3800 Value *Cond = getValue(Record, 2, NextValueNo,
3801 Type::getInt1Ty(Context));
3802 if (!FalseDest || !Cond)
3803 return Error("Invalid record");
3804 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3805 InstructionList.push_back(I);
3809 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3811 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3812 // "New" SwitchInst format with case ranges. The changes to write this
3813 // format were reverted but we still recognize bitcode that uses it.
3814 // Hopefully someday we will have support for case ranges and can use
3815 // this format again.
3817 Type *OpTy = getTypeByID(Record[1]);
3818 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3820 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3821 BasicBlock *Default = getBasicBlock(Record[3]);
3822 if (!OpTy || !Cond || !Default)
3823 return Error("Invalid record");
3825 unsigned NumCases = Record[4];
3827 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3828 InstructionList.push_back(SI);
3830 unsigned CurIdx = 5;
3831 for (unsigned i = 0; i != NumCases; ++i) {
3832 SmallVector<ConstantInt*, 1> CaseVals;
3833 unsigned NumItems = Record[CurIdx++];
3834 for (unsigned ci = 0; ci != NumItems; ++ci) {
3835 bool isSingleNumber = Record[CurIdx++];
3838 unsigned ActiveWords = 1;
3839 if (ValueBitWidth > 64)
3840 ActiveWords = Record[CurIdx++];
3841 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3843 CurIdx += ActiveWords;
3845 if (!isSingleNumber) {
3847 if (ValueBitWidth > 64)
3848 ActiveWords = Record[CurIdx++];
3850 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3852 CurIdx += ActiveWords;
3854 // FIXME: It is not clear whether values in the range should be
3855 // compared as signed or unsigned values. The partially
3856 // implemented changes that used this format in the past used
3857 // unsigned comparisons.
3858 for ( ; Low.ule(High); ++Low)
3859 CaseVals.push_back(ConstantInt::get(Context, Low));
3861 CaseVals.push_back(ConstantInt::get(Context, Low));
3863 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3864 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3865 cve = CaseVals.end(); cvi != cve; ++cvi)
3866 SI->addCase(*cvi, DestBB);
3872 // Old SwitchInst format without case ranges.
3874 if (Record.size() < 3 || (Record.size() & 1) == 0)
3875 return Error("Invalid record");
3876 Type *OpTy = getTypeByID(Record[0]);
3877 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3878 BasicBlock *Default = getBasicBlock(Record[2]);
3879 if (!OpTy || !Cond || !Default)
3880 return Error("Invalid record");
3881 unsigned NumCases = (Record.size()-3)/2;
3882 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3883 InstructionList.push_back(SI);
3884 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3885 ConstantInt *CaseVal =
3886 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3887 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3888 if (!CaseVal || !DestBB) {
3890 return Error("Invalid record");
3892 SI->addCase(CaseVal, DestBB);
3897 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3898 if (Record.size() < 2)
3899 return Error("Invalid record");
3900 Type *OpTy = getTypeByID(Record[0]);
3901 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3902 if (!OpTy || !Address)
3903 return Error("Invalid record");
3904 unsigned NumDests = Record.size()-2;
3905 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3906 InstructionList.push_back(IBI);
3907 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3908 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3909 IBI->addDestination(DestBB);
3912 return Error("Invalid record");
3919 case bitc::FUNC_CODE_INST_INVOKE: {
3920 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3921 if (Record.size() < 4)
3922 return Error("Invalid record");
3924 AttributeSet PAL = getAttributes(Record[OpNum++]);
3925 unsigned CCInfo = Record[OpNum++];
3926 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3927 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3929 FunctionType *FTy = nullptr;
3930 if (CCInfo >> 13 & 1 &&
3931 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3932 return Error("Explicit invoke type is not a function type");
3935 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3936 return Error("Invalid record");
3938 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3940 return Error("Callee is not a pointer");
3942 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3944 return Error("Callee is not of pointer to function type");
3945 } else if (CalleeTy->getElementType() != FTy)
3946 return Error("Explicit invoke type does not match pointee type of "
3948 if (Record.size() < FTy->getNumParams() + OpNum)
3949 return Error("Insufficient operands to call");
3951 SmallVector<Value*, 16> Ops;
3952 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3953 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3954 FTy->getParamType(i)));
3956 return Error("Invalid record");
3959 if (!FTy->isVarArg()) {
3960 if (Record.size() != OpNum)
3961 return Error("Invalid record");
3963 // Read type/value pairs for varargs params.
3964 while (OpNum != Record.size()) {
3966 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3967 return Error("Invalid record");
3972 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3973 InstructionList.push_back(I);
3975 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
3976 cast<InvokeInst>(I)->setAttributes(PAL);
3979 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3981 Value *Val = nullptr;
3982 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3983 return Error("Invalid record");
3984 I = ResumeInst::Create(Val);
3985 InstructionList.push_back(I);
3988 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3989 I = new UnreachableInst(Context);
3990 InstructionList.push_back(I);
3992 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3993 if (Record.size() < 1 || ((Record.size()-1)&1))
3994 return Error("Invalid record");
3995 Type *Ty = getTypeByID(Record[0]);
3997 return Error("Invalid record");
3999 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4000 InstructionList.push_back(PN);
4002 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4004 // With the new function encoding, it is possible that operands have
4005 // negative IDs (for forward references). Use a signed VBR
4006 // representation to keep the encoding small.
4008 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4010 V = getValue(Record, 1+i, NextValueNo, Ty);
4011 BasicBlock *BB = getBasicBlock(Record[2+i]);
4013 return Error("Invalid record");
4014 PN->addIncoming(V, BB);
4020 case bitc::FUNC_CODE_INST_LANDINGPAD: {
4021 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4023 if (Record.size() < 4)
4024 return Error("Invalid record");
4025 Type *Ty = getTypeByID(Record[Idx++]);
4027 return Error("Invalid record");
4028 Value *PersFn = nullptr;
4029 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4030 return Error("Invalid record");
4032 bool IsCleanup = !!Record[Idx++];
4033 unsigned NumClauses = Record[Idx++];
4034 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
4035 LP->setCleanup(IsCleanup);
4036 for (unsigned J = 0; J != NumClauses; ++J) {
4037 LandingPadInst::ClauseType CT =
4038 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4041 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4043 return Error("Invalid record");
4046 assert((CT != LandingPadInst::Catch ||
4047 !isa<ArrayType>(Val->getType())) &&
4048 "Catch clause has a invalid type!");
4049 assert((CT != LandingPadInst::Filter ||
4050 isa<ArrayType>(Val->getType())) &&
4051 "Filter clause has invalid type!");
4052 LP->addClause(cast<Constant>(Val));
4056 InstructionList.push_back(I);
4060 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4061 if (Record.size() != 4)
4062 return Error("Invalid record");
4063 uint64_t AlignRecord = Record[3];
4064 const uint64_t InAllocaMask = uint64_t(1) << 5;
4065 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4066 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4067 bool InAlloca = AlignRecord & InAllocaMask;
4068 Type *Ty = getTypeByID(Record[0]);
4069 if ((AlignRecord & ExplicitTypeMask) == 0) {
4070 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4072 return Error("Old-style alloca with a non-pointer type");
4073 Ty = PTy->getElementType();
4075 Type *OpTy = getTypeByID(Record[1]);
4076 Value *Size = getFnValueByID(Record[2], OpTy);
4078 if (std::error_code EC =
4079 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4083 return Error("Invalid record");
4084 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4085 AI->setUsedWithInAlloca(InAlloca);
4087 InstructionList.push_back(I);
4090 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4093 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4094 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4095 return Error("Invalid record");
4098 if (OpNum + 3 == Record.size())
4099 Ty = getTypeByID(Record[OpNum++]);
4100 if (std::error_code EC =
4101 TypeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4104 Ty = cast<PointerType>(Op->getType())->getElementType();
4107 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4109 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4111 InstructionList.push_back(I);
4114 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4115 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4118 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4119 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4120 return Error("Invalid record");
4123 if (OpNum + 5 == Record.size())
4124 Ty = getTypeByID(Record[OpNum++]);
4125 if (std::error_code EC =
4126 TypeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4129 Ty = cast<PointerType>(Op->getType())->getElementType();
4131 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4132 if (Ordering == NotAtomic || Ordering == Release ||
4133 Ordering == AcquireRelease)
4134 return Error("Invalid record");
4135 if (Ordering != NotAtomic && Record[OpNum] == 0)
4136 return Error("Invalid record");
4137 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4140 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4142 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4144 InstructionList.push_back(I);
4147 case bitc::FUNC_CODE_INST_STORE:
4148 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4151 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4152 (BitCode == bitc::FUNC_CODE_INST_STORE
4153 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4154 : popValue(Record, OpNum, NextValueNo,
4155 cast<PointerType>(Ptr->getType())->getElementType(),
4157 OpNum + 2 != Record.size())
4158 return Error("Invalid record");
4160 if (std::error_code EC = TypeCheckLoadStoreInst(
4161 DiagnosticHandler, Val->getType(), Ptr->getType()))
4164 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4166 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4167 InstructionList.push_back(I);
4170 case bitc::FUNC_CODE_INST_STOREATOMIC:
4171 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4172 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4175 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4176 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4177 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4178 : popValue(Record, OpNum, NextValueNo,
4179 cast<PointerType>(Ptr->getType())->getElementType(),
4181 OpNum + 4 != Record.size())
4182 return Error("Invalid record");
4184 if (std::error_code EC = TypeCheckLoadStoreInst(
4185 DiagnosticHandler, Val->getType(), Ptr->getType()))
4187 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4188 if (Ordering == NotAtomic || Ordering == Acquire ||
4189 Ordering == AcquireRelease)
4190 return Error("Invalid record");
4191 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4192 if (Ordering != NotAtomic && Record[OpNum] == 0)
4193 return Error("Invalid record");
4196 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4198 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4199 InstructionList.push_back(I);
4202 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4203 case bitc::FUNC_CODE_INST_CMPXCHG: {
4204 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4205 // failureordering?, isweak?]
4207 Value *Ptr, *Cmp, *New;
4208 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4209 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4210 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4211 : popValue(Record, OpNum, NextValueNo,
4212 cast<PointerType>(Ptr->getType())->getElementType(),
4214 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4215 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4216 return Error("Invalid record");
4217 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4218 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4219 return Error("Invalid record");
4220 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4222 if (std::error_code EC = TypeCheckLoadStoreInst(
4223 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4225 AtomicOrdering FailureOrdering;
4226 if (Record.size() < 7)
4228 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4230 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4232 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4234 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4236 if (Record.size() < 8) {
4237 // Before weak cmpxchgs existed, the instruction simply returned the
4238 // value loaded from memory, so bitcode files from that era will be
4239 // expecting the first component of a modern cmpxchg.
4240 CurBB->getInstList().push_back(I);
4241 I = ExtractValueInst::Create(I, 0);
4243 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4246 InstructionList.push_back(I);
4249 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4250 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4253 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4254 popValue(Record, OpNum, NextValueNo,
4255 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4256 OpNum+4 != Record.size())
4257 return Error("Invalid record");
4258 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4259 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4260 Operation > AtomicRMWInst::LAST_BINOP)
4261 return Error("Invalid record");
4262 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4263 if (Ordering == NotAtomic || Ordering == Unordered)
4264 return Error("Invalid record");
4265 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4266 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4267 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4268 InstructionList.push_back(I);
4271 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4272 if (2 != Record.size())
4273 return Error("Invalid record");
4274 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4275 if (Ordering == NotAtomic || Ordering == Unordered ||
4276 Ordering == Monotonic)
4277 return Error("Invalid record");
4278 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4279 I = new FenceInst(Context, Ordering, SynchScope);
4280 InstructionList.push_back(I);
4283 case bitc::FUNC_CODE_INST_CALL: {
4284 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4285 if (Record.size() < 3)
4286 return Error("Invalid record");
4289 AttributeSet PAL = getAttributes(Record[OpNum++]);
4290 unsigned CCInfo = Record[OpNum++];
4292 FunctionType *FTy = nullptr;
4293 if (CCInfo >> 15 & 1 &&
4294 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4295 return Error("Explicit call type is not a function type");
4298 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4299 return Error("Invalid record");
4301 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4303 return Error("Callee is not a pointer type");
4305 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4307 return Error("Callee is not of pointer to function type");
4308 } else if (OpTy->getElementType() != FTy)
4309 return Error("Explicit call type does not match pointee type of "
4311 if (Record.size() < FTy->getNumParams() + OpNum)
4312 return Error("Insufficient operands to call");
4314 SmallVector<Value*, 16> Args;
4315 // Read the fixed params.
4316 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4317 if (FTy->getParamType(i)->isLabelTy())
4318 Args.push_back(getBasicBlock(Record[OpNum]));
4320 Args.push_back(getValue(Record, OpNum, NextValueNo,
4321 FTy->getParamType(i)));
4323 return Error("Invalid record");
4326 // Read type/value pairs for varargs params.
4327 if (!FTy->isVarArg()) {
4328 if (OpNum != Record.size())
4329 return Error("Invalid record");
4331 while (OpNum != Record.size()) {
4333 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4334 return Error("Invalid record");
4339 I = CallInst::Create(FTy, Callee, Args);
4340 InstructionList.push_back(I);
4341 cast<CallInst>(I)->setCallingConv(
4342 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4343 CallInst::TailCallKind TCK = CallInst::TCK_None;
4345 TCK = CallInst::TCK_Tail;
4346 if (CCInfo & (1 << 14))
4347 TCK = CallInst::TCK_MustTail;
4348 cast<CallInst>(I)->setTailCallKind(TCK);
4349 cast<CallInst>(I)->setAttributes(PAL);
4352 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4353 if (Record.size() < 3)
4354 return Error("Invalid record");
4355 Type *OpTy = getTypeByID(Record[0]);
4356 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4357 Type *ResTy = getTypeByID(Record[2]);
4358 if (!OpTy || !Op || !ResTy)
4359 return Error("Invalid record");
4360 I = new VAArgInst(Op, ResTy);
4361 InstructionList.push_back(I);
4366 // Add instruction to end of current BB. If there is no current BB, reject
4370 return Error("Invalid instruction with no BB");
4372 CurBB->getInstList().push_back(I);
4374 // If this was a terminator instruction, move to the next block.
4375 if (isa<TerminatorInst>(I)) {
4377 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4380 // Non-void values get registered in the value table for future use.
4381 if (I && !I->getType()->isVoidTy())
4382 ValueList.AssignValue(I, NextValueNo++);
4387 // Check the function list for unresolved values.
4388 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4389 if (!A->getParent()) {
4390 // We found at least one unresolved value. Nuke them all to avoid leaks.
4391 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4392 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4393 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4397 return Error("Never resolved value found in function");
4401 // FIXME: Check for unresolved forward-declared metadata references
4402 // and clean up leaks.
4404 // Trim the value list down to the size it was before we parsed this function.
4405 ValueList.shrinkTo(ModuleValueListSize);
4406 MDValueList.shrinkTo(ModuleMDValueListSize);
4407 std::vector<BasicBlock*>().swap(FunctionBBs);
4408 return std::error_code();
4411 /// Find the function body in the bitcode stream
4412 std::error_code BitcodeReader::FindFunctionInStream(
4414 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4415 while (DeferredFunctionInfoIterator->second == 0) {
4416 if (Stream.AtEndOfStream())
4417 return Error("Could not find function in stream");
4418 // ParseModule will parse the next body in the stream and set its
4419 // position in the DeferredFunctionInfo map.
4420 if (std::error_code EC = ParseModule(true))
4423 return std::error_code();
4426 //===----------------------------------------------------------------------===//
4427 // GVMaterializer implementation
4428 //===----------------------------------------------------------------------===//
4430 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4432 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4433 if (std::error_code EC = materializeMetadata())
4436 Function *F = dyn_cast<Function>(GV);
4437 // If it's not a function or is already material, ignore the request.
4438 if (!F || !F->isMaterializable())
4439 return std::error_code();
4441 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4442 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4443 // If its position is recorded as 0, its body is somewhere in the stream
4444 // but we haven't seen it yet.
4445 if (DFII->second == 0 && LazyStreamer)
4446 if (std::error_code EC = FindFunctionInStream(F, DFII))
4449 // Move the bit stream to the saved position of the deferred function body.
4450 Stream.JumpToBit(DFII->second);
4452 if (std::error_code EC = ParseFunctionBody(F))
4454 F->setIsMaterializable(false);
4459 // Upgrade any old intrinsic calls in the function.
4460 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4461 E = UpgradedIntrinsics.end(); I != E; ++I) {
4462 if (I->first != I->second) {
4463 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4465 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4466 UpgradeIntrinsicCall(CI, I->second);
4471 // Bring in any functions that this function forward-referenced via
4473 return materializeForwardReferencedFunctions();
4476 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4477 const Function *F = dyn_cast<Function>(GV);
4478 if (!F || F->isDeclaration())
4481 // Dematerializing F would leave dangling references that wouldn't be
4482 // reconnected on re-materialization.
4483 if (BlockAddressesTaken.count(F))
4486 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4489 void BitcodeReader::dematerialize(GlobalValue *GV) {
4490 Function *F = dyn_cast<Function>(GV);
4491 // If this function isn't dematerializable, this is a noop.
4492 if (!F || !isDematerializable(F))
4495 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4497 // Just forget the function body, we can remat it later.
4498 F->dropAllReferences();
4499 F->setIsMaterializable(true);
4502 std::error_code BitcodeReader::materializeModule(Module *M) {
4503 assert(M == TheModule &&
4504 "Can only Materialize the Module this BitcodeReader is attached to.");
4506 if (std::error_code EC = materializeMetadata())
4509 // Promise to materialize all forward references.
4510 WillMaterializeAllForwardRefs = true;
4512 // Iterate over the module, deserializing any functions that are still on
4514 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4516 if (std::error_code EC = materialize(F))
4519 // At this point, if there are any function bodies, the current bit is
4520 // pointing to the END_BLOCK record after them. Now make sure the rest
4521 // of the bits in the module have been read.
4525 // Check that all block address forward references got resolved (as we
4527 if (!BasicBlockFwdRefs.empty())
4528 return Error("Never resolved function from blockaddress");
4530 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4531 // delete the old functions to clean up. We can't do this unless the entire
4532 // module is materialized because there could always be another function body
4533 // with calls to the old function.
4534 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4535 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4536 if (I->first != I->second) {
4537 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4539 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4540 UpgradeIntrinsicCall(CI, I->second);
4542 if (!I->first->use_empty())
4543 I->first->replaceAllUsesWith(I->second);
4544 I->first->eraseFromParent();
4547 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4549 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4550 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4552 UpgradeDebugInfo(*M);
4553 return std::error_code();
4556 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4557 return IdentifiedStructTypes;
4560 std::error_code BitcodeReader::InitStream() {
4562 return InitLazyStream();
4563 return InitStreamFromBuffer();
4566 std::error_code BitcodeReader::InitStreamFromBuffer() {
4567 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4568 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4570 if (Buffer->getBufferSize() & 3)
4571 return Error("Invalid bitcode signature");
4573 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4574 // The magic number is 0x0B17C0DE stored in little endian.
4575 if (isBitcodeWrapper(BufPtr, BufEnd))
4576 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4577 return Error("Invalid bitcode wrapper header");
4579 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4580 Stream.init(&*StreamFile);
4582 return std::error_code();
4585 std::error_code BitcodeReader::InitLazyStream() {
4586 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4588 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4589 StreamingMemoryObject &Bytes = *OwnedBytes;
4590 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4591 Stream.init(&*StreamFile);
4593 unsigned char buf[16];
4594 if (Bytes.readBytes(buf, 16, 0) != 16)
4595 return Error("Invalid bitcode signature");
4597 if (!isBitcode(buf, buf + 16))
4598 return Error("Invalid bitcode signature");
4600 if (isBitcodeWrapper(buf, buf + 4)) {
4601 const unsigned char *bitcodeStart = buf;
4602 const unsigned char *bitcodeEnd = buf + 16;
4603 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4604 Bytes.dropLeadingBytes(bitcodeStart - buf);
4605 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4607 return std::error_code();
4611 class BitcodeErrorCategoryType : public std::error_category {
4612 const char *name() const LLVM_NOEXCEPT override {
4613 return "llvm.bitcode";
4615 std::string message(int IE) const override {
4616 BitcodeError E = static_cast<BitcodeError>(IE);
4618 case BitcodeError::InvalidBitcodeSignature:
4619 return "Invalid bitcode signature";
4620 case BitcodeError::CorruptedBitcode:
4621 return "Corrupted bitcode";
4623 llvm_unreachable("Unknown error type!");
4628 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4630 const std::error_category &llvm::BitcodeErrorCategory() {
4631 return *ErrorCategory;
4634 //===----------------------------------------------------------------------===//
4635 // External interface
4636 //===----------------------------------------------------------------------===//
4638 /// \brief Get a lazy one-at-time loading module from bitcode.
4640 /// This isn't always used in a lazy context. In particular, it's also used by
4641 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4642 /// in forward-referenced functions from block address references.
4644 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4645 /// materialize everything -- in particular, if this isn't truly lazy.
4646 static ErrorOr<Module *>
4647 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4648 LLVMContext &Context, bool WillMaterializeAll,
4649 DiagnosticHandlerFunction DiagnosticHandler,
4650 bool ShouldLazyLoadMetadata = false) {
4651 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4653 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4654 M->setMaterializer(R);
4656 auto cleanupOnError = [&](std::error_code EC) {
4657 R->releaseBuffer(); // Never take ownership on error.
4658 delete M; // Also deletes R.
4662 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4663 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4664 return cleanupOnError(EC);
4666 if (!WillMaterializeAll)
4667 // Resolve forward references from blockaddresses.
4668 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4669 return cleanupOnError(EC);
4671 Buffer.release(); // The BitcodeReader owns it now.
4676 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4677 LLVMContext &Context,
4678 DiagnosticHandlerFunction DiagnosticHandler,
4679 bool ShouldLazyLoadMetadata) {
4680 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4681 DiagnosticHandler, ShouldLazyLoadMetadata);
4684 ErrorOr<std::unique_ptr<Module>>
4685 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4686 LLVMContext &Context,
4687 DiagnosticHandlerFunction DiagnosticHandler) {
4688 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4689 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4690 M->setMaterializer(R);
4691 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4693 return std::move(M);
4697 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4698 DiagnosticHandlerFunction DiagnosticHandler) {
4699 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4700 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4701 std::move(Buf), Context, true, DiagnosticHandler);
4704 Module *M = ModuleOrErr.get();
4705 // Read in the entire module, and destroy the BitcodeReader.
4706 if (std::error_code EC = M->materializeAllPermanently()) {
4711 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4712 // written. We must defer until the Module has been fully materialized.
4718 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4719 DiagnosticHandlerFunction DiagnosticHandler) {
4720 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4721 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4723 ErrorOr<std::string> Triple = R->parseTriple();
4724 if (Triple.getError())
4726 return Triple.get();