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 ResultTy = getTypeByID(Record[1]);
1479 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1480 return Error("Invalid type");
1481 ResultTy = ArrayType::get(ResultTy, Record[0]);
1483 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1484 if (Record.size() < 2)
1485 return Error("Invalid record");
1486 ResultTy = getTypeByID(Record[1]);
1487 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1488 return Error("Invalid type");
1489 ResultTy = VectorType::get(ResultTy, Record[0]);
1493 if (NumRecords >= TypeList.size())
1494 return Error("Invalid TYPE table");
1495 if (TypeList[NumRecords])
1497 "Invalid TYPE table: Only named structs can be forward referenced");
1498 assert(ResultTy && "Didn't read a type?");
1499 TypeList[NumRecords++] = ResultTy;
1503 std::error_code BitcodeReader::ParseValueSymbolTable() {
1504 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1505 return Error("Invalid record");
1507 SmallVector<uint64_t, 64> Record;
1509 Triple TT(TheModule->getTargetTriple());
1511 // Read all the records for this value table.
1512 SmallString<128> ValueName;
1514 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1516 switch (Entry.Kind) {
1517 case BitstreamEntry::SubBlock: // Handled for us already.
1518 case BitstreamEntry::Error:
1519 return Error("Malformed block");
1520 case BitstreamEntry::EndBlock:
1521 return std::error_code();
1522 case BitstreamEntry::Record:
1523 // The interesting case.
1529 switch (Stream.readRecord(Entry.ID, Record)) {
1530 default: // Default behavior: unknown type.
1532 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1533 if (ConvertToString(Record, 1, ValueName))
1534 return Error("Invalid record");
1535 unsigned ValueID = Record[0];
1536 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1537 return Error("Invalid record");
1538 Value *V = ValueList[ValueID];
1540 V->setName(StringRef(ValueName.data(), ValueName.size()));
1541 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1542 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1543 if (TT.isOSBinFormatMachO())
1544 GO->setComdat(nullptr);
1546 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1552 case bitc::VST_CODE_BBENTRY: {
1553 if (ConvertToString(Record, 1, ValueName))
1554 return Error("Invalid record");
1555 BasicBlock *BB = getBasicBlock(Record[0]);
1557 return Error("Invalid record");
1559 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1567 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1569 std::error_code BitcodeReader::ParseMetadata() {
1570 IsMetadataMaterialized = true;
1571 unsigned NextMDValueNo = MDValueList.size();
1573 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1574 return Error("Invalid record");
1576 SmallVector<uint64_t, 64> Record;
1579 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1580 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1582 return getMD(ID - 1);
1585 auto getMDString = [&](unsigned ID) -> MDString *{
1586 // This requires that the ID is not really a forward reference. In
1587 // particular, the MDString must already have been resolved.
1588 return cast_or_null<MDString>(getMDOrNull(ID));
1591 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1592 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1594 // Read all the records.
1596 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1598 switch (Entry.Kind) {
1599 case BitstreamEntry::SubBlock: // Handled for us already.
1600 case BitstreamEntry::Error:
1601 return Error("Malformed block");
1602 case BitstreamEntry::EndBlock:
1603 MDValueList.tryToResolveCycles();
1604 return std::error_code();
1605 case BitstreamEntry::Record:
1606 // The interesting case.
1612 unsigned Code = Stream.readRecord(Entry.ID, Record);
1613 bool IsDistinct = false;
1615 default: // Default behavior: ignore.
1617 case bitc::METADATA_NAME: {
1618 // Read name of the named metadata.
1619 SmallString<8> Name(Record.begin(), Record.end());
1621 Code = Stream.ReadCode();
1623 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1624 unsigned NextBitCode = Stream.readRecord(Code, Record);
1625 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1627 // Read named metadata elements.
1628 unsigned Size = Record.size();
1629 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1630 for (unsigned i = 0; i != Size; ++i) {
1631 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1633 return Error("Invalid record");
1634 NMD->addOperand(MD);
1638 case bitc::METADATA_OLD_FN_NODE: {
1639 // FIXME: Remove in 4.0.
1640 // This is a LocalAsMetadata record, the only type of function-local
1642 if (Record.size() % 2 == 1)
1643 return Error("Invalid record");
1645 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1646 // to be legal, but there's no upgrade path.
1647 auto dropRecord = [&] {
1648 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1650 if (Record.size() != 2) {
1655 Type *Ty = getTypeByID(Record[0]);
1656 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1661 MDValueList.AssignValue(
1662 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1666 case bitc::METADATA_OLD_NODE: {
1667 // FIXME: Remove in 4.0.
1668 if (Record.size() % 2 == 1)
1669 return Error("Invalid record");
1671 unsigned Size = Record.size();
1672 SmallVector<Metadata *, 8> Elts;
1673 for (unsigned i = 0; i != Size; i += 2) {
1674 Type *Ty = getTypeByID(Record[i]);
1676 return Error("Invalid record");
1677 if (Ty->isMetadataTy())
1678 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1679 else if (!Ty->isVoidTy()) {
1681 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1682 assert(isa<ConstantAsMetadata>(MD) &&
1683 "Expected non-function-local metadata");
1686 Elts.push_back(nullptr);
1688 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1691 case bitc::METADATA_VALUE: {
1692 if (Record.size() != 2)
1693 return Error("Invalid record");
1695 Type *Ty = getTypeByID(Record[0]);
1696 if (Ty->isMetadataTy() || Ty->isVoidTy())
1697 return Error("Invalid record");
1699 MDValueList.AssignValue(
1700 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1704 case bitc::METADATA_DISTINCT_NODE:
1707 case bitc::METADATA_NODE: {
1708 SmallVector<Metadata *, 8> Elts;
1709 Elts.reserve(Record.size());
1710 for (unsigned ID : Record)
1711 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1712 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1713 : MDNode::get(Context, Elts),
1717 case bitc::METADATA_LOCATION: {
1718 if (Record.size() != 5)
1719 return Error("Invalid record");
1721 unsigned Line = Record[1];
1722 unsigned Column = Record[2];
1723 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1724 Metadata *InlinedAt =
1725 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1726 MDValueList.AssignValue(
1727 GET_OR_DISTINCT(DILocation, Record[0],
1728 (Context, Line, Column, Scope, InlinedAt)),
1732 case bitc::METADATA_GENERIC_DEBUG: {
1733 if (Record.size() < 4)
1734 return Error("Invalid record");
1736 unsigned Tag = Record[1];
1737 unsigned Version = Record[2];
1739 if (Tag >= 1u << 16 || Version != 0)
1740 return Error("Invalid record");
1742 auto *Header = getMDString(Record[3]);
1743 SmallVector<Metadata *, 8> DwarfOps;
1744 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1745 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1747 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1748 (Context, Tag, Header, DwarfOps)),
1752 case bitc::METADATA_SUBRANGE: {
1753 if (Record.size() != 3)
1754 return Error("Invalid record");
1756 MDValueList.AssignValue(
1757 GET_OR_DISTINCT(DISubrange, Record[0],
1758 (Context, Record[1], unrotateSign(Record[2]))),
1762 case bitc::METADATA_ENUMERATOR: {
1763 if (Record.size() != 3)
1764 return Error("Invalid record");
1766 MDValueList.AssignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1767 (Context, unrotateSign(Record[1]),
1768 getMDString(Record[2]))),
1772 case bitc::METADATA_BASIC_TYPE: {
1773 if (Record.size() != 6)
1774 return Error("Invalid record");
1776 MDValueList.AssignValue(
1777 GET_OR_DISTINCT(DIBasicType, Record[0],
1778 (Context, Record[1], getMDString(Record[2]),
1779 Record[3], Record[4], Record[5])),
1783 case bitc::METADATA_DERIVED_TYPE: {
1784 if (Record.size() != 12)
1785 return Error("Invalid record");
1787 MDValueList.AssignValue(
1788 GET_OR_DISTINCT(DIDerivedType, Record[0],
1789 (Context, Record[1], getMDString(Record[2]),
1790 getMDOrNull(Record[3]), Record[4],
1791 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1792 Record[7], Record[8], Record[9], Record[10],
1793 getMDOrNull(Record[11]))),
1797 case bitc::METADATA_COMPOSITE_TYPE: {
1798 if (Record.size() != 16)
1799 return Error("Invalid record");
1801 MDValueList.AssignValue(
1802 GET_OR_DISTINCT(DICompositeType, Record[0],
1803 (Context, Record[1], getMDString(Record[2]),
1804 getMDOrNull(Record[3]), Record[4],
1805 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1806 Record[7], Record[8], Record[9], Record[10],
1807 getMDOrNull(Record[11]), Record[12],
1808 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1809 getMDString(Record[15]))),
1813 case bitc::METADATA_SUBROUTINE_TYPE: {
1814 if (Record.size() != 3)
1815 return Error("Invalid record");
1817 MDValueList.AssignValue(
1818 GET_OR_DISTINCT(DISubroutineType, Record[0],
1819 (Context, Record[1], getMDOrNull(Record[2]))),
1823 case bitc::METADATA_FILE: {
1824 if (Record.size() != 3)
1825 return Error("Invalid record");
1827 MDValueList.AssignValue(
1828 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1829 getMDString(Record[2]))),
1833 case bitc::METADATA_COMPILE_UNIT: {
1834 if (Record.size() != 14)
1835 return Error("Invalid record");
1837 MDValueList.AssignValue(
1838 GET_OR_DISTINCT(DICompileUnit, Record[0],
1839 (Context, Record[1], getMDOrNull(Record[2]),
1840 getMDString(Record[3]), Record[4],
1841 getMDString(Record[5]), Record[6],
1842 getMDString(Record[7]), Record[8],
1843 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1844 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1845 getMDOrNull(Record[13]))),
1849 case bitc::METADATA_SUBPROGRAM: {
1850 if (Record.size() != 19)
1851 return Error("Invalid record");
1853 MDValueList.AssignValue(
1855 DISubprogram, Record[0],
1856 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1857 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1858 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1859 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1860 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1861 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1865 case bitc::METADATA_LEXICAL_BLOCK: {
1866 if (Record.size() != 5)
1867 return Error("Invalid record");
1869 MDValueList.AssignValue(
1870 GET_OR_DISTINCT(DILexicalBlock, Record[0],
1871 (Context, getMDOrNull(Record[1]),
1872 getMDOrNull(Record[2]), Record[3], Record[4])),
1876 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1877 if (Record.size() != 4)
1878 return Error("Invalid record");
1880 MDValueList.AssignValue(
1881 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1882 (Context, getMDOrNull(Record[1]),
1883 getMDOrNull(Record[2]), Record[3])),
1887 case bitc::METADATA_NAMESPACE: {
1888 if (Record.size() != 5)
1889 return Error("Invalid record");
1891 MDValueList.AssignValue(
1892 GET_OR_DISTINCT(DINamespace, Record[0],
1893 (Context, getMDOrNull(Record[1]),
1894 getMDOrNull(Record[2]), getMDString(Record[3]),
1899 case bitc::METADATA_TEMPLATE_TYPE: {
1900 if (Record.size() != 3)
1901 return Error("Invalid record");
1903 MDValueList.AssignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1905 (Context, getMDString(Record[1]),
1906 getMDOrNull(Record[2]))),
1910 case bitc::METADATA_TEMPLATE_VALUE: {
1911 if (Record.size() != 5)
1912 return Error("Invalid record");
1914 MDValueList.AssignValue(
1915 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1916 (Context, Record[1], getMDString(Record[2]),
1917 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1921 case bitc::METADATA_GLOBAL_VAR: {
1922 if (Record.size() != 11)
1923 return Error("Invalid record");
1925 MDValueList.AssignValue(
1926 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1927 (Context, getMDOrNull(Record[1]),
1928 getMDString(Record[2]), getMDString(Record[3]),
1929 getMDOrNull(Record[4]), Record[5],
1930 getMDOrNull(Record[6]), Record[7], Record[8],
1931 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1935 case bitc::METADATA_LOCAL_VAR: {
1936 // 10th field is for the obseleted 'inlinedAt:' field.
1937 if (Record.size() != 9 && Record.size() != 10)
1938 return Error("Invalid record");
1940 MDValueList.AssignValue(
1941 GET_OR_DISTINCT(DILocalVariable, Record[0],
1942 (Context, Record[1], getMDOrNull(Record[2]),
1943 getMDString(Record[3]), getMDOrNull(Record[4]),
1944 Record[5], getMDOrNull(Record[6]), Record[7],
1949 case bitc::METADATA_EXPRESSION: {
1950 if (Record.size() < 1)
1951 return Error("Invalid record");
1953 MDValueList.AssignValue(
1954 GET_OR_DISTINCT(DIExpression, Record[0],
1955 (Context, makeArrayRef(Record).slice(1))),
1959 case bitc::METADATA_OBJC_PROPERTY: {
1960 if (Record.size() != 8)
1961 return Error("Invalid record");
1963 MDValueList.AssignValue(
1964 GET_OR_DISTINCT(DIObjCProperty, Record[0],
1965 (Context, getMDString(Record[1]),
1966 getMDOrNull(Record[2]), Record[3],
1967 getMDString(Record[4]), getMDString(Record[5]),
1968 Record[6], getMDOrNull(Record[7]))),
1972 case bitc::METADATA_IMPORTED_ENTITY: {
1973 if (Record.size() != 6)
1974 return Error("Invalid record");
1976 MDValueList.AssignValue(
1977 GET_OR_DISTINCT(DIImportedEntity, Record[0],
1978 (Context, Record[1], getMDOrNull(Record[2]),
1979 getMDOrNull(Record[3]), Record[4],
1980 getMDString(Record[5]))),
1984 case bitc::METADATA_STRING: {
1985 std::string String(Record.begin(), Record.end());
1986 llvm::UpgradeMDStringConstant(String);
1987 Metadata *MD = MDString::get(Context, String);
1988 MDValueList.AssignValue(MD, NextMDValueNo++);
1991 case bitc::METADATA_KIND: {
1992 if (Record.size() < 2)
1993 return Error("Invalid record");
1995 unsigned Kind = Record[0];
1996 SmallString<8> Name(Record.begin()+1, Record.end());
1998 unsigned NewKind = TheModule->getMDKindID(Name.str());
1999 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2000 return Error("Conflicting METADATA_KIND records");
2005 #undef GET_OR_DISTINCT
2008 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
2009 /// the LSB for dense VBR encoding.
2010 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2015 // There is no such thing as -0 with integers. "-0" really means MININT.
2019 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
2020 /// values and aliases that we can.
2021 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
2022 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2023 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2024 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2025 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2027 GlobalInitWorklist.swap(GlobalInits);
2028 AliasInitWorklist.swap(AliasInits);
2029 FunctionPrefixWorklist.swap(FunctionPrefixes);
2030 FunctionPrologueWorklist.swap(FunctionPrologues);
2032 while (!GlobalInitWorklist.empty()) {
2033 unsigned ValID = GlobalInitWorklist.back().second;
2034 if (ValID >= ValueList.size()) {
2035 // Not ready to resolve this yet, it requires something later in the file.
2036 GlobalInits.push_back(GlobalInitWorklist.back());
2038 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2039 GlobalInitWorklist.back().first->setInitializer(C);
2041 return Error("Expected a constant");
2043 GlobalInitWorklist.pop_back();
2046 while (!AliasInitWorklist.empty()) {
2047 unsigned ValID = AliasInitWorklist.back().second;
2048 if (ValID >= ValueList.size()) {
2049 AliasInits.push_back(AliasInitWorklist.back());
2051 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2052 AliasInitWorklist.back().first->setAliasee(C);
2054 return Error("Expected a constant");
2056 AliasInitWorklist.pop_back();
2059 while (!FunctionPrefixWorklist.empty()) {
2060 unsigned ValID = FunctionPrefixWorklist.back().second;
2061 if (ValID >= ValueList.size()) {
2062 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2064 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2065 FunctionPrefixWorklist.back().first->setPrefixData(C);
2067 return Error("Expected a constant");
2069 FunctionPrefixWorklist.pop_back();
2072 while (!FunctionPrologueWorklist.empty()) {
2073 unsigned ValID = FunctionPrologueWorklist.back().second;
2074 if (ValID >= ValueList.size()) {
2075 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2077 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2078 FunctionPrologueWorklist.back().first->setPrologueData(C);
2080 return Error("Expected a constant");
2082 FunctionPrologueWorklist.pop_back();
2085 return std::error_code();
2088 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2089 SmallVector<uint64_t, 8> Words(Vals.size());
2090 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2091 BitcodeReader::decodeSignRotatedValue);
2093 return APInt(TypeBits, Words);
2096 std::error_code BitcodeReader::ParseConstants() {
2097 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2098 return Error("Invalid record");
2100 SmallVector<uint64_t, 64> Record;
2102 // Read all the records for this value table.
2103 Type *CurTy = Type::getInt32Ty(Context);
2104 unsigned NextCstNo = ValueList.size();
2106 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2108 switch (Entry.Kind) {
2109 case BitstreamEntry::SubBlock: // Handled for us already.
2110 case BitstreamEntry::Error:
2111 return Error("Malformed block");
2112 case BitstreamEntry::EndBlock:
2113 if (NextCstNo != ValueList.size())
2114 return Error("Invalid ronstant reference");
2116 // Once all the constants have been read, go through and resolve forward
2118 ValueList.ResolveConstantForwardRefs();
2119 return std::error_code();
2120 case BitstreamEntry::Record:
2121 // The interesting case.
2128 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2130 default: // Default behavior: unknown constant
2131 case bitc::CST_CODE_UNDEF: // UNDEF
2132 V = UndefValue::get(CurTy);
2134 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2136 return Error("Invalid record");
2137 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2138 return Error("Invalid record");
2139 CurTy = TypeList[Record[0]];
2140 continue; // Skip the ValueList manipulation.
2141 case bitc::CST_CODE_NULL: // NULL
2142 V = Constant::getNullValue(CurTy);
2144 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2145 if (!CurTy->isIntegerTy() || Record.empty())
2146 return Error("Invalid record");
2147 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2149 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2150 if (!CurTy->isIntegerTy() || Record.empty())
2151 return Error("Invalid record");
2153 APInt VInt = ReadWideAPInt(Record,
2154 cast<IntegerType>(CurTy)->getBitWidth());
2155 V = ConstantInt::get(Context, VInt);
2159 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2161 return Error("Invalid record");
2162 if (CurTy->isHalfTy())
2163 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2164 APInt(16, (uint16_t)Record[0])));
2165 else if (CurTy->isFloatTy())
2166 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2167 APInt(32, (uint32_t)Record[0])));
2168 else if (CurTy->isDoubleTy())
2169 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2170 APInt(64, Record[0])));
2171 else if (CurTy->isX86_FP80Ty()) {
2172 // Bits are not stored the same way as a normal i80 APInt, compensate.
2173 uint64_t Rearrange[2];
2174 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2175 Rearrange[1] = Record[0] >> 48;
2176 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2177 APInt(80, Rearrange)));
2178 } else if (CurTy->isFP128Ty())
2179 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2180 APInt(128, Record)));
2181 else if (CurTy->isPPC_FP128Ty())
2182 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2183 APInt(128, Record)));
2185 V = UndefValue::get(CurTy);
2189 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2191 return Error("Invalid record");
2193 unsigned Size = Record.size();
2194 SmallVector<Constant*, 16> Elts;
2196 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2197 for (unsigned i = 0; i != Size; ++i)
2198 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2199 STy->getElementType(i)));
2200 V = ConstantStruct::get(STy, Elts);
2201 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2202 Type *EltTy = ATy->getElementType();
2203 for (unsigned i = 0; i != Size; ++i)
2204 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2205 V = ConstantArray::get(ATy, Elts);
2206 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2207 Type *EltTy = VTy->getElementType();
2208 for (unsigned i = 0; i != Size; ++i)
2209 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2210 V = ConstantVector::get(Elts);
2212 V = UndefValue::get(CurTy);
2216 case bitc::CST_CODE_STRING: // STRING: [values]
2217 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2219 return Error("Invalid record");
2221 SmallString<16> Elts(Record.begin(), Record.end());
2222 V = ConstantDataArray::getString(Context, Elts,
2223 BitCode == bitc::CST_CODE_CSTRING);
2226 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2228 return Error("Invalid record");
2230 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2231 unsigned Size = Record.size();
2233 if (EltTy->isIntegerTy(8)) {
2234 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2235 if (isa<VectorType>(CurTy))
2236 V = ConstantDataVector::get(Context, Elts);
2238 V = ConstantDataArray::get(Context, Elts);
2239 } else if (EltTy->isIntegerTy(16)) {
2240 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2241 if (isa<VectorType>(CurTy))
2242 V = ConstantDataVector::get(Context, Elts);
2244 V = ConstantDataArray::get(Context, Elts);
2245 } else if (EltTy->isIntegerTy(32)) {
2246 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2247 if (isa<VectorType>(CurTy))
2248 V = ConstantDataVector::get(Context, Elts);
2250 V = ConstantDataArray::get(Context, Elts);
2251 } else if (EltTy->isIntegerTy(64)) {
2252 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2253 if (isa<VectorType>(CurTy))
2254 V = ConstantDataVector::get(Context, Elts);
2256 V = ConstantDataArray::get(Context, Elts);
2257 } else if (EltTy->isFloatTy()) {
2258 SmallVector<float, 16> Elts(Size);
2259 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2260 if (isa<VectorType>(CurTy))
2261 V = ConstantDataVector::get(Context, Elts);
2263 V = ConstantDataArray::get(Context, Elts);
2264 } else if (EltTy->isDoubleTy()) {
2265 SmallVector<double, 16> Elts(Size);
2266 std::transform(Record.begin(), Record.end(), Elts.begin(),
2268 if (isa<VectorType>(CurTy))
2269 V = ConstantDataVector::get(Context, Elts);
2271 V = ConstantDataArray::get(Context, Elts);
2273 return Error("Invalid type for value");
2278 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2279 if (Record.size() < 3)
2280 return Error("Invalid record");
2281 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2283 V = UndefValue::get(CurTy); // Unknown binop.
2285 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2286 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2288 if (Record.size() >= 4) {
2289 if (Opc == Instruction::Add ||
2290 Opc == Instruction::Sub ||
2291 Opc == Instruction::Mul ||
2292 Opc == Instruction::Shl) {
2293 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2294 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2295 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2296 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2297 } else if (Opc == Instruction::SDiv ||
2298 Opc == Instruction::UDiv ||
2299 Opc == Instruction::LShr ||
2300 Opc == Instruction::AShr) {
2301 if (Record[3] & (1 << bitc::PEO_EXACT))
2302 Flags |= SDivOperator::IsExact;
2305 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2309 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2310 if (Record.size() < 3)
2311 return Error("Invalid record");
2312 int Opc = GetDecodedCastOpcode(Record[0]);
2314 V = UndefValue::get(CurTy); // Unknown cast.
2316 Type *OpTy = getTypeByID(Record[1]);
2318 return Error("Invalid record");
2319 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2320 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2321 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2325 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2326 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2328 Type *PointeeType = nullptr;
2329 if (Record.size() % 2)
2330 PointeeType = getTypeByID(Record[OpNum++]);
2331 SmallVector<Constant*, 16> Elts;
2332 while (OpNum != Record.size()) {
2333 Type *ElTy = getTypeByID(Record[OpNum++]);
2335 return Error("Invalid record");
2336 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2341 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2343 return Error("Explicit gep operator type does not match pointee type "
2344 "of pointer operand");
2346 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2347 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2349 bitc::CST_CODE_CE_INBOUNDS_GEP);
2352 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2353 if (Record.size() < 3)
2354 return Error("Invalid record");
2356 Type *SelectorTy = Type::getInt1Ty(Context);
2358 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2359 // vector. Otherwise, it must be a single bit.
2360 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2361 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2362 VTy->getNumElements());
2364 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2366 ValueList.getConstantFwdRef(Record[1],CurTy),
2367 ValueList.getConstantFwdRef(Record[2],CurTy));
2370 case bitc::CST_CODE_CE_EXTRACTELT
2371 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2372 if (Record.size() < 3)
2373 return Error("Invalid record");
2375 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2377 return Error("Invalid record");
2378 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2379 Constant *Op1 = nullptr;
2380 if (Record.size() == 4) {
2381 Type *IdxTy = getTypeByID(Record[2]);
2383 return Error("Invalid record");
2384 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2385 } else // TODO: Remove with llvm 4.0
2386 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2388 return Error("Invalid record");
2389 V = ConstantExpr::getExtractElement(Op0, Op1);
2392 case bitc::CST_CODE_CE_INSERTELT
2393 : { // CE_INSERTELT: [opval, opval, opty, opval]
2394 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2395 if (Record.size() < 3 || !OpTy)
2396 return Error("Invalid record");
2397 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2398 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2399 OpTy->getElementType());
2400 Constant *Op2 = nullptr;
2401 if (Record.size() == 4) {
2402 Type *IdxTy = getTypeByID(Record[2]);
2404 return Error("Invalid record");
2405 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2406 } else // TODO: Remove with llvm 4.0
2407 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2409 return Error("Invalid record");
2410 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2413 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2414 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2415 if (Record.size() < 3 || !OpTy)
2416 return Error("Invalid record");
2417 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2418 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2419 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2420 OpTy->getNumElements());
2421 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2422 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2425 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2426 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2428 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2429 if (Record.size() < 4 || !RTy || !OpTy)
2430 return Error("Invalid record");
2431 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2432 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2433 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2434 RTy->getNumElements());
2435 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2436 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2439 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2440 if (Record.size() < 4)
2441 return Error("Invalid record");
2442 Type *OpTy = getTypeByID(Record[0]);
2444 return Error("Invalid record");
2445 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2446 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2448 if (OpTy->isFPOrFPVectorTy())
2449 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2451 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2454 // This maintains backward compatibility, pre-asm dialect keywords.
2455 // FIXME: Remove with the 4.0 release.
2456 case bitc::CST_CODE_INLINEASM_OLD: {
2457 if (Record.size() < 2)
2458 return Error("Invalid record");
2459 std::string AsmStr, ConstrStr;
2460 bool HasSideEffects = Record[0] & 1;
2461 bool IsAlignStack = Record[0] >> 1;
2462 unsigned AsmStrSize = Record[1];
2463 if (2+AsmStrSize >= Record.size())
2464 return Error("Invalid record");
2465 unsigned ConstStrSize = Record[2+AsmStrSize];
2466 if (3+AsmStrSize+ConstStrSize > Record.size())
2467 return Error("Invalid record");
2469 for (unsigned i = 0; i != AsmStrSize; ++i)
2470 AsmStr += (char)Record[2+i];
2471 for (unsigned i = 0; i != ConstStrSize; ++i)
2472 ConstrStr += (char)Record[3+AsmStrSize+i];
2473 PointerType *PTy = cast<PointerType>(CurTy);
2474 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2475 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2478 // This version adds support for the asm dialect keywords (e.g.,
2480 case bitc::CST_CODE_INLINEASM: {
2481 if (Record.size() < 2)
2482 return Error("Invalid record");
2483 std::string AsmStr, ConstrStr;
2484 bool HasSideEffects = Record[0] & 1;
2485 bool IsAlignStack = (Record[0] >> 1) & 1;
2486 unsigned AsmDialect = Record[0] >> 2;
2487 unsigned AsmStrSize = Record[1];
2488 if (2+AsmStrSize >= Record.size())
2489 return Error("Invalid record");
2490 unsigned ConstStrSize = Record[2+AsmStrSize];
2491 if (3+AsmStrSize+ConstStrSize > Record.size())
2492 return Error("Invalid record");
2494 for (unsigned i = 0; i != AsmStrSize; ++i)
2495 AsmStr += (char)Record[2+i];
2496 for (unsigned i = 0; i != ConstStrSize; ++i)
2497 ConstrStr += (char)Record[3+AsmStrSize+i];
2498 PointerType *PTy = cast<PointerType>(CurTy);
2499 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2500 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2501 InlineAsm::AsmDialect(AsmDialect));
2504 case bitc::CST_CODE_BLOCKADDRESS:{
2505 if (Record.size() < 3)
2506 return Error("Invalid record");
2507 Type *FnTy = getTypeByID(Record[0]);
2509 return Error("Invalid record");
2511 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2513 return Error("Invalid record");
2515 // Don't let Fn get dematerialized.
2516 BlockAddressesTaken.insert(Fn);
2518 // If the function is already parsed we can insert the block address right
2521 unsigned BBID = Record[2];
2523 // Invalid reference to entry block.
2524 return Error("Invalid ID");
2526 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2527 for (size_t I = 0, E = BBID; I != E; ++I) {
2529 return Error("Invalid ID");
2534 // Otherwise insert a placeholder and remember it so it can be inserted
2535 // when the function is parsed.
2536 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2538 BasicBlockFwdRefQueue.push_back(Fn);
2539 if (FwdBBs.size() < BBID + 1)
2540 FwdBBs.resize(BBID + 1);
2542 FwdBBs[BBID] = BasicBlock::Create(Context);
2545 V = BlockAddress::get(Fn, BB);
2550 ValueList.AssignValue(V, NextCstNo);
2555 std::error_code BitcodeReader::ParseUseLists() {
2556 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2557 return Error("Invalid record");
2559 // Read all the records.
2560 SmallVector<uint64_t, 64> Record;
2562 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2564 switch (Entry.Kind) {
2565 case BitstreamEntry::SubBlock: // Handled for us already.
2566 case BitstreamEntry::Error:
2567 return Error("Malformed block");
2568 case BitstreamEntry::EndBlock:
2569 return std::error_code();
2570 case BitstreamEntry::Record:
2571 // The interesting case.
2575 // Read a use list record.
2578 switch (Stream.readRecord(Entry.ID, Record)) {
2579 default: // Default behavior: unknown type.
2581 case bitc::USELIST_CODE_BB:
2584 case bitc::USELIST_CODE_DEFAULT: {
2585 unsigned RecordLength = Record.size();
2586 if (RecordLength < 3)
2587 // Records should have at least an ID and two indexes.
2588 return Error("Invalid record");
2589 unsigned ID = Record.back();
2594 assert(ID < FunctionBBs.size() && "Basic block not found");
2595 V = FunctionBBs[ID];
2598 unsigned NumUses = 0;
2599 SmallDenseMap<const Use *, unsigned, 16> Order;
2600 for (const Use &U : V->uses()) {
2601 if (++NumUses > Record.size())
2603 Order[&U] = Record[NumUses - 1];
2605 if (Order.size() != Record.size() || NumUses > Record.size())
2606 // Mismatches can happen if the functions are being materialized lazily
2607 // (out-of-order), or a value has been upgraded.
2610 V->sortUseList([&](const Use &L, const Use &R) {
2611 return Order.lookup(&L) < Order.lookup(&R);
2619 /// When we see the block for metadata, remember where it is and then skip it.
2620 /// This lets us lazily deserialize the metadata.
2621 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2622 // Save the current stream state.
2623 uint64_t CurBit = Stream.GetCurrentBitNo();
2624 DeferredMetadataInfo.push_back(CurBit);
2626 // Skip over the block for now.
2627 if (Stream.SkipBlock())
2628 return Error("Invalid record");
2629 return std::error_code();
2632 std::error_code BitcodeReader::materializeMetadata() {
2633 for (uint64_t BitPos : DeferredMetadataInfo) {
2634 // Move the bit stream to the saved position.
2635 Stream.JumpToBit(BitPos);
2636 if (std::error_code EC = ParseMetadata())
2639 DeferredMetadataInfo.clear();
2640 return std::error_code();
2643 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2645 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2646 /// remember where it is and then skip it. This lets us lazily deserialize the
2648 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2649 // Get the function we are talking about.
2650 if (FunctionsWithBodies.empty())
2651 return Error("Insufficient function protos");
2653 Function *Fn = FunctionsWithBodies.back();
2654 FunctionsWithBodies.pop_back();
2656 // Save the current stream state.
2657 uint64_t CurBit = Stream.GetCurrentBitNo();
2658 DeferredFunctionInfo[Fn] = CurBit;
2660 // Skip over the function block for now.
2661 if (Stream.SkipBlock())
2662 return Error("Invalid record");
2663 return std::error_code();
2666 std::error_code BitcodeReader::GlobalCleanup() {
2667 // Patch the initializers for globals and aliases up.
2668 ResolveGlobalAndAliasInits();
2669 if (!GlobalInits.empty() || !AliasInits.empty())
2670 return Error("Malformed global initializer set");
2672 // Look for intrinsic functions which need to be upgraded at some point
2673 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2676 if (UpgradeIntrinsicFunction(FI, NewFn))
2677 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2680 // Look for global variables which need to be renamed.
2681 for (Module::global_iterator
2682 GI = TheModule->global_begin(), GE = TheModule->global_end();
2684 GlobalVariable *GV = GI++;
2685 UpgradeGlobalVariable(GV);
2688 // Force deallocation of memory for these vectors to favor the client that
2689 // want lazy deserialization.
2690 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2691 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2692 return std::error_code();
2695 std::error_code BitcodeReader::ParseModule(bool Resume,
2696 bool ShouldLazyLoadMetadata) {
2698 Stream.JumpToBit(NextUnreadBit);
2699 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2700 return Error("Invalid record");
2702 SmallVector<uint64_t, 64> Record;
2703 std::vector<std::string> SectionTable;
2704 std::vector<std::string> GCTable;
2706 // Read all the records for this module.
2708 BitstreamEntry Entry = Stream.advance();
2710 switch (Entry.Kind) {
2711 case BitstreamEntry::Error:
2712 return Error("Malformed block");
2713 case BitstreamEntry::EndBlock:
2714 return GlobalCleanup();
2716 case BitstreamEntry::SubBlock:
2718 default: // Skip unknown content.
2719 if (Stream.SkipBlock())
2720 return Error("Invalid record");
2722 case bitc::BLOCKINFO_BLOCK_ID:
2723 if (Stream.ReadBlockInfoBlock())
2724 return Error("Malformed block");
2726 case bitc::PARAMATTR_BLOCK_ID:
2727 if (std::error_code EC = ParseAttributeBlock())
2730 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2731 if (std::error_code EC = ParseAttributeGroupBlock())
2734 case bitc::TYPE_BLOCK_ID_NEW:
2735 if (std::error_code EC = ParseTypeTable())
2738 case bitc::VALUE_SYMTAB_BLOCK_ID:
2739 if (std::error_code EC = ParseValueSymbolTable())
2741 SeenValueSymbolTable = true;
2743 case bitc::CONSTANTS_BLOCK_ID:
2744 if (std::error_code EC = ParseConstants())
2746 if (std::error_code EC = ResolveGlobalAndAliasInits())
2749 case bitc::METADATA_BLOCK_ID:
2750 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2751 if (std::error_code EC = rememberAndSkipMetadata())
2755 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2756 if (std::error_code EC = ParseMetadata())
2759 case bitc::FUNCTION_BLOCK_ID:
2760 // If this is the first function body we've seen, reverse the
2761 // FunctionsWithBodies list.
2762 if (!SeenFirstFunctionBody) {
2763 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2764 if (std::error_code EC = GlobalCleanup())
2766 SeenFirstFunctionBody = true;
2769 if (std::error_code EC = RememberAndSkipFunctionBody())
2771 // For streaming bitcode, suspend parsing when we reach the function
2772 // bodies. Subsequent materialization calls will resume it when
2773 // necessary. For streaming, the function bodies must be at the end of
2774 // the bitcode. If the bitcode file is old, the symbol table will be
2775 // at the end instead and will not have been seen yet. In this case,
2776 // just finish the parse now.
2777 if (LazyStreamer && SeenValueSymbolTable) {
2778 NextUnreadBit = Stream.GetCurrentBitNo();
2779 return std::error_code();
2782 case bitc::USELIST_BLOCK_ID:
2783 if (std::error_code EC = ParseUseLists())
2789 case BitstreamEntry::Record:
2790 // The interesting case.
2796 switch (Stream.readRecord(Entry.ID, Record)) {
2797 default: break; // Default behavior, ignore unknown content.
2798 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2799 if (Record.size() < 1)
2800 return Error("Invalid record");
2801 // Only version #0 and #1 are supported so far.
2802 unsigned module_version = Record[0];
2803 switch (module_version) {
2805 return Error("Invalid value");
2807 UseRelativeIDs = false;
2810 UseRelativeIDs = true;
2815 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2817 if (ConvertToString(Record, 0, S))
2818 return Error("Invalid record");
2819 TheModule->setTargetTriple(S);
2822 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2824 if (ConvertToString(Record, 0, S))
2825 return Error("Invalid record");
2826 TheModule->setDataLayout(S);
2829 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2831 if (ConvertToString(Record, 0, S))
2832 return Error("Invalid record");
2833 TheModule->setModuleInlineAsm(S);
2836 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2837 // FIXME: Remove in 4.0.
2839 if (ConvertToString(Record, 0, S))
2840 return Error("Invalid record");
2844 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2846 if (ConvertToString(Record, 0, S))
2847 return Error("Invalid record");
2848 SectionTable.push_back(S);
2851 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2853 if (ConvertToString(Record, 0, S))
2854 return Error("Invalid record");
2855 GCTable.push_back(S);
2858 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2859 if (Record.size() < 2)
2860 return Error("Invalid record");
2861 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2862 unsigned ComdatNameSize = Record[1];
2863 std::string ComdatName;
2864 ComdatName.reserve(ComdatNameSize);
2865 for (unsigned i = 0; i != ComdatNameSize; ++i)
2866 ComdatName += (char)Record[2 + i];
2867 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2868 C->setSelectionKind(SK);
2869 ComdatList.push_back(C);
2872 // GLOBALVAR: [pointer type, isconst, initid,
2873 // linkage, alignment, section, visibility, threadlocal,
2874 // unnamed_addr, externally_initialized, dllstorageclass,
2876 case bitc::MODULE_CODE_GLOBALVAR: {
2877 if (Record.size() < 6)
2878 return Error("Invalid record");
2879 Type *Ty = getTypeByID(Record[0]);
2881 return Error("Invalid record");
2882 bool isConstant = Record[1] & 1;
2883 bool explicitType = Record[1] & 2;
2884 unsigned AddressSpace;
2886 AddressSpace = Record[1] >> 2;
2888 if (!Ty->isPointerTy())
2889 return Error("Invalid type for value");
2890 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2891 Ty = cast<PointerType>(Ty)->getElementType();
2894 uint64_t RawLinkage = Record[3];
2895 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2897 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2899 std::string Section;
2901 if (Record[5]-1 >= SectionTable.size())
2902 return Error("Invalid ID");
2903 Section = SectionTable[Record[5]-1];
2905 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2906 // Local linkage must have default visibility.
2907 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2908 // FIXME: Change to an error if non-default in 4.0.
2909 Visibility = GetDecodedVisibility(Record[6]);
2911 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2912 if (Record.size() > 7)
2913 TLM = GetDecodedThreadLocalMode(Record[7]);
2915 bool UnnamedAddr = false;
2916 if (Record.size() > 8)
2917 UnnamedAddr = Record[8];
2919 bool ExternallyInitialized = false;
2920 if (Record.size() > 9)
2921 ExternallyInitialized = Record[9];
2923 GlobalVariable *NewGV =
2924 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2925 TLM, AddressSpace, ExternallyInitialized);
2926 NewGV->setAlignment(Alignment);
2927 if (!Section.empty())
2928 NewGV->setSection(Section);
2929 NewGV->setVisibility(Visibility);
2930 NewGV->setUnnamedAddr(UnnamedAddr);
2932 if (Record.size() > 10)
2933 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2935 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2937 ValueList.push_back(NewGV);
2939 // Remember which value to use for the global initializer.
2940 if (unsigned InitID = Record[2])
2941 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2943 if (Record.size() > 11) {
2944 if (unsigned ComdatID = Record[11]) {
2945 assert(ComdatID <= ComdatList.size());
2946 NewGV->setComdat(ComdatList[ComdatID - 1]);
2948 } else if (hasImplicitComdat(RawLinkage)) {
2949 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2953 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2954 // alignment, section, visibility, gc, unnamed_addr,
2955 // prologuedata, dllstorageclass, comdat, prefixdata]
2956 case bitc::MODULE_CODE_FUNCTION: {
2957 if (Record.size() < 8)
2958 return Error("Invalid record");
2959 Type *Ty = getTypeByID(Record[0]);
2961 return Error("Invalid record");
2962 if (auto *PTy = dyn_cast<PointerType>(Ty))
2963 Ty = PTy->getElementType();
2964 auto *FTy = dyn_cast<FunctionType>(Ty);
2966 return Error("Invalid type for value");
2968 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2971 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2972 bool isProto = Record[2];
2973 uint64_t RawLinkage = Record[3];
2974 Func->setLinkage(getDecodedLinkage(RawLinkage));
2975 Func->setAttributes(getAttributes(Record[4]));
2978 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2980 Func->setAlignment(Alignment);
2982 if (Record[6]-1 >= SectionTable.size())
2983 return Error("Invalid ID");
2984 Func->setSection(SectionTable[Record[6]-1]);
2986 // Local linkage must have default visibility.
2987 if (!Func->hasLocalLinkage())
2988 // FIXME: Change to an error if non-default in 4.0.
2989 Func->setVisibility(GetDecodedVisibility(Record[7]));
2990 if (Record.size() > 8 && Record[8]) {
2991 if (Record[8]-1 > GCTable.size())
2992 return Error("Invalid ID");
2993 Func->setGC(GCTable[Record[8]-1].c_str());
2995 bool UnnamedAddr = false;
2996 if (Record.size() > 9)
2997 UnnamedAddr = Record[9];
2998 Func->setUnnamedAddr(UnnamedAddr);
2999 if (Record.size() > 10 && Record[10] != 0)
3000 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3002 if (Record.size() > 11)
3003 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
3005 UpgradeDLLImportExportLinkage(Func, RawLinkage);
3007 if (Record.size() > 12) {
3008 if (unsigned ComdatID = Record[12]) {
3009 assert(ComdatID <= ComdatList.size());
3010 Func->setComdat(ComdatList[ComdatID - 1]);
3012 } else if (hasImplicitComdat(RawLinkage)) {
3013 Func->setComdat(reinterpret_cast<Comdat *>(1));
3016 if (Record.size() > 13 && Record[13] != 0)
3017 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3019 ValueList.push_back(Func);
3021 // If this is a function with a body, remember the prototype we are
3022 // creating now, so that we can match up the body with them later.
3024 Func->setIsMaterializable(true);
3025 FunctionsWithBodies.push_back(Func);
3027 DeferredFunctionInfo[Func] = 0;
3031 // ALIAS: [alias type, aliasee val#, linkage]
3032 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3033 case bitc::MODULE_CODE_ALIAS: {
3034 if (Record.size() < 3)
3035 return Error("Invalid record");
3036 Type *Ty = getTypeByID(Record[0]);
3038 return Error("Invalid record");
3039 auto *PTy = dyn_cast<PointerType>(Ty);
3041 return Error("Invalid type for value");
3044 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
3045 getDecodedLinkage(Record[2]), "", TheModule);
3046 // Old bitcode files didn't have visibility field.
3047 // Local linkage must have default visibility.
3048 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3049 // FIXME: Change to an error if non-default in 4.0.
3050 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3051 if (Record.size() > 4)
3052 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3054 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3055 if (Record.size() > 5)
3056 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3057 if (Record.size() > 6)
3058 NewGA->setUnnamedAddr(Record[6]);
3059 ValueList.push_back(NewGA);
3060 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3063 /// MODULE_CODE_PURGEVALS: [numvals]
3064 case bitc::MODULE_CODE_PURGEVALS:
3065 // Trim down the value list to the specified size.
3066 if (Record.size() < 1 || Record[0] > ValueList.size())
3067 return Error("Invalid record");
3068 ValueList.shrinkTo(Record[0]);
3075 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3076 bool ShouldLazyLoadMetadata) {
3077 TheModule = nullptr;
3079 if (std::error_code EC = InitStream())
3082 // Sniff for the signature.
3083 if (Stream.Read(8) != 'B' ||
3084 Stream.Read(8) != 'C' ||
3085 Stream.Read(4) != 0x0 ||
3086 Stream.Read(4) != 0xC ||
3087 Stream.Read(4) != 0xE ||
3088 Stream.Read(4) != 0xD)
3089 return Error("Invalid bitcode signature");
3091 // We expect a number of well-defined blocks, though we don't necessarily
3092 // need to understand them all.
3094 if (Stream.AtEndOfStream()) {
3096 return std::error_code();
3097 // We didn't really read a proper Module.
3098 return Error("Malformed IR file");
3101 BitstreamEntry Entry =
3102 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3104 switch (Entry.Kind) {
3105 case BitstreamEntry::Error:
3106 return Error("Malformed block");
3107 case BitstreamEntry::EndBlock:
3108 return std::error_code();
3110 case BitstreamEntry::SubBlock:
3112 case bitc::BLOCKINFO_BLOCK_ID:
3113 if (Stream.ReadBlockInfoBlock())
3114 return Error("Malformed block");
3116 case bitc::MODULE_BLOCK_ID:
3117 // Reject multiple MODULE_BLOCK's in a single bitstream.
3119 return Error("Invalid multiple blocks");
3121 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3124 return std::error_code();
3127 if (Stream.SkipBlock())
3128 return Error("Invalid record");
3132 case BitstreamEntry::Record:
3133 // There should be no records in the top-level of blocks.
3135 // The ranlib in Xcode 4 will align archive members by appending newlines
3136 // to the end of them. If this file size is a multiple of 4 but not 8, we
3137 // have to read and ignore these final 4 bytes :-(
3138 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3139 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3140 Stream.AtEndOfStream())
3141 return std::error_code();
3143 return Error("Invalid record");
3148 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3149 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3150 return Error("Invalid record");
3152 SmallVector<uint64_t, 64> Record;
3155 // Read all the records for this module.
3157 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3159 switch (Entry.Kind) {
3160 case BitstreamEntry::SubBlock: // Handled for us already.
3161 case BitstreamEntry::Error:
3162 return Error("Malformed block");
3163 case BitstreamEntry::EndBlock:
3165 case BitstreamEntry::Record:
3166 // The interesting case.
3171 switch (Stream.readRecord(Entry.ID, Record)) {
3172 default: break; // Default behavior, ignore unknown content.
3173 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3175 if (ConvertToString(Record, 0, S))
3176 return Error("Invalid record");
3183 llvm_unreachable("Exit infinite loop");
3186 ErrorOr<std::string> BitcodeReader::parseTriple() {
3187 if (std::error_code EC = InitStream())
3190 // Sniff for the signature.
3191 if (Stream.Read(8) != 'B' ||
3192 Stream.Read(8) != 'C' ||
3193 Stream.Read(4) != 0x0 ||
3194 Stream.Read(4) != 0xC ||
3195 Stream.Read(4) != 0xE ||
3196 Stream.Read(4) != 0xD)
3197 return Error("Invalid bitcode signature");
3199 // We expect a number of well-defined blocks, though we don't necessarily
3200 // need to understand them all.
3202 BitstreamEntry Entry = Stream.advance();
3204 switch (Entry.Kind) {
3205 case BitstreamEntry::Error:
3206 return Error("Malformed block");
3207 case BitstreamEntry::EndBlock:
3208 return std::error_code();
3210 case BitstreamEntry::SubBlock:
3211 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3212 return parseModuleTriple();
3214 // Ignore other sub-blocks.
3215 if (Stream.SkipBlock())
3216 return Error("Malformed block");
3219 case BitstreamEntry::Record:
3220 Stream.skipRecord(Entry.ID);
3226 /// ParseMetadataAttachment - Parse metadata attachments.
3227 std::error_code BitcodeReader::ParseMetadataAttachment(Function &F) {
3228 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3229 return Error("Invalid record");
3231 SmallVector<uint64_t, 64> Record;
3233 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3235 switch (Entry.Kind) {
3236 case BitstreamEntry::SubBlock: // Handled for us already.
3237 case BitstreamEntry::Error:
3238 return Error("Malformed block");
3239 case BitstreamEntry::EndBlock:
3240 return std::error_code();
3241 case BitstreamEntry::Record:
3242 // The interesting case.
3246 // Read a metadata attachment record.
3248 switch (Stream.readRecord(Entry.ID, Record)) {
3249 default: // Default behavior: ignore.
3251 case bitc::METADATA_ATTACHMENT: {
3252 unsigned RecordLength = Record.size();
3254 return Error("Invalid record");
3255 if (RecordLength % 2 == 0) {
3256 // A function attachment.
3257 for (unsigned I = 0; I != RecordLength; I += 2) {
3258 auto K = MDKindMap.find(Record[I]);
3259 if (K == MDKindMap.end())
3260 return Error("Invalid ID");
3261 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3262 F.setMetadata(K->second, cast<MDNode>(MD));
3267 // An instruction attachment.
3268 Instruction *Inst = InstructionList[Record[0]];
3269 for (unsigned i = 1; i != RecordLength; i = i+2) {
3270 unsigned Kind = Record[i];
3271 DenseMap<unsigned, unsigned>::iterator I =
3272 MDKindMap.find(Kind);
3273 if (I == MDKindMap.end())
3274 return Error("Invalid ID");
3275 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3276 if (isa<LocalAsMetadata>(Node))
3277 // Drop the attachment. This used to be legal, but there's no
3280 Inst->setMetadata(I->second, cast<MDNode>(Node));
3281 if (I->second == LLVMContext::MD_tbaa)
3282 InstsWithTBAATag.push_back(Inst);
3290 /// ParseFunctionBody - Lazily parse the specified function body block.
3291 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3292 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3293 return Error("Invalid record");
3295 InstructionList.clear();
3296 unsigned ModuleValueListSize = ValueList.size();
3297 unsigned ModuleMDValueListSize = MDValueList.size();
3299 // Add all the function arguments to the value table.
3300 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3301 ValueList.push_back(I);
3303 unsigned NextValueNo = ValueList.size();
3304 BasicBlock *CurBB = nullptr;
3305 unsigned CurBBNo = 0;
3308 auto getLastInstruction = [&]() -> Instruction * {
3309 if (CurBB && !CurBB->empty())
3310 return &CurBB->back();
3311 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3312 !FunctionBBs[CurBBNo - 1]->empty())
3313 return &FunctionBBs[CurBBNo - 1]->back();
3317 // Read all the records.
3318 SmallVector<uint64_t, 64> Record;
3320 BitstreamEntry Entry = Stream.advance();
3322 switch (Entry.Kind) {
3323 case BitstreamEntry::Error:
3324 return Error("Malformed block");
3325 case BitstreamEntry::EndBlock:
3326 goto OutOfRecordLoop;
3328 case BitstreamEntry::SubBlock:
3330 default: // Skip unknown content.
3331 if (Stream.SkipBlock())
3332 return Error("Invalid record");
3334 case bitc::CONSTANTS_BLOCK_ID:
3335 if (std::error_code EC = ParseConstants())
3337 NextValueNo = ValueList.size();
3339 case bitc::VALUE_SYMTAB_BLOCK_ID:
3340 if (std::error_code EC = ParseValueSymbolTable())
3343 case bitc::METADATA_ATTACHMENT_ID:
3344 if (std::error_code EC = ParseMetadataAttachment(*F))
3347 case bitc::METADATA_BLOCK_ID:
3348 if (std::error_code EC = ParseMetadata())
3351 case bitc::USELIST_BLOCK_ID:
3352 if (std::error_code EC = ParseUseLists())
3358 case BitstreamEntry::Record:
3359 // The interesting case.
3365 Instruction *I = nullptr;
3366 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3368 default: // Default behavior: reject
3369 return Error("Invalid value");
3370 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3371 if (Record.size() < 1 || Record[0] == 0)
3372 return Error("Invalid record");
3373 // Create all the basic blocks for the function.
3374 FunctionBBs.resize(Record[0]);
3376 // See if anything took the address of blocks in this function.
3377 auto BBFRI = BasicBlockFwdRefs.find(F);
3378 if (BBFRI == BasicBlockFwdRefs.end()) {
3379 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3380 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3382 auto &BBRefs = BBFRI->second;
3383 // Check for invalid basic block references.
3384 if (BBRefs.size() > FunctionBBs.size())
3385 return Error("Invalid ID");
3386 assert(!BBRefs.empty() && "Unexpected empty array");
3387 assert(!BBRefs.front() && "Invalid reference to entry block");
3388 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3390 if (I < RE && BBRefs[I]) {
3391 BBRefs[I]->insertInto(F);
3392 FunctionBBs[I] = BBRefs[I];
3394 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3397 // Erase from the table.
3398 BasicBlockFwdRefs.erase(BBFRI);
3401 CurBB = FunctionBBs[0];
3405 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3406 // This record indicates that the last instruction is at the same
3407 // location as the previous instruction with a location.
3408 I = getLastInstruction();
3411 return Error("Invalid record");
3412 I->setDebugLoc(LastLoc);
3416 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3417 I = getLastInstruction();
3418 if (!I || Record.size() < 4)
3419 return Error("Invalid record");
3421 unsigned Line = Record[0], Col = Record[1];
3422 unsigned ScopeID = Record[2], IAID = Record[3];
3424 MDNode *Scope = nullptr, *IA = nullptr;
3425 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3426 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3427 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3428 I->setDebugLoc(LastLoc);
3433 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3436 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3437 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3438 OpNum+1 > Record.size())
3439 return Error("Invalid record");
3441 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3443 return Error("Invalid record");
3444 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3445 InstructionList.push_back(I);
3446 if (OpNum < Record.size()) {
3447 if (Opc == Instruction::Add ||
3448 Opc == Instruction::Sub ||
3449 Opc == Instruction::Mul ||
3450 Opc == Instruction::Shl) {
3451 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3452 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3453 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3454 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3455 } else if (Opc == Instruction::SDiv ||
3456 Opc == Instruction::UDiv ||
3457 Opc == Instruction::LShr ||
3458 Opc == Instruction::AShr) {
3459 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3460 cast<BinaryOperator>(I)->setIsExact(true);
3461 } else if (isa<FPMathOperator>(I)) {
3463 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3464 FMF.setUnsafeAlgebra();
3465 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3467 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3469 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3470 FMF.setNoSignedZeros();
3471 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3472 FMF.setAllowReciprocal();
3474 I->setFastMathFlags(FMF);
3480 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3483 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3484 OpNum+2 != Record.size())
3485 return Error("Invalid record");
3487 Type *ResTy = getTypeByID(Record[OpNum]);
3488 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3489 if (Opc == -1 || !ResTy)
3490 return Error("Invalid record");
3491 Instruction *Temp = nullptr;
3492 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3494 InstructionList.push_back(Temp);
3495 CurBB->getInstList().push_back(Temp);
3498 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3500 InstructionList.push_back(I);
3503 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3504 case bitc::FUNC_CODE_INST_GEP_OLD:
3505 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3511 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3512 InBounds = Record[OpNum++];
3513 Ty = getTypeByID(Record[OpNum++]);
3515 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3520 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3521 return Error("Invalid record");
3525 cast<SequentialType>(BasePtr->getType()->getScalarType())
3528 "Explicit gep type does not match pointee type of pointer operand");
3530 SmallVector<Value*, 16> GEPIdx;
3531 while (OpNum != Record.size()) {
3533 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3534 return Error("Invalid record");
3535 GEPIdx.push_back(Op);
3538 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3540 InstructionList.push_back(I);
3542 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3546 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3547 // EXTRACTVAL: [opty, opval, n x indices]
3550 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3551 return Error("Invalid record");
3553 SmallVector<unsigned, 4> EXTRACTVALIdx;
3554 Type *CurTy = Agg->getType();
3555 for (unsigned RecSize = Record.size();
3556 OpNum != RecSize; ++OpNum) {
3557 bool IsArray = CurTy->isArrayTy();
3558 bool IsStruct = CurTy->isStructTy();
3559 uint64_t Index = Record[OpNum];
3561 if (!IsStruct && !IsArray)
3562 return Error("EXTRACTVAL: Invalid type");
3563 if ((unsigned)Index != Index)
3564 return Error("Invalid value");
3565 if (IsStruct && Index >= CurTy->subtypes().size())
3566 return Error("EXTRACTVAL: Invalid struct index");
3567 if (IsArray && Index >= CurTy->getArrayNumElements())
3568 return Error("EXTRACTVAL: Invalid array index");
3569 EXTRACTVALIdx.push_back((unsigned)Index);
3572 CurTy = CurTy->subtypes()[Index];
3574 CurTy = CurTy->subtypes()[0];
3577 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3578 InstructionList.push_back(I);
3582 case bitc::FUNC_CODE_INST_INSERTVAL: {
3583 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3586 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3587 return Error("Invalid record");
3589 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3590 return Error("Invalid record");
3592 SmallVector<unsigned, 4> INSERTVALIdx;
3593 Type *CurTy = Agg->getType();
3594 for (unsigned RecSize = Record.size();
3595 OpNum != RecSize; ++OpNum) {
3596 bool IsArray = CurTy->isArrayTy();
3597 bool IsStruct = CurTy->isStructTy();
3598 uint64_t Index = Record[OpNum];
3600 if (!IsStruct && !IsArray)
3601 return Error("INSERTVAL: Invalid type");
3602 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3603 return Error("Invalid type");
3604 if ((unsigned)Index != Index)
3605 return Error("Invalid value");
3606 if (IsStruct && Index >= CurTy->subtypes().size())
3607 return Error("INSERTVAL: Invalid struct index");
3608 if (IsArray && Index >= CurTy->getArrayNumElements())
3609 return Error("INSERTVAL: Invalid array index");
3611 INSERTVALIdx.push_back((unsigned)Index);
3613 CurTy = CurTy->subtypes()[Index];
3615 CurTy = CurTy->subtypes()[0];
3618 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3619 InstructionList.push_back(I);
3623 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3624 // obsolete form of select
3625 // handles select i1 ... in old bitcode
3627 Value *TrueVal, *FalseVal, *Cond;
3628 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3629 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3630 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3631 return Error("Invalid record");
3633 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3634 InstructionList.push_back(I);
3638 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3639 // new form of select
3640 // handles select i1 or select [N x i1]
3642 Value *TrueVal, *FalseVal, *Cond;
3643 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3644 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3645 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3646 return Error("Invalid record");
3648 // select condition can be either i1 or [N x i1]
3649 if (VectorType* vector_type =
3650 dyn_cast<VectorType>(Cond->getType())) {
3652 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3653 return Error("Invalid type for value");
3656 if (Cond->getType() != Type::getInt1Ty(Context))
3657 return Error("Invalid type for value");
3660 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3661 InstructionList.push_back(I);
3665 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3668 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3669 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3670 return Error("Invalid record");
3671 if (!Vec->getType()->isVectorTy())
3672 return Error("Invalid type for value");
3673 I = ExtractElementInst::Create(Vec, Idx);
3674 InstructionList.push_back(I);
3678 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3680 Value *Vec, *Elt, *Idx;
3681 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3682 return Error("Invalid record");
3683 if (!Vec->getType()->isVectorTy())
3684 return Error("Invalid type for value");
3685 if (popValue(Record, OpNum, NextValueNo,
3686 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3687 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3688 return Error("Invalid record");
3689 I = InsertElementInst::Create(Vec, Elt, Idx);
3690 InstructionList.push_back(I);
3694 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3696 Value *Vec1, *Vec2, *Mask;
3697 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3698 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3699 return Error("Invalid record");
3701 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3702 return Error("Invalid record");
3703 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3704 return Error("Invalid type for value");
3705 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3706 InstructionList.push_back(I);
3710 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3711 // Old form of ICmp/FCmp returning bool
3712 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3713 // both legal on vectors but had different behaviour.
3714 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3715 // FCmp/ICmp returning bool or vector of bool
3719 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3720 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3721 OpNum+1 != Record.size())
3722 return Error("Invalid record");
3724 if (LHS->getType()->isFPOrFPVectorTy())
3725 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3727 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3728 InstructionList.push_back(I);
3732 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3734 unsigned Size = Record.size();
3736 I = ReturnInst::Create(Context);
3737 InstructionList.push_back(I);
3742 Value *Op = nullptr;
3743 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3744 return Error("Invalid record");
3745 if (OpNum != Record.size())
3746 return Error("Invalid record");
3748 I = ReturnInst::Create(Context, Op);
3749 InstructionList.push_back(I);
3752 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3753 if (Record.size() != 1 && Record.size() != 3)
3754 return Error("Invalid record");
3755 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3757 return Error("Invalid record");
3759 if (Record.size() == 1) {
3760 I = BranchInst::Create(TrueDest);
3761 InstructionList.push_back(I);
3764 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3765 Value *Cond = getValue(Record, 2, NextValueNo,
3766 Type::getInt1Ty(Context));
3767 if (!FalseDest || !Cond)
3768 return Error("Invalid record");
3769 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3770 InstructionList.push_back(I);
3774 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3776 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3777 // "New" SwitchInst format with case ranges. The changes to write this
3778 // format were reverted but we still recognize bitcode that uses it.
3779 // Hopefully someday we will have support for case ranges and can use
3780 // this format again.
3782 Type *OpTy = getTypeByID(Record[1]);
3783 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3785 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3786 BasicBlock *Default = getBasicBlock(Record[3]);
3787 if (!OpTy || !Cond || !Default)
3788 return Error("Invalid record");
3790 unsigned NumCases = Record[4];
3792 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3793 InstructionList.push_back(SI);
3795 unsigned CurIdx = 5;
3796 for (unsigned i = 0; i != NumCases; ++i) {
3797 SmallVector<ConstantInt*, 1> CaseVals;
3798 unsigned NumItems = Record[CurIdx++];
3799 for (unsigned ci = 0; ci != NumItems; ++ci) {
3800 bool isSingleNumber = Record[CurIdx++];
3803 unsigned ActiveWords = 1;
3804 if (ValueBitWidth > 64)
3805 ActiveWords = Record[CurIdx++];
3806 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3808 CurIdx += ActiveWords;
3810 if (!isSingleNumber) {
3812 if (ValueBitWidth > 64)
3813 ActiveWords = Record[CurIdx++];
3815 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3817 CurIdx += ActiveWords;
3819 // FIXME: It is not clear whether values in the range should be
3820 // compared as signed or unsigned values. The partially
3821 // implemented changes that used this format in the past used
3822 // unsigned comparisons.
3823 for ( ; Low.ule(High); ++Low)
3824 CaseVals.push_back(ConstantInt::get(Context, Low));
3826 CaseVals.push_back(ConstantInt::get(Context, Low));
3828 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3829 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3830 cve = CaseVals.end(); cvi != cve; ++cvi)
3831 SI->addCase(*cvi, DestBB);
3837 // Old SwitchInst format without case ranges.
3839 if (Record.size() < 3 || (Record.size() & 1) == 0)
3840 return Error("Invalid record");
3841 Type *OpTy = getTypeByID(Record[0]);
3842 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3843 BasicBlock *Default = getBasicBlock(Record[2]);
3844 if (!OpTy || !Cond || !Default)
3845 return Error("Invalid record");
3846 unsigned NumCases = (Record.size()-3)/2;
3847 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3848 InstructionList.push_back(SI);
3849 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3850 ConstantInt *CaseVal =
3851 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3852 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3853 if (!CaseVal || !DestBB) {
3855 return Error("Invalid record");
3857 SI->addCase(CaseVal, DestBB);
3862 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3863 if (Record.size() < 2)
3864 return Error("Invalid record");
3865 Type *OpTy = getTypeByID(Record[0]);
3866 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3867 if (!OpTy || !Address)
3868 return Error("Invalid record");
3869 unsigned NumDests = Record.size()-2;
3870 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3871 InstructionList.push_back(IBI);
3872 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3873 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3874 IBI->addDestination(DestBB);
3877 return Error("Invalid record");
3884 case bitc::FUNC_CODE_INST_INVOKE: {
3885 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3886 if (Record.size() < 4)
3887 return Error("Invalid record");
3889 AttributeSet PAL = getAttributes(Record[OpNum++]);
3890 unsigned CCInfo = Record[OpNum++];
3891 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3892 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3894 FunctionType *FTy = nullptr;
3895 if (CCInfo >> 13 & 1 &&
3896 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3897 return Error("Explicit invoke type is not a function type");
3900 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3901 return Error("Invalid record");
3903 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3905 return Error("Callee is not a pointer");
3907 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3909 return Error("Callee is not of pointer to function type");
3910 } else if (CalleeTy->getElementType() != FTy)
3911 return Error("Explicit invoke type does not match pointee type of "
3913 if (Record.size() < FTy->getNumParams() + OpNum)
3914 return Error("Insufficient operands to call");
3916 SmallVector<Value*, 16> Ops;
3917 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3918 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3919 FTy->getParamType(i)));
3921 return Error("Invalid record");
3924 if (!FTy->isVarArg()) {
3925 if (Record.size() != OpNum)
3926 return Error("Invalid record");
3928 // Read type/value pairs for varargs params.
3929 while (OpNum != Record.size()) {
3931 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3932 return Error("Invalid record");
3937 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3938 InstructionList.push_back(I);
3940 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
3941 cast<InvokeInst>(I)->setAttributes(PAL);
3944 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3946 Value *Val = nullptr;
3947 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3948 return Error("Invalid record");
3949 I = ResumeInst::Create(Val);
3950 InstructionList.push_back(I);
3953 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3954 I = new UnreachableInst(Context);
3955 InstructionList.push_back(I);
3957 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3958 if (Record.size() < 1 || ((Record.size()-1)&1))
3959 return Error("Invalid record");
3960 Type *Ty = getTypeByID(Record[0]);
3962 return Error("Invalid record");
3964 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3965 InstructionList.push_back(PN);
3967 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3969 // With the new function encoding, it is possible that operands have
3970 // negative IDs (for forward references). Use a signed VBR
3971 // representation to keep the encoding small.
3973 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3975 V = getValue(Record, 1+i, NextValueNo, Ty);
3976 BasicBlock *BB = getBasicBlock(Record[2+i]);
3978 return Error("Invalid record");
3979 PN->addIncoming(V, BB);
3985 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3986 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3988 if (Record.size() < 4)
3989 return Error("Invalid record");
3990 Type *Ty = getTypeByID(Record[Idx++]);
3992 return Error("Invalid record");
3993 Value *PersFn = nullptr;
3994 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3995 return Error("Invalid record");
3997 bool IsCleanup = !!Record[Idx++];
3998 unsigned NumClauses = Record[Idx++];
3999 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
4000 LP->setCleanup(IsCleanup);
4001 for (unsigned J = 0; J != NumClauses; ++J) {
4002 LandingPadInst::ClauseType CT =
4003 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4006 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4008 return Error("Invalid record");
4011 assert((CT != LandingPadInst::Catch ||
4012 !isa<ArrayType>(Val->getType())) &&
4013 "Catch clause has a invalid type!");
4014 assert((CT != LandingPadInst::Filter ||
4015 isa<ArrayType>(Val->getType())) &&
4016 "Filter clause has invalid type!");
4017 LP->addClause(cast<Constant>(Val));
4021 InstructionList.push_back(I);
4025 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4026 if (Record.size() != 4)
4027 return Error("Invalid record");
4028 uint64_t AlignRecord = Record[3];
4029 const uint64_t InAllocaMask = uint64_t(1) << 5;
4030 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4031 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4032 bool InAlloca = AlignRecord & InAllocaMask;
4033 Type *Ty = getTypeByID(Record[0]);
4034 if ((AlignRecord & ExplicitTypeMask) == 0) {
4035 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4037 return Error("Old-style alloca with a non-pointer type");
4038 Ty = PTy->getElementType();
4040 Type *OpTy = getTypeByID(Record[1]);
4041 Value *Size = getFnValueByID(Record[2], OpTy);
4043 if (std::error_code EC =
4044 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4048 return Error("Invalid record");
4049 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4050 AI->setUsedWithInAlloca(InAlloca);
4052 InstructionList.push_back(I);
4055 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4058 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4059 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4060 return Error("Invalid record");
4063 if (OpNum + 3 == Record.size())
4064 Ty = getTypeByID(Record[OpNum++]);
4066 Ty = cast<PointerType>(Op->getType())->getElementType();
4067 else if (Ty != cast<PointerType>(Op->getType())->getElementType())
4068 return Error("Explicit load type does not match pointee type of "
4072 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4074 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4076 InstructionList.push_back(I);
4079 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4080 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4083 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4084 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4085 return Error("Invalid record");
4088 if (OpNum + 5 == Record.size())
4089 Ty = getTypeByID(Record[OpNum++]);
4091 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4092 if (Ordering == NotAtomic || Ordering == Release ||
4093 Ordering == AcquireRelease)
4094 return Error("Invalid record");
4095 if (Ordering != NotAtomic && Record[OpNum] == 0)
4096 return Error("Invalid record");
4097 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4100 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4102 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4105 assert((!Ty || Ty == I->getType()) &&
4106 "Explicit type doesn't match pointee type of the first operand");
4108 InstructionList.push_back(I);
4111 case bitc::FUNC_CODE_INST_STORE:
4112 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4115 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4116 (BitCode == bitc::FUNC_CODE_INST_STORE
4117 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4118 : popValue(Record, OpNum, NextValueNo,
4119 cast<PointerType>(Ptr->getType())->getElementType(),
4121 OpNum + 2 != Record.size())
4122 return Error("Invalid record");
4124 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4126 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4127 InstructionList.push_back(I);
4130 case bitc::FUNC_CODE_INST_STOREATOMIC:
4131 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4132 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4135 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4136 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4137 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4138 : popValue(Record, OpNum, NextValueNo,
4139 cast<PointerType>(Ptr->getType())->getElementType(),
4141 OpNum + 4 != Record.size())
4142 return Error("Invalid record");
4144 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4145 if (Ordering == NotAtomic || Ordering == Acquire ||
4146 Ordering == AcquireRelease)
4147 return Error("Invalid record");
4148 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4149 if (Ordering != NotAtomic && Record[OpNum] == 0)
4150 return Error("Invalid record");
4153 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4155 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4156 InstructionList.push_back(I);
4159 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4160 case bitc::FUNC_CODE_INST_CMPXCHG: {
4161 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4162 // failureordering?, isweak?]
4164 Value *Ptr, *Cmp, *New;
4165 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4166 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4167 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4168 : popValue(Record, OpNum, NextValueNo,
4169 cast<PointerType>(Ptr->getType())->getElementType(),
4171 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4172 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4173 return Error("Invalid record");
4174 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4175 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4176 return Error("Invalid record");
4177 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4179 AtomicOrdering FailureOrdering;
4180 if (Record.size() < 7)
4182 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4184 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4186 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4188 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4190 if (Record.size() < 8) {
4191 // Before weak cmpxchgs existed, the instruction simply returned the
4192 // value loaded from memory, so bitcode files from that era will be
4193 // expecting the first component of a modern cmpxchg.
4194 CurBB->getInstList().push_back(I);
4195 I = ExtractValueInst::Create(I, 0);
4197 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4200 InstructionList.push_back(I);
4203 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4204 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4207 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4208 popValue(Record, OpNum, NextValueNo,
4209 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4210 OpNum+4 != Record.size())
4211 return Error("Invalid record");
4212 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4213 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4214 Operation > AtomicRMWInst::LAST_BINOP)
4215 return Error("Invalid record");
4216 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4217 if (Ordering == NotAtomic || Ordering == Unordered)
4218 return Error("Invalid record");
4219 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4220 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4221 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4222 InstructionList.push_back(I);
4225 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4226 if (2 != Record.size())
4227 return Error("Invalid record");
4228 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4229 if (Ordering == NotAtomic || Ordering == Unordered ||
4230 Ordering == Monotonic)
4231 return Error("Invalid record");
4232 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4233 I = new FenceInst(Context, Ordering, SynchScope);
4234 InstructionList.push_back(I);
4237 case bitc::FUNC_CODE_INST_CALL: {
4238 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4239 if (Record.size() < 3)
4240 return Error("Invalid record");
4243 AttributeSet PAL = getAttributes(Record[OpNum++]);
4244 unsigned CCInfo = Record[OpNum++];
4246 FunctionType *FTy = nullptr;
4247 if (CCInfo >> 15 & 1 &&
4248 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4249 return Error("Explicit call type is not a function type");
4252 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4253 return Error("Invalid record");
4255 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4257 return Error("Callee is not a pointer type");
4259 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4261 return Error("Callee is not of pointer to function type");
4262 } else if (OpTy->getElementType() != FTy)
4263 return Error("Explicit call type does not match pointee type of "
4265 if (Record.size() < FTy->getNumParams() + OpNum)
4266 return Error("Insufficient operands to call");
4268 SmallVector<Value*, 16> Args;
4269 // Read the fixed params.
4270 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4271 if (FTy->getParamType(i)->isLabelTy())
4272 Args.push_back(getBasicBlock(Record[OpNum]));
4274 Args.push_back(getValue(Record, OpNum, NextValueNo,
4275 FTy->getParamType(i)));
4277 return Error("Invalid record");
4280 // Read type/value pairs for varargs params.
4281 if (!FTy->isVarArg()) {
4282 if (OpNum != Record.size())
4283 return Error("Invalid record");
4285 while (OpNum != Record.size()) {
4287 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4288 return Error("Invalid record");
4293 I = CallInst::Create(FTy, Callee, Args);
4294 InstructionList.push_back(I);
4295 cast<CallInst>(I)->setCallingConv(
4296 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4297 CallInst::TailCallKind TCK = CallInst::TCK_None;
4299 TCK = CallInst::TCK_Tail;
4300 if (CCInfo & (1 << 14))
4301 TCK = CallInst::TCK_MustTail;
4302 cast<CallInst>(I)->setTailCallKind(TCK);
4303 cast<CallInst>(I)->setAttributes(PAL);
4306 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4307 if (Record.size() < 3)
4308 return Error("Invalid record");
4309 Type *OpTy = getTypeByID(Record[0]);
4310 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4311 Type *ResTy = getTypeByID(Record[2]);
4312 if (!OpTy || !Op || !ResTy)
4313 return Error("Invalid record");
4314 I = new VAArgInst(Op, ResTy);
4315 InstructionList.push_back(I);
4320 // Add instruction to end of current BB. If there is no current BB, reject
4324 return Error("Invalid instruction with no BB");
4326 CurBB->getInstList().push_back(I);
4328 // If this was a terminator instruction, move to the next block.
4329 if (isa<TerminatorInst>(I)) {
4331 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4334 // Non-void values get registered in the value table for future use.
4335 if (I && !I->getType()->isVoidTy())
4336 ValueList.AssignValue(I, NextValueNo++);
4341 // Check the function list for unresolved values.
4342 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4343 if (!A->getParent()) {
4344 // We found at least one unresolved value. Nuke them all to avoid leaks.
4345 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4346 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4347 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4351 return Error("Never resolved value found in function");
4355 // FIXME: Check for unresolved forward-declared metadata references
4356 // and clean up leaks.
4358 // Trim the value list down to the size it was before we parsed this function.
4359 ValueList.shrinkTo(ModuleValueListSize);
4360 MDValueList.shrinkTo(ModuleMDValueListSize);
4361 std::vector<BasicBlock*>().swap(FunctionBBs);
4362 return std::error_code();
4365 /// Find the function body in the bitcode stream
4366 std::error_code BitcodeReader::FindFunctionInStream(
4368 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4369 while (DeferredFunctionInfoIterator->second == 0) {
4370 if (Stream.AtEndOfStream())
4371 return Error("Could not find function in stream");
4372 // ParseModule will parse the next body in the stream and set its
4373 // position in the DeferredFunctionInfo map.
4374 if (std::error_code EC = ParseModule(true))
4377 return std::error_code();
4380 //===----------------------------------------------------------------------===//
4381 // GVMaterializer implementation
4382 //===----------------------------------------------------------------------===//
4384 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4386 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4387 if (std::error_code EC = materializeMetadata())
4390 Function *F = dyn_cast<Function>(GV);
4391 // If it's not a function or is already material, ignore the request.
4392 if (!F || !F->isMaterializable())
4393 return std::error_code();
4395 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4396 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4397 // If its position is recorded as 0, its body is somewhere in the stream
4398 // but we haven't seen it yet.
4399 if (DFII->second == 0 && LazyStreamer)
4400 if (std::error_code EC = FindFunctionInStream(F, DFII))
4403 // Move the bit stream to the saved position of the deferred function body.
4404 Stream.JumpToBit(DFII->second);
4406 if (std::error_code EC = ParseFunctionBody(F))
4408 F->setIsMaterializable(false);
4413 // Upgrade any old intrinsic calls in the function.
4414 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4415 E = UpgradedIntrinsics.end(); I != E; ++I) {
4416 if (I->first != I->second) {
4417 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4419 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4420 UpgradeIntrinsicCall(CI, I->second);
4425 // Bring in any functions that this function forward-referenced via
4427 return materializeForwardReferencedFunctions();
4430 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4431 const Function *F = dyn_cast<Function>(GV);
4432 if (!F || F->isDeclaration())
4435 // Dematerializing F would leave dangling references that wouldn't be
4436 // reconnected on re-materialization.
4437 if (BlockAddressesTaken.count(F))
4440 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4443 void BitcodeReader::Dematerialize(GlobalValue *GV) {
4444 Function *F = dyn_cast<Function>(GV);
4445 // If this function isn't dematerializable, this is a noop.
4446 if (!F || !isDematerializable(F))
4449 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4451 // Just forget the function body, we can remat it later.
4452 F->dropAllReferences();
4453 F->setIsMaterializable(true);
4456 std::error_code BitcodeReader::MaterializeModule(Module *M) {
4457 assert(M == TheModule &&
4458 "Can only Materialize the Module this BitcodeReader is attached to.");
4460 if (std::error_code EC = materializeMetadata())
4463 // Promise to materialize all forward references.
4464 WillMaterializeAllForwardRefs = true;
4466 // Iterate over the module, deserializing any functions that are still on
4468 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4470 if (std::error_code EC = materialize(F))
4473 // At this point, if there are any function bodies, the current bit is
4474 // pointing to the END_BLOCK record after them. Now make sure the rest
4475 // of the bits in the module have been read.
4479 // Check that all block address forward references got resolved (as we
4481 if (!BasicBlockFwdRefs.empty())
4482 return Error("Never resolved function from blockaddress");
4484 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4485 // delete the old functions to clean up. We can't do this unless the entire
4486 // module is materialized because there could always be another function body
4487 // with calls to the old function.
4488 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4489 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4490 if (I->first != I->second) {
4491 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4493 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4494 UpgradeIntrinsicCall(CI, I->second);
4496 if (!I->first->use_empty())
4497 I->first->replaceAllUsesWith(I->second);
4498 I->first->eraseFromParent();
4501 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4503 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4504 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4506 UpgradeDebugInfo(*M);
4507 return std::error_code();
4510 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4511 return IdentifiedStructTypes;
4514 std::error_code BitcodeReader::InitStream() {
4516 return InitLazyStream();
4517 return InitStreamFromBuffer();
4520 std::error_code BitcodeReader::InitStreamFromBuffer() {
4521 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4522 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4524 if (Buffer->getBufferSize() & 3)
4525 return Error("Invalid bitcode signature");
4527 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4528 // The magic number is 0x0B17C0DE stored in little endian.
4529 if (isBitcodeWrapper(BufPtr, BufEnd))
4530 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4531 return Error("Invalid bitcode wrapper header");
4533 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4534 Stream.init(&*StreamFile);
4536 return std::error_code();
4539 std::error_code BitcodeReader::InitLazyStream() {
4540 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4542 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4543 StreamingMemoryObject &Bytes = *OwnedBytes;
4544 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4545 Stream.init(&*StreamFile);
4547 unsigned char buf[16];
4548 if (Bytes.readBytes(buf, 16, 0) != 16)
4549 return Error("Invalid bitcode signature");
4551 if (!isBitcode(buf, buf + 16))
4552 return Error("Invalid bitcode signature");
4554 if (isBitcodeWrapper(buf, buf + 4)) {
4555 const unsigned char *bitcodeStart = buf;
4556 const unsigned char *bitcodeEnd = buf + 16;
4557 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4558 Bytes.dropLeadingBytes(bitcodeStart - buf);
4559 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4561 return std::error_code();
4565 class BitcodeErrorCategoryType : public std::error_category {
4566 const char *name() const LLVM_NOEXCEPT override {
4567 return "llvm.bitcode";
4569 std::string message(int IE) const override {
4570 BitcodeError E = static_cast<BitcodeError>(IE);
4572 case BitcodeError::InvalidBitcodeSignature:
4573 return "Invalid bitcode signature";
4574 case BitcodeError::CorruptedBitcode:
4575 return "Corrupted bitcode";
4577 llvm_unreachable("Unknown error type!");
4582 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4584 const std::error_category &llvm::BitcodeErrorCategory() {
4585 return *ErrorCategory;
4588 //===----------------------------------------------------------------------===//
4589 // External interface
4590 //===----------------------------------------------------------------------===//
4592 /// \brief Get a lazy one-at-time loading module from bitcode.
4594 /// This isn't always used in a lazy context. In particular, it's also used by
4595 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4596 /// in forward-referenced functions from block address references.
4598 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4599 /// materialize everything -- in particular, if this isn't truly lazy.
4600 static ErrorOr<Module *>
4601 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4602 LLVMContext &Context, bool WillMaterializeAll,
4603 DiagnosticHandlerFunction DiagnosticHandler,
4604 bool ShouldLazyLoadMetadata = false) {
4605 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4607 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4608 M->setMaterializer(R);
4610 auto cleanupOnError = [&](std::error_code EC) {
4611 R->releaseBuffer(); // Never take ownership on error.
4612 delete M; // Also deletes R.
4616 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4617 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4618 return cleanupOnError(EC);
4620 if (!WillMaterializeAll)
4621 // Resolve forward references from blockaddresses.
4622 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4623 return cleanupOnError(EC);
4625 Buffer.release(); // The BitcodeReader owns it now.
4630 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4631 LLVMContext &Context,
4632 DiagnosticHandlerFunction DiagnosticHandler,
4633 bool ShouldLazyLoadMetadata) {
4634 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4635 DiagnosticHandler, ShouldLazyLoadMetadata);
4638 ErrorOr<std::unique_ptr<Module>>
4639 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4640 LLVMContext &Context,
4641 DiagnosticHandlerFunction DiagnosticHandler) {
4642 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4643 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4644 M->setMaterializer(R);
4645 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4647 return std::move(M);
4651 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4652 DiagnosticHandlerFunction DiagnosticHandler) {
4653 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4654 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4655 std::move(Buf), Context, true, DiagnosticHandler);
4658 Module *M = ModuleOrErr.get();
4659 // Read in the entire module, and destroy the BitcodeReader.
4660 if (std::error_code EC = M->materializeAllPermanently()) {
4665 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4666 // written. We must defer until the Module has been fully materialized.
4672 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4673 DiagnosticHandlerFunction DiagnosticHandler) {
4674 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4675 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4677 ErrorOr<std::string> Triple = R->parseTriple();
4678 if (Triple.getError())
4680 return Triple.get();