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) {
796 if (Value *V = ValuePtrs[Idx]) {
797 // If the types don't match, it's invalid.
798 if (Ty && Ty != V->getType())
803 // No type specified, must be invalid reference.
804 if (!Ty) return nullptr;
806 // Create and return a placeholder, which will later be RAUW'd.
807 Value *V = new Argument(Ty);
812 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
813 /// resolves any forward references. The idea behind this is that we sometimes
814 /// get constants (such as large arrays) which reference *many* forward ref
815 /// constants. Replacing each of these causes a lot of thrashing when
816 /// building/reuniquing the constant. Instead of doing this, we look at all the
817 /// uses and rewrite all the place holders at once for any constant that uses
819 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
820 // Sort the values by-pointer so that they are efficient to look up with a
822 std::sort(ResolveConstants.begin(), ResolveConstants.end());
824 SmallVector<Constant*, 64> NewOps;
826 while (!ResolveConstants.empty()) {
827 Value *RealVal = operator[](ResolveConstants.back().second);
828 Constant *Placeholder = ResolveConstants.back().first;
829 ResolveConstants.pop_back();
831 // Loop over all users of the placeholder, updating them to reference the
832 // new value. If they reference more than one placeholder, update them all
834 while (!Placeholder->use_empty()) {
835 auto UI = Placeholder->user_begin();
838 // If the using object isn't uniqued, just update the operands. This
839 // handles instructions and initializers for global variables.
840 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
841 UI.getUse().set(RealVal);
845 // Otherwise, we have a constant that uses the placeholder. Replace that
846 // constant with a new constant that has *all* placeholder uses updated.
847 Constant *UserC = cast<Constant>(U);
848 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
851 if (!isa<ConstantPlaceHolder>(*I)) {
852 // Not a placeholder reference.
854 } else if (*I == Placeholder) {
855 // Common case is that it just references this one placeholder.
858 // Otherwise, look up the placeholder in ResolveConstants.
859 ResolveConstantsTy::iterator It =
860 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
861 std::pair<Constant*, unsigned>(cast<Constant>(*I),
863 assert(It != ResolveConstants.end() && It->first == *I);
864 NewOp = operator[](It->second);
867 NewOps.push_back(cast<Constant>(NewOp));
870 // Make the new constant.
872 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
873 NewC = ConstantArray::get(UserCA->getType(), NewOps);
874 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
875 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
876 } else if (isa<ConstantVector>(UserC)) {
877 NewC = ConstantVector::get(NewOps);
879 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
880 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
883 UserC->replaceAllUsesWith(NewC);
884 UserC->destroyConstant();
888 // Update all ValueHandles, they should be the only users at this point.
889 Placeholder->replaceAllUsesWith(RealVal);
894 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
903 TrackingMDRef &OldMD = MDValuePtrs[Idx];
909 // If there was a forward reference to this value, replace it.
910 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
911 PrevMD->replaceAllUsesWith(MD);
915 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
919 if (Metadata *MD = MDValuePtrs[Idx])
922 // Track forward refs to be resolved later.
924 MinFwdRef = std::min(MinFwdRef, Idx);
925 MaxFwdRef = std::max(MaxFwdRef, Idx);
928 MinFwdRef = MaxFwdRef = Idx;
932 // Create and return a placeholder, which will later be RAUW'd.
933 Metadata *MD = MDNode::getTemporary(Context, None).release();
934 MDValuePtrs[Idx].reset(MD);
938 void BitcodeReaderMDValueList::tryToResolveCycles() {
944 // Still forward references... can't resolve cycles.
947 // Resolve any cycles.
948 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
949 auto &MD = MDValuePtrs[I];
950 auto *N = dyn_cast_or_null<MDNode>(MD);
954 assert(!N->isTemporary() && "Unexpected forward reference");
958 // Make sure we return early again until there's another forward ref.
962 Type *BitcodeReader::getTypeByID(unsigned ID) {
963 // The type table size is always specified correctly.
964 if (ID >= TypeList.size())
967 if (Type *Ty = TypeList[ID])
970 // If we have a forward reference, the only possible case is when it is to a
971 // named struct. Just create a placeholder for now.
972 return TypeList[ID] = createIdentifiedStructType(Context);
975 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
977 auto *Ret = StructType::create(Context, Name);
978 IdentifiedStructTypes.push_back(Ret);
982 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
983 auto *Ret = StructType::create(Context);
984 IdentifiedStructTypes.push_back(Ret);
989 //===----------------------------------------------------------------------===//
990 // Functions for parsing blocks from the bitcode file
991 //===----------------------------------------------------------------------===//
994 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
995 /// been decoded from the given integer. This function must stay in sync with
996 /// 'encodeLLVMAttributesForBitcode'.
997 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
998 uint64_t EncodedAttrs) {
999 // FIXME: Remove in 4.0.
1001 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1002 // the bits above 31 down by 11 bits.
1003 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1004 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1005 "Alignment must be a power of two.");
1008 B.addAlignmentAttr(Alignment);
1009 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1010 (EncodedAttrs & 0xffff));
1013 std::error_code BitcodeReader::ParseAttributeBlock() {
1014 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1015 return Error("Invalid record");
1017 if (!MAttributes.empty())
1018 return Error("Invalid multiple blocks");
1020 SmallVector<uint64_t, 64> Record;
1022 SmallVector<AttributeSet, 8> Attrs;
1024 // Read all the records.
1026 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1028 switch (Entry.Kind) {
1029 case BitstreamEntry::SubBlock: // Handled for us already.
1030 case BitstreamEntry::Error:
1031 return Error("Malformed block");
1032 case BitstreamEntry::EndBlock:
1033 return std::error_code();
1034 case BitstreamEntry::Record:
1035 // The interesting case.
1041 switch (Stream.readRecord(Entry.ID, Record)) {
1042 default: // Default behavior: ignore.
1044 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1045 // FIXME: Remove in 4.0.
1046 if (Record.size() & 1)
1047 return Error("Invalid record");
1049 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1051 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1052 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1055 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1059 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1060 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1061 Attrs.push_back(MAttributeGroups[Record[i]]);
1063 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1071 // Returns Attribute::None on unrecognized codes.
1072 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1075 return Attribute::None;
1076 case bitc::ATTR_KIND_ALIGNMENT:
1077 return Attribute::Alignment;
1078 case bitc::ATTR_KIND_ALWAYS_INLINE:
1079 return Attribute::AlwaysInline;
1080 case bitc::ATTR_KIND_BUILTIN:
1081 return Attribute::Builtin;
1082 case bitc::ATTR_KIND_BY_VAL:
1083 return Attribute::ByVal;
1084 case bitc::ATTR_KIND_IN_ALLOCA:
1085 return Attribute::InAlloca;
1086 case bitc::ATTR_KIND_COLD:
1087 return Attribute::Cold;
1088 case bitc::ATTR_KIND_INLINE_HINT:
1089 return Attribute::InlineHint;
1090 case bitc::ATTR_KIND_IN_REG:
1091 return Attribute::InReg;
1092 case bitc::ATTR_KIND_JUMP_TABLE:
1093 return Attribute::JumpTable;
1094 case bitc::ATTR_KIND_MIN_SIZE:
1095 return Attribute::MinSize;
1096 case bitc::ATTR_KIND_NAKED:
1097 return Attribute::Naked;
1098 case bitc::ATTR_KIND_NEST:
1099 return Attribute::Nest;
1100 case bitc::ATTR_KIND_NO_ALIAS:
1101 return Attribute::NoAlias;
1102 case bitc::ATTR_KIND_NO_BUILTIN:
1103 return Attribute::NoBuiltin;
1104 case bitc::ATTR_KIND_NO_CAPTURE:
1105 return Attribute::NoCapture;
1106 case bitc::ATTR_KIND_NO_DUPLICATE:
1107 return Attribute::NoDuplicate;
1108 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1109 return Attribute::NoImplicitFloat;
1110 case bitc::ATTR_KIND_NO_INLINE:
1111 return Attribute::NoInline;
1112 case bitc::ATTR_KIND_NON_LAZY_BIND:
1113 return Attribute::NonLazyBind;
1114 case bitc::ATTR_KIND_NON_NULL:
1115 return Attribute::NonNull;
1116 case bitc::ATTR_KIND_DEREFERENCEABLE:
1117 return Attribute::Dereferenceable;
1118 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1119 return Attribute::DereferenceableOrNull;
1120 case bitc::ATTR_KIND_NO_RED_ZONE:
1121 return Attribute::NoRedZone;
1122 case bitc::ATTR_KIND_NO_RETURN:
1123 return Attribute::NoReturn;
1124 case bitc::ATTR_KIND_NO_UNWIND:
1125 return Attribute::NoUnwind;
1126 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1127 return Attribute::OptimizeForSize;
1128 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1129 return Attribute::OptimizeNone;
1130 case bitc::ATTR_KIND_READ_NONE:
1131 return Attribute::ReadNone;
1132 case bitc::ATTR_KIND_READ_ONLY:
1133 return Attribute::ReadOnly;
1134 case bitc::ATTR_KIND_RETURNED:
1135 return Attribute::Returned;
1136 case bitc::ATTR_KIND_RETURNS_TWICE:
1137 return Attribute::ReturnsTwice;
1138 case bitc::ATTR_KIND_S_EXT:
1139 return Attribute::SExt;
1140 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1141 return Attribute::StackAlignment;
1142 case bitc::ATTR_KIND_STACK_PROTECT:
1143 return Attribute::StackProtect;
1144 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1145 return Attribute::StackProtectReq;
1146 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1147 return Attribute::StackProtectStrong;
1148 case bitc::ATTR_KIND_STRUCT_RET:
1149 return Attribute::StructRet;
1150 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1151 return Attribute::SanitizeAddress;
1152 case bitc::ATTR_KIND_SANITIZE_THREAD:
1153 return Attribute::SanitizeThread;
1154 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1155 return Attribute::SanitizeMemory;
1156 case bitc::ATTR_KIND_UW_TABLE:
1157 return Attribute::UWTable;
1158 case bitc::ATTR_KIND_Z_EXT:
1159 return Attribute::ZExt;
1163 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1164 unsigned &Alignment) {
1165 // Note: Alignment in bitcode files is incremented by 1, so that zero
1166 // can be used for default alignment.
1167 if (Exponent > Value::MaxAlignmentExponent + 1)
1168 return Error("Invalid alignment value");
1169 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1170 return std::error_code();
1173 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1174 Attribute::AttrKind *Kind) {
1175 *Kind = GetAttrFromCode(Code);
1176 if (*Kind == Attribute::None)
1177 return Error(BitcodeError::CorruptedBitcode,
1178 "Unknown attribute kind (" + Twine(Code) + ")");
1179 return std::error_code();
1182 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
1183 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1184 return Error("Invalid record");
1186 if (!MAttributeGroups.empty())
1187 return Error("Invalid multiple blocks");
1189 SmallVector<uint64_t, 64> Record;
1191 // Read all the records.
1193 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1195 switch (Entry.Kind) {
1196 case BitstreamEntry::SubBlock: // Handled for us already.
1197 case BitstreamEntry::Error:
1198 return Error("Malformed block");
1199 case BitstreamEntry::EndBlock:
1200 return std::error_code();
1201 case BitstreamEntry::Record:
1202 // The interesting case.
1208 switch (Stream.readRecord(Entry.ID, Record)) {
1209 default: // Default behavior: ignore.
1211 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1212 if (Record.size() < 3)
1213 return Error("Invalid record");
1215 uint64_t GrpID = Record[0];
1216 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1219 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1220 if (Record[i] == 0) { // Enum attribute
1221 Attribute::AttrKind Kind;
1222 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1225 B.addAttribute(Kind);
1226 } else if (Record[i] == 1) { // Integer attribute
1227 Attribute::AttrKind Kind;
1228 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1230 if (Kind == Attribute::Alignment)
1231 B.addAlignmentAttr(Record[++i]);
1232 else if (Kind == Attribute::StackAlignment)
1233 B.addStackAlignmentAttr(Record[++i]);
1234 else if (Kind == Attribute::Dereferenceable)
1235 B.addDereferenceableAttr(Record[++i]);
1236 else if (Kind == Attribute::DereferenceableOrNull)
1237 B.addDereferenceableOrNullAttr(Record[++i]);
1238 } else { // String attribute
1239 assert((Record[i] == 3 || Record[i] == 4) &&
1240 "Invalid attribute group entry");
1241 bool HasValue = (Record[i++] == 4);
1242 SmallString<64> KindStr;
1243 SmallString<64> ValStr;
1245 while (Record[i] != 0 && i != e)
1246 KindStr += Record[i++];
1247 assert(Record[i] == 0 && "Kind string not null terminated");
1250 // Has a value associated with it.
1251 ++i; // Skip the '0' that terminates the "kind" string.
1252 while (Record[i] != 0 && i != e)
1253 ValStr += Record[i++];
1254 assert(Record[i] == 0 && "Value string not null terminated");
1257 B.addAttribute(KindStr.str(), ValStr.str());
1261 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1268 std::error_code BitcodeReader::ParseTypeTable() {
1269 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1270 return Error("Invalid record");
1272 return ParseTypeTableBody();
1275 std::error_code BitcodeReader::ParseTypeTableBody() {
1276 if (!TypeList.empty())
1277 return Error("Invalid multiple blocks");
1279 SmallVector<uint64_t, 64> Record;
1280 unsigned NumRecords = 0;
1282 SmallString<64> TypeName;
1284 // Read all the records for this type table.
1286 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1288 switch (Entry.Kind) {
1289 case BitstreamEntry::SubBlock: // Handled for us already.
1290 case BitstreamEntry::Error:
1291 return Error("Malformed block");
1292 case BitstreamEntry::EndBlock:
1293 if (NumRecords != TypeList.size())
1294 return Error("Malformed block");
1295 return std::error_code();
1296 case BitstreamEntry::Record:
1297 // The interesting case.
1303 Type *ResultTy = nullptr;
1304 switch (Stream.readRecord(Entry.ID, Record)) {
1306 return Error("Invalid value");
1307 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1308 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1309 // type list. This allows us to reserve space.
1310 if (Record.size() < 1)
1311 return Error("Invalid record");
1312 TypeList.resize(Record[0]);
1314 case bitc::TYPE_CODE_VOID: // VOID
1315 ResultTy = Type::getVoidTy(Context);
1317 case bitc::TYPE_CODE_HALF: // HALF
1318 ResultTy = Type::getHalfTy(Context);
1320 case bitc::TYPE_CODE_FLOAT: // FLOAT
1321 ResultTy = Type::getFloatTy(Context);
1323 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1324 ResultTy = Type::getDoubleTy(Context);
1326 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1327 ResultTy = Type::getX86_FP80Ty(Context);
1329 case bitc::TYPE_CODE_FP128: // FP128
1330 ResultTy = Type::getFP128Ty(Context);
1332 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1333 ResultTy = Type::getPPC_FP128Ty(Context);
1335 case bitc::TYPE_CODE_LABEL: // LABEL
1336 ResultTy = Type::getLabelTy(Context);
1338 case bitc::TYPE_CODE_METADATA: // METADATA
1339 ResultTy = Type::getMetadataTy(Context);
1341 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1342 ResultTy = Type::getX86_MMXTy(Context);
1344 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1345 if (Record.size() < 1)
1346 return Error("Invalid record");
1348 uint64_t NumBits = Record[0];
1349 if (NumBits < IntegerType::MIN_INT_BITS ||
1350 NumBits > IntegerType::MAX_INT_BITS)
1351 return Error("Bitwidth for integer type out of range");
1352 ResultTy = IntegerType::get(Context, NumBits);
1355 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1356 // [pointee type, address space]
1357 if (Record.size() < 1)
1358 return Error("Invalid record");
1359 unsigned AddressSpace = 0;
1360 if (Record.size() == 2)
1361 AddressSpace = Record[1];
1362 ResultTy = getTypeByID(Record[0]);
1364 !PointerType::isValidElementType(ResultTy))
1365 return Error("Invalid type");
1366 ResultTy = PointerType::get(ResultTy, AddressSpace);
1369 case bitc::TYPE_CODE_FUNCTION_OLD: {
1370 // FIXME: attrid is dead, remove it in LLVM 4.0
1371 // FUNCTION: [vararg, attrid, retty, paramty x N]
1372 if (Record.size() < 3)
1373 return Error("Invalid record");
1374 SmallVector<Type*, 8> ArgTys;
1375 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1376 if (Type *T = getTypeByID(Record[i]))
1377 ArgTys.push_back(T);
1382 ResultTy = getTypeByID(Record[2]);
1383 if (!ResultTy || ArgTys.size() < Record.size()-3)
1384 return Error("Invalid type");
1386 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1389 case bitc::TYPE_CODE_FUNCTION: {
1390 // FUNCTION: [vararg, retty, paramty x N]
1391 if (Record.size() < 2)
1392 return Error("Invalid record");
1393 SmallVector<Type*, 8> ArgTys;
1394 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1395 if (Type *T = getTypeByID(Record[i]))
1396 ArgTys.push_back(T);
1401 ResultTy = getTypeByID(Record[1]);
1402 if (!ResultTy || ArgTys.size() < Record.size()-2)
1403 return Error("Invalid type");
1405 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1408 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1409 if (Record.size() < 1)
1410 return Error("Invalid record");
1411 SmallVector<Type*, 8> EltTys;
1412 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1413 if (Type *T = getTypeByID(Record[i]))
1414 EltTys.push_back(T);
1418 if (EltTys.size() != Record.size()-1)
1419 return Error("Invalid type");
1420 ResultTy = StructType::get(Context, EltTys, Record[0]);
1423 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1424 if (ConvertToString(Record, 0, TypeName))
1425 return Error("Invalid record");
1428 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1429 if (Record.size() < 1)
1430 return Error("Invalid record");
1432 if (NumRecords >= TypeList.size())
1433 return Error("Invalid TYPE table");
1435 // Check to see if this was forward referenced, if so fill in the temp.
1436 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1438 Res->setName(TypeName);
1439 TypeList[NumRecords] = nullptr;
1440 } else // Otherwise, create a new struct.
1441 Res = createIdentifiedStructType(Context, TypeName);
1444 SmallVector<Type*, 8> EltTys;
1445 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1446 if (Type *T = getTypeByID(Record[i]))
1447 EltTys.push_back(T);
1451 if (EltTys.size() != Record.size()-1)
1452 return Error("Invalid record");
1453 Res->setBody(EltTys, Record[0]);
1457 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1458 if (Record.size() != 1)
1459 return Error("Invalid record");
1461 if (NumRecords >= TypeList.size())
1462 return Error("Invalid TYPE table");
1464 // Check to see if this was forward referenced, if so fill in the temp.
1465 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1467 Res->setName(TypeName);
1468 TypeList[NumRecords] = nullptr;
1469 } else // Otherwise, create a new struct with no body.
1470 Res = createIdentifiedStructType(Context, TypeName);
1475 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1476 if (Record.size() < 2)
1477 return Error("Invalid record");
1478 if ((ResultTy = getTypeByID(Record[1])) &&
1479 ArrayType::isValidElementType(ResultTy))
1480 ResultTy = ArrayType::get(ResultTy, Record[0]);
1482 return Error("Invalid type");
1484 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1485 if (Record.size() < 2)
1486 return Error("Invalid record");
1487 if ((ResultTy = getTypeByID(Record[1])) &&
1488 StructType::isValidElementType(ResultTy))
1489 ResultTy = VectorType::get(ResultTy, Record[0]);
1491 return Error("Invalid type");
1495 if (NumRecords >= TypeList.size())
1496 return Error("Invalid TYPE table");
1497 if (TypeList[NumRecords])
1499 "Invalid TYPE table: Only named structs can be forward referenced");
1500 assert(ResultTy && "Didn't read a type?");
1501 TypeList[NumRecords++] = ResultTy;
1505 std::error_code BitcodeReader::ParseValueSymbolTable() {
1506 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1507 return Error("Invalid record");
1509 SmallVector<uint64_t, 64> Record;
1511 Triple TT(TheModule->getTargetTriple());
1513 // Read all the records for this value table.
1514 SmallString<128> ValueName;
1516 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1518 switch (Entry.Kind) {
1519 case BitstreamEntry::SubBlock: // Handled for us already.
1520 case BitstreamEntry::Error:
1521 return Error("Malformed block");
1522 case BitstreamEntry::EndBlock:
1523 return std::error_code();
1524 case BitstreamEntry::Record:
1525 // The interesting case.
1531 switch (Stream.readRecord(Entry.ID, Record)) {
1532 default: // Default behavior: unknown type.
1534 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1535 if (ConvertToString(Record, 1, ValueName))
1536 return Error("Invalid record");
1537 unsigned ValueID = Record[0];
1538 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1539 return Error("Invalid record");
1540 Value *V = ValueList[ValueID];
1542 V->setName(StringRef(ValueName.data(), ValueName.size()));
1543 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1544 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1545 if (TT.isOSBinFormatMachO())
1546 GO->setComdat(nullptr);
1548 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1554 case bitc::VST_CODE_BBENTRY: {
1555 if (ConvertToString(Record, 1, ValueName))
1556 return Error("Invalid record");
1557 BasicBlock *BB = getBasicBlock(Record[0]);
1559 return Error("Invalid record");
1561 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1569 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1571 std::error_code BitcodeReader::ParseMetadata() {
1572 IsMetadataMaterialized = true;
1573 unsigned NextMDValueNo = MDValueList.size();
1575 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1576 return Error("Invalid record");
1578 SmallVector<uint64_t, 64> Record;
1581 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1582 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1584 return getMD(ID - 1);
1587 auto getMDString = [&](unsigned ID) -> MDString *{
1588 // This requires that the ID is not really a forward reference. In
1589 // particular, the MDString must already have been resolved.
1590 return cast_or_null<MDString>(getMDOrNull(ID));
1593 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1594 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1596 // Read all the records.
1598 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1600 switch (Entry.Kind) {
1601 case BitstreamEntry::SubBlock: // Handled for us already.
1602 case BitstreamEntry::Error:
1603 return Error("Malformed block");
1604 case BitstreamEntry::EndBlock:
1605 MDValueList.tryToResolveCycles();
1606 return std::error_code();
1607 case BitstreamEntry::Record:
1608 // The interesting case.
1614 unsigned Code = Stream.readRecord(Entry.ID, Record);
1615 bool IsDistinct = false;
1617 default: // Default behavior: ignore.
1619 case bitc::METADATA_NAME: {
1620 // Read name of the named metadata.
1621 SmallString<8> Name(Record.begin(), Record.end());
1623 Code = Stream.ReadCode();
1625 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1626 unsigned NextBitCode = Stream.readRecord(Code, Record);
1627 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1629 // Read named metadata elements.
1630 unsigned Size = Record.size();
1631 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1632 for (unsigned i = 0; i != Size; ++i) {
1633 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1635 return Error("Invalid record");
1636 NMD->addOperand(MD);
1640 case bitc::METADATA_OLD_FN_NODE: {
1641 // FIXME: Remove in 4.0.
1642 // This is a LocalAsMetadata record, the only type of function-local
1644 if (Record.size() % 2 == 1)
1645 return Error("Invalid record");
1647 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1648 // to be legal, but there's no upgrade path.
1649 auto dropRecord = [&] {
1650 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1652 if (Record.size() != 2) {
1657 Type *Ty = getTypeByID(Record[0]);
1658 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1663 MDValueList.AssignValue(
1664 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1668 case bitc::METADATA_OLD_NODE: {
1669 // FIXME: Remove in 4.0.
1670 if (Record.size() % 2 == 1)
1671 return Error("Invalid record");
1673 unsigned Size = Record.size();
1674 SmallVector<Metadata *, 8> Elts;
1675 for (unsigned i = 0; i != Size; i += 2) {
1676 Type *Ty = getTypeByID(Record[i]);
1678 return Error("Invalid record");
1679 if (Ty->isMetadataTy())
1680 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1681 else if (!Ty->isVoidTy()) {
1683 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1684 assert(isa<ConstantAsMetadata>(MD) &&
1685 "Expected non-function-local metadata");
1688 Elts.push_back(nullptr);
1690 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1693 case bitc::METADATA_VALUE: {
1694 if (Record.size() != 2)
1695 return Error("Invalid record");
1697 Type *Ty = getTypeByID(Record[0]);
1698 if (Ty->isMetadataTy() || Ty->isVoidTy())
1699 return Error("Invalid record");
1701 MDValueList.AssignValue(
1702 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1706 case bitc::METADATA_DISTINCT_NODE:
1709 case bitc::METADATA_NODE: {
1710 SmallVector<Metadata *, 8> Elts;
1711 Elts.reserve(Record.size());
1712 for (unsigned ID : Record)
1713 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1714 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1715 : MDNode::get(Context, Elts),
1719 case bitc::METADATA_LOCATION: {
1720 if (Record.size() != 5)
1721 return Error("Invalid record");
1723 unsigned Line = Record[1];
1724 unsigned Column = Record[2];
1725 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1726 Metadata *InlinedAt =
1727 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1728 MDValueList.AssignValue(
1729 GET_OR_DISTINCT(MDLocation, Record[0],
1730 (Context, Line, Column, Scope, InlinedAt)),
1734 case bitc::METADATA_GENERIC_DEBUG: {
1735 if (Record.size() < 4)
1736 return Error("Invalid record");
1738 unsigned Tag = Record[1];
1739 unsigned Version = Record[2];
1741 if (Tag >= 1u << 16 || Version != 0)
1742 return Error("Invalid record");
1744 auto *Header = getMDString(Record[3]);
1745 SmallVector<Metadata *, 8> DwarfOps;
1746 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1747 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1749 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1750 (Context, Tag, Header, DwarfOps)),
1754 case bitc::METADATA_SUBRANGE: {
1755 if (Record.size() != 3)
1756 return Error("Invalid record");
1758 MDValueList.AssignValue(
1759 GET_OR_DISTINCT(MDSubrange, Record[0],
1760 (Context, Record[1], unrotateSign(Record[2]))),
1764 case bitc::METADATA_ENUMERATOR: {
1765 if (Record.size() != 3)
1766 return Error("Invalid record");
1768 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1769 (Context, unrotateSign(Record[1]),
1770 getMDString(Record[2]))),
1774 case bitc::METADATA_BASIC_TYPE: {
1775 if (Record.size() != 6)
1776 return Error("Invalid record");
1778 MDValueList.AssignValue(
1779 GET_OR_DISTINCT(MDBasicType, Record[0],
1780 (Context, Record[1], getMDString(Record[2]),
1781 Record[3], Record[4], Record[5])),
1785 case bitc::METADATA_DERIVED_TYPE: {
1786 if (Record.size() != 12)
1787 return Error("Invalid record");
1789 MDValueList.AssignValue(
1790 GET_OR_DISTINCT(MDDerivedType, Record[0],
1791 (Context, Record[1], getMDString(Record[2]),
1792 getMDOrNull(Record[3]), Record[4],
1793 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1794 Record[7], Record[8], Record[9], Record[10],
1795 getMDOrNull(Record[11]))),
1799 case bitc::METADATA_COMPOSITE_TYPE: {
1800 if (Record.size() != 16)
1801 return Error("Invalid record");
1803 MDValueList.AssignValue(
1804 GET_OR_DISTINCT(MDCompositeType, Record[0],
1805 (Context, Record[1], getMDString(Record[2]),
1806 getMDOrNull(Record[3]), Record[4],
1807 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1808 Record[7], Record[8], Record[9], Record[10],
1809 getMDOrNull(Record[11]), Record[12],
1810 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1811 getMDString(Record[15]))),
1815 case bitc::METADATA_SUBROUTINE_TYPE: {
1816 if (Record.size() != 3)
1817 return Error("Invalid record");
1819 MDValueList.AssignValue(
1820 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1821 (Context, Record[1], getMDOrNull(Record[2]))),
1825 case bitc::METADATA_FILE: {
1826 if (Record.size() != 3)
1827 return Error("Invalid record");
1829 MDValueList.AssignValue(
1830 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1831 getMDString(Record[2]))),
1835 case bitc::METADATA_COMPILE_UNIT: {
1836 if (Record.size() != 14)
1837 return Error("Invalid record");
1839 MDValueList.AssignValue(
1840 GET_OR_DISTINCT(MDCompileUnit, Record[0],
1841 (Context, Record[1], getMDOrNull(Record[2]),
1842 getMDString(Record[3]), Record[4],
1843 getMDString(Record[5]), Record[6],
1844 getMDString(Record[7]), Record[8],
1845 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1846 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1847 getMDOrNull(Record[13]))),
1851 case bitc::METADATA_SUBPROGRAM: {
1852 if (Record.size() != 19)
1853 return Error("Invalid record");
1855 MDValueList.AssignValue(
1857 MDSubprogram, Record[0],
1858 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1859 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1860 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1861 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1862 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1863 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1867 case bitc::METADATA_LEXICAL_BLOCK: {
1868 if (Record.size() != 5)
1869 return Error("Invalid record");
1871 MDValueList.AssignValue(
1872 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1873 (Context, getMDOrNull(Record[1]),
1874 getMDOrNull(Record[2]), Record[3], Record[4])),
1878 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1879 if (Record.size() != 4)
1880 return Error("Invalid record");
1882 MDValueList.AssignValue(
1883 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1884 (Context, getMDOrNull(Record[1]),
1885 getMDOrNull(Record[2]), Record[3])),
1889 case bitc::METADATA_NAMESPACE: {
1890 if (Record.size() != 5)
1891 return Error("Invalid record");
1893 MDValueList.AssignValue(
1894 GET_OR_DISTINCT(MDNamespace, Record[0],
1895 (Context, getMDOrNull(Record[1]),
1896 getMDOrNull(Record[2]), getMDString(Record[3]),
1901 case bitc::METADATA_TEMPLATE_TYPE: {
1902 if (Record.size() != 3)
1903 return Error("Invalid record");
1905 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1907 (Context, getMDString(Record[1]),
1908 getMDOrNull(Record[2]))),
1912 case bitc::METADATA_TEMPLATE_VALUE: {
1913 if (Record.size() != 5)
1914 return Error("Invalid record");
1916 MDValueList.AssignValue(
1917 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1918 (Context, Record[1], getMDString(Record[2]),
1919 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1923 case bitc::METADATA_GLOBAL_VAR: {
1924 if (Record.size() != 11)
1925 return Error("Invalid record");
1927 MDValueList.AssignValue(
1928 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1929 (Context, getMDOrNull(Record[1]),
1930 getMDString(Record[2]), getMDString(Record[3]),
1931 getMDOrNull(Record[4]), Record[5],
1932 getMDOrNull(Record[6]), Record[7], Record[8],
1933 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1937 case bitc::METADATA_LOCAL_VAR: {
1938 // 10th field is for the obseleted 'inlinedAt:' field.
1939 if (Record.size() != 9 && Record.size() != 10)
1940 return Error("Invalid record");
1942 MDValueList.AssignValue(
1943 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1944 (Context, Record[1], getMDOrNull(Record[2]),
1945 getMDString(Record[3]), getMDOrNull(Record[4]),
1946 Record[5], getMDOrNull(Record[6]), Record[7],
1951 case bitc::METADATA_EXPRESSION: {
1952 if (Record.size() < 1)
1953 return Error("Invalid record");
1955 MDValueList.AssignValue(
1956 GET_OR_DISTINCT(MDExpression, Record[0],
1957 (Context, makeArrayRef(Record).slice(1))),
1961 case bitc::METADATA_OBJC_PROPERTY: {
1962 if (Record.size() != 8)
1963 return Error("Invalid record");
1965 MDValueList.AssignValue(
1966 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1967 (Context, getMDString(Record[1]),
1968 getMDOrNull(Record[2]), Record[3],
1969 getMDString(Record[4]), getMDString(Record[5]),
1970 Record[6], getMDOrNull(Record[7]))),
1974 case bitc::METADATA_IMPORTED_ENTITY: {
1975 if (Record.size() != 6)
1976 return Error("Invalid record");
1978 MDValueList.AssignValue(
1979 GET_OR_DISTINCT(MDImportedEntity, Record[0],
1980 (Context, Record[1], getMDOrNull(Record[2]),
1981 getMDOrNull(Record[3]), Record[4],
1982 getMDString(Record[5]))),
1986 case bitc::METADATA_STRING: {
1987 std::string String(Record.begin(), Record.end());
1988 llvm::UpgradeMDStringConstant(String);
1989 Metadata *MD = MDString::get(Context, String);
1990 MDValueList.AssignValue(MD, NextMDValueNo++);
1993 case bitc::METADATA_KIND: {
1994 if (Record.size() < 2)
1995 return Error("Invalid record");
1997 unsigned Kind = Record[0];
1998 SmallString<8> Name(Record.begin()+1, Record.end());
2000 unsigned NewKind = TheModule->getMDKindID(Name.str());
2001 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2002 return Error("Conflicting METADATA_KIND records");
2007 #undef GET_OR_DISTINCT
2010 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
2011 /// the LSB for dense VBR encoding.
2012 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2017 // There is no such thing as -0 with integers. "-0" really means MININT.
2021 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
2022 /// values and aliases that we can.
2023 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
2024 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2025 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2026 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2027 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2029 GlobalInitWorklist.swap(GlobalInits);
2030 AliasInitWorklist.swap(AliasInits);
2031 FunctionPrefixWorklist.swap(FunctionPrefixes);
2032 FunctionPrologueWorklist.swap(FunctionPrologues);
2034 while (!GlobalInitWorklist.empty()) {
2035 unsigned ValID = GlobalInitWorklist.back().second;
2036 if (ValID >= ValueList.size()) {
2037 // Not ready to resolve this yet, it requires something later in the file.
2038 GlobalInits.push_back(GlobalInitWorklist.back());
2040 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2041 GlobalInitWorklist.back().first->setInitializer(C);
2043 return Error("Expected a constant");
2045 GlobalInitWorklist.pop_back();
2048 while (!AliasInitWorklist.empty()) {
2049 unsigned ValID = AliasInitWorklist.back().second;
2050 if (ValID >= ValueList.size()) {
2051 AliasInits.push_back(AliasInitWorklist.back());
2053 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2054 AliasInitWorklist.back().first->setAliasee(C);
2056 return Error("Expected a constant");
2058 AliasInitWorklist.pop_back();
2061 while (!FunctionPrefixWorklist.empty()) {
2062 unsigned ValID = FunctionPrefixWorklist.back().second;
2063 if (ValID >= ValueList.size()) {
2064 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2066 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2067 FunctionPrefixWorklist.back().first->setPrefixData(C);
2069 return Error("Expected a constant");
2071 FunctionPrefixWorklist.pop_back();
2074 while (!FunctionPrologueWorklist.empty()) {
2075 unsigned ValID = FunctionPrologueWorklist.back().second;
2076 if (ValID >= ValueList.size()) {
2077 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2079 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2080 FunctionPrologueWorklist.back().first->setPrologueData(C);
2082 return Error("Expected a constant");
2084 FunctionPrologueWorklist.pop_back();
2087 return std::error_code();
2090 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2091 SmallVector<uint64_t, 8> Words(Vals.size());
2092 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2093 BitcodeReader::decodeSignRotatedValue);
2095 return APInt(TypeBits, Words);
2098 std::error_code BitcodeReader::ParseConstants() {
2099 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2100 return Error("Invalid record");
2102 SmallVector<uint64_t, 64> Record;
2104 // Read all the records for this value table.
2105 Type *CurTy = Type::getInt32Ty(Context);
2106 unsigned NextCstNo = ValueList.size();
2108 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2110 switch (Entry.Kind) {
2111 case BitstreamEntry::SubBlock: // Handled for us already.
2112 case BitstreamEntry::Error:
2113 return Error("Malformed block");
2114 case BitstreamEntry::EndBlock:
2115 if (NextCstNo != ValueList.size())
2116 return Error("Invalid ronstant reference");
2118 // Once all the constants have been read, go through and resolve forward
2120 ValueList.ResolveConstantForwardRefs();
2121 return std::error_code();
2122 case BitstreamEntry::Record:
2123 // The interesting case.
2130 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2132 default: // Default behavior: unknown constant
2133 case bitc::CST_CODE_UNDEF: // UNDEF
2134 V = UndefValue::get(CurTy);
2136 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2138 return Error("Invalid record");
2139 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2140 return Error("Invalid record");
2141 CurTy = TypeList[Record[0]];
2142 continue; // Skip the ValueList manipulation.
2143 case bitc::CST_CODE_NULL: // NULL
2144 V = Constant::getNullValue(CurTy);
2146 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2147 if (!CurTy->isIntegerTy() || Record.empty())
2148 return Error("Invalid record");
2149 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2151 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2152 if (!CurTy->isIntegerTy() || Record.empty())
2153 return Error("Invalid record");
2155 APInt VInt = ReadWideAPInt(Record,
2156 cast<IntegerType>(CurTy)->getBitWidth());
2157 V = ConstantInt::get(Context, VInt);
2161 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2163 return Error("Invalid record");
2164 if (CurTy->isHalfTy())
2165 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2166 APInt(16, (uint16_t)Record[0])));
2167 else if (CurTy->isFloatTy())
2168 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2169 APInt(32, (uint32_t)Record[0])));
2170 else if (CurTy->isDoubleTy())
2171 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2172 APInt(64, Record[0])));
2173 else if (CurTy->isX86_FP80Ty()) {
2174 // Bits are not stored the same way as a normal i80 APInt, compensate.
2175 uint64_t Rearrange[2];
2176 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2177 Rearrange[1] = Record[0] >> 48;
2178 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2179 APInt(80, Rearrange)));
2180 } else if (CurTy->isFP128Ty())
2181 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2182 APInt(128, Record)));
2183 else if (CurTy->isPPC_FP128Ty())
2184 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2185 APInt(128, Record)));
2187 V = UndefValue::get(CurTy);
2191 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2193 return Error("Invalid record");
2195 unsigned Size = Record.size();
2196 SmallVector<Constant*, 16> Elts;
2198 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2199 for (unsigned i = 0; i != Size; ++i)
2200 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2201 STy->getElementType(i)));
2202 V = ConstantStruct::get(STy, Elts);
2203 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2204 Type *EltTy = ATy->getElementType();
2205 for (unsigned i = 0; i != Size; ++i)
2206 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2207 V = ConstantArray::get(ATy, Elts);
2208 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2209 Type *EltTy = VTy->getElementType();
2210 for (unsigned i = 0; i != Size; ++i)
2211 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2212 V = ConstantVector::get(Elts);
2214 V = UndefValue::get(CurTy);
2218 case bitc::CST_CODE_STRING: // STRING: [values]
2219 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2221 return Error("Invalid record");
2223 SmallString<16> Elts(Record.begin(), Record.end());
2224 V = ConstantDataArray::getString(Context, Elts,
2225 BitCode == bitc::CST_CODE_CSTRING);
2228 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2230 return Error("Invalid record");
2232 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2233 unsigned Size = Record.size();
2235 if (EltTy->isIntegerTy(8)) {
2236 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2237 if (isa<VectorType>(CurTy))
2238 V = ConstantDataVector::get(Context, Elts);
2240 V = ConstantDataArray::get(Context, Elts);
2241 } else if (EltTy->isIntegerTy(16)) {
2242 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2243 if (isa<VectorType>(CurTy))
2244 V = ConstantDataVector::get(Context, Elts);
2246 V = ConstantDataArray::get(Context, Elts);
2247 } else if (EltTy->isIntegerTy(32)) {
2248 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2249 if (isa<VectorType>(CurTy))
2250 V = ConstantDataVector::get(Context, Elts);
2252 V = ConstantDataArray::get(Context, Elts);
2253 } else if (EltTy->isIntegerTy(64)) {
2254 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2255 if (isa<VectorType>(CurTy))
2256 V = ConstantDataVector::get(Context, Elts);
2258 V = ConstantDataArray::get(Context, Elts);
2259 } else if (EltTy->isFloatTy()) {
2260 SmallVector<float, 16> Elts(Size);
2261 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2262 if (isa<VectorType>(CurTy))
2263 V = ConstantDataVector::get(Context, Elts);
2265 V = ConstantDataArray::get(Context, Elts);
2266 } else if (EltTy->isDoubleTy()) {
2267 SmallVector<double, 16> Elts(Size);
2268 std::transform(Record.begin(), Record.end(), Elts.begin(),
2270 if (isa<VectorType>(CurTy))
2271 V = ConstantDataVector::get(Context, Elts);
2273 V = ConstantDataArray::get(Context, Elts);
2275 return Error("Invalid type for value");
2280 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2281 if (Record.size() < 3)
2282 return Error("Invalid record");
2283 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2285 V = UndefValue::get(CurTy); // Unknown binop.
2287 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2288 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2290 if (Record.size() >= 4) {
2291 if (Opc == Instruction::Add ||
2292 Opc == Instruction::Sub ||
2293 Opc == Instruction::Mul ||
2294 Opc == Instruction::Shl) {
2295 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2296 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2297 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2298 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2299 } else if (Opc == Instruction::SDiv ||
2300 Opc == Instruction::UDiv ||
2301 Opc == Instruction::LShr ||
2302 Opc == Instruction::AShr) {
2303 if (Record[3] & (1 << bitc::PEO_EXACT))
2304 Flags |= SDivOperator::IsExact;
2307 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2311 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2312 if (Record.size() < 3)
2313 return Error("Invalid record");
2314 int Opc = GetDecodedCastOpcode(Record[0]);
2316 V = UndefValue::get(CurTy); // Unknown cast.
2318 Type *OpTy = getTypeByID(Record[1]);
2320 return Error("Invalid record");
2321 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2322 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2323 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2327 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2328 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2330 Type *PointeeType = nullptr;
2331 if (Record.size() % 2)
2332 PointeeType = getTypeByID(Record[OpNum++]);
2333 SmallVector<Constant*, 16> Elts;
2334 while (OpNum != Record.size()) {
2335 Type *ElTy = getTypeByID(Record[OpNum++]);
2337 return Error("Invalid record");
2338 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2343 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2345 return Error("Explicit gep operator type does not match pointee type "
2346 "of pointer operand");
2348 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2349 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2351 bitc::CST_CODE_CE_INBOUNDS_GEP);
2354 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2355 if (Record.size() < 3)
2356 return Error("Invalid record");
2358 Type *SelectorTy = Type::getInt1Ty(Context);
2360 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2361 // vector. Otherwise, it must be a single bit.
2362 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2363 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2364 VTy->getNumElements());
2366 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2368 ValueList.getConstantFwdRef(Record[1],CurTy),
2369 ValueList.getConstantFwdRef(Record[2],CurTy));
2372 case bitc::CST_CODE_CE_EXTRACTELT
2373 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2374 if (Record.size() < 3)
2375 return Error("Invalid record");
2377 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2379 return Error("Invalid record");
2380 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2381 Constant *Op1 = nullptr;
2382 if (Record.size() == 4) {
2383 Type *IdxTy = getTypeByID(Record[2]);
2385 return Error("Invalid record");
2386 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2387 } else // TODO: Remove with llvm 4.0
2388 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2390 return Error("Invalid record");
2391 V = ConstantExpr::getExtractElement(Op0, Op1);
2394 case bitc::CST_CODE_CE_INSERTELT
2395 : { // CE_INSERTELT: [opval, opval, opty, opval]
2396 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2397 if (Record.size() < 3 || !OpTy)
2398 return Error("Invalid record");
2399 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2400 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2401 OpTy->getElementType());
2402 Constant *Op2 = nullptr;
2403 if (Record.size() == 4) {
2404 Type *IdxTy = getTypeByID(Record[2]);
2406 return Error("Invalid record");
2407 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2408 } else // TODO: Remove with llvm 4.0
2409 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2411 return Error("Invalid record");
2412 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2415 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2416 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2417 if (Record.size() < 3 || !OpTy)
2418 return Error("Invalid record");
2419 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2420 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2421 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2422 OpTy->getNumElements());
2423 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2424 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2427 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2428 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2430 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2431 if (Record.size() < 4 || !RTy || !OpTy)
2432 return Error("Invalid record");
2433 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2434 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2435 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2436 RTy->getNumElements());
2437 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2438 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2441 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2442 if (Record.size() < 4)
2443 return Error("Invalid record");
2444 Type *OpTy = getTypeByID(Record[0]);
2446 return Error("Invalid record");
2447 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2448 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2450 if (OpTy->isFPOrFPVectorTy())
2451 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2453 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2456 // This maintains backward compatibility, pre-asm dialect keywords.
2457 // FIXME: Remove with the 4.0 release.
2458 case bitc::CST_CODE_INLINEASM_OLD: {
2459 if (Record.size() < 2)
2460 return Error("Invalid record");
2461 std::string AsmStr, ConstrStr;
2462 bool HasSideEffects = Record[0] & 1;
2463 bool IsAlignStack = Record[0] >> 1;
2464 unsigned AsmStrSize = Record[1];
2465 if (2+AsmStrSize >= Record.size())
2466 return Error("Invalid record");
2467 unsigned ConstStrSize = Record[2+AsmStrSize];
2468 if (3+AsmStrSize+ConstStrSize > Record.size())
2469 return Error("Invalid record");
2471 for (unsigned i = 0; i != AsmStrSize; ++i)
2472 AsmStr += (char)Record[2+i];
2473 for (unsigned i = 0; i != ConstStrSize; ++i)
2474 ConstrStr += (char)Record[3+AsmStrSize+i];
2475 PointerType *PTy = cast<PointerType>(CurTy);
2476 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2477 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2480 // This version adds support for the asm dialect keywords (e.g.,
2482 case bitc::CST_CODE_INLINEASM: {
2483 if (Record.size() < 2)
2484 return Error("Invalid record");
2485 std::string AsmStr, ConstrStr;
2486 bool HasSideEffects = Record[0] & 1;
2487 bool IsAlignStack = (Record[0] >> 1) & 1;
2488 unsigned AsmDialect = Record[0] >> 2;
2489 unsigned AsmStrSize = Record[1];
2490 if (2+AsmStrSize >= Record.size())
2491 return Error("Invalid record");
2492 unsigned ConstStrSize = Record[2+AsmStrSize];
2493 if (3+AsmStrSize+ConstStrSize > Record.size())
2494 return Error("Invalid record");
2496 for (unsigned i = 0; i != AsmStrSize; ++i)
2497 AsmStr += (char)Record[2+i];
2498 for (unsigned i = 0; i != ConstStrSize; ++i)
2499 ConstrStr += (char)Record[3+AsmStrSize+i];
2500 PointerType *PTy = cast<PointerType>(CurTy);
2501 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2502 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2503 InlineAsm::AsmDialect(AsmDialect));
2506 case bitc::CST_CODE_BLOCKADDRESS:{
2507 if (Record.size() < 3)
2508 return Error("Invalid record");
2509 Type *FnTy = getTypeByID(Record[0]);
2511 return Error("Invalid record");
2513 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2515 return Error("Invalid record");
2517 // Don't let Fn get dematerialized.
2518 BlockAddressesTaken.insert(Fn);
2520 // If the function is already parsed we can insert the block address right
2523 unsigned BBID = Record[2];
2525 // Invalid reference to entry block.
2526 return Error("Invalid ID");
2528 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2529 for (size_t I = 0, E = BBID; I != E; ++I) {
2531 return Error("Invalid ID");
2536 // Otherwise insert a placeholder and remember it so it can be inserted
2537 // when the function is parsed.
2538 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2540 BasicBlockFwdRefQueue.push_back(Fn);
2541 if (FwdBBs.size() < BBID + 1)
2542 FwdBBs.resize(BBID + 1);
2544 FwdBBs[BBID] = BasicBlock::Create(Context);
2547 V = BlockAddress::get(Fn, BB);
2552 ValueList.AssignValue(V, NextCstNo);
2557 std::error_code BitcodeReader::ParseUseLists() {
2558 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2559 return Error("Invalid record");
2561 // Read all the records.
2562 SmallVector<uint64_t, 64> Record;
2564 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2566 switch (Entry.Kind) {
2567 case BitstreamEntry::SubBlock: // Handled for us already.
2568 case BitstreamEntry::Error:
2569 return Error("Malformed block");
2570 case BitstreamEntry::EndBlock:
2571 return std::error_code();
2572 case BitstreamEntry::Record:
2573 // The interesting case.
2577 // Read a use list record.
2580 switch (Stream.readRecord(Entry.ID, Record)) {
2581 default: // Default behavior: unknown type.
2583 case bitc::USELIST_CODE_BB:
2586 case bitc::USELIST_CODE_DEFAULT: {
2587 unsigned RecordLength = Record.size();
2588 if (RecordLength < 3)
2589 // Records should have at least an ID and two indexes.
2590 return Error("Invalid record");
2591 unsigned ID = Record.back();
2596 assert(ID < FunctionBBs.size() && "Basic block not found");
2597 V = FunctionBBs[ID];
2600 unsigned NumUses = 0;
2601 SmallDenseMap<const Use *, unsigned, 16> Order;
2602 for (const Use &U : V->uses()) {
2603 if (++NumUses > Record.size())
2605 Order[&U] = Record[NumUses - 1];
2607 if (Order.size() != Record.size() || NumUses > Record.size())
2608 // Mismatches can happen if the functions are being materialized lazily
2609 // (out-of-order), or a value has been upgraded.
2612 V->sortUseList([&](const Use &L, const Use &R) {
2613 return Order.lookup(&L) < Order.lookup(&R);
2621 /// When we see the block for metadata, remember where it is and then skip it.
2622 /// This lets us lazily deserialize the metadata.
2623 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2624 // Save the current stream state.
2625 uint64_t CurBit = Stream.GetCurrentBitNo();
2626 DeferredMetadataInfo.push_back(CurBit);
2628 // Skip over the block for now.
2629 if (Stream.SkipBlock())
2630 return Error("Invalid record");
2631 return std::error_code();
2634 std::error_code BitcodeReader::materializeMetadata() {
2635 for (uint64_t BitPos : DeferredMetadataInfo) {
2636 // Move the bit stream to the saved position.
2637 Stream.JumpToBit(BitPos);
2638 if (std::error_code EC = ParseMetadata())
2641 DeferredMetadataInfo.clear();
2642 return std::error_code();
2645 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2647 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2648 /// remember where it is and then skip it. This lets us lazily deserialize the
2650 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2651 // Get the function we are talking about.
2652 if (FunctionsWithBodies.empty())
2653 return Error("Insufficient function protos");
2655 Function *Fn = FunctionsWithBodies.back();
2656 FunctionsWithBodies.pop_back();
2658 // Save the current stream state.
2659 uint64_t CurBit = Stream.GetCurrentBitNo();
2660 DeferredFunctionInfo[Fn] = CurBit;
2662 // Skip over the function block for now.
2663 if (Stream.SkipBlock())
2664 return Error("Invalid record");
2665 return std::error_code();
2668 std::error_code BitcodeReader::GlobalCleanup() {
2669 // Patch the initializers for globals and aliases up.
2670 ResolveGlobalAndAliasInits();
2671 if (!GlobalInits.empty() || !AliasInits.empty())
2672 return Error("Malformed global initializer set");
2674 // Look for intrinsic functions which need to be upgraded at some point
2675 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2678 if (UpgradeIntrinsicFunction(FI, NewFn))
2679 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2682 // Look for global variables which need to be renamed.
2683 for (Module::global_iterator
2684 GI = TheModule->global_begin(), GE = TheModule->global_end();
2686 GlobalVariable *GV = GI++;
2687 UpgradeGlobalVariable(GV);
2690 // Force deallocation of memory for these vectors to favor the client that
2691 // want lazy deserialization.
2692 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2693 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2694 return std::error_code();
2697 std::error_code BitcodeReader::ParseModule(bool Resume,
2698 bool ShouldLazyLoadMetadata) {
2700 Stream.JumpToBit(NextUnreadBit);
2701 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2702 return Error("Invalid record");
2704 SmallVector<uint64_t, 64> Record;
2705 std::vector<std::string> SectionTable;
2706 std::vector<std::string> GCTable;
2708 // Read all the records for this module.
2710 BitstreamEntry Entry = Stream.advance();
2712 switch (Entry.Kind) {
2713 case BitstreamEntry::Error:
2714 return Error("Malformed block");
2715 case BitstreamEntry::EndBlock:
2716 return GlobalCleanup();
2718 case BitstreamEntry::SubBlock:
2720 default: // Skip unknown content.
2721 if (Stream.SkipBlock())
2722 return Error("Invalid record");
2724 case bitc::BLOCKINFO_BLOCK_ID:
2725 if (Stream.ReadBlockInfoBlock())
2726 return Error("Malformed block");
2728 case bitc::PARAMATTR_BLOCK_ID:
2729 if (std::error_code EC = ParseAttributeBlock())
2732 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2733 if (std::error_code EC = ParseAttributeGroupBlock())
2736 case bitc::TYPE_BLOCK_ID_NEW:
2737 if (std::error_code EC = ParseTypeTable())
2740 case bitc::VALUE_SYMTAB_BLOCK_ID:
2741 if (std::error_code EC = ParseValueSymbolTable())
2743 SeenValueSymbolTable = true;
2745 case bitc::CONSTANTS_BLOCK_ID:
2746 if (std::error_code EC = ParseConstants())
2748 if (std::error_code EC = ResolveGlobalAndAliasInits())
2751 case bitc::METADATA_BLOCK_ID:
2752 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2753 if (std::error_code EC = rememberAndSkipMetadata())
2757 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2758 if (std::error_code EC = ParseMetadata())
2761 case bitc::FUNCTION_BLOCK_ID:
2762 // If this is the first function body we've seen, reverse the
2763 // FunctionsWithBodies list.
2764 if (!SeenFirstFunctionBody) {
2765 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2766 if (std::error_code EC = GlobalCleanup())
2768 SeenFirstFunctionBody = true;
2771 if (std::error_code EC = RememberAndSkipFunctionBody())
2773 // For streaming bitcode, suspend parsing when we reach the function
2774 // bodies. Subsequent materialization calls will resume it when
2775 // necessary. For streaming, the function bodies must be at the end of
2776 // the bitcode. If the bitcode file is old, the symbol table will be
2777 // at the end instead and will not have been seen yet. In this case,
2778 // just finish the parse now.
2779 if (LazyStreamer && SeenValueSymbolTable) {
2780 NextUnreadBit = Stream.GetCurrentBitNo();
2781 return std::error_code();
2784 case bitc::USELIST_BLOCK_ID:
2785 if (std::error_code EC = ParseUseLists())
2791 case BitstreamEntry::Record:
2792 // The interesting case.
2798 switch (Stream.readRecord(Entry.ID, Record)) {
2799 default: break; // Default behavior, ignore unknown content.
2800 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2801 if (Record.size() < 1)
2802 return Error("Invalid record");
2803 // Only version #0 and #1 are supported so far.
2804 unsigned module_version = Record[0];
2805 switch (module_version) {
2807 return Error("Invalid value");
2809 UseRelativeIDs = false;
2812 UseRelativeIDs = true;
2817 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2819 if (ConvertToString(Record, 0, S))
2820 return Error("Invalid record");
2821 TheModule->setTargetTriple(S);
2824 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2826 if (ConvertToString(Record, 0, S))
2827 return Error("Invalid record");
2828 TheModule->setDataLayout(S);
2831 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2833 if (ConvertToString(Record, 0, S))
2834 return Error("Invalid record");
2835 TheModule->setModuleInlineAsm(S);
2838 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2839 // FIXME: Remove in 4.0.
2841 if (ConvertToString(Record, 0, S))
2842 return Error("Invalid record");
2846 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2848 if (ConvertToString(Record, 0, S))
2849 return Error("Invalid record");
2850 SectionTable.push_back(S);
2853 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2855 if (ConvertToString(Record, 0, S))
2856 return Error("Invalid record");
2857 GCTable.push_back(S);
2860 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2861 if (Record.size() < 2)
2862 return Error("Invalid record");
2863 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2864 unsigned ComdatNameSize = Record[1];
2865 std::string ComdatName;
2866 ComdatName.reserve(ComdatNameSize);
2867 for (unsigned i = 0; i != ComdatNameSize; ++i)
2868 ComdatName += (char)Record[2 + i];
2869 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2870 C->setSelectionKind(SK);
2871 ComdatList.push_back(C);
2874 // GLOBALVAR: [pointer type, isconst, initid,
2875 // linkage, alignment, section, visibility, threadlocal,
2876 // unnamed_addr, externally_initialized, dllstorageclass,
2878 case bitc::MODULE_CODE_GLOBALVAR: {
2879 if (Record.size() < 6)
2880 return Error("Invalid record");
2881 Type *Ty = getTypeByID(Record[0]);
2883 return Error("Invalid record");
2884 bool isConstant = Record[1] & 1;
2885 bool explicitType = Record[1] & 2;
2886 unsigned AddressSpace;
2888 AddressSpace = Record[1] >> 2;
2890 if (!Ty->isPointerTy())
2891 return Error("Invalid type for value");
2892 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2893 Ty = cast<PointerType>(Ty)->getElementType();
2896 uint64_t RawLinkage = Record[3];
2897 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2899 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2901 std::string Section;
2903 if (Record[5]-1 >= SectionTable.size())
2904 return Error("Invalid ID");
2905 Section = SectionTable[Record[5]-1];
2907 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2908 // Local linkage must have default visibility.
2909 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2910 // FIXME: Change to an error if non-default in 4.0.
2911 Visibility = GetDecodedVisibility(Record[6]);
2913 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2914 if (Record.size() > 7)
2915 TLM = GetDecodedThreadLocalMode(Record[7]);
2917 bool UnnamedAddr = false;
2918 if (Record.size() > 8)
2919 UnnamedAddr = Record[8];
2921 bool ExternallyInitialized = false;
2922 if (Record.size() > 9)
2923 ExternallyInitialized = Record[9];
2925 GlobalVariable *NewGV =
2926 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2927 TLM, AddressSpace, ExternallyInitialized);
2928 NewGV->setAlignment(Alignment);
2929 if (!Section.empty())
2930 NewGV->setSection(Section);
2931 NewGV->setVisibility(Visibility);
2932 NewGV->setUnnamedAddr(UnnamedAddr);
2934 if (Record.size() > 10)
2935 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2937 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2939 ValueList.push_back(NewGV);
2941 // Remember which value to use for the global initializer.
2942 if (unsigned InitID = Record[2])
2943 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2945 if (Record.size() > 11) {
2946 if (unsigned ComdatID = Record[11]) {
2947 assert(ComdatID <= ComdatList.size());
2948 NewGV->setComdat(ComdatList[ComdatID - 1]);
2950 } else if (hasImplicitComdat(RawLinkage)) {
2951 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2955 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2956 // alignment, section, visibility, gc, unnamed_addr,
2957 // prologuedata, dllstorageclass, comdat, prefixdata]
2958 case bitc::MODULE_CODE_FUNCTION: {
2959 if (Record.size() < 8)
2960 return Error("Invalid record");
2961 Type *Ty = getTypeByID(Record[0]);
2963 return Error("Invalid record");
2964 if (auto *PTy = dyn_cast<PointerType>(Ty))
2965 Ty = PTy->getElementType();
2966 auto *FTy = dyn_cast<FunctionType>(Ty);
2968 return Error("Invalid type for value");
2970 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2973 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2974 bool isProto = Record[2];
2975 uint64_t RawLinkage = Record[3];
2976 Func->setLinkage(getDecodedLinkage(RawLinkage));
2977 Func->setAttributes(getAttributes(Record[4]));
2980 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2982 Func->setAlignment(Alignment);
2984 if (Record[6]-1 >= SectionTable.size())
2985 return Error("Invalid ID");
2986 Func->setSection(SectionTable[Record[6]-1]);
2988 // Local linkage must have default visibility.
2989 if (!Func->hasLocalLinkage())
2990 // FIXME: Change to an error if non-default in 4.0.
2991 Func->setVisibility(GetDecodedVisibility(Record[7]));
2992 if (Record.size() > 8 && Record[8]) {
2993 if (Record[8]-1 > GCTable.size())
2994 return Error("Invalid ID");
2995 Func->setGC(GCTable[Record[8]-1].c_str());
2997 bool UnnamedAddr = false;
2998 if (Record.size() > 9)
2999 UnnamedAddr = Record[9];
3000 Func->setUnnamedAddr(UnnamedAddr);
3001 if (Record.size() > 10 && Record[10] != 0)
3002 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3004 if (Record.size() > 11)
3005 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
3007 UpgradeDLLImportExportLinkage(Func, RawLinkage);
3009 if (Record.size() > 12) {
3010 if (unsigned ComdatID = Record[12]) {
3011 assert(ComdatID <= ComdatList.size());
3012 Func->setComdat(ComdatList[ComdatID - 1]);
3014 } else if (hasImplicitComdat(RawLinkage)) {
3015 Func->setComdat(reinterpret_cast<Comdat *>(1));
3018 if (Record.size() > 13 && Record[13] != 0)
3019 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3021 ValueList.push_back(Func);
3023 // If this is a function with a body, remember the prototype we are
3024 // creating now, so that we can match up the body with them later.
3026 Func->setIsMaterializable(true);
3027 FunctionsWithBodies.push_back(Func);
3029 DeferredFunctionInfo[Func] = 0;
3033 // ALIAS: [alias type, aliasee val#, linkage]
3034 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3035 case bitc::MODULE_CODE_ALIAS: {
3036 if (Record.size() < 3)
3037 return Error("Invalid record");
3038 Type *Ty = getTypeByID(Record[0]);
3040 return Error("Invalid record");
3041 auto *PTy = dyn_cast<PointerType>(Ty);
3043 return Error("Invalid type for value");
3046 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
3047 getDecodedLinkage(Record[2]), "", TheModule);
3048 // Old bitcode files didn't have visibility field.
3049 // Local linkage must have default visibility.
3050 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3051 // FIXME: Change to an error if non-default in 4.0.
3052 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3053 if (Record.size() > 4)
3054 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3056 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3057 if (Record.size() > 5)
3058 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3059 if (Record.size() > 6)
3060 NewGA->setUnnamedAddr(Record[6]);
3061 ValueList.push_back(NewGA);
3062 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3065 /// MODULE_CODE_PURGEVALS: [numvals]
3066 case bitc::MODULE_CODE_PURGEVALS:
3067 // Trim down the value list to the specified size.
3068 if (Record.size() < 1 || Record[0] > ValueList.size())
3069 return Error("Invalid record");
3070 ValueList.shrinkTo(Record[0]);
3077 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3078 bool ShouldLazyLoadMetadata) {
3079 TheModule = nullptr;
3081 if (std::error_code EC = InitStream())
3084 // Sniff for the signature.
3085 if (Stream.Read(8) != 'B' ||
3086 Stream.Read(8) != 'C' ||
3087 Stream.Read(4) != 0x0 ||
3088 Stream.Read(4) != 0xC ||
3089 Stream.Read(4) != 0xE ||
3090 Stream.Read(4) != 0xD)
3091 return Error("Invalid bitcode signature");
3093 // We expect a number of well-defined blocks, though we don't necessarily
3094 // need to understand them all.
3096 if (Stream.AtEndOfStream()) {
3098 return std::error_code();
3099 // We didn't really read a proper Module.
3100 return Error("Malformed IR file");
3103 BitstreamEntry Entry =
3104 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3106 switch (Entry.Kind) {
3107 case BitstreamEntry::Error:
3108 return Error("Malformed block");
3109 case BitstreamEntry::EndBlock:
3110 return std::error_code();
3112 case BitstreamEntry::SubBlock:
3114 case bitc::BLOCKINFO_BLOCK_ID:
3115 if (Stream.ReadBlockInfoBlock())
3116 return Error("Malformed block");
3118 case bitc::MODULE_BLOCK_ID:
3119 // Reject multiple MODULE_BLOCK's in a single bitstream.
3121 return Error("Invalid multiple blocks");
3123 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3126 return std::error_code();
3129 if (Stream.SkipBlock())
3130 return Error("Invalid record");
3134 case BitstreamEntry::Record:
3135 // There should be no records in the top-level of blocks.
3137 // The ranlib in Xcode 4 will align archive members by appending newlines
3138 // to the end of them. If this file size is a multiple of 4 but not 8, we
3139 // have to read and ignore these final 4 bytes :-(
3140 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3141 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3142 Stream.AtEndOfStream())
3143 return std::error_code();
3145 return Error("Invalid record");
3150 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3151 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3152 return Error("Invalid record");
3154 SmallVector<uint64_t, 64> Record;
3157 // Read all the records for this module.
3159 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3161 switch (Entry.Kind) {
3162 case BitstreamEntry::SubBlock: // Handled for us already.
3163 case BitstreamEntry::Error:
3164 return Error("Malformed block");
3165 case BitstreamEntry::EndBlock:
3167 case BitstreamEntry::Record:
3168 // The interesting case.
3173 switch (Stream.readRecord(Entry.ID, Record)) {
3174 default: break; // Default behavior, ignore unknown content.
3175 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3177 if (ConvertToString(Record, 0, S))
3178 return Error("Invalid record");
3185 llvm_unreachable("Exit infinite loop");
3188 ErrorOr<std::string> BitcodeReader::parseTriple() {
3189 if (std::error_code EC = InitStream())
3192 // Sniff for the signature.
3193 if (Stream.Read(8) != 'B' ||
3194 Stream.Read(8) != 'C' ||
3195 Stream.Read(4) != 0x0 ||
3196 Stream.Read(4) != 0xC ||
3197 Stream.Read(4) != 0xE ||
3198 Stream.Read(4) != 0xD)
3199 return Error("Invalid bitcode signature");
3201 // We expect a number of well-defined blocks, though we don't necessarily
3202 // need to understand them all.
3204 BitstreamEntry Entry = Stream.advance();
3206 switch (Entry.Kind) {
3207 case BitstreamEntry::Error:
3208 return Error("Malformed block");
3209 case BitstreamEntry::EndBlock:
3210 return std::error_code();
3212 case BitstreamEntry::SubBlock:
3213 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3214 return parseModuleTriple();
3216 // Ignore other sub-blocks.
3217 if (Stream.SkipBlock())
3218 return Error("Malformed block");
3221 case BitstreamEntry::Record:
3222 Stream.skipRecord(Entry.ID);
3228 /// ParseMetadataAttachment - Parse metadata attachments.
3229 std::error_code BitcodeReader::ParseMetadataAttachment(Function &F) {
3230 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3231 return Error("Invalid record");
3233 SmallVector<uint64_t, 64> Record;
3235 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3237 switch (Entry.Kind) {
3238 case BitstreamEntry::SubBlock: // Handled for us already.
3239 case BitstreamEntry::Error:
3240 return Error("Malformed block");
3241 case BitstreamEntry::EndBlock:
3242 return std::error_code();
3243 case BitstreamEntry::Record:
3244 // The interesting case.
3248 // Read a metadata attachment record.
3250 switch (Stream.readRecord(Entry.ID, Record)) {
3251 default: // Default behavior: ignore.
3253 case bitc::METADATA_ATTACHMENT: {
3254 unsigned RecordLength = Record.size();
3256 return Error("Invalid record");
3257 if (RecordLength % 2 == 0) {
3258 // A function attachment.
3259 for (unsigned I = 0; I != RecordLength; I += 2) {
3260 auto K = MDKindMap.find(Record[I]);
3261 if (K == MDKindMap.end())
3262 return Error("Invalid ID");
3263 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3264 F.setMetadata(K->second, cast<MDNode>(MD));
3269 // An instruction attachment.
3270 Instruction *Inst = InstructionList[Record[0]];
3271 for (unsigned i = 1; i != RecordLength; i = i+2) {
3272 unsigned Kind = Record[i];
3273 DenseMap<unsigned, unsigned>::iterator I =
3274 MDKindMap.find(Kind);
3275 if (I == MDKindMap.end())
3276 return Error("Invalid ID");
3277 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3278 if (isa<LocalAsMetadata>(Node))
3279 // Drop the attachment. This used to be legal, but there's no
3282 Inst->setMetadata(I->second, cast<MDNode>(Node));
3283 if (I->second == LLVMContext::MD_tbaa)
3284 InstsWithTBAATag.push_back(Inst);
3292 /// ParseFunctionBody - Lazily parse the specified function body block.
3293 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3294 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3295 return Error("Invalid record");
3297 InstructionList.clear();
3298 unsigned ModuleValueListSize = ValueList.size();
3299 unsigned ModuleMDValueListSize = MDValueList.size();
3301 // Add all the function arguments to the value table.
3302 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3303 ValueList.push_back(I);
3305 unsigned NextValueNo = ValueList.size();
3306 BasicBlock *CurBB = nullptr;
3307 unsigned CurBBNo = 0;
3310 auto getLastInstruction = [&]() -> Instruction * {
3311 if (CurBB && !CurBB->empty())
3312 return &CurBB->back();
3313 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3314 !FunctionBBs[CurBBNo - 1]->empty())
3315 return &FunctionBBs[CurBBNo - 1]->back();
3319 // Read all the records.
3320 SmallVector<uint64_t, 64> Record;
3322 BitstreamEntry Entry = Stream.advance();
3324 switch (Entry.Kind) {
3325 case BitstreamEntry::Error:
3326 return Error("Malformed block");
3327 case BitstreamEntry::EndBlock:
3328 goto OutOfRecordLoop;
3330 case BitstreamEntry::SubBlock:
3332 default: // Skip unknown content.
3333 if (Stream.SkipBlock())
3334 return Error("Invalid record");
3336 case bitc::CONSTANTS_BLOCK_ID:
3337 if (std::error_code EC = ParseConstants())
3339 NextValueNo = ValueList.size();
3341 case bitc::VALUE_SYMTAB_BLOCK_ID:
3342 if (std::error_code EC = ParseValueSymbolTable())
3345 case bitc::METADATA_ATTACHMENT_ID:
3346 if (std::error_code EC = ParseMetadataAttachment(*F))
3349 case bitc::METADATA_BLOCK_ID:
3350 if (std::error_code EC = ParseMetadata())
3353 case bitc::USELIST_BLOCK_ID:
3354 if (std::error_code EC = ParseUseLists())
3360 case BitstreamEntry::Record:
3361 // The interesting case.
3367 Instruction *I = nullptr;
3368 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3370 default: // Default behavior: reject
3371 return Error("Invalid value");
3372 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3373 if (Record.size() < 1 || Record[0] == 0)
3374 return Error("Invalid record");
3375 // Create all the basic blocks for the function.
3376 FunctionBBs.resize(Record[0]);
3378 // See if anything took the address of blocks in this function.
3379 auto BBFRI = BasicBlockFwdRefs.find(F);
3380 if (BBFRI == BasicBlockFwdRefs.end()) {
3381 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3382 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3384 auto &BBRefs = BBFRI->second;
3385 // Check for invalid basic block references.
3386 if (BBRefs.size() > FunctionBBs.size())
3387 return Error("Invalid ID");
3388 assert(!BBRefs.empty() && "Unexpected empty array");
3389 assert(!BBRefs.front() && "Invalid reference to entry block");
3390 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3392 if (I < RE && BBRefs[I]) {
3393 BBRefs[I]->insertInto(F);
3394 FunctionBBs[I] = BBRefs[I];
3396 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3399 // Erase from the table.
3400 BasicBlockFwdRefs.erase(BBFRI);
3403 CurBB = FunctionBBs[0];
3407 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3408 // This record indicates that the last instruction is at the same
3409 // location as the previous instruction with a location.
3410 I = getLastInstruction();
3413 return Error("Invalid record");
3414 I->setDebugLoc(LastLoc);
3418 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3419 I = getLastInstruction();
3420 if (!I || Record.size() < 4)
3421 return Error("Invalid record");
3423 unsigned Line = Record[0], Col = Record[1];
3424 unsigned ScopeID = Record[2], IAID = Record[3];
3426 MDNode *Scope = nullptr, *IA = nullptr;
3427 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3428 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3429 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3430 I->setDebugLoc(LastLoc);
3435 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3438 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3439 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3440 OpNum+1 > Record.size())
3441 return Error("Invalid record");
3443 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3445 return Error("Invalid record");
3446 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3447 InstructionList.push_back(I);
3448 if (OpNum < Record.size()) {
3449 if (Opc == Instruction::Add ||
3450 Opc == Instruction::Sub ||
3451 Opc == Instruction::Mul ||
3452 Opc == Instruction::Shl) {
3453 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3454 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3455 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3456 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3457 } else if (Opc == Instruction::SDiv ||
3458 Opc == Instruction::UDiv ||
3459 Opc == Instruction::LShr ||
3460 Opc == Instruction::AShr) {
3461 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3462 cast<BinaryOperator>(I)->setIsExact(true);
3463 } else if (isa<FPMathOperator>(I)) {
3465 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3466 FMF.setUnsafeAlgebra();
3467 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3469 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3471 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3472 FMF.setNoSignedZeros();
3473 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3474 FMF.setAllowReciprocal();
3476 I->setFastMathFlags(FMF);
3482 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3485 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3486 OpNum+2 != Record.size())
3487 return Error("Invalid record");
3489 Type *ResTy = getTypeByID(Record[OpNum]);
3490 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3491 if (Opc == -1 || !ResTy)
3492 return Error("Invalid record");
3493 Instruction *Temp = nullptr;
3494 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3496 InstructionList.push_back(Temp);
3497 CurBB->getInstList().push_back(Temp);
3500 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3502 InstructionList.push_back(I);
3505 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3506 case bitc::FUNC_CODE_INST_GEP_OLD:
3507 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3513 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3514 InBounds = Record[OpNum++];
3515 Ty = getTypeByID(Record[OpNum++]);
3517 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3522 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3523 return Error("Invalid record");
3527 cast<SequentialType>(BasePtr->getType()->getScalarType())
3530 "Explicit gep type does not match pointee type of pointer operand");
3532 SmallVector<Value*, 16> GEPIdx;
3533 while (OpNum != Record.size()) {
3535 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3536 return Error("Invalid record");
3537 GEPIdx.push_back(Op);
3540 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3542 InstructionList.push_back(I);
3544 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3548 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3549 // EXTRACTVAL: [opty, opval, n x indices]
3552 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3553 return Error("Invalid record");
3555 SmallVector<unsigned, 4> EXTRACTVALIdx;
3556 Type *CurTy = Agg->getType();
3557 for (unsigned RecSize = Record.size();
3558 OpNum != RecSize; ++OpNum) {
3559 bool IsArray = CurTy->isArrayTy();
3560 bool IsStruct = CurTy->isStructTy();
3561 uint64_t Index = Record[OpNum];
3563 if (!IsStruct && !IsArray)
3564 return Error("EXTRACTVAL: Invalid type");
3565 if ((unsigned)Index != Index)
3566 return Error("Invalid value");
3567 if (IsStruct && Index >= CurTy->subtypes().size())
3568 return Error("EXTRACTVAL: Invalid struct index");
3569 if (IsArray && Index >= CurTy->getArrayNumElements())
3570 return Error("EXTRACTVAL: Invalid array index");
3571 EXTRACTVALIdx.push_back((unsigned)Index);
3574 CurTy = CurTy->subtypes()[Index];
3576 CurTy = CurTy->subtypes()[0];
3579 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3580 InstructionList.push_back(I);
3584 case bitc::FUNC_CODE_INST_INSERTVAL: {
3585 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3588 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3589 return Error("Invalid record");
3591 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3592 return Error("Invalid record");
3594 SmallVector<unsigned, 4> INSERTVALIdx;
3595 Type *CurTy = Agg->getType();
3596 for (unsigned RecSize = Record.size();
3597 OpNum != RecSize; ++OpNum) {
3598 bool IsArray = CurTy->isArrayTy();
3599 bool IsStruct = CurTy->isStructTy();
3600 uint64_t Index = Record[OpNum];
3602 if (!IsStruct && !IsArray)
3603 return Error("INSERTVAL: Invalid type");
3604 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3605 return Error("Invalid type");
3606 if ((unsigned)Index != Index)
3607 return Error("Invalid value");
3608 if (IsStruct && Index >= CurTy->subtypes().size())
3609 return Error("INSERTVAL: Invalid struct index");
3610 if (IsArray && Index >= CurTy->getArrayNumElements())
3611 return Error("INSERTVAL: Invalid array index");
3613 INSERTVALIdx.push_back((unsigned)Index);
3615 CurTy = CurTy->subtypes()[Index];
3617 CurTy = CurTy->subtypes()[0];
3620 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3621 InstructionList.push_back(I);
3625 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3626 // obsolete form of select
3627 // handles select i1 ... in old bitcode
3629 Value *TrueVal, *FalseVal, *Cond;
3630 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3631 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3632 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3633 return Error("Invalid record");
3635 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3636 InstructionList.push_back(I);
3640 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3641 // new form of select
3642 // handles select i1 or select [N x i1]
3644 Value *TrueVal, *FalseVal, *Cond;
3645 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3646 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3647 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3648 return Error("Invalid record");
3650 // select condition can be either i1 or [N x i1]
3651 if (VectorType* vector_type =
3652 dyn_cast<VectorType>(Cond->getType())) {
3654 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3655 return Error("Invalid type for value");
3658 if (Cond->getType() != Type::getInt1Ty(Context))
3659 return Error("Invalid type for value");
3662 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3663 InstructionList.push_back(I);
3667 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3670 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3671 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3672 return Error("Invalid record");
3673 if (!Vec->getType()->isVectorTy())
3674 return Error("Invalid type for value");
3675 I = ExtractElementInst::Create(Vec, Idx);
3676 InstructionList.push_back(I);
3680 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3682 Value *Vec, *Elt, *Idx;
3683 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3684 return Error("Invalid record");
3685 if (!Vec->getType()->isVectorTy())
3686 return Error("Invalid type for value");
3687 if (popValue(Record, OpNum, NextValueNo,
3688 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3689 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3690 return Error("Invalid record");
3691 I = InsertElementInst::Create(Vec, Elt, Idx);
3692 InstructionList.push_back(I);
3696 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3698 Value *Vec1, *Vec2, *Mask;
3699 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3700 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3701 return Error("Invalid record");
3703 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3704 return Error("Invalid record");
3705 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3706 return Error("Invalid type for value");
3707 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3708 InstructionList.push_back(I);
3712 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3713 // Old form of ICmp/FCmp returning bool
3714 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3715 // both legal on vectors but had different behaviour.
3716 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3717 // FCmp/ICmp returning bool or vector of bool
3721 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3722 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3723 OpNum+1 != Record.size())
3724 return Error("Invalid record");
3726 if (LHS->getType()->isFPOrFPVectorTy())
3727 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3729 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3730 InstructionList.push_back(I);
3734 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3736 unsigned Size = Record.size();
3738 I = ReturnInst::Create(Context);
3739 InstructionList.push_back(I);
3744 Value *Op = nullptr;
3745 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3746 return Error("Invalid record");
3747 if (OpNum != Record.size())
3748 return Error("Invalid record");
3750 I = ReturnInst::Create(Context, Op);
3751 InstructionList.push_back(I);
3754 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3755 if (Record.size() != 1 && Record.size() != 3)
3756 return Error("Invalid record");
3757 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3759 return Error("Invalid record");
3761 if (Record.size() == 1) {
3762 I = BranchInst::Create(TrueDest);
3763 InstructionList.push_back(I);
3766 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3767 Value *Cond = getValue(Record, 2, NextValueNo,
3768 Type::getInt1Ty(Context));
3769 if (!FalseDest || !Cond)
3770 return Error("Invalid record");
3771 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3772 InstructionList.push_back(I);
3776 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3778 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3779 // "New" SwitchInst format with case ranges. The changes to write this
3780 // format were reverted but we still recognize bitcode that uses it.
3781 // Hopefully someday we will have support for case ranges and can use
3782 // this format again.
3784 Type *OpTy = getTypeByID(Record[1]);
3785 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3787 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3788 BasicBlock *Default = getBasicBlock(Record[3]);
3789 if (!OpTy || !Cond || !Default)
3790 return Error("Invalid record");
3792 unsigned NumCases = Record[4];
3794 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3795 InstructionList.push_back(SI);
3797 unsigned CurIdx = 5;
3798 for (unsigned i = 0; i != NumCases; ++i) {
3799 SmallVector<ConstantInt*, 1> CaseVals;
3800 unsigned NumItems = Record[CurIdx++];
3801 for (unsigned ci = 0; ci != NumItems; ++ci) {
3802 bool isSingleNumber = Record[CurIdx++];
3805 unsigned ActiveWords = 1;
3806 if (ValueBitWidth > 64)
3807 ActiveWords = Record[CurIdx++];
3808 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3810 CurIdx += ActiveWords;
3812 if (!isSingleNumber) {
3814 if (ValueBitWidth > 64)
3815 ActiveWords = Record[CurIdx++];
3817 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3819 CurIdx += ActiveWords;
3821 // FIXME: It is not clear whether values in the range should be
3822 // compared as signed or unsigned values. The partially
3823 // implemented changes that used this format in the past used
3824 // unsigned comparisons.
3825 for ( ; Low.ule(High); ++Low)
3826 CaseVals.push_back(ConstantInt::get(Context, Low));
3828 CaseVals.push_back(ConstantInt::get(Context, Low));
3830 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3831 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3832 cve = CaseVals.end(); cvi != cve; ++cvi)
3833 SI->addCase(*cvi, DestBB);
3839 // Old SwitchInst format without case ranges.
3841 if (Record.size() < 3 || (Record.size() & 1) == 0)
3842 return Error("Invalid record");
3843 Type *OpTy = getTypeByID(Record[0]);
3844 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3845 BasicBlock *Default = getBasicBlock(Record[2]);
3846 if (!OpTy || !Cond || !Default)
3847 return Error("Invalid record");
3848 unsigned NumCases = (Record.size()-3)/2;
3849 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3850 InstructionList.push_back(SI);
3851 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3852 ConstantInt *CaseVal =
3853 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3854 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3855 if (!CaseVal || !DestBB) {
3857 return Error("Invalid record");
3859 SI->addCase(CaseVal, DestBB);
3864 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3865 if (Record.size() < 2)
3866 return Error("Invalid record");
3867 Type *OpTy = getTypeByID(Record[0]);
3868 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3869 if (!OpTy || !Address)
3870 return Error("Invalid record");
3871 unsigned NumDests = Record.size()-2;
3872 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3873 InstructionList.push_back(IBI);
3874 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3875 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3876 IBI->addDestination(DestBB);
3879 return Error("Invalid record");
3886 case bitc::FUNC_CODE_INST_INVOKE: {
3887 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3888 if (Record.size() < 4)
3889 return Error("Invalid record");
3891 AttributeSet PAL = getAttributes(Record[OpNum++]);
3892 unsigned CCInfo = Record[OpNum++];
3893 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3894 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3896 FunctionType *FTy = nullptr;
3897 if (CCInfo >> 13 & 1 &&
3898 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3899 return Error("Explicit invoke type is not a function type");
3902 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3903 return Error("Invalid record");
3905 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3907 return Error("Callee is not a pointer");
3909 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3911 return Error("Callee is not of pointer to function type");
3912 } else if (CalleeTy->getElementType() != FTy)
3913 return Error("Explicit invoke type does not match pointee type of "
3915 if (Record.size() < FTy->getNumParams() + OpNum)
3916 return Error("Insufficient operands to call");
3918 SmallVector<Value*, 16> Ops;
3919 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3920 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3921 FTy->getParamType(i)));
3923 return Error("Invalid record");
3926 if (!FTy->isVarArg()) {
3927 if (Record.size() != OpNum)
3928 return Error("Invalid record");
3930 // Read type/value pairs for varargs params.
3931 while (OpNum != Record.size()) {
3933 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3934 return Error("Invalid record");
3939 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3940 InstructionList.push_back(I);
3942 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
3943 cast<InvokeInst>(I)->setAttributes(PAL);
3946 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3948 Value *Val = nullptr;
3949 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3950 return Error("Invalid record");
3951 I = ResumeInst::Create(Val);
3952 InstructionList.push_back(I);
3955 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3956 I = new UnreachableInst(Context);
3957 InstructionList.push_back(I);
3959 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3960 if (Record.size() < 1 || ((Record.size()-1)&1))
3961 return Error("Invalid record");
3962 Type *Ty = getTypeByID(Record[0]);
3964 return Error("Invalid record");
3966 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3967 InstructionList.push_back(PN);
3969 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3971 // With the new function encoding, it is possible that operands have
3972 // negative IDs (for forward references). Use a signed VBR
3973 // representation to keep the encoding small.
3975 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3977 V = getValue(Record, 1+i, NextValueNo, Ty);
3978 BasicBlock *BB = getBasicBlock(Record[2+i]);
3980 return Error("Invalid record");
3981 PN->addIncoming(V, BB);
3987 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3988 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3990 if (Record.size() < 4)
3991 return Error("Invalid record");
3992 Type *Ty = getTypeByID(Record[Idx++]);
3994 return Error("Invalid record");
3995 Value *PersFn = nullptr;
3996 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3997 return Error("Invalid record");
3999 bool IsCleanup = !!Record[Idx++];
4000 unsigned NumClauses = Record[Idx++];
4001 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
4002 LP->setCleanup(IsCleanup);
4003 for (unsigned J = 0; J != NumClauses; ++J) {
4004 LandingPadInst::ClauseType CT =
4005 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4008 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4010 return Error("Invalid record");
4013 assert((CT != LandingPadInst::Catch ||
4014 !isa<ArrayType>(Val->getType())) &&
4015 "Catch clause has a invalid type!");
4016 assert((CT != LandingPadInst::Filter ||
4017 isa<ArrayType>(Val->getType())) &&
4018 "Filter clause has invalid type!");
4019 LP->addClause(cast<Constant>(Val));
4023 InstructionList.push_back(I);
4027 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4028 if (Record.size() != 4)
4029 return Error("Invalid record");
4030 uint64_t AlignRecord = Record[3];
4031 const uint64_t InAllocaMask = uint64_t(1) << 5;
4032 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4033 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4034 bool InAlloca = AlignRecord & InAllocaMask;
4035 Type *Ty = getTypeByID(Record[0]);
4036 if ((AlignRecord & ExplicitTypeMask) == 0) {
4037 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4039 return Error("Old-style alloca with a non-pointer type");
4040 Ty = PTy->getElementType();
4042 Type *OpTy = getTypeByID(Record[1]);
4043 Value *Size = getFnValueByID(Record[2], OpTy);
4045 if (std::error_code EC =
4046 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4050 return Error("Invalid record");
4051 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4052 AI->setUsedWithInAlloca(InAlloca);
4054 InstructionList.push_back(I);
4057 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4060 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4061 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4062 return Error("Invalid record");
4065 if (OpNum + 3 == Record.size())
4066 Ty = getTypeByID(Record[OpNum++]);
4068 Ty = cast<PointerType>(Op->getType())->getElementType();
4069 else if (Ty != cast<PointerType>(Op->getType())->getElementType())
4070 return Error("Explicit load type does not match pointee type of "
4074 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4076 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4078 InstructionList.push_back(I);
4081 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4082 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4085 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4086 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4087 return Error("Invalid record");
4090 if (OpNum + 5 == Record.size())
4091 Ty = getTypeByID(Record[OpNum++]);
4093 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4094 if (Ordering == NotAtomic || Ordering == Release ||
4095 Ordering == AcquireRelease)
4096 return Error("Invalid record");
4097 if (Ordering != NotAtomic && Record[OpNum] == 0)
4098 return Error("Invalid record");
4099 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4102 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4104 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4107 assert((!Ty || Ty == I->getType()) &&
4108 "Explicit type doesn't match pointee type of the first operand");
4110 InstructionList.push_back(I);
4113 case bitc::FUNC_CODE_INST_STORE:
4114 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4117 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4118 (BitCode == bitc::FUNC_CODE_INST_STORE
4119 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4120 : popValue(Record, OpNum, NextValueNo,
4121 cast<PointerType>(Ptr->getType())->getElementType(),
4123 OpNum + 2 != Record.size())
4124 return Error("Invalid record");
4126 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4128 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4129 InstructionList.push_back(I);
4132 case bitc::FUNC_CODE_INST_STOREATOMIC:
4133 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4134 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4137 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4138 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4139 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4140 : popValue(Record, OpNum, NextValueNo,
4141 cast<PointerType>(Ptr->getType())->getElementType(),
4143 OpNum + 4 != Record.size())
4144 return Error("Invalid record");
4146 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4147 if (Ordering == NotAtomic || Ordering == Acquire ||
4148 Ordering == AcquireRelease)
4149 return Error("Invalid record");
4150 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4151 if (Ordering != NotAtomic && Record[OpNum] == 0)
4152 return Error("Invalid record");
4155 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4157 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4158 InstructionList.push_back(I);
4161 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4162 case bitc::FUNC_CODE_INST_CMPXCHG: {
4163 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4164 // failureordering?, isweak?]
4166 Value *Ptr, *Cmp, *New;
4167 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4168 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4169 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4170 : popValue(Record, OpNum, NextValueNo,
4171 cast<PointerType>(Ptr->getType())->getElementType(),
4173 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4174 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4175 return Error("Invalid record");
4176 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4177 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4178 return Error("Invalid record");
4179 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4181 AtomicOrdering FailureOrdering;
4182 if (Record.size() < 7)
4184 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4186 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4188 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4190 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4192 if (Record.size() < 8) {
4193 // Before weak cmpxchgs existed, the instruction simply returned the
4194 // value loaded from memory, so bitcode files from that era will be
4195 // expecting the first component of a modern cmpxchg.
4196 CurBB->getInstList().push_back(I);
4197 I = ExtractValueInst::Create(I, 0);
4199 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4202 InstructionList.push_back(I);
4205 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4206 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4209 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4210 popValue(Record, OpNum, NextValueNo,
4211 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4212 OpNum+4 != Record.size())
4213 return Error("Invalid record");
4214 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4215 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4216 Operation > AtomicRMWInst::LAST_BINOP)
4217 return Error("Invalid record");
4218 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4219 if (Ordering == NotAtomic || Ordering == Unordered)
4220 return Error("Invalid record");
4221 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4222 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4223 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4224 InstructionList.push_back(I);
4227 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4228 if (2 != Record.size())
4229 return Error("Invalid record");
4230 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4231 if (Ordering == NotAtomic || Ordering == Unordered ||
4232 Ordering == Monotonic)
4233 return Error("Invalid record");
4234 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4235 I = new FenceInst(Context, Ordering, SynchScope);
4236 InstructionList.push_back(I);
4239 case bitc::FUNC_CODE_INST_CALL: {
4240 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4241 if (Record.size() < 3)
4242 return Error("Invalid record");
4245 AttributeSet PAL = getAttributes(Record[OpNum++]);
4246 unsigned CCInfo = Record[OpNum++];
4248 FunctionType *FTy = nullptr;
4249 if (CCInfo >> 15 & 1 &&
4250 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4251 return Error("Explicit call type is not a function type");
4254 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4255 return Error("Invalid record");
4257 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4259 return Error("Callee is not a pointer type");
4261 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4263 return Error("Callee is not of pointer to function type");
4264 } else if (OpTy->getElementType() != FTy)
4265 return Error("Explicit call type does not match pointee type of "
4267 if (Record.size() < FTy->getNumParams() + OpNum)
4268 return Error("Insufficient operands to call");
4270 SmallVector<Value*, 16> Args;
4271 // Read the fixed params.
4272 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4273 if (FTy->getParamType(i)->isLabelTy())
4274 Args.push_back(getBasicBlock(Record[OpNum]));
4276 Args.push_back(getValue(Record, OpNum, NextValueNo,
4277 FTy->getParamType(i)));
4279 return Error("Invalid record");
4282 // Read type/value pairs for varargs params.
4283 if (!FTy->isVarArg()) {
4284 if (OpNum != Record.size())
4285 return Error("Invalid record");
4287 while (OpNum != Record.size()) {
4289 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4290 return Error("Invalid record");
4295 I = CallInst::Create(FTy, Callee, Args);
4296 InstructionList.push_back(I);
4297 cast<CallInst>(I)->setCallingConv(
4298 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4299 CallInst::TailCallKind TCK = CallInst::TCK_None;
4301 TCK = CallInst::TCK_Tail;
4302 if (CCInfo & (1 << 14))
4303 TCK = CallInst::TCK_MustTail;
4304 cast<CallInst>(I)->setTailCallKind(TCK);
4305 cast<CallInst>(I)->setAttributes(PAL);
4308 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4309 if (Record.size() < 3)
4310 return Error("Invalid record");
4311 Type *OpTy = getTypeByID(Record[0]);
4312 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4313 Type *ResTy = getTypeByID(Record[2]);
4314 if (!OpTy || !Op || !ResTy)
4315 return Error("Invalid record");
4316 I = new VAArgInst(Op, ResTy);
4317 InstructionList.push_back(I);
4322 // Add instruction to end of current BB. If there is no current BB, reject
4326 return Error("Invalid instruction with no BB");
4328 CurBB->getInstList().push_back(I);
4330 // If this was a terminator instruction, move to the next block.
4331 if (isa<TerminatorInst>(I)) {
4333 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4336 // Non-void values get registered in the value table for future use.
4337 if (I && !I->getType()->isVoidTy())
4338 ValueList.AssignValue(I, NextValueNo++);
4343 // Check the function list for unresolved values.
4344 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4345 if (!A->getParent()) {
4346 // We found at least one unresolved value. Nuke them all to avoid leaks.
4347 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4348 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4349 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4353 return Error("Never resolved value found in function");
4357 // FIXME: Check for unresolved forward-declared metadata references
4358 // and clean up leaks.
4360 // Trim the value list down to the size it was before we parsed this function.
4361 ValueList.shrinkTo(ModuleValueListSize);
4362 MDValueList.shrinkTo(ModuleMDValueListSize);
4363 std::vector<BasicBlock*>().swap(FunctionBBs);
4364 return std::error_code();
4367 /// Find the function body in the bitcode stream
4368 std::error_code BitcodeReader::FindFunctionInStream(
4370 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4371 while (DeferredFunctionInfoIterator->second == 0) {
4372 if (Stream.AtEndOfStream())
4373 return Error("Could not find function in stream");
4374 // ParseModule will parse the next body in the stream and set its
4375 // position in the DeferredFunctionInfo map.
4376 if (std::error_code EC = ParseModule(true))
4379 return std::error_code();
4382 //===----------------------------------------------------------------------===//
4383 // GVMaterializer implementation
4384 //===----------------------------------------------------------------------===//
4386 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4388 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4389 if (std::error_code EC = materializeMetadata())
4392 Function *F = dyn_cast<Function>(GV);
4393 // If it's not a function or is already material, ignore the request.
4394 if (!F || !F->isMaterializable())
4395 return std::error_code();
4397 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4398 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4399 // If its position is recorded as 0, its body is somewhere in the stream
4400 // but we haven't seen it yet.
4401 if (DFII->second == 0 && LazyStreamer)
4402 if (std::error_code EC = FindFunctionInStream(F, DFII))
4405 // Move the bit stream to the saved position of the deferred function body.
4406 Stream.JumpToBit(DFII->second);
4408 if (std::error_code EC = ParseFunctionBody(F))
4410 F->setIsMaterializable(false);
4415 // Upgrade any old intrinsic calls in the function.
4416 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4417 E = UpgradedIntrinsics.end(); I != E; ++I) {
4418 if (I->first != I->second) {
4419 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4421 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4422 UpgradeIntrinsicCall(CI, I->second);
4427 // Bring in any functions that this function forward-referenced via
4429 return materializeForwardReferencedFunctions();
4432 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4433 const Function *F = dyn_cast<Function>(GV);
4434 if (!F || F->isDeclaration())
4437 // Dematerializing F would leave dangling references that wouldn't be
4438 // reconnected on re-materialization.
4439 if (BlockAddressesTaken.count(F))
4442 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4445 void BitcodeReader::Dematerialize(GlobalValue *GV) {
4446 Function *F = dyn_cast<Function>(GV);
4447 // If this function isn't dematerializable, this is a noop.
4448 if (!F || !isDematerializable(F))
4451 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4453 // Just forget the function body, we can remat it later.
4454 F->dropAllReferences();
4455 F->setIsMaterializable(true);
4458 std::error_code BitcodeReader::MaterializeModule(Module *M) {
4459 assert(M == TheModule &&
4460 "Can only Materialize the Module this BitcodeReader is attached to.");
4462 if (std::error_code EC = materializeMetadata())
4465 // Promise to materialize all forward references.
4466 WillMaterializeAllForwardRefs = true;
4468 // Iterate over the module, deserializing any functions that are still on
4470 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4472 if (std::error_code EC = materialize(F))
4475 // At this point, if there are any function bodies, the current bit is
4476 // pointing to the END_BLOCK record after them. Now make sure the rest
4477 // of the bits in the module have been read.
4481 // Check that all block address forward references got resolved (as we
4483 if (!BasicBlockFwdRefs.empty())
4484 return Error("Never resolved function from blockaddress");
4486 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4487 // delete the old functions to clean up. We can't do this unless the entire
4488 // module is materialized because there could always be another function body
4489 // with calls to the old function.
4490 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4491 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4492 if (I->first != I->second) {
4493 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4495 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4496 UpgradeIntrinsicCall(CI, I->second);
4498 if (!I->first->use_empty())
4499 I->first->replaceAllUsesWith(I->second);
4500 I->first->eraseFromParent();
4503 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4505 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4506 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4508 UpgradeDebugInfo(*M);
4509 return std::error_code();
4512 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4513 return IdentifiedStructTypes;
4516 std::error_code BitcodeReader::InitStream() {
4518 return InitLazyStream();
4519 return InitStreamFromBuffer();
4522 std::error_code BitcodeReader::InitStreamFromBuffer() {
4523 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4524 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4526 if (Buffer->getBufferSize() & 3)
4527 return Error("Invalid bitcode signature");
4529 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4530 // The magic number is 0x0B17C0DE stored in little endian.
4531 if (isBitcodeWrapper(BufPtr, BufEnd))
4532 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4533 return Error("Invalid bitcode wrapper header");
4535 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4536 Stream.init(&*StreamFile);
4538 return std::error_code();
4541 std::error_code BitcodeReader::InitLazyStream() {
4542 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4544 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4545 StreamingMemoryObject &Bytes = *OwnedBytes;
4546 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4547 Stream.init(&*StreamFile);
4549 unsigned char buf[16];
4550 if (Bytes.readBytes(buf, 16, 0) != 16)
4551 return Error("Invalid bitcode signature");
4553 if (!isBitcode(buf, buf + 16))
4554 return Error("Invalid bitcode signature");
4556 if (isBitcodeWrapper(buf, buf + 4)) {
4557 const unsigned char *bitcodeStart = buf;
4558 const unsigned char *bitcodeEnd = buf + 16;
4559 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4560 Bytes.dropLeadingBytes(bitcodeStart - buf);
4561 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4563 return std::error_code();
4567 class BitcodeErrorCategoryType : public std::error_category {
4568 const char *name() const LLVM_NOEXCEPT override {
4569 return "llvm.bitcode";
4571 std::string message(int IE) const override {
4572 BitcodeError E = static_cast<BitcodeError>(IE);
4574 case BitcodeError::InvalidBitcodeSignature:
4575 return "Invalid bitcode signature";
4576 case BitcodeError::CorruptedBitcode:
4577 return "Corrupted bitcode";
4579 llvm_unreachable("Unknown error type!");
4584 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4586 const std::error_category &llvm::BitcodeErrorCategory() {
4587 return *ErrorCategory;
4590 //===----------------------------------------------------------------------===//
4591 // External interface
4592 //===----------------------------------------------------------------------===//
4594 /// \brief Get a lazy one-at-time loading module from bitcode.
4596 /// This isn't always used in a lazy context. In particular, it's also used by
4597 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4598 /// in forward-referenced functions from block address references.
4600 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4601 /// materialize everything -- in particular, if this isn't truly lazy.
4602 static ErrorOr<Module *>
4603 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4604 LLVMContext &Context, bool WillMaterializeAll,
4605 DiagnosticHandlerFunction DiagnosticHandler,
4606 bool ShouldLazyLoadMetadata = false) {
4607 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4609 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4610 M->setMaterializer(R);
4612 auto cleanupOnError = [&](std::error_code EC) {
4613 R->releaseBuffer(); // Never take ownership on error.
4614 delete M; // Also deletes R.
4618 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4619 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4620 return cleanupOnError(EC);
4622 if (!WillMaterializeAll)
4623 // Resolve forward references from blockaddresses.
4624 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4625 return cleanupOnError(EC);
4627 Buffer.release(); // The BitcodeReader owns it now.
4632 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4633 LLVMContext &Context,
4634 DiagnosticHandlerFunction DiagnosticHandler,
4635 bool ShouldLazyLoadMetadata) {
4636 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4637 DiagnosticHandler, ShouldLazyLoadMetadata);
4640 ErrorOr<std::unique_ptr<Module>>
4641 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4642 LLVMContext &Context,
4643 DiagnosticHandlerFunction DiagnosticHandler) {
4644 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4645 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4646 M->setMaterializer(R);
4647 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4649 return std::move(M);
4653 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4654 DiagnosticHandlerFunction DiagnosticHandler) {
4655 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4656 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4657 std::move(Buf), Context, true, DiagnosticHandler);
4660 Module *M = ModuleOrErr.get();
4661 // Read in the entire module, and destroy the BitcodeReader.
4662 if (std::error_code EC = M->materializeAllPermanently()) {
4667 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4668 // written. We must defer until the Module has been fully materialized.
4674 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4675 DiagnosticHandlerFunction DiagnosticHandler) {
4676 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4677 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4679 ErrorOr<std::string> Triple = R->parseTriple();
4680 if (Triple.getError())
4682 return Triple.get();