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 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
405 return ::Error(DiagnosticHandler, make_error_code(E), Message);
408 std::error_code BitcodeReader::Error(const Twine &Message) {
409 return ::Error(DiagnosticHandler,
410 make_error_code(BitcodeError::CorruptedBitcode), Message);
413 std::error_code BitcodeReader::Error(BitcodeError E) {
414 return ::Error(DiagnosticHandler, make_error_code(E));
417 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
421 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
424 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
425 DiagnosticHandlerFunction DiagnosticHandler)
426 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
427 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
428 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
429 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
430 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
432 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
433 DiagnosticHandlerFunction DiagnosticHandler)
434 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
435 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
436 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
437 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
438 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
440 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
441 if (WillMaterializeAllForwardRefs)
442 return std::error_code();
444 // Prevent recursion.
445 WillMaterializeAllForwardRefs = true;
447 while (!BasicBlockFwdRefQueue.empty()) {
448 Function *F = BasicBlockFwdRefQueue.front();
449 BasicBlockFwdRefQueue.pop_front();
450 assert(F && "Expected valid function");
451 if (!BasicBlockFwdRefs.count(F))
452 // Already materialized.
455 // Check for a function that isn't materializable to prevent an infinite
456 // loop. When parsing a blockaddress stored in a global variable, there
457 // isn't a trivial way to check if a function will have a body without a
458 // linear search through FunctionsWithBodies, so just check it here.
459 if (!F->isMaterializable())
460 return Error("Never resolved function from blockaddress");
462 // Try to materialize F.
463 if (std::error_code EC = materialize(F))
466 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
469 WillMaterializeAllForwardRefs = false;
470 return std::error_code();
473 void BitcodeReader::FreeState() {
475 std::vector<Type*>().swap(TypeList);
478 std::vector<Comdat *>().swap(ComdatList);
480 std::vector<AttributeSet>().swap(MAttributes);
481 std::vector<BasicBlock*>().swap(FunctionBBs);
482 std::vector<Function*>().swap(FunctionsWithBodies);
483 DeferredFunctionInfo.clear();
484 DeferredMetadataInfo.clear();
487 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
488 BasicBlockFwdRefQueue.clear();
491 //===----------------------------------------------------------------------===//
492 // Helper functions to implement forward reference resolution, etc.
493 //===----------------------------------------------------------------------===//
495 /// ConvertToString - Convert a string from a record into an std::string, return
497 template<typename StrTy>
498 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
500 if (Idx > Record.size())
503 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
504 Result += (char)Record[i];
508 static bool hasImplicitComdat(size_t Val) {
512 case 1: // Old WeakAnyLinkage
513 case 4: // Old LinkOnceAnyLinkage
514 case 10: // Old WeakODRLinkage
515 case 11: // Old LinkOnceODRLinkage
520 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
522 default: // Map unknown/new linkages to external
524 return GlobalValue::ExternalLinkage;
526 return GlobalValue::AppendingLinkage;
528 return GlobalValue::InternalLinkage;
530 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
532 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
534 return GlobalValue::ExternalWeakLinkage;
536 return GlobalValue::CommonLinkage;
538 return GlobalValue::PrivateLinkage;
540 return GlobalValue::AvailableExternallyLinkage;
542 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
544 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
546 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
547 case 1: // Old value with implicit comdat.
549 return GlobalValue::WeakAnyLinkage;
550 case 10: // Old value with implicit comdat.
552 return GlobalValue::WeakODRLinkage;
553 case 4: // Old value with implicit comdat.
555 return GlobalValue::LinkOnceAnyLinkage;
556 case 11: // Old value with implicit comdat.
558 return GlobalValue::LinkOnceODRLinkage;
562 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
564 default: // Map unknown visibilities to default.
565 case 0: return GlobalValue::DefaultVisibility;
566 case 1: return GlobalValue::HiddenVisibility;
567 case 2: return GlobalValue::ProtectedVisibility;
571 static GlobalValue::DLLStorageClassTypes
572 GetDecodedDLLStorageClass(unsigned Val) {
574 default: // Map unknown values to default.
575 case 0: return GlobalValue::DefaultStorageClass;
576 case 1: return GlobalValue::DLLImportStorageClass;
577 case 2: return GlobalValue::DLLExportStorageClass;
581 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
583 case 0: return GlobalVariable::NotThreadLocal;
584 default: // Map unknown non-zero value to general dynamic.
585 case 1: return GlobalVariable::GeneralDynamicTLSModel;
586 case 2: return GlobalVariable::LocalDynamicTLSModel;
587 case 3: return GlobalVariable::InitialExecTLSModel;
588 case 4: return GlobalVariable::LocalExecTLSModel;
592 static int GetDecodedCastOpcode(unsigned Val) {
595 case bitc::CAST_TRUNC : return Instruction::Trunc;
596 case bitc::CAST_ZEXT : return Instruction::ZExt;
597 case bitc::CAST_SEXT : return Instruction::SExt;
598 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
599 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
600 case bitc::CAST_UITOFP : return Instruction::UIToFP;
601 case bitc::CAST_SITOFP : return Instruction::SIToFP;
602 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
603 case bitc::CAST_FPEXT : return Instruction::FPExt;
604 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
605 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
606 case bitc::CAST_BITCAST : return Instruction::BitCast;
607 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
611 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
612 bool IsFP = Ty->isFPOrFPVectorTy();
613 // BinOps are only valid for int/fp or vector of int/fp types
614 if (!IsFP && !Ty->isIntOrIntVectorTy())
620 case bitc::BINOP_ADD:
621 return IsFP ? Instruction::FAdd : Instruction::Add;
622 case bitc::BINOP_SUB:
623 return IsFP ? Instruction::FSub : Instruction::Sub;
624 case bitc::BINOP_MUL:
625 return IsFP ? Instruction::FMul : Instruction::Mul;
626 case bitc::BINOP_UDIV:
627 return IsFP ? -1 : Instruction::UDiv;
628 case bitc::BINOP_SDIV:
629 return IsFP ? Instruction::FDiv : Instruction::SDiv;
630 case bitc::BINOP_UREM:
631 return IsFP ? -1 : Instruction::URem;
632 case bitc::BINOP_SREM:
633 return IsFP ? Instruction::FRem : Instruction::SRem;
634 case bitc::BINOP_SHL:
635 return IsFP ? -1 : Instruction::Shl;
636 case bitc::BINOP_LSHR:
637 return IsFP ? -1 : Instruction::LShr;
638 case bitc::BINOP_ASHR:
639 return IsFP ? -1 : Instruction::AShr;
640 case bitc::BINOP_AND:
641 return IsFP ? -1 : Instruction::And;
643 return IsFP ? -1 : Instruction::Or;
644 case bitc::BINOP_XOR:
645 return IsFP ? -1 : Instruction::Xor;
649 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
651 default: return AtomicRMWInst::BAD_BINOP;
652 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
653 case bitc::RMW_ADD: return AtomicRMWInst::Add;
654 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
655 case bitc::RMW_AND: return AtomicRMWInst::And;
656 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
657 case bitc::RMW_OR: return AtomicRMWInst::Or;
658 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
659 case bitc::RMW_MAX: return AtomicRMWInst::Max;
660 case bitc::RMW_MIN: return AtomicRMWInst::Min;
661 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
662 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
666 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
668 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
669 case bitc::ORDERING_UNORDERED: return Unordered;
670 case bitc::ORDERING_MONOTONIC: return Monotonic;
671 case bitc::ORDERING_ACQUIRE: return Acquire;
672 case bitc::ORDERING_RELEASE: return Release;
673 case bitc::ORDERING_ACQREL: return AcquireRelease;
674 default: // Map unknown orderings to sequentially-consistent.
675 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
679 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
681 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
682 default: // Map unknown scopes to cross-thread.
683 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
687 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
689 default: // Map unknown selection kinds to any.
690 case bitc::COMDAT_SELECTION_KIND_ANY:
692 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
693 return Comdat::ExactMatch;
694 case bitc::COMDAT_SELECTION_KIND_LARGEST:
695 return Comdat::Largest;
696 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
697 return Comdat::NoDuplicates;
698 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
699 return Comdat::SameSize;
703 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
705 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
706 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
712 /// @brief A class for maintaining the slot number definition
713 /// as a placeholder for the actual definition for forward constants defs.
714 class ConstantPlaceHolder : public ConstantExpr {
715 void operator=(const ConstantPlaceHolder &) = delete;
717 // allocate space for exactly one operand
718 void *operator new(size_t s) {
719 return User::operator new(s, 1);
721 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
722 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
723 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
726 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
727 static bool classof(const Value *V) {
728 return isa<ConstantExpr>(V) &&
729 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
733 /// Provide fast operand accessors
734 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
738 // FIXME: can we inherit this from ConstantExpr?
740 struct OperandTraits<ConstantPlaceHolder> :
741 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
743 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
747 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
756 WeakVH &OldV = ValuePtrs[Idx];
762 // Handle constants and non-constants (e.g. instrs) differently for
764 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
765 ResolveConstants.push_back(std::make_pair(PHC, Idx));
768 // If there was a forward reference to this value, replace it.
769 Value *PrevVal = OldV;
770 OldV->replaceAllUsesWith(V);
776 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
781 if (Value *V = ValuePtrs[Idx]) {
782 assert(Ty == V->getType() && "Type mismatch in constant table!");
783 return cast<Constant>(V);
786 // Create and return a placeholder, which will later be RAUW'd.
787 Constant *C = new ConstantPlaceHolder(Ty, Context);
792 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
793 // Bail out for a clearly invalid value. This would make us call resize(0)
800 if (Value *V = ValuePtrs[Idx]) {
801 // If the types don't match, it's invalid.
802 if (Ty && Ty != V->getType())
807 // No type specified, must be invalid reference.
808 if (!Ty) return nullptr;
810 // Create and return a placeholder, which will later be RAUW'd.
811 Value *V = new Argument(Ty);
816 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
817 /// resolves any forward references. The idea behind this is that we sometimes
818 /// get constants (such as large arrays) which reference *many* forward ref
819 /// constants. Replacing each of these causes a lot of thrashing when
820 /// building/reuniquing the constant. Instead of doing this, we look at all the
821 /// uses and rewrite all the place holders at once for any constant that uses
823 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
824 // Sort the values by-pointer so that they are efficient to look up with a
826 std::sort(ResolveConstants.begin(), ResolveConstants.end());
828 SmallVector<Constant*, 64> NewOps;
830 while (!ResolveConstants.empty()) {
831 Value *RealVal = operator[](ResolveConstants.back().second);
832 Constant *Placeholder = ResolveConstants.back().first;
833 ResolveConstants.pop_back();
835 // Loop over all users of the placeholder, updating them to reference the
836 // new value. If they reference more than one placeholder, update them all
838 while (!Placeholder->use_empty()) {
839 auto UI = Placeholder->user_begin();
842 // If the using object isn't uniqued, just update the operands. This
843 // handles instructions and initializers for global variables.
844 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
845 UI.getUse().set(RealVal);
849 // Otherwise, we have a constant that uses the placeholder. Replace that
850 // constant with a new constant that has *all* placeholder uses updated.
851 Constant *UserC = cast<Constant>(U);
852 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
855 if (!isa<ConstantPlaceHolder>(*I)) {
856 // Not a placeholder reference.
858 } else if (*I == Placeholder) {
859 // Common case is that it just references this one placeholder.
862 // Otherwise, look up the placeholder in ResolveConstants.
863 ResolveConstantsTy::iterator It =
864 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
865 std::pair<Constant*, unsigned>(cast<Constant>(*I),
867 assert(It != ResolveConstants.end() && It->first == *I);
868 NewOp = operator[](It->second);
871 NewOps.push_back(cast<Constant>(NewOp));
874 // Make the new constant.
876 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
877 NewC = ConstantArray::get(UserCA->getType(), NewOps);
878 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
879 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
880 } else if (isa<ConstantVector>(UserC)) {
881 NewC = ConstantVector::get(NewOps);
883 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
884 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
887 UserC->replaceAllUsesWith(NewC);
888 UserC->destroyConstant();
892 // Update all ValueHandles, they should be the only users at this point.
893 Placeholder->replaceAllUsesWith(RealVal);
898 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
907 TrackingMDRef &OldMD = MDValuePtrs[Idx];
913 // If there was a forward reference to this value, replace it.
914 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
915 PrevMD->replaceAllUsesWith(MD);
919 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
923 if (Metadata *MD = MDValuePtrs[Idx])
926 // Track forward refs to be resolved later.
928 MinFwdRef = std::min(MinFwdRef, Idx);
929 MaxFwdRef = std::max(MaxFwdRef, Idx);
932 MinFwdRef = MaxFwdRef = Idx;
936 // Create and return a placeholder, which will later be RAUW'd.
937 Metadata *MD = MDNode::getTemporary(Context, None).release();
938 MDValuePtrs[Idx].reset(MD);
942 void BitcodeReaderMDValueList::tryToResolveCycles() {
948 // Still forward references... can't resolve cycles.
951 // Resolve any cycles.
952 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
953 auto &MD = MDValuePtrs[I];
954 auto *N = dyn_cast_or_null<MDNode>(MD);
958 assert(!N->isTemporary() && "Unexpected forward reference");
962 // Make sure we return early again until there's another forward ref.
966 Type *BitcodeReader::getTypeByID(unsigned ID) {
967 // The type table size is always specified correctly.
968 if (ID >= TypeList.size())
971 if (Type *Ty = TypeList[ID])
974 // If we have a forward reference, the only possible case is when it is to a
975 // named struct. Just create a placeholder for now.
976 return TypeList[ID] = createIdentifiedStructType(Context);
979 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
981 auto *Ret = StructType::create(Context, Name);
982 IdentifiedStructTypes.push_back(Ret);
986 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
987 auto *Ret = StructType::create(Context);
988 IdentifiedStructTypes.push_back(Ret);
993 //===----------------------------------------------------------------------===//
994 // Functions for parsing blocks from the bitcode file
995 //===----------------------------------------------------------------------===//
998 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
999 /// been decoded from the given integer. This function must stay in sync with
1000 /// 'encodeLLVMAttributesForBitcode'.
1001 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1002 uint64_t EncodedAttrs) {
1003 // FIXME: Remove in 4.0.
1005 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1006 // the bits above 31 down by 11 bits.
1007 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1008 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1009 "Alignment must be a power of two.");
1012 B.addAlignmentAttr(Alignment);
1013 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1014 (EncodedAttrs & 0xffff));
1017 std::error_code BitcodeReader::ParseAttributeBlock() {
1018 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1019 return Error("Invalid record");
1021 if (!MAttributes.empty())
1022 return Error("Invalid multiple blocks");
1024 SmallVector<uint64_t, 64> Record;
1026 SmallVector<AttributeSet, 8> Attrs;
1028 // Read all the records.
1030 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1032 switch (Entry.Kind) {
1033 case BitstreamEntry::SubBlock: // Handled for us already.
1034 case BitstreamEntry::Error:
1035 return Error("Malformed block");
1036 case BitstreamEntry::EndBlock:
1037 return std::error_code();
1038 case BitstreamEntry::Record:
1039 // The interesting case.
1045 switch (Stream.readRecord(Entry.ID, Record)) {
1046 default: // Default behavior: ignore.
1048 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1049 // FIXME: Remove in 4.0.
1050 if (Record.size() & 1)
1051 return Error("Invalid record");
1053 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1055 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1056 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1059 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1063 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1064 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1065 Attrs.push_back(MAttributeGroups[Record[i]]);
1067 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1075 // Returns Attribute::None on unrecognized codes.
1076 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1079 return Attribute::None;
1080 case bitc::ATTR_KIND_ALIGNMENT:
1081 return Attribute::Alignment;
1082 case bitc::ATTR_KIND_ALWAYS_INLINE:
1083 return Attribute::AlwaysInline;
1084 case bitc::ATTR_KIND_BUILTIN:
1085 return Attribute::Builtin;
1086 case bitc::ATTR_KIND_BY_VAL:
1087 return Attribute::ByVal;
1088 case bitc::ATTR_KIND_IN_ALLOCA:
1089 return Attribute::InAlloca;
1090 case bitc::ATTR_KIND_COLD:
1091 return Attribute::Cold;
1092 case bitc::ATTR_KIND_INLINE_HINT:
1093 return Attribute::InlineHint;
1094 case bitc::ATTR_KIND_IN_REG:
1095 return Attribute::InReg;
1096 case bitc::ATTR_KIND_JUMP_TABLE:
1097 return Attribute::JumpTable;
1098 case bitc::ATTR_KIND_MIN_SIZE:
1099 return Attribute::MinSize;
1100 case bitc::ATTR_KIND_NAKED:
1101 return Attribute::Naked;
1102 case bitc::ATTR_KIND_NEST:
1103 return Attribute::Nest;
1104 case bitc::ATTR_KIND_NO_ALIAS:
1105 return Attribute::NoAlias;
1106 case bitc::ATTR_KIND_NO_BUILTIN:
1107 return Attribute::NoBuiltin;
1108 case bitc::ATTR_KIND_NO_CAPTURE:
1109 return Attribute::NoCapture;
1110 case bitc::ATTR_KIND_NO_DUPLICATE:
1111 return Attribute::NoDuplicate;
1112 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1113 return Attribute::NoImplicitFloat;
1114 case bitc::ATTR_KIND_NO_INLINE:
1115 return Attribute::NoInline;
1116 case bitc::ATTR_KIND_NON_LAZY_BIND:
1117 return Attribute::NonLazyBind;
1118 case bitc::ATTR_KIND_NON_NULL:
1119 return Attribute::NonNull;
1120 case bitc::ATTR_KIND_DEREFERENCEABLE:
1121 return Attribute::Dereferenceable;
1122 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1123 return Attribute::DereferenceableOrNull;
1124 case bitc::ATTR_KIND_NO_RED_ZONE:
1125 return Attribute::NoRedZone;
1126 case bitc::ATTR_KIND_NO_RETURN:
1127 return Attribute::NoReturn;
1128 case bitc::ATTR_KIND_NO_UNWIND:
1129 return Attribute::NoUnwind;
1130 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1131 return Attribute::OptimizeForSize;
1132 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1133 return Attribute::OptimizeNone;
1134 case bitc::ATTR_KIND_READ_NONE:
1135 return Attribute::ReadNone;
1136 case bitc::ATTR_KIND_READ_ONLY:
1137 return Attribute::ReadOnly;
1138 case bitc::ATTR_KIND_RETURNED:
1139 return Attribute::Returned;
1140 case bitc::ATTR_KIND_RETURNS_TWICE:
1141 return Attribute::ReturnsTwice;
1142 case bitc::ATTR_KIND_S_EXT:
1143 return Attribute::SExt;
1144 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1145 return Attribute::StackAlignment;
1146 case bitc::ATTR_KIND_STACK_PROTECT:
1147 return Attribute::StackProtect;
1148 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1149 return Attribute::StackProtectReq;
1150 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1151 return Attribute::StackProtectStrong;
1152 case bitc::ATTR_KIND_STRUCT_RET:
1153 return Attribute::StructRet;
1154 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1155 return Attribute::SanitizeAddress;
1156 case bitc::ATTR_KIND_SANITIZE_THREAD:
1157 return Attribute::SanitizeThread;
1158 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1159 return Attribute::SanitizeMemory;
1160 case bitc::ATTR_KIND_UW_TABLE:
1161 return Attribute::UWTable;
1162 case bitc::ATTR_KIND_Z_EXT:
1163 return Attribute::ZExt;
1167 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1168 unsigned &Alignment) {
1169 // Note: Alignment in bitcode files is incremented by 1, so that zero
1170 // can be used for default alignment.
1171 if (Exponent > Value::MaxAlignmentExponent + 1)
1172 return Error("Invalid alignment value");
1173 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1174 return std::error_code();
1177 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1178 Attribute::AttrKind *Kind) {
1179 *Kind = GetAttrFromCode(Code);
1180 if (*Kind == Attribute::None)
1181 return Error(BitcodeError::CorruptedBitcode,
1182 "Unknown attribute kind (" + Twine(Code) + ")");
1183 return std::error_code();
1186 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
1187 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1188 return Error("Invalid record");
1190 if (!MAttributeGroups.empty())
1191 return Error("Invalid multiple blocks");
1193 SmallVector<uint64_t, 64> Record;
1195 // Read all the records.
1197 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1199 switch (Entry.Kind) {
1200 case BitstreamEntry::SubBlock: // Handled for us already.
1201 case BitstreamEntry::Error:
1202 return Error("Malformed block");
1203 case BitstreamEntry::EndBlock:
1204 return std::error_code();
1205 case BitstreamEntry::Record:
1206 // The interesting case.
1212 switch (Stream.readRecord(Entry.ID, Record)) {
1213 default: // Default behavior: ignore.
1215 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1216 if (Record.size() < 3)
1217 return Error("Invalid record");
1219 uint64_t GrpID = Record[0];
1220 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1223 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1224 if (Record[i] == 0) { // Enum attribute
1225 Attribute::AttrKind Kind;
1226 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1229 B.addAttribute(Kind);
1230 } else if (Record[i] == 1) { // Integer attribute
1231 Attribute::AttrKind Kind;
1232 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1234 if (Kind == Attribute::Alignment)
1235 B.addAlignmentAttr(Record[++i]);
1236 else if (Kind == Attribute::StackAlignment)
1237 B.addStackAlignmentAttr(Record[++i]);
1238 else if (Kind == Attribute::Dereferenceable)
1239 B.addDereferenceableAttr(Record[++i]);
1240 else if (Kind == Attribute::DereferenceableOrNull)
1241 B.addDereferenceableOrNullAttr(Record[++i]);
1242 } else { // String attribute
1243 assert((Record[i] == 3 || Record[i] == 4) &&
1244 "Invalid attribute group entry");
1245 bool HasValue = (Record[i++] == 4);
1246 SmallString<64> KindStr;
1247 SmallString<64> ValStr;
1249 while (Record[i] != 0 && i != e)
1250 KindStr += Record[i++];
1251 assert(Record[i] == 0 && "Kind string not null terminated");
1254 // Has a value associated with it.
1255 ++i; // Skip the '0' that terminates the "kind" string.
1256 while (Record[i] != 0 && i != e)
1257 ValStr += Record[i++];
1258 assert(Record[i] == 0 && "Value string not null terminated");
1261 B.addAttribute(KindStr.str(), ValStr.str());
1265 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1272 std::error_code BitcodeReader::ParseTypeTable() {
1273 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1274 return Error("Invalid record");
1276 return ParseTypeTableBody();
1279 std::error_code BitcodeReader::ParseTypeTableBody() {
1280 if (!TypeList.empty())
1281 return Error("Invalid multiple blocks");
1283 SmallVector<uint64_t, 64> Record;
1284 unsigned NumRecords = 0;
1286 SmallString<64> TypeName;
1288 // Read all the records for this type table.
1290 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1292 switch (Entry.Kind) {
1293 case BitstreamEntry::SubBlock: // Handled for us already.
1294 case BitstreamEntry::Error:
1295 return Error("Malformed block");
1296 case BitstreamEntry::EndBlock:
1297 if (NumRecords != TypeList.size())
1298 return Error("Malformed block");
1299 return std::error_code();
1300 case BitstreamEntry::Record:
1301 // The interesting case.
1307 Type *ResultTy = nullptr;
1308 switch (Stream.readRecord(Entry.ID, Record)) {
1310 return Error("Invalid value");
1311 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1312 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1313 // type list. This allows us to reserve space.
1314 if (Record.size() < 1)
1315 return Error("Invalid record");
1316 TypeList.resize(Record[0]);
1318 case bitc::TYPE_CODE_VOID: // VOID
1319 ResultTy = Type::getVoidTy(Context);
1321 case bitc::TYPE_CODE_HALF: // HALF
1322 ResultTy = Type::getHalfTy(Context);
1324 case bitc::TYPE_CODE_FLOAT: // FLOAT
1325 ResultTy = Type::getFloatTy(Context);
1327 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1328 ResultTy = Type::getDoubleTy(Context);
1330 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1331 ResultTy = Type::getX86_FP80Ty(Context);
1333 case bitc::TYPE_CODE_FP128: // FP128
1334 ResultTy = Type::getFP128Ty(Context);
1336 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1337 ResultTy = Type::getPPC_FP128Ty(Context);
1339 case bitc::TYPE_CODE_LABEL: // LABEL
1340 ResultTy = Type::getLabelTy(Context);
1342 case bitc::TYPE_CODE_METADATA: // METADATA
1343 ResultTy = Type::getMetadataTy(Context);
1345 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1346 ResultTy = Type::getX86_MMXTy(Context);
1348 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1349 if (Record.size() < 1)
1350 return Error("Invalid record");
1352 uint64_t NumBits = Record[0];
1353 if (NumBits < IntegerType::MIN_INT_BITS ||
1354 NumBits > IntegerType::MAX_INT_BITS)
1355 return Error("Bitwidth for integer type out of range");
1356 ResultTy = IntegerType::get(Context, NumBits);
1359 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1360 // [pointee type, address space]
1361 if (Record.size() < 1)
1362 return Error("Invalid record");
1363 unsigned AddressSpace = 0;
1364 if (Record.size() == 2)
1365 AddressSpace = Record[1];
1366 ResultTy = getTypeByID(Record[0]);
1368 !PointerType::isValidElementType(ResultTy))
1369 return Error("Invalid type");
1370 ResultTy = PointerType::get(ResultTy, AddressSpace);
1373 case bitc::TYPE_CODE_FUNCTION_OLD: {
1374 // FIXME: attrid is dead, remove it in LLVM 4.0
1375 // FUNCTION: [vararg, attrid, retty, paramty x N]
1376 if (Record.size() < 3)
1377 return Error("Invalid record");
1378 SmallVector<Type*, 8> ArgTys;
1379 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1380 if (Type *T = getTypeByID(Record[i]))
1381 ArgTys.push_back(T);
1386 ResultTy = getTypeByID(Record[2]);
1387 if (!ResultTy || ArgTys.size() < Record.size()-3)
1388 return Error("Invalid type");
1390 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1393 case bitc::TYPE_CODE_FUNCTION: {
1394 // FUNCTION: [vararg, retty, paramty x N]
1395 if (Record.size() < 2)
1396 return Error("Invalid record");
1397 SmallVector<Type*, 8> ArgTys;
1398 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1399 if (Type *T = getTypeByID(Record[i]))
1400 ArgTys.push_back(T);
1405 ResultTy = getTypeByID(Record[1]);
1406 if (!ResultTy || ArgTys.size() < Record.size()-2)
1407 return Error("Invalid type");
1409 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1412 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1413 if (Record.size() < 1)
1414 return Error("Invalid record");
1415 SmallVector<Type*, 8> EltTys;
1416 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1417 if (Type *T = getTypeByID(Record[i]))
1418 EltTys.push_back(T);
1422 if (EltTys.size() != Record.size()-1)
1423 return Error("Invalid type");
1424 ResultTy = StructType::get(Context, EltTys, Record[0]);
1427 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1428 if (ConvertToString(Record, 0, TypeName))
1429 return Error("Invalid record");
1432 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1433 if (Record.size() < 1)
1434 return Error("Invalid record");
1436 if (NumRecords >= TypeList.size())
1437 return Error("Invalid TYPE table");
1439 // Check to see if this was forward referenced, if so fill in the temp.
1440 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1442 Res->setName(TypeName);
1443 TypeList[NumRecords] = nullptr;
1444 } else // Otherwise, create a new struct.
1445 Res = createIdentifiedStructType(Context, TypeName);
1448 SmallVector<Type*, 8> EltTys;
1449 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1450 if (Type *T = getTypeByID(Record[i]))
1451 EltTys.push_back(T);
1455 if (EltTys.size() != Record.size()-1)
1456 return Error("Invalid record");
1457 Res->setBody(EltTys, Record[0]);
1461 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1462 if (Record.size() != 1)
1463 return Error("Invalid record");
1465 if (NumRecords >= TypeList.size())
1466 return Error("Invalid TYPE table");
1468 // Check to see if this was forward referenced, if so fill in the temp.
1469 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1471 Res->setName(TypeName);
1472 TypeList[NumRecords] = nullptr;
1473 } else // Otherwise, create a new struct with no body.
1474 Res = createIdentifiedStructType(Context, TypeName);
1479 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1480 if (Record.size() < 2)
1481 return Error("Invalid record");
1482 ResultTy = getTypeByID(Record[1]);
1483 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1484 return Error("Invalid type");
1485 ResultTy = ArrayType::get(ResultTy, Record[0]);
1487 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1488 if (Record.size() < 2)
1489 return Error("Invalid record");
1490 ResultTy = getTypeByID(Record[1]);
1491 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1492 return Error("Invalid type");
1493 ResultTy = VectorType::get(ResultTy, Record[0]);
1497 if (NumRecords >= TypeList.size())
1498 return Error("Invalid TYPE table");
1499 if (TypeList[NumRecords])
1501 "Invalid TYPE table: Only named structs can be forward referenced");
1502 assert(ResultTy && "Didn't read a type?");
1503 TypeList[NumRecords++] = ResultTy;
1507 std::error_code BitcodeReader::ParseValueSymbolTable() {
1508 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1509 return Error("Invalid record");
1511 SmallVector<uint64_t, 64> Record;
1513 Triple TT(TheModule->getTargetTriple());
1515 // Read all the records for this value table.
1516 SmallString<128> ValueName;
1518 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1520 switch (Entry.Kind) {
1521 case BitstreamEntry::SubBlock: // Handled for us already.
1522 case BitstreamEntry::Error:
1523 return Error("Malformed block");
1524 case BitstreamEntry::EndBlock:
1525 return std::error_code();
1526 case BitstreamEntry::Record:
1527 // The interesting case.
1533 switch (Stream.readRecord(Entry.ID, Record)) {
1534 default: // Default behavior: unknown type.
1536 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1537 if (ConvertToString(Record, 1, ValueName))
1538 return Error("Invalid record");
1539 unsigned ValueID = Record[0];
1540 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1541 return Error("Invalid record");
1542 Value *V = ValueList[ValueID];
1544 V->setName(StringRef(ValueName.data(), ValueName.size()));
1545 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1546 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1547 if (TT.isOSBinFormatMachO())
1548 GO->setComdat(nullptr);
1550 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1556 case bitc::VST_CODE_BBENTRY: {
1557 if (ConvertToString(Record, 1, ValueName))
1558 return Error("Invalid record");
1559 BasicBlock *BB = getBasicBlock(Record[0]);
1561 return Error("Invalid record");
1563 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1571 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1573 std::error_code BitcodeReader::ParseMetadata() {
1574 IsMetadataMaterialized = true;
1575 unsigned NextMDValueNo = MDValueList.size();
1577 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1578 return Error("Invalid record");
1580 SmallVector<uint64_t, 64> Record;
1583 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1584 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1586 return getMD(ID - 1);
1589 auto getMDString = [&](unsigned ID) -> MDString *{
1590 // This requires that the ID is not really a forward reference. In
1591 // particular, the MDString must already have been resolved.
1592 return cast_or_null<MDString>(getMDOrNull(ID));
1595 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1596 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1598 // Read all the records.
1600 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1602 switch (Entry.Kind) {
1603 case BitstreamEntry::SubBlock: // Handled for us already.
1604 case BitstreamEntry::Error:
1605 return Error("Malformed block");
1606 case BitstreamEntry::EndBlock:
1607 MDValueList.tryToResolveCycles();
1608 return std::error_code();
1609 case BitstreamEntry::Record:
1610 // The interesting case.
1616 unsigned Code = Stream.readRecord(Entry.ID, Record);
1617 bool IsDistinct = false;
1619 default: // Default behavior: ignore.
1621 case bitc::METADATA_NAME: {
1622 // Read name of the named metadata.
1623 SmallString<8> Name(Record.begin(), Record.end());
1625 Code = Stream.ReadCode();
1627 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1628 unsigned NextBitCode = Stream.readRecord(Code, Record);
1629 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1631 // Read named metadata elements.
1632 unsigned Size = Record.size();
1633 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1634 for (unsigned i = 0; i != Size; ++i) {
1635 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1637 return Error("Invalid record");
1638 NMD->addOperand(MD);
1642 case bitc::METADATA_OLD_FN_NODE: {
1643 // FIXME: Remove in 4.0.
1644 // This is a LocalAsMetadata record, the only type of function-local
1646 if (Record.size() % 2 == 1)
1647 return Error("Invalid record");
1649 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1650 // to be legal, but there's no upgrade path.
1651 auto dropRecord = [&] {
1652 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1654 if (Record.size() != 2) {
1659 Type *Ty = getTypeByID(Record[0]);
1660 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1665 MDValueList.AssignValue(
1666 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1670 case bitc::METADATA_OLD_NODE: {
1671 // FIXME: Remove in 4.0.
1672 if (Record.size() % 2 == 1)
1673 return Error("Invalid record");
1675 unsigned Size = Record.size();
1676 SmallVector<Metadata *, 8> Elts;
1677 for (unsigned i = 0; i != Size; i += 2) {
1678 Type *Ty = getTypeByID(Record[i]);
1680 return Error("Invalid record");
1681 if (Ty->isMetadataTy())
1682 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1683 else if (!Ty->isVoidTy()) {
1685 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1686 assert(isa<ConstantAsMetadata>(MD) &&
1687 "Expected non-function-local metadata");
1690 Elts.push_back(nullptr);
1692 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1695 case bitc::METADATA_VALUE: {
1696 if (Record.size() != 2)
1697 return Error("Invalid record");
1699 Type *Ty = getTypeByID(Record[0]);
1700 if (Ty->isMetadataTy() || Ty->isVoidTy())
1701 return Error("Invalid record");
1703 MDValueList.AssignValue(
1704 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1708 case bitc::METADATA_DISTINCT_NODE:
1711 case bitc::METADATA_NODE: {
1712 SmallVector<Metadata *, 8> Elts;
1713 Elts.reserve(Record.size());
1714 for (unsigned ID : Record)
1715 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1716 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1717 : MDNode::get(Context, Elts),
1721 case bitc::METADATA_LOCATION: {
1722 if (Record.size() != 5)
1723 return Error("Invalid record");
1725 unsigned Line = Record[1];
1726 unsigned Column = Record[2];
1727 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1728 Metadata *InlinedAt =
1729 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1730 MDValueList.AssignValue(
1731 GET_OR_DISTINCT(DILocation, Record[0],
1732 (Context, Line, Column, Scope, InlinedAt)),
1736 case bitc::METADATA_GENERIC_DEBUG: {
1737 if (Record.size() < 4)
1738 return Error("Invalid record");
1740 unsigned Tag = Record[1];
1741 unsigned Version = Record[2];
1743 if (Tag >= 1u << 16 || Version != 0)
1744 return Error("Invalid record");
1746 auto *Header = getMDString(Record[3]);
1747 SmallVector<Metadata *, 8> DwarfOps;
1748 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1749 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1751 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1752 (Context, Tag, Header, DwarfOps)),
1756 case bitc::METADATA_SUBRANGE: {
1757 if (Record.size() != 3)
1758 return Error("Invalid record");
1760 MDValueList.AssignValue(
1761 GET_OR_DISTINCT(DISubrange, Record[0],
1762 (Context, Record[1], unrotateSign(Record[2]))),
1766 case bitc::METADATA_ENUMERATOR: {
1767 if (Record.size() != 3)
1768 return Error("Invalid record");
1770 MDValueList.AssignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1771 (Context, unrotateSign(Record[1]),
1772 getMDString(Record[2]))),
1776 case bitc::METADATA_BASIC_TYPE: {
1777 if (Record.size() != 6)
1778 return Error("Invalid record");
1780 MDValueList.AssignValue(
1781 GET_OR_DISTINCT(DIBasicType, Record[0],
1782 (Context, Record[1], getMDString(Record[2]),
1783 Record[3], Record[4], Record[5])),
1787 case bitc::METADATA_DERIVED_TYPE: {
1788 if (Record.size() != 12)
1789 return Error("Invalid record");
1791 MDValueList.AssignValue(
1792 GET_OR_DISTINCT(DIDerivedType, Record[0],
1793 (Context, Record[1], getMDString(Record[2]),
1794 getMDOrNull(Record[3]), Record[4],
1795 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1796 Record[7], Record[8], Record[9], Record[10],
1797 getMDOrNull(Record[11]))),
1801 case bitc::METADATA_COMPOSITE_TYPE: {
1802 if (Record.size() != 16)
1803 return Error("Invalid record");
1805 MDValueList.AssignValue(
1806 GET_OR_DISTINCT(DICompositeType, Record[0],
1807 (Context, Record[1], getMDString(Record[2]),
1808 getMDOrNull(Record[3]), Record[4],
1809 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1810 Record[7], Record[8], Record[9], Record[10],
1811 getMDOrNull(Record[11]), Record[12],
1812 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1813 getMDString(Record[15]))),
1817 case bitc::METADATA_SUBROUTINE_TYPE: {
1818 if (Record.size() != 3)
1819 return Error("Invalid record");
1821 MDValueList.AssignValue(
1822 GET_OR_DISTINCT(DISubroutineType, Record[0],
1823 (Context, Record[1], getMDOrNull(Record[2]))),
1827 case bitc::METADATA_FILE: {
1828 if (Record.size() != 3)
1829 return Error("Invalid record");
1831 MDValueList.AssignValue(
1832 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1833 getMDString(Record[2]))),
1837 case bitc::METADATA_COMPILE_UNIT: {
1838 if (Record.size() != 14)
1839 return Error("Invalid record");
1841 MDValueList.AssignValue(
1842 GET_OR_DISTINCT(DICompileUnit, Record[0],
1843 (Context, Record[1], getMDOrNull(Record[2]),
1844 getMDString(Record[3]), Record[4],
1845 getMDString(Record[5]), Record[6],
1846 getMDString(Record[7]), Record[8],
1847 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1848 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1849 getMDOrNull(Record[13]))),
1853 case bitc::METADATA_SUBPROGRAM: {
1854 if (Record.size() != 19)
1855 return Error("Invalid record");
1857 MDValueList.AssignValue(
1859 DISubprogram, Record[0],
1860 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1861 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1862 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1863 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1864 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1865 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1869 case bitc::METADATA_LEXICAL_BLOCK: {
1870 if (Record.size() != 5)
1871 return Error("Invalid record");
1873 MDValueList.AssignValue(
1874 GET_OR_DISTINCT(DILexicalBlock, Record[0],
1875 (Context, getMDOrNull(Record[1]),
1876 getMDOrNull(Record[2]), Record[3], Record[4])),
1880 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1881 if (Record.size() != 4)
1882 return Error("Invalid record");
1884 MDValueList.AssignValue(
1885 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1886 (Context, getMDOrNull(Record[1]),
1887 getMDOrNull(Record[2]), Record[3])),
1891 case bitc::METADATA_NAMESPACE: {
1892 if (Record.size() != 5)
1893 return Error("Invalid record");
1895 MDValueList.AssignValue(
1896 GET_OR_DISTINCT(DINamespace, Record[0],
1897 (Context, getMDOrNull(Record[1]),
1898 getMDOrNull(Record[2]), getMDString(Record[3]),
1903 case bitc::METADATA_TEMPLATE_TYPE: {
1904 if (Record.size() != 3)
1905 return Error("Invalid record");
1907 MDValueList.AssignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1909 (Context, getMDString(Record[1]),
1910 getMDOrNull(Record[2]))),
1914 case bitc::METADATA_TEMPLATE_VALUE: {
1915 if (Record.size() != 5)
1916 return Error("Invalid record");
1918 MDValueList.AssignValue(
1919 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1920 (Context, Record[1], getMDString(Record[2]),
1921 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1925 case bitc::METADATA_GLOBAL_VAR: {
1926 if (Record.size() != 11)
1927 return Error("Invalid record");
1929 MDValueList.AssignValue(
1930 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1931 (Context, getMDOrNull(Record[1]),
1932 getMDString(Record[2]), getMDString(Record[3]),
1933 getMDOrNull(Record[4]), Record[5],
1934 getMDOrNull(Record[6]), Record[7], Record[8],
1935 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1939 case bitc::METADATA_LOCAL_VAR: {
1940 // 10th field is for the obseleted 'inlinedAt:' field.
1941 if (Record.size() != 9 && Record.size() != 10)
1942 return Error("Invalid record");
1944 MDValueList.AssignValue(
1945 GET_OR_DISTINCT(DILocalVariable, Record[0],
1946 (Context, Record[1], getMDOrNull(Record[2]),
1947 getMDString(Record[3]), getMDOrNull(Record[4]),
1948 Record[5], getMDOrNull(Record[6]), Record[7],
1953 case bitc::METADATA_EXPRESSION: {
1954 if (Record.size() < 1)
1955 return Error("Invalid record");
1957 MDValueList.AssignValue(
1958 GET_OR_DISTINCT(DIExpression, Record[0],
1959 (Context, makeArrayRef(Record).slice(1))),
1963 case bitc::METADATA_OBJC_PROPERTY: {
1964 if (Record.size() != 8)
1965 return Error("Invalid record");
1967 MDValueList.AssignValue(
1968 GET_OR_DISTINCT(DIObjCProperty, Record[0],
1969 (Context, getMDString(Record[1]),
1970 getMDOrNull(Record[2]), Record[3],
1971 getMDString(Record[4]), getMDString(Record[5]),
1972 Record[6], getMDOrNull(Record[7]))),
1976 case bitc::METADATA_IMPORTED_ENTITY: {
1977 if (Record.size() != 6)
1978 return Error("Invalid record");
1980 MDValueList.AssignValue(
1981 GET_OR_DISTINCT(DIImportedEntity, Record[0],
1982 (Context, Record[1], getMDOrNull(Record[2]),
1983 getMDOrNull(Record[3]), Record[4],
1984 getMDString(Record[5]))),
1988 case bitc::METADATA_STRING: {
1989 std::string String(Record.begin(), Record.end());
1990 llvm::UpgradeMDStringConstant(String);
1991 Metadata *MD = MDString::get(Context, String);
1992 MDValueList.AssignValue(MD, NextMDValueNo++);
1995 case bitc::METADATA_KIND: {
1996 if (Record.size() < 2)
1997 return Error("Invalid record");
1999 unsigned Kind = Record[0];
2000 SmallString<8> Name(Record.begin()+1, Record.end());
2002 unsigned NewKind = TheModule->getMDKindID(Name.str());
2003 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2004 return Error("Conflicting METADATA_KIND records");
2009 #undef GET_OR_DISTINCT
2012 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
2013 /// the LSB for dense VBR encoding.
2014 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2019 // There is no such thing as -0 with integers. "-0" really means MININT.
2023 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
2024 /// values and aliases that we can.
2025 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
2026 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2027 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2028 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2029 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2031 GlobalInitWorklist.swap(GlobalInits);
2032 AliasInitWorklist.swap(AliasInits);
2033 FunctionPrefixWorklist.swap(FunctionPrefixes);
2034 FunctionPrologueWorklist.swap(FunctionPrologues);
2036 while (!GlobalInitWorklist.empty()) {
2037 unsigned ValID = GlobalInitWorklist.back().second;
2038 if (ValID >= ValueList.size()) {
2039 // Not ready to resolve this yet, it requires something later in the file.
2040 GlobalInits.push_back(GlobalInitWorklist.back());
2042 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2043 GlobalInitWorklist.back().first->setInitializer(C);
2045 return Error("Expected a constant");
2047 GlobalInitWorklist.pop_back();
2050 while (!AliasInitWorklist.empty()) {
2051 unsigned ValID = AliasInitWorklist.back().second;
2052 if (ValID >= ValueList.size()) {
2053 AliasInits.push_back(AliasInitWorklist.back());
2055 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2056 AliasInitWorklist.back().first->setAliasee(C);
2058 return Error("Expected a constant");
2060 AliasInitWorklist.pop_back();
2063 while (!FunctionPrefixWorklist.empty()) {
2064 unsigned ValID = FunctionPrefixWorklist.back().second;
2065 if (ValID >= ValueList.size()) {
2066 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2068 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2069 FunctionPrefixWorklist.back().first->setPrefixData(C);
2071 return Error("Expected a constant");
2073 FunctionPrefixWorklist.pop_back();
2076 while (!FunctionPrologueWorklist.empty()) {
2077 unsigned ValID = FunctionPrologueWorklist.back().second;
2078 if (ValID >= ValueList.size()) {
2079 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2081 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2082 FunctionPrologueWorklist.back().first->setPrologueData(C);
2084 return Error("Expected a constant");
2086 FunctionPrologueWorklist.pop_back();
2089 return std::error_code();
2092 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2093 SmallVector<uint64_t, 8> Words(Vals.size());
2094 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2095 BitcodeReader::decodeSignRotatedValue);
2097 return APInt(TypeBits, Words);
2100 std::error_code BitcodeReader::ParseConstants() {
2101 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2102 return Error("Invalid record");
2104 SmallVector<uint64_t, 64> Record;
2106 // Read all the records for this value table.
2107 Type *CurTy = Type::getInt32Ty(Context);
2108 unsigned NextCstNo = ValueList.size();
2110 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2112 switch (Entry.Kind) {
2113 case BitstreamEntry::SubBlock: // Handled for us already.
2114 case BitstreamEntry::Error:
2115 return Error("Malformed block");
2116 case BitstreamEntry::EndBlock:
2117 if (NextCstNo != ValueList.size())
2118 return Error("Invalid ronstant reference");
2120 // Once all the constants have been read, go through and resolve forward
2122 ValueList.ResolveConstantForwardRefs();
2123 return std::error_code();
2124 case BitstreamEntry::Record:
2125 // The interesting case.
2132 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2134 default: // Default behavior: unknown constant
2135 case bitc::CST_CODE_UNDEF: // UNDEF
2136 V = UndefValue::get(CurTy);
2138 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2140 return Error("Invalid record");
2141 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2142 return Error("Invalid record");
2143 CurTy = TypeList[Record[0]];
2144 continue; // Skip the ValueList manipulation.
2145 case bitc::CST_CODE_NULL: // NULL
2146 V = Constant::getNullValue(CurTy);
2148 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2149 if (!CurTy->isIntegerTy() || Record.empty())
2150 return Error("Invalid record");
2151 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2153 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2154 if (!CurTy->isIntegerTy() || Record.empty())
2155 return Error("Invalid record");
2157 APInt VInt = ReadWideAPInt(Record,
2158 cast<IntegerType>(CurTy)->getBitWidth());
2159 V = ConstantInt::get(Context, VInt);
2163 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2165 return Error("Invalid record");
2166 if (CurTy->isHalfTy())
2167 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2168 APInt(16, (uint16_t)Record[0])));
2169 else if (CurTy->isFloatTy())
2170 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2171 APInt(32, (uint32_t)Record[0])));
2172 else if (CurTy->isDoubleTy())
2173 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2174 APInt(64, Record[0])));
2175 else if (CurTy->isX86_FP80Ty()) {
2176 // Bits are not stored the same way as a normal i80 APInt, compensate.
2177 uint64_t Rearrange[2];
2178 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2179 Rearrange[1] = Record[0] >> 48;
2180 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2181 APInt(80, Rearrange)));
2182 } else if (CurTy->isFP128Ty())
2183 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2184 APInt(128, Record)));
2185 else if (CurTy->isPPC_FP128Ty())
2186 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2187 APInt(128, Record)));
2189 V = UndefValue::get(CurTy);
2193 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2195 return Error("Invalid record");
2197 unsigned Size = Record.size();
2198 SmallVector<Constant*, 16> Elts;
2200 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2201 for (unsigned i = 0; i != Size; ++i)
2202 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2203 STy->getElementType(i)));
2204 V = ConstantStruct::get(STy, Elts);
2205 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2206 Type *EltTy = ATy->getElementType();
2207 for (unsigned i = 0; i != Size; ++i)
2208 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2209 V = ConstantArray::get(ATy, Elts);
2210 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2211 Type *EltTy = VTy->getElementType();
2212 for (unsigned i = 0; i != Size; ++i)
2213 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2214 V = ConstantVector::get(Elts);
2216 V = UndefValue::get(CurTy);
2220 case bitc::CST_CODE_STRING: // STRING: [values]
2221 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2223 return Error("Invalid record");
2225 SmallString<16> Elts(Record.begin(), Record.end());
2226 V = ConstantDataArray::getString(Context, Elts,
2227 BitCode == bitc::CST_CODE_CSTRING);
2230 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2232 return Error("Invalid record");
2234 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2235 unsigned Size = Record.size();
2237 if (EltTy->isIntegerTy(8)) {
2238 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2239 if (isa<VectorType>(CurTy))
2240 V = ConstantDataVector::get(Context, Elts);
2242 V = ConstantDataArray::get(Context, Elts);
2243 } else if (EltTy->isIntegerTy(16)) {
2244 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2245 if (isa<VectorType>(CurTy))
2246 V = ConstantDataVector::get(Context, Elts);
2248 V = ConstantDataArray::get(Context, Elts);
2249 } else if (EltTy->isIntegerTy(32)) {
2250 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2251 if (isa<VectorType>(CurTy))
2252 V = ConstantDataVector::get(Context, Elts);
2254 V = ConstantDataArray::get(Context, Elts);
2255 } else if (EltTy->isIntegerTy(64)) {
2256 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2257 if (isa<VectorType>(CurTy))
2258 V = ConstantDataVector::get(Context, Elts);
2260 V = ConstantDataArray::get(Context, Elts);
2261 } else if (EltTy->isFloatTy()) {
2262 SmallVector<float, 16> Elts(Size);
2263 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2264 if (isa<VectorType>(CurTy))
2265 V = ConstantDataVector::get(Context, Elts);
2267 V = ConstantDataArray::get(Context, Elts);
2268 } else if (EltTy->isDoubleTy()) {
2269 SmallVector<double, 16> Elts(Size);
2270 std::transform(Record.begin(), Record.end(), Elts.begin(),
2272 if (isa<VectorType>(CurTy))
2273 V = ConstantDataVector::get(Context, Elts);
2275 V = ConstantDataArray::get(Context, Elts);
2277 return Error("Invalid type for value");
2282 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2283 if (Record.size() < 3)
2284 return Error("Invalid record");
2285 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2287 V = UndefValue::get(CurTy); // Unknown binop.
2289 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2290 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2292 if (Record.size() >= 4) {
2293 if (Opc == Instruction::Add ||
2294 Opc == Instruction::Sub ||
2295 Opc == Instruction::Mul ||
2296 Opc == Instruction::Shl) {
2297 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2298 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2299 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2300 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2301 } else if (Opc == Instruction::SDiv ||
2302 Opc == Instruction::UDiv ||
2303 Opc == Instruction::LShr ||
2304 Opc == Instruction::AShr) {
2305 if (Record[3] & (1 << bitc::PEO_EXACT))
2306 Flags |= SDivOperator::IsExact;
2309 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2313 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2314 if (Record.size() < 3)
2315 return Error("Invalid record");
2316 int Opc = GetDecodedCastOpcode(Record[0]);
2318 V = UndefValue::get(CurTy); // Unknown cast.
2320 Type *OpTy = getTypeByID(Record[1]);
2322 return Error("Invalid record");
2323 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2324 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2325 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2329 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2330 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2332 Type *PointeeType = nullptr;
2333 if (Record.size() % 2)
2334 PointeeType = getTypeByID(Record[OpNum++]);
2335 SmallVector<Constant*, 16> Elts;
2336 while (OpNum != Record.size()) {
2337 Type *ElTy = getTypeByID(Record[OpNum++]);
2339 return Error("Invalid record");
2340 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2345 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2347 return Error("Explicit gep operator type does not match pointee type "
2348 "of pointer operand");
2350 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2351 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2353 bitc::CST_CODE_CE_INBOUNDS_GEP);
2356 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2357 if (Record.size() < 3)
2358 return Error("Invalid record");
2360 Type *SelectorTy = Type::getInt1Ty(Context);
2362 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2363 // vector. Otherwise, it must be a single bit.
2364 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2365 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2366 VTy->getNumElements());
2368 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2370 ValueList.getConstantFwdRef(Record[1],CurTy),
2371 ValueList.getConstantFwdRef(Record[2],CurTy));
2374 case bitc::CST_CODE_CE_EXTRACTELT
2375 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2376 if (Record.size() < 3)
2377 return Error("Invalid record");
2379 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2381 return Error("Invalid record");
2382 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2383 Constant *Op1 = nullptr;
2384 if (Record.size() == 4) {
2385 Type *IdxTy = getTypeByID(Record[2]);
2387 return Error("Invalid record");
2388 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2389 } else // TODO: Remove with llvm 4.0
2390 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2392 return Error("Invalid record");
2393 V = ConstantExpr::getExtractElement(Op0, Op1);
2396 case bitc::CST_CODE_CE_INSERTELT
2397 : { // CE_INSERTELT: [opval, opval, opty, opval]
2398 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2399 if (Record.size() < 3 || !OpTy)
2400 return Error("Invalid record");
2401 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2402 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2403 OpTy->getElementType());
2404 Constant *Op2 = nullptr;
2405 if (Record.size() == 4) {
2406 Type *IdxTy = getTypeByID(Record[2]);
2408 return Error("Invalid record");
2409 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2410 } else // TODO: Remove with llvm 4.0
2411 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2413 return Error("Invalid record");
2414 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2417 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2418 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2419 if (Record.size() < 3 || !OpTy)
2420 return Error("Invalid record");
2421 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2422 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2423 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2424 OpTy->getNumElements());
2425 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2426 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2429 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2430 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2432 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2433 if (Record.size() < 4 || !RTy || !OpTy)
2434 return Error("Invalid record");
2435 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2436 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2437 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2438 RTy->getNumElements());
2439 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2440 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2443 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2444 if (Record.size() < 4)
2445 return Error("Invalid record");
2446 Type *OpTy = getTypeByID(Record[0]);
2448 return Error("Invalid record");
2449 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2450 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2452 if (OpTy->isFPOrFPVectorTy())
2453 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2455 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2458 // This maintains backward compatibility, pre-asm dialect keywords.
2459 // FIXME: Remove with the 4.0 release.
2460 case bitc::CST_CODE_INLINEASM_OLD: {
2461 if (Record.size() < 2)
2462 return Error("Invalid record");
2463 std::string AsmStr, ConstrStr;
2464 bool HasSideEffects = Record[0] & 1;
2465 bool IsAlignStack = Record[0] >> 1;
2466 unsigned AsmStrSize = Record[1];
2467 if (2+AsmStrSize >= Record.size())
2468 return Error("Invalid record");
2469 unsigned ConstStrSize = Record[2+AsmStrSize];
2470 if (3+AsmStrSize+ConstStrSize > Record.size())
2471 return Error("Invalid record");
2473 for (unsigned i = 0; i != AsmStrSize; ++i)
2474 AsmStr += (char)Record[2+i];
2475 for (unsigned i = 0; i != ConstStrSize; ++i)
2476 ConstrStr += (char)Record[3+AsmStrSize+i];
2477 PointerType *PTy = cast<PointerType>(CurTy);
2478 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2479 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2482 // This version adds support for the asm dialect keywords (e.g.,
2484 case bitc::CST_CODE_INLINEASM: {
2485 if (Record.size() < 2)
2486 return Error("Invalid record");
2487 std::string AsmStr, ConstrStr;
2488 bool HasSideEffects = Record[0] & 1;
2489 bool IsAlignStack = (Record[0] >> 1) & 1;
2490 unsigned AsmDialect = Record[0] >> 2;
2491 unsigned AsmStrSize = Record[1];
2492 if (2+AsmStrSize >= Record.size())
2493 return Error("Invalid record");
2494 unsigned ConstStrSize = Record[2+AsmStrSize];
2495 if (3+AsmStrSize+ConstStrSize > Record.size())
2496 return Error("Invalid record");
2498 for (unsigned i = 0; i != AsmStrSize; ++i)
2499 AsmStr += (char)Record[2+i];
2500 for (unsigned i = 0; i != ConstStrSize; ++i)
2501 ConstrStr += (char)Record[3+AsmStrSize+i];
2502 PointerType *PTy = cast<PointerType>(CurTy);
2503 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2504 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2505 InlineAsm::AsmDialect(AsmDialect));
2508 case bitc::CST_CODE_BLOCKADDRESS:{
2509 if (Record.size() < 3)
2510 return Error("Invalid record");
2511 Type *FnTy = getTypeByID(Record[0]);
2513 return Error("Invalid record");
2515 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2517 return Error("Invalid record");
2519 // Don't let Fn get dematerialized.
2520 BlockAddressesTaken.insert(Fn);
2522 // If the function is already parsed we can insert the block address right
2525 unsigned BBID = Record[2];
2527 // Invalid reference to entry block.
2528 return Error("Invalid ID");
2530 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2531 for (size_t I = 0, E = BBID; I != E; ++I) {
2533 return Error("Invalid ID");
2538 // Otherwise insert a placeholder and remember it so it can be inserted
2539 // when the function is parsed.
2540 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2542 BasicBlockFwdRefQueue.push_back(Fn);
2543 if (FwdBBs.size() < BBID + 1)
2544 FwdBBs.resize(BBID + 1);
2546 FwdBBs[BBID] = BasicBlock::Create(Context);
2549 V = BlockAddress::get(Fn, BB);
2554 ValueList.AssignValue(V, NextCstNo);
2559 std::error_code BitcodeReader::ParseUseLists() {
2560 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2561 return Error("Invalid record");
2563 // Read all the records.
2564 SmallVector<uint64_t, 64> Record;
2566 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2568 switch (Entry.Kind) {
2569 case BitstreamEntry::SubBlock: // Handled for us already.
2570 case BitstreamEntry::Error:
2571 return Error("Malformed block");
2572 case BitstreamEntry::EndBlock:
2573 return std::error_code();
2574 case BitstreamEntry::Record:
2575 // The interesting case.
2579 // Read a use list record.
2582 switch (Stream.readRecord(Entry.ID, Record)) {
2583 default: // Default behavior: unknown type.
2585 case bitc::USELIST_CODE_BB:
2588 case bitc::USELIST_CODE_DEFAULT: {
2589 unsigned RecordLength = Record.size();
2590 if (RecordLength < 3)
2591 // Records should have at least an ID and two indexes.
2592 return Error("Invalid record");
2593 unsigned ID = Record.back();
2598 assert(ID < FunctionBBs.size() && "Basic block not found");
2599 V = FunctionBBs[ID];
2602 unsigned NumUses = 0;
2603 SmallDenseMap<const Use *, unsigned, 16> Order;
2604 for (const Use &U : V->uses()) {
2605 if (++NumUses > Record.size())
2607 Order[&U] = Record[NumUses - 1];
2609 if (Order.size() != Record.size() || NumUses > Record.size())
2610 // Mismatches can happen if the functions are being materialized lazily
2611 // (out-of-order), or a value has been upgraded.
2614 V->sortUseList([&](const Use &L, const Use &R) {
2615 return Order.lookup(&L) < Order.lookup(&R);
2623 /// When we see the block for metadata, remember where it is and then skip it.
2624 /// This lets us lazily deserialize the metadata.
2625 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2626 // Save the current stream state.
2627 uint64_t CurBit = Stream.GetCurrentBitNo();
2628 DeferredMetadataInfo.push_back(CurBit);
2630 // Skip over the block for now.
2631 if (Stream.SkipBlock())
2632 return Error("Invalid record");
2633 return std::error_code();
2636 std::error_code BitcodeReader::materializeMetadata() {
2637 for (uint64_t BitPos : DeferredMetadataInfo) {
2638 // Move the bit stream to the saved position.
2639 Stream.JumpToBit(BitPos);
2640 if (std::error_code EC = ParseMetadata())
2643 DeferredMetadataInfo.clear();
2644 return std::error_code();
2647 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2649 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2650 /// remember where it is and then skip it. This lets us lazily deserialize the
2652 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2653 // Get the function we are talking about.
2654 if (FunctionsWithBodies.empty())
2655 return Error("Insufficient function protos");
2657 Function *Fn = FunctionsWithBodies.back();
2658 FunctionsWithBodies.pop_back();
2660 // Save the current stream state.
2661 uint64_t CurBit = Stream.GetCurrentBitNo();
2662 DeferredFunctionInfo[Fn] = CurBit;
2664 // Skip over the function block for now.
2665 if (Stream.SkipBlock())
2666 return Error("Invalid record");
2667 return std::error_code();
2670 std::error_code BitcodeReader::GlobalCleanup() {
2671 // Patch the initializers for globals and aliases up.
2672 ResolveGlobalAndAliasInits();
2673 if (!GlobalInits.empty() || !AliasInits.empty())
2674 return Error("Malformed global initializer set");
2676 // Look for intrinsic functions which need to be upgraded at some point
2677 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2680 if (UpgradeIntrinsicFunction(FI, NewFn))
2681 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2684 // Look for global variables which need to be renamed.
2685 for (Module::global_iterator
2686 GI = TheModule->global_begin(), GE = TheModule->global_end();
2688 GlobalVariable *GV = GI++;
2689 UpgradeGlobalVariable(GV);
2692 // Force deallocation of memory for these vectors to favor the client that
2693 // want lazy deserialization.
2694 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2695 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2696 return std::error_code();
2699 std::error_code BitcodeReader::ParseModule(bool Resume,
2700 bool ShouldLazyLoadMetadata) {
2702 Stream.JumpToBit(NextUnreadBit);
2703 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2704 return Error("Invalid record");
2706 SmallVector<uint64_t, 64> Record;
2707 std::vector<std::string> SectionTable;
2708 std::vector<std::string> GCTable;
2710 // Read all the records for this module.
2712 BitstreamEntry Entry = Stream.advance();
2714 switch (Entry.Kind) {
2715 case BitstreamEntry::Error:
2716 return Error("Malformed block");
2717 case BitstreamEntry::EndBlock:
2718 return GlobalCleanup();
2720 case BitstreamEntry::SubBlock:
2722 default: // Skip unknown content.
2723 if (Stream.SkipBlock())
2724 return Error("Invalid record");
2726 case bitc::BLOCKINFO_BLOCK_ID:
2727 if (Stream.ReadBlockInfoBlock())
2728 return Error("Malformed block");
2730 case bitc::PARAMATTR_BLOCK_ID:
2731 if (std::error_code EC = ParseAttributeBlock())
2734 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2735 if (std::error_code EC = ParseAttributeGroupBlock())
2738 case bitc::TYPE_BLOCK_ID_NEW:
2739 if (std::error_code EC = ParseTypeTable())
2742 case bitc::VALUE_SYMTAB_BLOCK_ID:
2743 if (std::error_code EC = ParseValueSymbolTable())
2745 SeenValueSymbolTable = true;
2747 case bitc::CONSTANTS_BLOCK_ID:
2748 if (std::error_code EC = ParseConstants())
2750 if (std::error_code EC = ResolveGlobalAndAliasInits())
2753 case bitc::METADATA_BLOCK_ID:
2754 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2755 if (std::error_code EC = rememberAndSkipMetadata())
2759 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2760 if (std::error_code EC = ParseMetadata())
2763 case bitc::FUNCTION_BLOCK_ID:
2764 // If this is the first function body we've seen, reverse the
2765 // FunctionsWithBodies list.
2766 if (!SeenFirstFunctionBody) {
2767 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2768 if (std::error_code EC = GlobalCleanup())
2770 SeenFirstFunctionBody = true;
2773 if (std::error_code EC = RememberAndSkipFunctionBody())
2775 // For streaming bitcode, suspend parsing when we reach the function
2776 // bodies. Subsequent materialization calls will resume it when
2777 // necessary. For streaming, the function bodies must be at the end of
2778 // the bitcode. If the bitcode file is old, the symbol table will be
2779 // at the end instead and will not have been seen yet. In this case,
2780 // just finish the parse now.
2781 if (LazyStreamer && SeenValueSymbolTable) {
2782 NextUnreadBit = Stream.GetCurrentBitNo();
2783 return std::error_code();
2786 case bitc::USELIST_BLOCK_ID:
2787 if (std::error_code EC = ParseUseLists())
2793 case BitstreamEntry::Record:
2794 // The interesting case.
2800 switch (Stream.readRecord(Entry.ID, Record)) {
2801 default: break; // Default behavior, ignore unknown content.
2802 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2803 if (Record.size() < 1)
2804 return Error("Invalid record");
2805 // Only version #0 and #1 are supported so far.
2806 unsigned module_version = Record[0];
2807 switch (module_version) {
2809 return Error("Invalid value");
2811 UseRelativeIDs = false;
2814 UseRelativeIDs = true;
2819 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2821 if (ConvertToString(Record, 0, S))
2822 return Error("Invalid record");
2823 TheModule->setTargetTriple(S);
2826 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2828 if (ConvertToString(Record, 0, S))
2829 return Error("Invalid record");
2830 TheModule->setDataLayout(S);
2833 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2835 if (ConvertToString(Record, 0, S))
2836 return Error("Invalid record");
2837 TheModule->setModuleInlineAsm(S);
2840 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2841 // FIXME: Remove in 4.0.
2843 if (ConvertToString(Record, 0, S))
2844 return Error("Invalid record");
2848 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2850 if (ConvertToString(Record, 0, S))
2851 return Error("Invalid record");
2852 SectionTable.push_back(S);
2855 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2857 if (ConvertToString(Record, 0, S))
2858 return Error("Invalid record");
2859 GCTable.push_back(S);
2862 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2863 if (Record.size() < 2)
2864 return Error("Invalid record");
2865 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2866 unsigned ComdatNameSize = Record[1];
2867 std::string ComdatName;
2868 ComdatName.reserve(ComdatNameSize);
2869 for (unsigned i = 0; i != ComdatNameSize; ++i)
2870 ComdatName += (char)Record[2 + i];
2871 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2872 C->setSelectionKind(SK);
2873 ComdatList.push_back(C);
2876 // GLOBALVAR: [pointer type, isconst, initid,
2877 // linkage, alignment, section, visibility, threadlocal,
2878 // unnamed_addr, externally_initialized, dllstorageclass,
2880 case bitc::MODULE_CODE_GLOBALVAR: {
2881 if (Record.size() < 6)
2882 return Error("Invalid record");
2883 Type *Ty = getTypeByID(Record[0]);
2885 return Error("Invalid record");
2886 bool isConstant = Record[1] & 1;
2887 bool explicitType = Record[1] & 2;
2888 unsigned AddressSpace;
2890 AddressSpace = Record[1] >> 2;
2892 if (!Ty->isPointerTy())
2893 return Error("Invalid type for value");
2894 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2895 Ty = cast<PointerType>(Ty)->getElementType();
2898 uint64_t RawLinkage = Record[3];
2899 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2901 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2903 std::string Section;
2905 if (Record[5]-1 >= SectionTable.size())
2906 return Error("Invalid ID");
2907 Section = SectionTable[Record[5]-1];
2909 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2910 // Local linkage must have default visibility.
2911 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2912 // FIXME: Change to an error if non-default in 4.0.
2913 Visibility = GetDecodedVisibility(Record[6]);
2915 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2916 if (Record.size() > 7)
2917 TLM = GetDecodedThreadLocalMode(Record[7]);
2919 bool UnnamedAddr = false;
2920 if (Record.size() > 8)
2921 UnnamedAddr = Record[8];
2923 bool ExternallyInitialized = false;
2924 if (Record.size() > 9)
2925 ExternallyInitialized = Record[9];
2927 GlobalVariable *NewGV =
2928 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2929 TLM, AddressSpace, ExternallyInitialized);
2930 NewGV->setAlignment(Alignment);
2931 if (!Section.empty())
2932 NewGV->setSection(Section);
2933 NewGV->setVisibility(Visibility);
2934 NewGV->setUnnamedAddr(UnnamedAddr);
2936 if (Record.size() > 10)
2937 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2939 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2941 ValueList.push_back(NewGV);
2943 // Remember which value to use for the global initializer.
2944 if (unsigned InitID = Record[2])
2945 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2947 if (Record.size() > 11) {
2948 if (unsigned ComdatID = Record[11]) {
2949 assert(ComdatID <= ComdatList.size());
2950 NewGV->setComdat(ComdatList[ComdatID - 1]);
2952 } else if (hasImplicitComdat(RawLinkage)) {
2953 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2957 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2958 // alignment, section, visibility, gc, unnamed_addr,
2959 // prologuedata, dllstorageclass, comdat, prefixdata]
2960 case bitc::MODULE_CODE_FUNCTION: {
2961 if (Record.size() < 8)
2962 return Error("Invalid record");
2963 Type *Ty = getTypeByID(Record[0]);
2965 return Error("Invalid record");
2966 if (auto *PTy = dyn_cast<PointerType>(Ty))
2967 Ty = PTy->getElementType();
2968 auto *FTy = dyn_cast<FunctionType>(Ty);
2970 return Error("Invalid type for value");
2972 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2975 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2976 bool isProto = Record[2];
2977 uint64_t RawLinkage = Record[3];
2978 Func->setLinkage(getDecodedLinkage(RawLinkage));
2979 Func->setAttributes(getAttributes(Record[4]));
2982 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2984 Func->setAlignment(Alignment);
2986 if (Record[6]-1 >= SectionTable.size())
2987 return Error("Invalid ID");
2988 Func->setSection(SectionTable[Record[6]-1]);
2990 // Local linkage must have default visibility.
2991 if (!Func->hasLocalLinkage())
2992 // FIXME: Change to an error if non-default in 4.0.
2993 Func->setVisibility(GetDecodedVisibility(Record[7]));
2994 if (Record.size() > 8 && Record[8]) {
2995 if (Record[8]-1 >= GCTable.size())
2996 return Error("Invalid ID");
2997 Func->setGC(GCTable[Record[8]-1].c_str());
2999 bool UnnamedAddr = false;
3000 if (Record.size() > 9)
3001 UnnamedAddr = Record[9];
3002 Func->setUnnamedAddr(UnnamedAddr);
3003 if (Record.size() > 10 && Record[10] != 0)
3004 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3006 if (Record.size() > 11)
3007 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
3009 UpgradeDLLImportExportLinkage(Func, RawLinkage);
3011 if (Record.size() > 12) {
3012 if (unsigned ComdatID = Record[12]) {
3013 assert(ComdatID <= ComdatList.size());
3014 Func->setComdat(ComdatList[ComdatID - 1]);
3016 } else if (hasImplicitComdat(RawLinkage)) {
3017 Func->setComdat(reinterpret_cast<Comdat *>(1));
3020 if (Record.size() > 13 && Record[13] != 0)
3021 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3023 ValueList.push_back(Func);
3025 // If this is a function with a body, remember the prototype we are
3026 // creating now, so that we can match up the body with them later.
3028 Func->setIsMaterializable(true);
3029 FunctionsWithBodies.push_back(Func);
3031 DeferredFunctionInfo[Func] = 0;
3035 // ALIAS: [alias type, aliasee val#, linkage]
3036 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3037 case bitc::MODULE_CODE_ALIAS: {
3038 if (Record.size() < 3)
3039 return Error("Invalid record");
3040 Type *Ty = getTypeByID(Record[0]);
3042 return Error("Invalid record");
3043 auto *PTy = dyn_cast<PointerType>(Ty);
3045 return Error("Invalid type for value");
3048 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3049 // Old bitcode files didn't have visibility field.
3050 // Local linkage must have default visibility.
3051 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3052 // FIXME: Change to an error if non-default in 4.0.
3053 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3054 if (Record.size() > 4)
3055 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3057 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3058 if (Record.size() > 5)
3059 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3060 if (Record.size() > 6)
3061 NewGA->setUnnamedAddr(Record[6]);
3062 ValueList.push_back(NewGA);
3063 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3066 /// MODULE_CODE_PURGEVALS: [numvals]
3067 case bitc::MODULE_CODE_PURGEVALS:
3068 // Trim down the value list to the specified size.
3069 if (Record.size() < 1 || Record[0] > ValueList.size())
3070 return Error("Invalid record");
3071 ValueList.shrinkTo(Record[0]);
3078 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3079 bool ShouldLazyLoadMetadata) {
3080 TheModule = nullptr;
3082 if (std::error_code EC = InitStream())
3085 // Sniff for the signature.
3086 if (Stream.Read(8) != 'B' ||
3087 Stream.Read(8) != 'C' ||
3088 Stream.Read(4) != 0x0 ||
3089 Stream.Read(4) != 0xC ||
3090 Stream.Read(4) != 0xE ||
3091 Stream.Read(4) != 0xD)
3092 return Error("Invalid bitcode signature");
3094 // We expect a number of well-defined blocks, though we don't necessarily
3095 // need to understand them all.
3097 if (Stream.AtEndOfStream()) {
3099 return std::error_code();
3100 // We didn't really read a proper Module.
3101 return Error("Malformed IR file");
3104 BitstreamEntry Entry =
3105 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3107 switch (Entry.Kind) {
3108 case BitstreamEntry::Error:
3109 return Error("Malformed block");
3110 case BitstreamEntry::EndBlock:
3111 return std::error_code();
3113 case BitstreamEntry::SubBlock:
3115 case bitc::BLOCKINFO_BLOCK_ID:
3116 if (Stream.ReadBlockInfoBlock())
3117 return Error("Malformed block");
3119 case bitc::MODULE_BLOCK_ID:
3120 // Reject multiple MODULE_BLOCK's in a single bitstream.
3122 return Error("Invalid multiple blocks");
3124 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3127 return std::error_code();
3130 if (Stream.SkipBlock())
3131 return Error("Invalid record");
3135 case BitstreamEntry::Record:
3136 // There should be no records in the top-level of blocks.
3138 // The ranlib in Xcode 4 will align archive members by appending newlines
3139 // to the end of them. If this file size is a multiple of 4 but not 8, we
3140 // have to read and ignore these final 4 bytes :-(
3141 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3142 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3143 Stream.AtEndOfStream())
3144 return std::error_code();
3146 return Error("Invalid record");
3151 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3152 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3153 return Error("Invalid record");
3155 SmallVector<uint64_t, 64> Record;
3158 // Read all the records for this module.
3160 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3162 switch (Entry.Kind) {
3163 case BitstreamEntry::SubBlock: // Handled for us already.
3164 case BitstreamEntry::Error:
3165 return Error("Malformed block");
3166 case BitstreamEntry::EndBlock:
3168 case BitstreamEntry::Record:
3169 // The interesting case.
3174 switch (Stream.readRecord(Entry.ID, Record)) {
3175 default: break; // Default behavior, ignore unknown content.
3176 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3178 if (ConvertToString(Record, 0, S))
3179 return Error("Invalid record");
3186 llvm_unreachable("Exit infinite loop");
3189 ErrorOr<std::string> BitcodeReader::parseTriple() {
3190 if (std::error_code EC = InitStream())
3193 // Sniff for the signature.
3194 if (Stream.Read(8) != 'B' ||
3195 Stream.Read(8) != 'C' ||
3196 Stream.Read(4) != 0x0 ||
3197 Stream.Read(4) != 0xC ||
3198 Stream.Read(4) != 0xE ||
3199 Stream.Read(4) != 0xD)
3200 return Error("Invalid bitcode signature");
3202 // We expect a number of well-defined blocks, though we don't necessarily
3203 // need to understand them all.
3205 BitstreamEntry Entry = Stream.advance();
3207 switch (Entry.Kind) {
3208 case BitstreamEntry::Error:
3209 return Error("Malformed block");
3210 case BitstreamEntry::EndBlock:
3211 return std::error_code();
3213 case BitstreamEntry::SubBlock:
3214 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3215 return parseModuleTriple();
3217 // Ignore other sub-blocks.
3218 if (Stream.SkipBlock())
3219 return Error("Malformed block");
3222 case BitstreamEntry::Record:
3223 Stream.skipRecord(Entry.ID);
3229 /// ParseMetadataAttachment - Parse metadata attachments.
3230 std::error_code BitcodeReader::ParseMetadataAttachment(Function &F) {
3231 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3232 return Error("Invalid record");
3234 SmallVector<uint64_t, 64> Record;
3236 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3238 switch (Entry.Kind) {
3239 case BitstreamEntry::SubBlock: // Handled for us already.
3240 case BitstreamEntry::Error:
3241 return Error("Malformed block");
3242 case BitstreamEntry::EndBlock:
3243 return std::error_code();
3244 case BitstreamEntry::Record:
3245 // The interesting case.
3249 // Read a metadata attachment record.
3251 switch (Stream.readRecord(Entry.ID, Record)) {
3252 default: // Default behavior: ignore.
3254 case bitc::METADATA_ATTACHMENT: {
3255 unsigned RecordLength = Record.size();
3257 return Error("Invalid record");
3258 if (RecordLength % 2 == 0) {
3259 // A function attachment.
3260 for (unsigned I = 0; I != RecordLength; I += 2) {
3261 auto K = MDKindMap.find(Record[I]);
3262 if (K == MDKindMap.end())
3263 return Error("Invalid ID");
3264 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3265 F.setMetadata(K->second, cast<MDNode>(MD));
3270 // An instruction attachment.
3271 Instruction *Inst = InstructionList[Record[0]];
3272 for (unsigned i = 1; i != RecordLength; i = i+2) {
3273 unsigned Kind = Record[i];
3274 DenseMap<unsigned, unsigned>::iterator I =
3275 MDKindMap.find(Kind);
3276 if (I == MDKindMap.end())
3277 return Error("Invalid ID");
3278 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3279 if (isa<LocalAsMetadata>(Node))
3280 // Drop the attachment. This used to be legal, but there's no
3283 Inst->setMetadata(I->second, cast<MDNode>(Node));
3284 if (I->second == LLVMContext::MD_tbaa)
3285 InstsWithTBAATag.push_back(Inst);
3293 /// ParseFunctionBody - Lazily parse the specified function body block.
3294 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3295 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3296 return Error("Invalid record");
3298 InstructionList.clear();
3299 unsigned ModuleValueListSize = ValueList.size();
3300 unsigned ModuleMDValueListSize = MDValueList.size();
3302 // Add all the function arguments to the value table.
3303 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3304 ValueList.push_back(I);
3306 unsigned NextValueNo = ValueList.size();
3307 BasicBlock *CurBB = nullptr;
3308 unsigned CurBBNo = 0;
3311 auto getLastInstruction = [&]() -> Instruction * {
3312 if (CurBB && !CurBB->empty())
3313 return &CurBB->back();
3314 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3315 !FunctionBBs[CurBBNo - 1]->empty())
3316 return &FunctionBBs[CurBBNo - 1]->back();
3320 // Read all the records.
3321 SmallVector<uint64_t, 64> Record;
3323 BitstreamEntry Entry = Stream.advance();
3325 switch (Entry.Kind) {
3326 case BitstreamEntry::Error:
3327 return Error("Malformed block");
3328 case BitstreamEntry::EndBlock:
3329 goto OutOfRecordLoop;
3331 case BitstreamEntry::SubBlock:
3333 default: // Skip unknown content.
3334 if (Stream.SkipBlock())
3335 return Error("Invalid record");
3337 case bitc::CONSTANTS_BLOCK_ID:
3338 if (std::error_code EC = ParseConstants())
3340 NextValueNo = ValueList.size();
3342 case bitc::VALUE_SYMTAB_BLOCK_ID:
3343 if (std::error_code EC = ParseValueSymbolTable())
3346 case bitc::METADATA_ATTACHMENT_ID:
3347 if (std::error_code EC = ParseMetadataAttachment(*F))
3350 case bitc::METADATA_BLOCK_ID:
3351 if (std::error_code EC = ParseMetadata())
3354 case bitc::USELIST_BLOCK_ID:
3355 if (std::error_code EC = ParseUseLists())
3361 case BitstreamEntry::Record:
3362 // The interesting case.
3368 Instruction *I = nullptr;
3369 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3371 default: // Default behavior: reject
3372 return Error("Invalid value");
3373 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3374 if (Record.size() < 1 || Record[0] == 0)
3375 return Error("Invalid record");
3376 // Create all the basic blocks for the function.
3377 FunctionBBs.resize(Record[0]);
3379 // See if anything took the address of blocks in this function.
3380 auto BBFRI = BasicBlockFwdRefs.find(F);
3381 if (BBFRI == BasicBlockFwdRefs.end()) {
3382 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3383 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3385 auto &BBRefs = BBFRI->second;
3386 // Check for invalid basic block references.
3387 if (BBRefs.size() > FunctionBBs.size())
3388 return Error("Invalid ID");
3389 assert(!BBRefs.empty() && "Unexpected empty array");
3390 assert(!BBRefs.front() && "Invalid reference to entry block");
3391 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3393 if (I < RE && BBRefs[I]) {
3394 BBRefs[I]->insertInto(F);
3395 FunctionBBs[I] = BBRefs[I];
3397 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3400 // Erase from the table.
3401 BasicBlockFwdRefs.erase(BBFRI);
3404 CurBB = FunctionBBs[0];
3408 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3409 // This record indicates that the last instruction is at the same
3410 // location as the previous instruction with a location.
3411 I = getLastInstruction();
3414 return Error("Invalid record");
3415 I->setDebugLoc(LastLoc);
3419 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3420 I = getLastInstruction();
3421 if (!I || Record.size() < 4)
3422 return Error("Invalid record");
3424 unsigned Line = Record[0], Col = Record[1];
3425 unsigned ScopeID = Record[2], IAID = Record[3];
3427 MDNode *Scope = nullptr, *IA = nullptr;
3428 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3429 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3430 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3431 I->setDebugLoc(LastLoc);
3436 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3439 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3440 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3441 OpNum+1 > Record.size())
3442 return Error("Invalid record");
3444 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3446 return Error("Invalid record");
3447 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3448 InstructionList.push_back(I);
3449 if (OpNum < Record.size()) {
3450 if (Opc == Instruction::Add ||
3451 Opc == Instruction::Sub ||
3452 Opc == Instruction::Mul ||
3453 Opc == Instruction::Shl) {
3454 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3455 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3456 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3457 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3458 } else if (Opc == Instruction::SDiv ||
3459 Opc == Instruction::UDiv ||
3460 Opc == Instruction::LShr ||
3461 Opc == Instruction::AShr) {
3462 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3463 cast<BinaryOperator>(I)->setIsExact(true);
3464 } else if (isa<FPMathOperator>(I)) {
3466 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3467 FMF.setUnsafeAlgebra();
3468 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3470 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3472 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3473 FMF.setNoSignedZeros();
3474 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3475 FMF.setAllowReciprocal();
3477 I->setFastMathFlags(FMF);
3483 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3486 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3487 OpNum+2 != Record.size())
3488 return Error("Invalid record");
3490 Type *ResTy = getTypeByID(Record[OpNum]);
3491 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3492 if (Opc == -1 || !ResTy)
3493 return Error("Invalid record");
3494 Instruction *Temp = nullptr;
3495 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3497 InstructionList.push_back(Temp);
3498 CurBB->getInstList().push_back(Temp);
3501 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3503 InstructionList.push_back(I);
3506 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3507 case bitc::FUNC_CODE_INST_GEP_OLD:
3508 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3514 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3515 InBounds = Record[OpNum++];
3516 Ty = getTypeByID(Record[OpNum++]);
3518 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3523 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3524 return Error("Invalid record");
3527 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3530 cast<SequentialType>(BasePtr->getType()->getScalarType())
3533 "Explicit gep type does not match pointee type of pointer operand");
3535 SmallVector<Value*, 16> GEPIdx;
3536 while (OpNum != Record.size()) {
3538 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3539 return Error("Invalid record");
3540 GEPIdx.push_back(Op);
3543 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3545 InstructionList.push_back(I);
3547 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3551 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3552 // EXTRACTVAL: [opty, opval, n x indices]
3555 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3556 return Error("Invalid record");
3558 SmallVector<unsigned, 4> EXTRACTVALIdx;
3559 Type *CurTy = Agg->getType();
3560 for (unsigned RecSize = Record.size();
3561 OpNum != RecSize; ++OpNum) {
3562 bool IsArray = CurTy->isArrayTy();
3563 bool IsStruct = CurTy->isStructTy();
3564 uint64_t Index = Record[OpNum];
3566 if (!IsStruct && !IsArray)
3567 return Error("EXTRACTVAL: Invalid type");
3568 if ((unsigned)Index != Index)
3569 return Error("Invalid value");
3570 if (IsStruct && Index >= CurTy->subtypes().size())
3571 return Error("EXTRACTVAL: Invalid struct index");
3572 if (IsArray && Index >= CurTy->getArrayNumElements())
3573 return Error("EXTRACTVAL: Invalid array index");
3574 EXTRACTVALIdx.push_back((unsigned)Index);
3577 CurTy = CurTy->subtypes()[Index];
3579 CurTy = CurTy->subtypes()[0];
3582 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3583 InstructionList.push_back(I);
3587 case bitc::FUNC_CODE_INST_INSERTVAL: {
3588 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3591 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3592 return Error("Invalid record");
3594 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3595 return Error("Invalid record");
3597 SmallVector<unsigned, 4> INSERTVALIdx;
3598 Type *CurTy = Agg->getType();
3599 for (unsigned RecSize = Record.size();
3600 OpNum != RecSize; ++OpNum) {
3601 bool IsArray = CurTy->isArrayTy();
3602 bool IsStruct = CurTy->isStructTy();
3603 uint64_t Index = Record[OpNum];
3605 if (!IsStruct && !IsArray)
3606 return Error("INSERTVAL: Invalid type");
3607 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3608 return Error("Invalid type");
3609 if ((unsigned)Index != Index)
3610 return Error("Invalid value");
3611 if (IsStruct && Index >= CurTy->subtypes().size())
3612 return Error("INSERTVAL: Invalid struct index");
3613 if (IsArray && Index >= CurTy->getArrayNumElements())
3614 return Error("INSERTVAL: Invalid array index");
3616 INSERTVALIdx.push_back((unsigned)Index);
3618 CurTy = CurTy->subtypes()[Index];
3620 CurTy = CurTy->subtypes()[0];
3623 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3624 InstructionList.push_back(I);
3628 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3629 // obsolete form of select
3630 // handles select i1 ... in old bitcode
3632 Value *TrueVal, *FalseVal, *Cond;
3633 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3634 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3635 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3636 return Error("Invalid record");
3638 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3639 InstructionList.push_back(I);
3643 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3644 // new form of select
3645 // handles select i1 or select [N x i1]
3647 Value *TrueVal, *FalseVal, *Cond;
3648 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3649 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3650 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3651 return Error("Invalid record");
3653 // select condition can be either i1 or [N x i1]
3654 if (VectorType* vector_type =
3655 dyn_cast<VectorType>(Cond->getType())) {
3657 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3658 return Error("Invalid type for value");
3661 if (Cond->getType() != Type::getInt1Ty(Context))
3662 return Error("Invalid type for value");
3665 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3666 InstructionList.push_back(I);
3670 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3673 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3674 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3675 return Error("Invalid record");
3676 if (!Vec->getType()->isVectorTy())
3677 return Error("Invalid type for value");
3678 I = ExtractElementInst::Create(Vec, Idx);
3679 InstructionList.push_back(I);
3683 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3685 Value *Vec, *Elt, *Idx;
3686 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3687 return Error("Invalid record");
3688 if (!Vec->getType()->isVectorTy())
3689 return Error("Invalid type for value");
3690 if (popValue(Record, OpNum, NextValueNo,
3691 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3692 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3693 return Error("Invalid record");
3694 I = InsertElementInst::Create(Vec, Elt, Idx);
3695 InstructionList.push_back(I);
3699 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3701 Value *Vec1, *Vec2, *Mask;
3702 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3703 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3704 return Error("Invalid record");
3706 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3707 return Error("Invalid record");
3708 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3709 return Error("Invalid type for value");
3710 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3711 InstructionList.push_back(I);
3715 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3716 // Old form of ICmp/FCmp returning bool
3717 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3718 // both legal on vectors but had different behaviour.
3719 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3720 // FCmp/ICmp returning bool or vector of bool
3724 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3725 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3726 OpNum+1 != Record.size())
3727 return Error("Invalid record");
3729 if (LHS->getType()->isFPOrFPVectorTy())
3730 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3732 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3733 InstructionList.push_back(I);
3737 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3739 unsigned Size = Record.size();
3741 I = ReturnInst::Create(Context);
3742 InstructionList.push_back(I);
3747 Value *Op = nullptr;
3748 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3749 return Error("Invalid record");
3750 if (OpNum != Record.size())
3751 return Error("Invalid record");
3753 I = ReturnInst::Create(Context, Op);
3754 InstructionList.push_back(I);
3757 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3758 if (Record.size() != 1 && Record.size() != 3)
3759 return Error("Invalid record");
3760 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3762 return Error("Invalid record");
3764 if (Record.size() == 1) {
3765 I = BranchInst::Create(TrueDest);
3766 InstructionList.push_back(I);
3769 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3770 Value *Cond = getValue(Record, 2, NextValueNo,
3771 Type::getInt1Ty(Context));
3772 if (!FalseDest || !Cond)
3773 return Error("Invalid record");
3774 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3775 InstructionList.push_back(I);
3779 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3781 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3782 // "New" SwitchInst format with case ranges. The changes to write this
3783 // format were reverted but we still recognize bitcode that uses it.
3784 // Hopefully someday we will have support for case ranges and can use
3785 // this format again.
3787 Type *OpTy = getTypeByID(Record[1]);
3788 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3790 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3791 BasicBlock *Default = getBasicBlock(Record[3]);
3792 if (!OpTy || !Cond || !Default)
3793 return Error("Invalid record");
3795 unsigned NumCases = Record[4];
3797 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3798 InstructionList.push_back(SI);
3800 unsigned CurIdx = 5;
3801 for (unsigned i = 0; i != NumCases; ++i) {
3802 SmallVector<ConstantInt*, 1> CaseVals;
3803 unsigned NumItems = Record[CurIdx++];
3804 for (unsigned ci = 0; ci != NumItems; ++ci) {
3805 bool isSingleNumber = Record[CurIdx++];
3808 unsigned ActiveWords = 1;
3809 if (ValueBitWidth > 64)
3810 ActiveWords = Record[CurIdx++];
3811 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3813 CurIdx += ActiveWords;
3815 if (!isSingleNumber) {
3817 if (ValueBitWidth > 64)
3818 ActiveWords = Record[CurIdx++];
3820 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3822 CurIdx += ActiveWords;
3824 // FIXME: It is not clear whether values in the range should be
3825 // compared as signed or unsigned values. The partially
3826 // implemented changes that used this format in the past used
3827 // unsigned comparisons.
3828 for ( ; Low.ule(High); ++Low)
3829 CaseVals.push_back(ConstantInt::get(Context, Low));
3831 CaseVals.push_back(ConstantInt::get(Context, Low));
3833 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3834 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3835 cve = CaseVals.end(); cvi != cve; ++cvi)
3836 SI->addCase(*cvi, DestBB);
3842 // Old SwitchInst format without case ranges.
3844 if (Record.size() < 3 || (Record.size() & 1) == 0)
3845 return Error("Invalid record");
3846 Type *OpTy = getTypeByID(Record[0]);
3847 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3848 BasicBlock *Default = getBasicBlock(Record[2]);
3849 if (!OpTy || !Cond || !Default)
3850 return Error("Invalid record");
3851 unsigned NumCases = (Record.size()-3)/2;
3852 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3853 InstructionList.push_back(SI);
3854 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3855 ConstantInt *CaseVal =
3856 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3857 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3858 if (!CaseVal || !DestBB) {
3860 return Error("Invalid record");
3862 SI->addCase(CaseVal, DestBB);
3867 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3868 if (Record.size() < 2)
3869 return Error("Invalid record");
3870 Type *OpTy = getTypeByID(Record[0]);
3871 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3872 if (!OpTy || !Address)
3873 return Error("Invalid record");
3874 unsigned NumDests = Record.size()-2;
3875 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3876 InstructionList.push_back(IBI);
3877 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3878 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3879 IBI->addDestination(DestBB);
3882 return Error("Invalid record");
3889 case bitc::FUNC_CODE_INST_INVOKE: {
3890 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3891 if (Record.size() < 4)
3892 return Error("Invalid record");
3894 AttributeSet PAL = getAttributes(Record[OpNum++]);
3895 unsigned CCInfo = Record[OpNum++];
3896 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3897 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3899 FunctionType *FTy = nullptr;
3900 if (CCInfo >> 13 & 1 &&
3901 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3902 return Error("Explicit invoke type is not a function type");
3905 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3906 return Error("Invalid record");
3908 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3910 return Error("Callee is not a pointer");
3912 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3914 return Error("Callee is not of pointer to function type");
3915 } else if (CalleeTy->getElementType() != FTy)
3916 return Error("Explicit invoke type does not match pointee type of "
3918 if (Record.size() < FTy->getNumParams() + OpNum)
3919 return Error("Insufficient operands to call");
3921 SmallVector<Value*, 16> Ops;
3922 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3923 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3924 FTy->getParamType(i)));
3926 return Error("Invalid record");
3929 if (!FTy->isVarArg()) {
3930 if (Record.size() != OpNum)
3931 return Error("Invalid record");
3933 // Read type/value pairs for varargs params.
3934 while (OpNum != Record.size()) {
3936 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3937 return Error("Invalid record");
3942 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3943 InstructionList.push_back(I);
3945 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
3946 cast<InvokeInst>(I)->setAttributes(PAL);
3949 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3951 Value *Val = nullptr;
3952 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3953 return Error("Invalid record");
3954 I = ResumeInst::Create(Val);
3955 InstructionList.push_back(I);
3958 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3959 I = new UnreachableInst(Context);
3960 InstructionList.push_back(I);
3962 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3963 if (Record.size() < 1 || ((Record.size()-1)&1))
3964 return Error("Invalid record");
3965 Type *Ty = getTypeByID(Record[0]);
3967 return Error("Invalid record");
3969 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3970 InstructionList.push_back(PN);
3972 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3974 // With the new function encoding, it is possible that operands have
3975 // negative IDs (for forward references). Use a signed VBR
3976 // representation to keep the encoding small.
3978 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3980 V = getValue(Record, 1+i, NextValueNo, Ty);
3981 BasicBlock *BB = getBasicBlock(Record[2+i]);
3983 return Error("Invalid record");
3984 PN->addIncoming(V, BB);
3990 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3991 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3993 if (Record.size() < 4)
3994 return Error("Invalid record");
3995 Type *Ty = getTypeByID(Record[Idx++]);
3997 return Error("Invalid record");
3998 Value *PersFn = nullptr;
3999 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4000 return Error("Invalid record");
4002 bool IsCleanup = !!Record[Idx++];
4003 unsigned NumClauses = Record[Idx++];
4004 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
4005 LP->setCleanup(IsCleanup);
4006 for (unsigned J = 0; J != NumClauses; ++J) {
4007 LandingPadInst::ClauseType CT =
4008 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4011 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4013 return Error("Invalid record");
4016 assert((CT != LandingPadInst::Catch ||
4017 !isa<ArrayType>(Val->getType())) &&
4018 "Catch clause has a invalid type!");
4019 assert((CT != LandingPadInst::Filter ||
4020 isa<ArrayType>(Val->getType())) &&
4021 "Filter clause has invalid type!");
4022 LP->addClause(cast<Constant>(Val));
4026 InstructionList.push_back(I);
4030 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4031 if (Record.size() != 4)
4032 return Error("Invalid record");
4033 uint64_t AlignRecord = Record[3];
4034 const uint64_t InAllocaMask = uint64_t(1) << 5;
4035 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4036 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4037 bool InAlloca = AlignRecord & InAllocaMask;
4038 Type *Ty = getTypeByID(Record[0]);
4039 if ((AlignRecord & ExplicitTypeMask) == 0) {
4040 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4042 return Error("Old-style alloca with a non-pointer type");
4043 Ty = PTy->getElementType();
4045 Type *OpTy = getTypeByID(Record[1]);
4046 Value *Size = getFnValueByID(Record[2], OpTy);
4048 if (std::error_code EC =
4049 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4053 return Error("Invalid record");
4054 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4055 AI->setUsedWithInAlloca(InAlloca);
4057 InstructionList.push_back(I);
4060 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4063 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4064 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4065 return Error("Invalid record");
4068 if (OpNum + 3 == Record.size())
4069 Ty = getTypeByID(Record[OpNum++]);
4070 if (!isa<PointerType>(Op->getType()))
4071 return Error("Load operand is not a pointer type");
4073 Ty = cast<PointerType>(Op->getType())->getElementType();
4074 else if (Ty != cast<PointerType>(Op->getType())->getElementType())
4075 return Error("Explicit load type does not match pointee type of "
4079 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4081 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4083 InstructionList.push_back(I);
4086 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4087 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4090 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4091 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4092 return Error("Invalid record");
4095 if (OpNum + 5 == Record.size())
4096 Ty = getTypeByID(Record[OpNum++]);
4098 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4099 if (Ordering == NotAtomic || Ordering == Release ||
4100 Ordering == AcquireRelease)
4101 return Error("Invalid record");
4102 if (Ordering != NotAtomic && Record[OpNum] == 0)
4103 return Error("Invalid record");
4104 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4107 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4109 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4112 assert((!Ty || Ty == I->getType()) &&
4113 "Explicit type doesn't match pointee type of the first operand");
4115 InstructionList.push_back(I);
4118 case bitc::FUNC_CODE_INST_STORE:
4119 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4122 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4123 (BitCode == bitc::FUNC_CODE_INST_STORE
4124 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4125 : popValue(Record, OpNum, NextValueNo,
4126 cast<PointerType>(Ptr->getType())->getElementType(),
4128 OpNum + 2 != Record.size())
4129 return Error("Invalid record");
4131 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4133 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4134 InstructionList.push_back(I);
4137 case bitc::FUNC_CODE_INST_STOREATOMIC:
4138 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4139 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4142 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4143 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4144 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4145 : popValue(Record, OpNum, NextValueNo,
4146 cast<PointerType>(Ptr->getType())->getElementType(),
4148 OpNum + 4 != Record.size())
4149 return Error("Invalid record");
4151 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4152 if (Ordering == NotAtomic || Ordering == Acquire ||
4153 Ordering == AcquireRelease)
4154 return Error("Invalid record");
4155 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4156 if (Ordering != NotAtomic && Record[OpNum] == 0)
4157 return Error("Invalid record");
4160 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4162 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4163 InstructionList.push_back(I);
4166 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4167 case bitc::FUNC_CODE_INST_CMPXCHG: {
4168 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4169 // failureordering?, isweak?]
4171 Value *Ptr, *Cmp, *New;
4172 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4173 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4174 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4175 : popValue(Record, OpNum, NextValueNo,
4176 cast<PointerType>(Ptr->getType())->getElementType(),
4178 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4179 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4180 return Error("Invalid record");
4181 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4182 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4183 return Error("Invalid record");
4184 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4186 AtomicOrdering FailureOrdering;
4187 if (Record.size() < 7)
4189 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4191 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4193 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4195 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4197 if (Record.size() < 8) {
4198 // Before weak cmpxchgs existed, the instruction simply returned the
4199 // value loaded from memory, so bitcode files from that era will be
4200 // expecting the first component of a modern cmpxchg.
4201 CurBB->getInstList().push_back(I);
4202 I = ExtractValueInst::Create(I, 0);
4204 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4207 InstructionList.push_back(I);
4210 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4211 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4214 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4215 popValue(Record, OpNum, NextValueNo,
4216 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4217 OpNum+4 != Record.size())
4218 return Error("Invalid record");
4219 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4220 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4221 Operation > AtomicRMWInst::LAST_BINOP)
4222 return Error("Invalid record");
4223 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4224 if (Ordering == NotAtomic || Ordering == Unordered)
4225 return Error("Invalid record");
4226 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4227 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4228 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4229 InstructionList.push_back(I);
4232 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4233 if (2 != Record.size())
4234 return Error("Invalid record");
4235 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4236 if (Ordering == NotAtomic || Ordering == Unordered ||
4237 Ordering == Monotonic)
4238 return Error("Invalid record");
4239 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4240 I = new FenceInst(Context, Ordering, SynchScope);
4241 InstructionList.push_back(I);
4244 case bitc::FUNC_CODE_INST_CALL: {
4245 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4246 if (Record.size() < 3)
4247 return Error("Invalid record");
4250 AttributeSet PAL = getAttributes(Record[OpNum++]);
4251 unsigned CCInfo = Record[OpNum++];
4253 FunctionType *FTy = nullptr;
4254 if (CCInfo >> 15 & 1 &&
4255 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4256 return Error("Explicit call type is not a function type");
4259 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4260 return Error("Invalid record");
4262 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4264 return Error("Callee is not a pointer type");
4266 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4268 return Error("Callee is not of pointer to function type");
4269 } else if (OpTy->getElementType() != FTy)
4270 return Error("Explicit call type does not match pointee type of "
4272 if (Record.size() < FTy->getNumParams() + OpNum)
4273 return Error("Insufficient operands to call");
4275 SmallVector<Value*, 16> Args;
4276 // Read the fixed params.
4277 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4278 if (FTy->getParamType(i)->isLabelTy())
4279 Args.push_back(getBasicBlock(Record[OpNum]));
4281 Args.push_back(getValue(Record, OpNum, NextValueNo,
4282 FTy->getParamType(i)));
4284 return Error("Invalid record");
4287 // Read type/value pairs for varargs params.
4288 if (!FTy->isVarArg()) {
4289 if (OpNum != Record.size())
4290 return Error("Invalid record");
4292 while (OpNum != Record.size()) {
4294 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4295 return Error("Invalid record");
4300 I = CallInst::Create(FTy, Callee, Args);
4301 InstructionList.push_back(I);
4302 cast<CallInst>(I)->setCallingConv(
4303 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4304 CallInst::TailCallKind TCK = CallInst::TCK_None;
4306 TCK = CallInst::TCK_Tail;
4307 if (CCInfo & (1 << 14))
4308 TCK = CallInst::TCK_MustTail;
4309 cast<CallInst>(I)->setTailCallKind(TCK);
4310 cast<CallInst>(I)->setAttributes(PAL);
4313 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4314 if (Record.size() < 3)
4315 return Error("Invalid record");
4316 Type *OpTy = getTypeByID(Record[0]);
4317 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4318 Type *ResTy = getTypeByID(Record[2]);
4319 if (!OpTy || !Op || !ResTy)
4320 return Error("Invalid record");
4321 I = new VAArgInst(Op, ResTy);
4322 InstructionList.push_back(I);
4327 // Add instruction to end of current BB. If there is no current BB, reject
4331 return Error("Invalid instruction with no BB");
4333 CurBB->getInstList().push_back(I);
4335 // If this was a terminator instruction, move to the next block.
4336 if (isa<TerminatorInst>(I)) {
4338 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4341 // Non-void values get registered in the value table for future use.
4342 if (I && !I->getType()->isVoidTy())
4343 ValueList.AssignValue(I, NextValueNo++);
4348 // Check the function list for unresolved values.
4349 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4350 if (!A->getParent()) {
4351 // We found at least one unresolved value. Nuke them all to avoid leaks.
4352 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4353 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4354 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4358 return Error("Never resolved value found in function");
4362 // FIXME: Check for unresolved forward-declared metadata references
4363 // and clean up leaks.
4365 // Trim the value list down to the size it was before we parsed this function.
4366 ValueList.shrinkTo(ModuleValueListSize);
4367 MDValueList.shrinkTo(ModuleMDValueListSize);
4368 std::vector<BasicBlock*>().swap(FunctionBBs);
4369 return std::error_code();
4372 /// Find the function body in the bitcode stream
4373 std::error_code BitcodeReader::FindFunctionInStream(
4375 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4376 while (DeferredFunctionInfoIterator->second == 0) {
4377 if (Stream.AtEndOfStream())
4378 return Error("Could not find function in stream");
4379 // ParseModule will parse the next body in the stream and set its
4380 // position in the DeferredFunctionInfo map.
4381 if (std::error_code EC = ParseModule(true))
4384 return std::error_code();
4387 //===----------------------------------------------------------------------===//
4388 // GVMaterializer implementation
4389 //===----------------------------------------------------------------------===//
4391 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4393 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4394 if (std::error_code EC = materializeMetadata())
4397 Function *F = dyn_cast<Function>(GV);
4398 // If it's not a function or is already material, ignore the request.
4399 if (!F || !F->isMaterializable())
4400 return std::error_code();
4402 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4403 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4404 // If its position is recorded as 0, its body is somewhere in the stream
4405 // but we haven't seen it yet.
4406 if (DFII->second == 0 && LazyStreamer)
4407 if (std::error_code EC = FindFunctionInStream(F, DFII))
4410 // Move the bit stream to the saved position of the deferred function body.
4411 Stream.JumpToBit(DFII->second);
4413 if (std::error_code EC = ParseFunctionBody(F))
4415 F->setIsMaterializable(false);
4420 // Upgrade any old intrinsic calls in the function.
4421 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4422 E = UpgradedIntrinsics.end(); I != E; ++I) {
4423 if (I->first != I->second) {
4424 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4426 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4427 UpgradeIntrinsicCall(CI, I->second);
4432 // Bring in any functions that this function forward-referenced via
4434 return materializeForwardReferencedFunctions();
4437 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4438 const Function *F = dyn_cast<Function>(GV);
4439 if (!F || F->isDeclaration())
4442 // Dematerializing F would leave dangling references that wouldn't be
4443 // reconnected on re-materialization.
4444 if (BlockAddressesTaken.count(F))
4447 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4450 void BitcodeReader::Dematerialize(GlobalValue *GV) {
4451 Function *F = dyn_cast<Function>(GV);
4452 // If this function isn't dematerializable, this is a noop.
4453 if (!F || !isDematerializable(F))
4456 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4458 // Just forget the function body, we can remat it later.
4459 F->dropAllReferences();
4460 F->setIsMaterializable(true);
4463 std::error_code BitcodeReader::MaterializeModule(Module *M) {
4464 assert(M == TheModule &&
4465 "Can only Materialize the Module this BitcodeReader is attached to.");
4467 if (std::error_code EC = materializeMetadata())
4470 // Promise to materialize all forward references.
4471 WillMaterializeAllForwardRefs = true;
4473 // Iterate over the module, deserializing any functions that are still on
4475 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4477 if (std::error_code EC = materialize(F))
4480 // At this point, if there are any function bodies, the current bit is
4481 // pointing to the END_BLOCK record after them. Now make sure the rest
4482 // of the bits in the module have been read.
4486 // Check that all block address forward references got resolved (as we
4488 if (!BasicBlockFwdRefs.empty())
4489 return Error("Never resolved function from blockaddress");
4491 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4492 // delete the old functions to clean up. We can't do this unless the entire
4493 // module is materialized because there could always be another function body
4494 // with calls to the old function.
4495 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4496 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4497 if (I->first != I->second) {
4498 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4500 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4501 UpgradeIntrinsicCall(CI, I->second);
4503 if (!I->first->use_empty())
4504 I->first->replaceAllUsesWith(I->second);
4505 I->first->eraseFromParent();
4508 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4510 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4511 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4513 UpgradeDebugInfo(*M);
4514 return std::error_code();
4517 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4518 return IdentifiedStructTypes;
4521 std::error_code BitcodeReader::InitStream() {
4523 return InitLazyStream();
4524 return InitStreamFromBuffer();
4527 std::error_code BitcodeReader::InitStreamFromBuffer() {
4528 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4529 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4531 if (Buffer->getBufferSize() & 3)
4532 return Error("Invalid bitcode signature");
4534 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4535 // The magic number is 0x0B17C0DE stored in little endian.
4536 if (isBitcodeWrapper(BufPtr, BufEnd))
4537 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4538 return Error("Invalid bitcode wrapper header");
4540 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4541 Stream.init(&*StreamFile);
4543 return std::error_code();
4546 std::error_code BitcodeReader::InitLazyStream() {
4547 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4549 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4550 StreamingMemoryObject &Bytes = *OwnedBytes;
4551 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4552 Stream.init(&*StreamFile);
4554 unsigned char buf[16];
4555 if (Bytes.readBytes(buf, 16, 0) != 16)
4556 return Error("Invalid bitcode signature");
4558 if (!isBitcode(buf, buf + 16))
4559 return Error("Invalid bitcode signature");
4561 if (isBitcodeWrapper(buf, buf + 4)) {
4562 const unsigned char *bitcodeStart = buf;
4563 const unsigned char *bitcodeEnd = buf + 16;
4564 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4565 Bytes.dropLeadingBytes(bitcodeStart - buf);
4566 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4568 return std::error_code();
4572 class BitcodeErrorCategoryType : public std::error_category {
4573 const char *name() const LLVM_NOEXCEPT override {
4574 return "llvm.bitcode";
4576 std::string message(int IE) const override {
4577 BitcodeError E = static_cast<BitcodeError>(IE);
4579 case BitcodeError::InvalidBitcodeSignature:
4580 return "Invalid bitcode signature";
4581 case BitcodeError::CorruptedBitcode:
4582 return "Corrupted bitcode";
4584 llvm_unreachable("Unknown error type!");
4589 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4591 const std::error_category &llvm::BitcodeErrorCategory() {
4592 return *ErrorCategory;
4595 //===----------------------------------------------------------------------===//
4596 // External interface
4597 //===----------------------------------------------------------------------===//
4599 /// \brief Get a lazy one-at-time loading module from bitcode.
4601 /// This isn't always used in a lazy context. In particular, it's also used by
4602 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4603 /// in forward-referenced functions from block address references.
4605 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4606 /// materialize everything -- in particular, if this isn't truly lazy.
4607 static ErrorOr<Module *>
4608 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4609 LLVMContext &Context, bool WillMaterializeAll,
4610 DiagnosticHandlerFunction DiagnosticHandler,
4611 bool ShouldLazyLoadMetadata = false) {
4612 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4614 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4615 M->setMaterializer(R);
4617 auto cleanupOnError = [&](std::error_code EC) {
4618 R->releaseBuffer(); // Never take ownership on error.
4619 delete M; // Also deletes R.
4623 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4624 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4625 return cleanupOnError(EC);
4627 if (!WillMaterializeAll)
4628 // Resolve forward references from blockaddresses.
4629 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4630 return cleanupOnError(EC);
4632 Buffer.release(); // The BitcodeReader owns it now.
4637 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4638 LLVMContext &Context,
4639 DiagnosticHandlerFunction DiagnosticHandler,
4640 bool ShouldLazyLoadMetadata) {
4641 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4642 DiagnosticHandler, ShouldLazyLoadMetadata);
4645 ErrorOr<std::unique_ptr<Module>>
4646 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4647 LLVMContext &Context,
4648 DiagnosticHandlerFunction DiagnosticHandler) {
4649 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4650 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4651 M->setMaterializer(R);
4652 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4654 return std::move(M);
4658 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4659 DiagnosticHandlerFunction DiagnosticHandler) {
4660 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4661 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4662 std::move(Buf), Context, true, DiagnosticHandler);
4665 Module *M = ModuleOrErr.get();
4666 // Read in the entire module, and destroy the BitcodeReader.
4667 if (std::error_code EC = M->materializeAllPermanently()) {
4672 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4673 // written. We must defer until the Module has been fully materialized.
4679 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4680 DiagnosticHandlerFunction DiagnosticHandler) {
4681 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4682 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4684 ErrorOr<std::string> Triple = R->parseTriple();
4685 if (Triple.getError())
4687 return Triple.get();