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/FunctionInfo.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/DataStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
42 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
45 class BitcodeReaderValueList {
46 std::vector<WeakVH> ValuePtrs;
48 /// As we resolve forward-referenced constants, we add information about them
49 /// to this vector. This allows us to resolve them in bulk instead of
50 /// resolving each reference at a time. See the code in
51 /// ResolveConstantForwardRefs for more information about this.
53 /// The key of this vector is the placeholder constant, the value is the slot
54 /// number that holds the resolved value.
55 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
56 ResolveConstantsTy ResolveConstants;
59 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
60 ~BitcodeReaderValueList() {
61 assert(ResolveConstants.empty() && "Constants not resolved?");
64 // vector compatibility methods
65 unsigned size() const { return ValuePtrs.size(); }
66 void resize(unsigned N) { ValuePtrs.resize(N); }
67 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
70 assert(ResolveConstants.empty() && "Constants not resolved?");
74 Value *operator[](unsigned i) const {
75 assert(i < ValuePtrs.size());
79 Value *back() const { return ValuePtrs.back(); }
80 void pop_back() { ValuePtrs.pop_back(); }
81 bool empty() const { return ValuePtrs.empty(); }
82 void shrinkTo(unsigned N) {
83 assert(N <= size() && "Invalid shrinkTo request!");
87 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
88 Value *getValueFwdRef(unsigned Idx, Type *Ty);
90 void assignValue(Value *V, unsigned Idx);
92 /// Once all constants are read, this method bulk resolves any forward
94 void resolveConstantForwardRefs();
97 class BitcodeReaderMetadataList {
102 std::vector<TrackingMDRef> MetadataPtrs;
104 LLVMContext &Context;
106 BitcodeReaderMetadataList(LLVMContext &C)
107 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
109 // vector compatibility methods
110 unsigned size() const { return MetadataPtrs.size(); }
111 void resize(unsigned N) { MetadataPtrs.resize(N); }
112 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
113 void clear() { MetadataPtrs.clear(); }
114 Metadata *back() const { return MetadataPtrs.back(); }
115 void pop_back() { MetadataPtrs.pop_back(); }
116 bool empty() const { return MetadataPtrs.empty(); }
118 Metadata *operator[](unsigned i) const {
119 assert(i < MetadataPtrs.size());
120 return MetadataPtrs[i];
123 void shrinkTo(unsigned N) {
124 assert(N <= size() && "Invalid shrinkTo request!");
125 MetadataPtrs.resize(N);
128 Metadata *getValueFwdRef(unsigned Idx);
129 void assignValue(Metadata *MD, unsigned Idx);
130 void tryToResolveCycles();
133 class BitcodeReader : public GVMaterializer {
134 LLVMContext &Context;
135 Module *TheModule = nullptr;
136 std::unique_ptr<MemoryBuffer> Buffer;
137 std::unique_ptr<BitstreamReader> StreamFile;
138 BitstreamCursor Stream;
139 // Next offset to start scanning for lazy parsing of function bodies.
140 uint64_t NextUnreadBit = 0;
141 // Last function offset found in the VST.
142 uint64_t LastFunctionBlockBit = 0;
143 bool SeenValueSymbolTable = false;
144 uint64_t VSTOffset = 0;
145 // Contains an arbitrary and optional string identifying the bitcode producer
146 std::string ProducerIdentification;
147 // Number of module level metadata records specified by the
148 // MODULE_CODE_METADATA_VALUES record.
149 unsigned NumModuleMDs = 0;
150 // Support older bitcode without the MODULE_CODE_METADATA_VALUES record.
151 bool SeenModuleValuesRecord = false;
153 std::vector<Type*> TypeList;
154 BitcodeReaderValueList ValueList;
155 BitcodeReaderMetadataList MetadataList;
156 std::vector<Comdat *> ComdatList;
157 SmallVector<Instruction *, 64> InstructionList;
159 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
160 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
161 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
162 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
163 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
165 SmallVector<Instruction*, 64> InstsWithTBAATag;
167 /// The set of attributes by index. Index zero in the file is for null, and
168 /// is thus not represented here. As such all indices are off by one.
169 std::vector<AttributeSet> MAttributes;
171 /// The set of attribute groups.
172 std::map<unsigned, AttributeSet> MAttributeGroups;
174 /// While parsing a function body, this is a list of the basic blocks for the
176 std::vector<BasicBlock*> FunctionBBs;
178 // When reading the module header, this list is populated with functions that
179 // have bodies later in the file.
180 std::vector<Function*> FunctionsWithBodies;
182 // When intrinsic functions are encountered which require upgrading they are
183 // stored here with their replacement function.
184 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
185 UpgradedIntrinsicMap UpgradedIntrinsics;
187 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
188 DenseMap<unsigned, unsigned> MDKindMap;
190 // Several operations happen after the module header has been read, but
191 // before function bodies are processed. This keeps track of whether
192 // we've done this yet.
193 bool SeenFirstFunctionBody = false;
195 /// When function bodies are initially scanned, this map contains info about
196 /// where to find deferred function body in the stream.
197 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
199 /// When Metadata block is initially scanned when parsing the module, we may
200 /// choose to defer parsing of the metadata. This vector contains info about
201 /// which Metadata blocks are deferred.
202 std::vector<uint64_t> DeferredMetadataInfo;
204 /// These are basic blocks forward-referenced by block addresses. They are
205 /// inserted lazily into functions when they're loaded. The basic block ID is
206 /// its index into the vector.
207 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
208 std::deque<Function *> BasicBlockFwdRefQueue;
210 /// Indicates that we are using a new encoding for instruction operands where
211 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
212 /// instruction number, for a more compact encoding. Some instruction
213 /// operands are not relative to the instruction ID: basic block numbers, and
214 /// types. Once the old style function blocks have been phased out, we would
215 /// not need this flag.
216 bool UseRelativeIDs = false;
218 /// True if all functions will be materialized, negating the need to process
219 /// (e.g.) blockaddress forward references.
220 bool WillMaterializeAllForwardRefs = false;
222 /// True if any Metadata block has been materialized.
223 bool IsMetadataMaterialized = false;
225 bool StripDebugInfo = false;
227 /// Functions that need to be matched with subprograms when upgrading old
229 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
231 std::vector<std::string> BundleTags;
234 std::error_code error(BitcodeError E, const Twine &Message);
235 std::error_code error(BitcodeError E);
236 std::error_code error(const Twine &Message);
238 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
239 BitcodeReader(LLVMContext &Context);
240 ~BitcodeReader() override { freeState(); }
242 std::error_code materializeForwardReferencedFunctions();
246 void releaseBuffer();
248 std::error_code materialize(GlobalValue *GV) override;
249 std::error_code materializeModule() override;
250 std::vector<StructType *> getIdentifiedStructTypes() const override;
252 /// \brief Main interface to parsing a bitcode buffer.
253 /// \returns true if an error occurred.
254 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
256 bool ShouldLazyLoadMetadata = false);
258 /// \brief Cheap mechanism to just extract module triple
259 /// \returns true if an error occurred.
260 ErrorOr<std::string> parseTriple();
262 /// Cheap mechanism to just extract the identification block out of bitcode.
263 ErrorOr<std::string> parseIdentificationBlock();
265 static uint64_t decodeSignRotatedValue(uint64_t V);
267 /// Materialize any deferred Metadata block.
268 std::error_code materializeMetadata() override;
270 void setStripDebugInfo() override;
272 /// Save the mapping between the metadata values and the corresponding
273 /// value id that were recorded in the MetadataList during parsing. If
274 /// OnlyTempMD is true, then only record those entries that are still
275 /// temporary metadata. This interface is used when metadata linking is
276 /// performed as a postpass, such as during function importing.
277 void saveMetadataList(DenseMap<const Metadata *, unsigned> &MetadataToIDs,
278 bool OnlyTempMD) override;
281 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
282 // ProducerIdentification data member, and do some basic enforcement on the
283 // "epoch" encoded in the bitcode.
284 std::error_code parseBitcodeVersion();
286 std::vector<StructType *> IdentifiedStructTypes;
287 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
288 StructType *createIdentifiedStructType(LLVMContext &Context);
290 Type *getTypeByID(unsigned ID);
291 Value *getFnValueByID(unsigned ID, Type *Ty) {
292 if (Ty && Ty->isMetadataTy())
293 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
294 return ValueList.getValueFwdRef(ID, Ty);
296 Metadata *getFnMetadataByID(unsigned ID) {
297 return MetadataList.getValueFwdRef(ID);
299 BasicBlock *getBasicBlock(unsigned ID) const {
300 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
301 return FunctionBBs[ID];
303 AttributeSet getAttributes(unsigned i) const {
304 if (i-1 < MAttributes.size())
305 return MAttributes[i-1];
306 return AttributeSet();
309 /// Read a value/type pair out of the specified record from slot 'Slot'.
310 /// Increment Slot past the number of slots used in the record. Return true on
312 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
313 unsigned InstNum, Value *&ResVal) {
314 if (Slot == Record.size()) return true;
315 unsigned ValNo = (unsigned)Record[Slot++];
316 // Adjust the ValNo, if it was encoded relative to the InstNum.
318 ValNo = InstNum - ValNo;
319 if (ValNo < InstNum) {
320 // If this is not a forward reference, just return the value we already
322 ResVal = getFnValueByID(ValNo, nullptr);
323 return ResVal == nullptr;
325 if (Slot == Record.size())
328 unsigned TypeNo = (unsigned)Record[Slot++];
329 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
330 return ResVal == nullptr;
333 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
334 /// past the number of slots used by the value in the record. Return true if
335 /// there is an error.
336 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
337 unsigned InstNum, Type *Ty, Value *&ResVal) {
338 if (getValue(Record, Slot, InstNum, Ty, ResVal))
340 // All values currently take a single record slot.
345 /// Like popValue, but does not increment the Slot number.
346 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
347 unsigned InstNum, Type *Ty, Value *&ResVal) {
348 ResVal = getValue(Record, Slot, InstNum, Ty);
349 return ResVal == nullptr;
352 /// Version of getValue that returns ResVal directly, or 0 if there is an
354 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
355 unsigned InstNum, Type *Ty) {
356 if (Slot == Record.size()) return nullptr;
357 unsigned ValNo = (unsigned)Record[Slot];
358 // Adjust the ValNo, if it was encoded relative to the InstNum.
360 ValNo = InstNum - ValNo;
361 return getFnValueByID(ValNo, Ty);
364 /// Like getValue, but decodes signed VBRs.
365 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
366 unsigned InstNum, Type *Ty) {
367 if (Slot == Record.size()) return nullptr;
368 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
369 // Adjust the ValNo, if it was encoded relative to the InstNum.
371 ValNo = InstNum - ValNo;
372 return getFnValueByID(ValNo, Ty);
375 /// Converts alignment exponent (i.e. power of two (or zero)) to the
376 /// corresponding alignment to use. If alignment is too large, returns
377 /// a corresponding error code.
378 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
379 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
380 std::error_code parseModule(uint64_t ResumeBit,
381 bool ShouldLazyLoadMetadata = false);
382 std::error_code parseAttributeBlock();
383 std::error_code parseAttributeGroupBlock();
384 std::error_code parseTypeTable();
385 std::error_code parseTypeTableBody();
386 std::error_code parseOperandBundleTags();
388 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
389 unsigned NameIndex, Triple &TT);
390 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
391 std::error_code parseConstants();
392 std::error_code rememberAndSkipFunctionBodies();
393 std::error_code rememberAndSkipFunctionBody();
394 /// Save the positions of the Metadata blocks and skip parsing the blocks.
395 std::error_code rememberAndSkipMetadata();
396 std::error_code parseFunctionBody(Function *F);
397 std::error_code globalCleanup();
398 std::error_code resolveGlobalAndAliasInits();
399 std::error_code parseMetadata(bool ModuleLevel = false);
400 std::error_code parseMetadataKinds();
401 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
402 std::error_code parseMetadataAttachment(Function &F);
403 ErrorOr<std::string> parseModuleTriple();
404 std::error_code parseUseLists();
405 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
406 std::error_code initStreamFromBuffer();
407 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
408 std::error_code findFunctionInStream(
410 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
413 /// Class to manage reading and parsing function summary index bitcode
415 class FunctionIndexBitcodeReader {
416 DiagnosticHandlerFunction DiagnosticHandler;
418 /// Eventually points to the function index built during parsing.
419 FunctionInfoIndex *TheIndex = nullptr;
421 std::unique_ptr<MemoryBuffer> Buffer;
422 std::unique_ptr<BitstreamReader> StreamFile;
423 BitstreamCursor Stream;
425 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
427 /// If false, the summary section is fully parsed into the index during
428 /// the initial parse. Otherwise, if true, the caller is expected to
429 /// invoke \a readFunctionSummary for each summary needed, and the summary
430 /// section is thus parsed lazily.
433 /// Used to indicate whether caller only wants to check for the presence
434 /// of the function summary bitcode section. All blocks are skipped,
435 /// but the SeenFuncSummary boolean is set.
436 bool CheckFuncSummaryPresenceOnly = false;
438 /// Indicates whether we have encountered a function summary section
439 /// yet during parsing, used when checking if file contains function
441 bool SeenFuncSummary = false;
443 /// \brief Map populated during function summary section parsing, and
444 /// consumed during ValueSymbolTable parsing.
446 /// Used to correlate summary records with VST entries. For the per-module
447 /// index this maps the ValueID to the parsed function summary, and
448 /// for the combined index this maps the summary record's bitcode
449 /// offset to the function summary (since in the combined index the
450 /// VST records do not hold value IDs but rather hold the function
451 /// summary record offset).
452 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
454 /// Map populated during module path string table parsing, from the
455 /// module ID to a string reference owned by the index's module
456 /// path string table, used to correlate with combined index function
458 DenseMap<uint64_t, StringRef> ModuleIdMap;
461 std::error_code error(BitcodeError E, const Twine &Message);
462 std::error_code error(BitcodeError E);
463 std::error_code error(const Twine &Message);
465 FunctionIndexBitcodeReader(MemoryBuffer *Buffer,
466 DiagnosticHandlerFunction DiagnosticHandler,
468 bool CheckFuncSummaryPresenceOnly = false);
469 FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler,
471 bool CheckFuncSummaryPresenceOnly = false);
472 ~FunctionIndexBitcodeReader() { freeState(); }
476 void releaseBuffer();
478 /// Check if the parser has encountered a function summary section.
479 bool foundFuncSummary() { return SeenFuncSummary; }
481 /// \brief Main interface to parsing a bitcode buffer.
482 /// \returns true if an error occurred.
483 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
484 FunctionInfoIndex *I);
486 /// \brief Interface for parsing a function summary lazily.
487 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
488 FunctionInfoIndex *I,
489 size_t FunctionSummaryOffset);
492 std::error_code parseModule();
493 std::error_code parseValueSymbolTable();
494 std::error_code parseEntireSummary();
495 std::error_code parseModuleStringTable();
496 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
497 std::error_code initStreamFromBuffer();
498 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
502 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
503 DiagnosticSeverity Severity,
505 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
507 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
509 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
510 std::error_code EC, const Twine &Message) {
511 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
512 DiagnosticHandler(DI);
516 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
517 std::error_code EC) {
518 return error(DiagnosticHandler, EC, EC.message());
521 static std::error_code error(LLVMContext &Context, std::error_code EC,
522 const Twine &Message) {
523 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
527 static std::error_code error(LLVMContext &Context, std::error_code EC) {
528 return error(Context, EC, EC.message());
531 static std::error_code error(LLVMContext &Context, const Twine &Message) {
532 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
536 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
537 if (!ProducerIdentification.empty()) {
538 return ::error(Context, make_error_code(E),
539 Message + " (Producer: '" + ProducerIdentification +
540 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
542 return ::error(Context, make_error_code(E), Message);
545 std::error_code BitcodeReader::error(const Twine &Message) {
546 if (!ProducerIdentification.empty()) {
547 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
548 Message + " (Producer: '" + ProducerIdentification +
549 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
551 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
555 std::error_code BitcodeReader::error(BitcodeError E) {
556 return ::error(Context, make_error_code(E));
559 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
560 : Context(Context), Buffer(Buffer), ValueList(Context),
561 MetadataList(Context) {}
563 BitcodeReader::BitcodeReader(LLVMContext &Context)
564 : Context(Context), Buffer(nullptr), ValueList(Context),
565 MetadataList(Context) {}
567 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
568 if (WillMaterializeAllForwardRefs)
569 return std::error_code();
571 // Prevent recursion.
572 WillMaterializeAllForwardRefs = true;
574 while (!BasicBlockFwdRefQueue.empty()) {
575 Function *F = BasicBlockFwdRefQueue.front();
576 BasicBlockFwdRefQueue.pop_front();
577 assert(F && "Expected valid function");
578 if (!BasicBlockFwdRefs.count(F))
579 // Already materialized.
582 // Check for a function that isn't materializable to prevent an infinite
583 // loop. When parsing a blockaddress stored in a global variable, there
584 // isn't a trivial way to check if a function will have a body without a
585 // linear search through FunctionsWithBodies, so just check it here.
586 if (!F->isMaterializable())
587 return error("Never resolved function from blockaddress");
589 // Try to materialize F.
590 if (std::error_code EC = materialize(F))
593 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
596 WillMaterializeAllForwardRefs = false;
597 return std::error_code();
600 void BitcodeReader::freeState() {
602 std::vector<Type*>().swap(TypeList);
604 MetadataList.clear();
605 std::vector<Comdat *>().swap(ComdatList);
607 std::vector<AttributeSet>().swap(MAttributes);
608 std::vector<BasicBlock*>().swap(FunctionBBs);
609 std::vector<Function*>().swap(FunctionsWithBodies);
610 DeferredFunctionInfo.clear();
611 DeferredMetadataInfo.clear();
614 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
615 BasicBlockFwdRefQueue.clear();
618 //===----------------------------------------------------------------------===//
619 // Helper functions to implement forward reference resolution, etc.
620 //===----------------------------------------------------------------------===//
622 /// Convert a string from a record into an std::string, return true on failure.
623 template <typename StrTy>
624 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
626 if (Idx > Record.size())
629 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
630 Result += (char)Record[i];
634 static bool hasImplicitComdat(size_t Val) {
638 case 1: // Old WeakAnyLinkage
639 case 4: // Old LinkOnceAnyLinkage
640 case 10: // Old WeakODRLinkage
641 case 11: // Old LinkOnceODRLinkage
646 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
648 default: // Map unknown/new linkages to external
650 return GlobalValue::ExternalLinkage;
652 return GlobalValue::AppendingLinkage;
654 return GlobalValue::InternalLinkage;
656 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
658 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
660 return GlobalValue::ExternalWeakLinkage;
662 return GlobalValue::CommonLinkage;
664 return GlobalValue::PrivateLinkage;
666 return GlobalValue::AvailableExternallyLinkage;
668 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
670 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
672 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
673 case 1: // Old value with implicit comdat.
675 return GlobalValue::WeakAnyLinkage;
676 case 10: // Old value with implicit comdat.
678 return GlobalValue::WeakODRLinkage;
679 case 4: // Old value with implicit comdat.
681 return GlobalValue::LinkOnceAnyLinkage;
682 case 11: // Old value with implicit comdat.
684 return GlobalValue::LinkOnceODRLinkage;
688 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
690 default: // Map unknown visibilities to default.
691 case 0: return GlobalValue::DefaultVisibility;
692 case 1: return GlobalValue::HiddenVisibility;
693 case 2: return GlobalValue::ProtectedVisibility;
697 static GlobalValue::DLLStorageClassTypes
698 getDecodedDLLStorageClass(unsigned Val) {
700 default: // Map unknown values to default.
701 case 0: return GlobalValue::DefaultStorageClass;
702 case 1: return GlobalValue::DLLImportStorageClass;
703 case 2: return GlobalValue::DLLExportStorageClass;
707 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
709 case 0: return GlobalVariable::NotThreadLocal;
710 default: // Map unknown non-zero value to general dynamic.
711 case 1: return GlobalVariable::GeneralDynamicTLSModel;
712 case 2: return GlobalVariable::LocalDynamicTLSModel;
713 case 3: return GlobalVariable::InitialExecTLSModel;
714 case 4: return GlobalVariable::LocalExecTLSModel;
718 static int getDecodedCastOpcode(unsigned Val) {
721 case bitc::CAST_TRUNC : return Instruction::Trunc;
722 case bitc::CAST_ZEXT : return Instruction::ZExt;
723 case bitc::CAST_SEXT : return Instruction::SExt;
724 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
725 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
726 case bitc::CAST_UITOFP : return Instruction::UIToFP;
727 case bitc::CAST_SITOFP : return Instruction::SIToFP;
728 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
729 case bitc::CAST_FPEXT : return Instruction::FPExt;
730 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
731 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
732 case bitc::CAST_BITCAST : return Instruction::BitCast;
733 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
737 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
738 bool IsFP = Ty->isFPOrFPVectorTy();
739 // BinOps are only valid for int/fp or vector of int/fp types
740 if (!IsFP && !Ty->isIntOrIntVectorTy())
746 case bitc::BINOP_ADD:
747 return IsFP ? Instruction::FAdd : Instruction::Add;
748 case bitc::BINOP_SUB:
749 return IsFP ? Instruction::FSub : Instruction::Sub;
750 case bitc::BINOP_MUL:
751 return IsFP ? Instruction::FMul : Instruction::Mul;
752 case bitc::BINOP_UDIV:
753 return IsFP ? -1 : Instruction::UDiv;
754 case bitc::BINOP_SDIV:
755 return IsFP ? Instruction::FDiv : Instruction::SDiv;
756 case bitc::BINOP_UREM:
757 return IsFP ? -1 : Instruction::URem;
758 case bitc::BINOP_SREM:
759 return IsFP ? Instruction::FRem : Instruction::SRem;
760 case bitc::BINOP_SHL:
761 return IsFP ? -1 : Instruction::Shl;
762 case bitc::BINOP_LSHR:
763 return IsFP ? -1 : Instruction::LShr;
764 case bitc::BINOP_ASHR:
765 return IsFP ? -1 : Instruction::AShr;
766 case bitc::BINOP_AND:
767 return IsFP ? -1 : Instruction::And;
769 return IsFP ? -1 : Instruction::Or;
770 case bitc::BINOP_XOR:
771 return IsFP ? -1 : Instruction::Xor;
775 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
777 default: return AtomicRMWInst::BAD_BINOP;
778 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
779 case bitc::RMW_ADD: return AtomicRMWInst::Add;
780 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
781 case bitc::RMW_AND: return AtomicRMWInst::And;
782 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
783 case bitc::RMW_OR: return AtomicRMWInst::Or;
784 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
785 case bitc::RMW_MAX: return AtomicRMWInst::Max;
786 case bitc::RMW_MIN: return AtomicRMWInst::Min;
787 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
788 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
792 static AtomicOrdering getDecodedOrdering(unsigned Val) {
794 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
795 case bitc::ORDERING_UNORDERED: return Unordered;
796 case bitc::ORDERING_MONOTONIC: return Monotonic;
797 case bitc::ORDERING_ACQUIRE: return Acquire;
798 case bitc::ORDERING_RELEASE: return Release;
799 case bitc::ORDERING_ACQREL: return AcquireRelease;
800 default: // Map unknown orderings to sequentially-consistent.
801 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
805 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
807 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
808 default: // Map unknown scopes to cross-thread.
809 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
813 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
815 default: // Map unknown selection kinds to any.
816 case bitc::COMDAT_SELECTION_KIND_ANY:
818 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
819 return Comdat::ExactMatch;
820 case bitc::COMDAT_SELECTION_KIND_LARGEST:
821 return Comdat::Largest;
822 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
823 return Comdat::NoDuplicates;
824 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
825 return Comdat::SameSize;
829 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
831 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
832 FMF.setUnsafeAlgebra();
833 if (0 != (Val & FastMathFlags::NoNaNs))
835 if (0 != (Val & FastMathFlags::NoInfs))
837 if (0 != (Val & FastMathFlags::NoSignedZeros))
838 FMF.setNoSignedZeros();
839 if (0 != (Val & FastMathFlags::AllowReciprocal))
840 FMF.setAllowReciprocal();
844 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
846 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
847 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
853 /// \brief A class for maintaining the slot number definition
854 /// as a placeholder for the actual definition for forward constants defs.
855 class ConstantPlaceHolder : public ConstantExpr {
856 void operator=(const ConstantPlaceHolder &) = delete;
859 // allocate space for exactly one operand
860 void *operator new(size_t s) { return User::operator new(s, 1); }
861 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
862 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
863 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
866 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
867 static bool classof(const Value *V) {
868 return isa<ConstantExpr>(V) &&
869 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
872 /// Provide fast operand accessors
873 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
877 // FIXME: can we inherit this from ConstantExpr?
879 struct OperandTraits<ConstantPlaceHolder> :
880 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
882 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
885 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
894 WeakVH &OldV = ValuePtrs[Idx];
900 // Handle constants and non-constants (e.g. instrs) differently for
902 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
903 ResolveConstants.push_back(std::make_pair(PHC, Idx));
906 // If there was a forward reference to this value, replace it.
907 Value *PrevVal = OldV;
908 OldV->replaceAllUsesWith(V);
916 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
921 if (Value *V = ValuePtrs[Idx]) {
922 if (Ty != V->getType())
923 report_fatal_error("Type mismatch in constant table!");
924 return cast<Constant>(V);
927 // Create and return a placeholder, which will later be RAUW'd.
928 Constant *C = new ConstantPlaceHolder(Ty, Context);
933 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
934 // Bail out for a clearly invalid value. This would make us call resize(0)
941 if (Value *V = ValuePtrs[Idx]) {
942 // If the types don't match, it's invalid.
943 if (Ty && Ty != V->getType())
948 // No type specified, must be invalid reference.
949 if (!Ty) return nullptr;
951 // Create and return a placeholder, which will later be RAUW'd.
952 Value *V = new Argument(Ty);
957 /// Once all constants are read, this method bulk resolves any forward
958 /// references. The idea behind this is that we sometimes get constants (such
959 /// as large arrays) which reference *many* forward ref constants. Replacing
960 /// each of these causes a lot of thrashing when building/reuniquing the
961 /// constant. Instead of doing this, we look at all the uses and rewrite all
962 /// the place holders at once for any constant that uses a placeholder.
963 void BitcodeReaderValueList::resolveConstantForwardRefs() {
964 // Sort the values by-pointer so that they are efficient to look up with a
966 std::sort(ResolveConstants.begin(), ResolveConstants.end());
968 SmallVector<Constant*, 64> NewOps;
970 while (!ResolveConstants.empty()) {
971 Value *RealVal = operator[](ResolveConstants.back().second);
972 Constant *Placeholder = ResolveConstants.back().first;
973 ResolveConstants.pop_back();
975 // Loop over all users of the placeholder, updating them to reference the
976 // new value. If they reference more than one placeholder, update them all
978 while (!Placeholder->use_empty()) {
979 auto UI = Placeholder->user_begin();
982 // If the using object isn't uniqued, just update the operands. This
983 // handles instructions and initializers for global variables.
984 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
985 UI.getUse().set(RealVal);
989 // Otherwise, we have a constant that uses the placeholder. Replace that
990 // constant with a new constant that has *all* placeholder uses updated.
991 Constant *UserC = cast<Constant>(U);
992 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
995 if (!isa<ConstantPlaceHolder>(*I)) {
996 // Not a placeholder reference.
998 } else if (*I == Placeholder) {
999 // Common case is that it just references this one placeholder.
1002 // Otherwise, look up the placeholder in ResolveConstants.
1003 ResolveConstantsTy::iterator It =
1004 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1005 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1007 assert(It != ResolveConstants.end() && It->first == *I);
1008 NewOp = operator[](It->second);
1011 NewOps.push_back(cast<Constant>(NewOp));
1014 // Make the new constant.
1016 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1017 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1018 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1019 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1020 } else if (isa<ConstantVector>(UserC)) {
1021 NewC = ConstantVector::get(NewOps);
1023 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1024 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1027 UserC->replaceAllUsesWith(NewC);
1028 UserC->destroyConstant();
1032 // Update all ValueHandles, they should be the only users at this point.
1033 Placeholder->replaceAllUsesWith(RealVal);
1038 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
1039 if (Idx == size()) {
1047 TrackingMDRef &OldMD = MetadataPtrs[Idx];
1053 // If there was a forward reference to this value, replace it.
1054 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1055 PrevMD->replaceAllUsesWith(MD);
1059 Metadata *BitcodeReaderMetadataList::getValueFwdRef(unsigned Idx) {
1063 if (Metadata *MD = MetadataPtrs[Idx])
1066 // Track forward refs to be resolved later.
1068 MinFwdRef = std::min(MinFwdRef, Idx);
1069 MaxFwdRef = std::max(MaxFwdRef, Idx);
1072 MinFwdRef = MaxFwdRef = Idx;
1076 // Create and return a placeholder, which will later be RAUW'd.
1077 Metadata *MD = MDNode::getTemporary(Context, None).release();
1078 MetadataPtrs[Idx].reset(MD);
1082 void BitcodeReaderMetadataList::tryToResolveCycles() {
1088 // Still forward references... can't resolve cycles.
1091 // Resolve any cycles.
1092 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1093 auto &MD = MetadataPtrs[I];
1094 auto *N = dyn_cast_or_null<MDNode>(MD);
1098 assert(!N->isTemporary() && "Unexpected forward reference");
1102 // Make sure we return early again until there's another forward ref.
1106 Type *BitcodeReader::getTypeByID(unsigned ID) {
1107 // The type table size is always specified correctly.
1108 if (ID >= TypeList.size())
1111 if (Type *Ty = TypeList[ID])
1114 // If we have a forward reference, the only possible case is when it is to a
1115 // named struct. Just create a placeholder for now.
1116 return TypeList[ID] = createIdentifiedStructType(Context);
1119 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1121 auto *Ret = StructType::create(Context, Name);
1122 IdentifiedStructTypes.push_back(Ret);
1126 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1127 auto *Ret = StructType::create(Context);
1128 IdentifiedStructTypes.push_back(Ret);
1133 //===----------------------------------------------------------------------===//
1134 // Functions for parsing blocks from the bitcode file
1135 //===----------------------------------------------------------------------===//
1138 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1139 /// been decoded from the given integer. This function must stay in sync with
1140 /// 'encodeLLVMAttributesForBitcode'.
1141 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1142 uint64_t EncodedAttrs) {
1143 // FIXME: Remove in 4.0.
1145 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1146 // the bits above 31 down by 11 bits.
1147 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1148 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1149 "Alignment must be a power of two.");
1152 B.addAlignmentAttr(Alignment);
1153 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1154 (EncodedAttrs & 0xffff));
1157 std::error_code BitcodeReader::parseAttributeBlock() {
1158 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1159 return error("Invalid record");
1161 if (!MAttributes.empty())
1162 return error("Invalid multiple blocks");
1164 SmallVector<uint64_t, 64> Record;
1166 SmallVector<AttributeSet, 8> Attrs;
1168 // Read all the records.
1170 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1172 switch (Entry.Kind) {
1173 case BitstreamEntry::SubBlock: // Handled for us already.
1174 case BitstreamEntry::Error:
1175 return error("Malformed block");
1176 case BitstreamEntry::EndBlock:
1177 return std::error_code();
1178 case BitstreamEntry::Record:
1179 // The interesting case.
1185 switch (Stream.readRecord(Entry.ID, Record)) {
1186 default: // Default behavior: ignore.
1188 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1189 // FIXME: Remove in 4.0.
1190 if (Record.size() & 1)
1191 return error("Invalid record");
1193 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1195 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1196 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1199 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1203 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1204 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1205 Attrs.push_back(MAttributeGroups[Record[i]]);
1207 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1215 // Returns Attribute::None on unrecognized codes.
1216 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1219 return Attribute::None;
1220 case bitc::ATTR_KIND_ALIGNMENT:
1221 return Attribute::Alignment;
1222 case bitc::ATTR_KIND_ALWAYS_INLINE:
1223 return Attribute::AlwaysInline;
1224 case bitc::ATTR_KIND_ARGMEMONLY:
1225 return Attribute::ArgMemOnly;
1226 case bitc::ATTR_KIND_BUILTIN:
1227 return Attribute::Builtin;
1228 case bitc::ATTR_KIND_BY_VAL:
1229 return Attribute::ByVal;
1230 case bitc::ATTR_KIND_IN_ALLOCA:
1231 return Attribute::InAlloca;
1232 case bitc::ATTR_KIND_COLD:
1233 return Attribute::Cold;
1234 case bitc::ATTR_KIND_CONVERGENT:
1235 return Attribute::Convergent;
1236 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1237 return Attribute::InaccessibleMemOnly;
1238 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1239 return Attribute::InaccessibleMemOrArgMemOnly;
1240 case bitc::ATTR_KIND_INLINE_HINT:
1241 return Attribute::InlineHint;
1242 case bitc::ATTR_KIND_IN_REG:
1243 return Attribute::InReg;
1244 case bitc::ATTR_KIND_JUMP_TABLE:
1245 return Attribute::JumpTable;
1246 case bitc::ATTR_KIND_MIN_SIZE:
1247 return Attribute::MinSize;
1248 case bitc::ATTR_KIND_NAKED:
1249 return Attribute::Naked;
1250 case bitc::ATTR_KIND_NEST:
1251 return Attribute::Nest;
1252 case bitc::ATTR_KIND_NO_ALIAS:
1253 return Attribute::NoAlias;
1254 case bitc::ATTR_KIND_NO_BUILTIN:
1255 return Attribute::NoBuiltin;
1256 case bitc::ATTR_KIND_NO_CAPTURE:
1257 return Attribute::NoCapture;
1258 case bitc::ATTR_KIND_NO_DUPLICATE:
1259 return Attribute::NoDuplicate;
1260 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1261 return Attribute::NoImplicitFloat;
1262 case bitc::ATTR_KIND_NO_INLINE:
1263 return Attribute::NoInline;
1264 case bitc::ATTR_KIND_NO_RECURSE:
1265 return Attribute::NoRecurse;
1266 case bitc::ATTR_KIND_NON_LAZY_BIND:
1267 return Attribute::NonLazyBind;
1268 case bitc::ATTR_KIND_NON_NULL:
1269 return Attribute::NonNull;
1270 case bitc::ATTR_KIND_DEREFERENCEABLE:
1271 return Attribute::Dereferenceable;
1272 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1273 return Attribute::DereferenceableOrNull;
1274 case bitc::ATTR_KIND_NO_RED_ZONE:
1275 return Attribute::NoRedZone;
1276 case bitc::ATTR_KIND_NO_RETURN:
1277 return Attribute::NoReturn;
1278 case bitc::ATTR_KIND_NO_UNWIND:
1279 return Attribute::NoUnwind;
1280 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1281 return Attribute::OptimizeForSize;
1282 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1283 return Attribute::OptimizeNone;
1284 case bitc::ATTR_KIND_READ_NONE:
1285 return Attribute::ReadNone;
1286 case bitc::ATTR_KIND_READ_ONLY:
1287 return Attribute::ReadOnly;
1288 case bitc::ATTR_KIND_RETURNED:
1289 return Attribute::Returned;
1290 case bitc::ATTR_KIND_RETURNS_TWICE:
1291 return Attribute::ReturnsTwice;
1292 case bitc::ATTR_KIND_S_EXT:
1293 return Attribute::SExt;
1294 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1295 return Attribute::StackAlignment;
1296 case bitc::ATTR_KIND_STACK_PROTECT:
1297 return Attribute::StackProtect;
1298 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1299 return Attribute::StackProtectReq;
1300 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1301 return Attribute::StackProtectStrong;
1302 case bitc::ATTR_KIND_SAFESTACK:
1303 return Attribute::SafeStack;
1304 case bitc::ATTR_KIND_STRUCT_RET:
1305 return Attribute::StructRet;
1306 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1307 return Attribute::SanitizeAddress;
1308 case bitc::ATTR_KIND_SANITIZE_THREAD:
1309 return Attribute::SanitizeThread;
1310 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1311 return Attribute::SanitizeMemory;
1312 case bitc::ATTR_KIND_UW_TABLE:
1313 return Attribute::UWTable;
1314 case bitc::ATTR_KIND_Z_EXT:
1315 return Attribute::ZExt;
1319 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1320 unsigned &Alignment) {
1321 // Note: Alignment in bitcode files is incremented by 1, so that zero
1322 // can be used for default alignment.
1323 if (Exponent > Value::MaxAlignmentExponent + 1)
1324 return error("Invalid alignment value");
1325 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1326 return std::error_code();
1329 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1330 Attribute::AttrKind *Kind) {
1331 *Kind = getAttrFromCode(Code);
1332 if (*Kind == Attribute::None)
1333 return error(BitcodeError::CorruptedBitcode,
1334 "Unknown attribute kind (" + Twine(Code) + ")");
1335 return std::error_code();
1338 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1339 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1340 return error("Invalid record");
1342 if (!MAttributeGroups.empty())
1343 return error("Invalid multiple blocks");
1345 SmallVector<uint64_t, 64> Record;
1347 // Read all the records.
1349 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1351 switch (Entry.Kind) {
1352 case BitstreamEntry::SubBlock: // Handled for us already.
1353 case BitstreamEntry::Error:
1354 return error("Malformed block");
1355 case BitstreamEntry::EndBlock:
1356 return std::error_code();
1357 case BitstreamEntry::Record:
1358 // The interesting case.
1364 switch (Stream.readRecord(Entry.ID, Record)) {
1365 default: // Default behavior: ignore.
1367 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1368 if (Record.size() < 3)
1369 return error("Invalid record");
1371 uint64_t GrpID = Record[0];
1372 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1375 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1376 if (Record[i] == 0) { // Enum attribute
1377 Attribute::AttrKind Kind;
1378 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1381 B.addAttribute(Kind);
1382 } else if (Record[i] == 1) { // Integer attribute
1383 Attribute::AttrKind Kind;
1384 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1386 if (Kind == Attribute::Alignment)
1387 B.addAlignmentAttr(Record[++i]);
1388 else if (Kind == Attribute::StackAlignment)
1389 B.addStackAlignmentAttr(Record[++i]);
1390 else if (Kind == Attribute::Dereferenceable)
1391 B.addDereferenceableAttr(Record[++i]);
1392 else if (Kind == Attribute::DereferenceableOrNull)
1393 B.addDereferenceableOrNullAttr(Record[++i]);
1394 } else { // String attribute
1395 assert((Record[i] == 3 || Record[i] == 4) &&
1396 "Invalid attribute group entry");
1397 bool HasValue = (Record[i++] == 4);
1398 SmallString<64> KindStr;
1399 SmallString<64> ValStr;
1401 while (Record[i] != 0 && i != e)
1402 KindStr += Record[i++];
1403 assert(Record[i] == 0 && "Kind string not null terminated");
1406 // Has a value associated with it.
1407 ++i; // Skip the '0' that terminates the "kind" string.
1408 while (Record[i] != 0 && i != e)
1409 ValStr += Record[i++];
1410 assert(Record[i] == 0 && "Value string not null terminated");
1413 B.addAttribute(KindStr.str(), ValStr.str());
1417 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1424 std::error_code BitcodeReader::parseTypeTable() {
1425 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1426 return error("Invalid record");
1428 return parseTypeTableBody();
1431 std::error_code BitcodeReader::parseTypeTableBody() {
1432 if (!TypeList.empty())
1433 return error("Invalid multiple blocks");
1435 SmallVector<uint64_t, 64> Record;
1436 unsigned NumRecords = 0;
1438 SmallString<64> TypeName;
1440 // Read all the records for this type table.
1442 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1444 switch (Entry.Kind) {
1445 case BitstreamEntry::SubBlock: // Handled for us already.
1446 case BitstreamEntry::Error:
1447 return error("Malformed block");
1448 case BitstreamEntry::EndBlock:
1449 if (NumRecords != TypeList.size())
1450 return error("Malformed block");
1451 return std::error_code();
1452 case BitstreamEntry::Record:
1453 // The interesting case.
1459 Type *ResultTy = nullptr;
1460 switch (Stream.readRecord(Entry.ID, Record)) {
1462 return error("Invalid value");
1463 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1464 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1465 // type list. This allows us to reserve space.
1466 if (Record.size() < 1)
1467 return error("Invalid record");
1468 TypeList.resize(Record[0]);
1470 case bitc::TYPE_CODE_VOID: // VOID
1471 ResultTy = Type::getVoidTy(Context);
1473 case bitc::TYPE_CODE_HALF: // HALF
1474 ResultTy = Type::getHalfTy(Context);
1476 case bitc::TYPE_CODE_FLOAT: // FLOAT
1477 ResultTy = Type::getFloatTy(Context);
1479 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1480 ResultTy = Type::getDoubleTy(Context);
1482 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1483 ResultTy = Type::getX86_FP80Ty(Context);
1485 case bitc::TYPE_CODE_FP128: // FP128
1486 ResultTy = Type::getFP128Ty(Context);
1488 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1489 ResultTy = Type::getPPC_FP128Ty(Context);
1491 case bitc::TYPE_CODE_LABEL: // LABEL
1492 ResultTy = Type::getLabelTy(Context);
1494 case bitc::TYPE_CODE_METADATA: // METADATA
1495 ResultTy = Type::getMetadataTy(Context);
1497 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1498 ResultTy = Type::getX86_MMXTy(Context);
1500 case bitc::TYPE_CODE_TOKEN: // TOKEN
1501 ResultTy = Type::getTokenTy(Context);
1503 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1504 if (Record.size() < 1)
1505 return error("Invalid record");
1507 uint64_t NumBits = Record[0];
1508 if (NumBits < IntegerType::MIN_INT_BITS ||
1509 NumBits > IntegerType::MAX_INT_BITS)
1510 return error("Bitwidth for integer type out of range");
1511 ResultTy = IntegerType::get(Context, NumBits);
1514 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1515 // [pointee type, address space]
1516 if (Record.size() < 1)
1517 return error("Invalid record");
1518 unsigned AddressSpace = 0;
1519 if (Record.size() == 2)
1520 AddressSpace = Record[1];
1521 ResultTy = getTypeByID(Record[0]);
1523 !PointerType::isValidElementType(ResultTy))
1524 return error("Invalid type");
1525 ResultTy = PointerType::get(ResultTy, AddressSpace);
1528 case bitc::TYPE_CODE_FUNCTION_OLD: {
1529 // FIXME: attrid is dead, remove it in LLVM 4.0
1530 // FUNCTION: [vararg, attrid, retty, paramty x N]
1531 if (Record.size() < 3)
1532 return error("Invalid record");
1533 SmallVector<Type*, 8> ArgTys;
1534 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1535 if (Type *T = getTypeByID(Record[i]))
1536 ArgTys.push_back(T);
1541 ResultTy = getTypeByID(Record[2]);
1542 if (!ResultTy || ArgTys.size() < Record.size()-3)
1543 return error("Invalid type");
1545 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1548 case bitc::TYPE_CODE_FUNCTION: {
1549 // FUNCTION: [vararg, retty, paramty x N]
1550 if (Record.size() < 2)
1551 return error("Invalid record");
1552 SmallVector<Type*, 8> ArgTys;
1553 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1554 if (Type *T = getTypeByID(Record[i])) {
1555 if (!FunctionType::isValidArgumentType(T))
1556 return error("Invalid function argument type");
1557 ArgTys.push_back(T);
1563 ResultTy = getTypeByID(Record[1]);
1564 if (!ResultTy || ArgTys.size() < Record.size()-2)
1565 return error("Invalid type");
1567 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1570 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1571 if (Record.size() < 1)
1572 return error("Invalid record");
1573 SmallVector<Type*, 8> EltTys;
1574 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1575 if (Type *T = getTypeByID(Record[i]))
1576 EltTys.push_back(T);
1580 if (EltTys.size() != Record.size()-1)
1581 return error("Invalid type");
1582 ResultTy = StructType::get(Context, EltTys, Record[0]);
1585 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1586 if (convertToString(Record, 0, TypeName))
1587 return error("Invalid record");
1590 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1591 if (Record.size() < 1)
1592 return error("Invalid record");
1594 if (NumRecords >= TypeList.size())
1595 return error("Invalid TYPE table");
1597 // Check to see if this was forward referenced, if so fill in the temp.
1598 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1600 Res->setName(TypeName);
1601 TypeList[NumRecords] = nullptr;
1602 } else // Otherwise, create a new struct.
1603 Res = createIdentifiedStructType(Context, TypeName);
1606 SmallVector<Type*, 8> EltTys;
1607 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1608 if (Type *T = getTypeByID(Record[i]))
1609 EltTys.push_back(T);
1613 if (EltTys.size() != Record.size()-1)
1614 return error("Invalid record");
1615 Res->setBody(EltTys, Record[0]);
1619 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1620 if (Record.size() != 1)
1621 return error("Invalid record");
1623 if (NumRecords >= TypeList.size())
1624 return error("Invalid TYPE table");
1626 // Check to see if this was forward referenced, if so fill in the temp.
1627 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1629 Res->setName(TypeName);
1630 TypeList[NumRecords] = nullptr;
1631 } else // Otherwise, create a new struct with no body.
1632 Res = createIdentifiedStructType(Context, TypeName);
1637 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1638 if (Record.size() < 2)
1639 return error("Invalid record");
1640 ResultTy = getTypeByID(Record[1]);
1641 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1642 return error("Invalid type");
1643 ResultTy = ArrayType::get(ResultTy, Record[0]);
1645 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1646 if (Record.size() < 2)
1647 return error("Invalid record");
1649 return error("Invalid vector length");
1650 ResultTy = getTypeByID(Record[1]);
1651 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1652 return error("Invalid type");
1653 ResultTy = VectorType::get(ResultTy, Record[0]);
1657 if (NumRecords >= TypeList.size())
1658 return error("Invalid TYPE table");
1659 if (TypeList[NumRecords])
1661 "Invalid TYPE table: Only named structs can be forward referenced");
1662 assert(ResultTy && "Didn't read a type?");
1663 TypeList[NumRecords++] = ResultTy;
1667 std::error_code BitcodeReader::parseOperandBundleTags() {
1668 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1669 return error("Invalid record");
1671 if (!BundleTags.empty())
1672 return error("Invalid multiple blocks");
1674 SmallVector<uint64_t, 64> Record;
1677 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1679 switch (Entry.Kind) {
1680 case BitstreamEntry::SubBlock: // Handled for us already.
1681 case BitstreamEntry::Error:
1682 return error("Malformed block");
1683 case BitstreamEntry::EndBlock:
1684 return std::error_code();
1685 case BitstreamEntry::Record:
1686 // The interesting case.
1690 // Tags are implicitly mapped to integers by their order.
1692 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1693 return error("Invalid record");
1695 // OPERAND_BUNDLE_TAG: [strchr x N]
1696 BundleTags.emplace_back();
1697 if (convertToString(Record, 0, BundleTags.back()))
1698 return error("Invalid record");
1703 /// Associate a value with its name from the given index in the provided record.
1704 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1705 unsigned NameIndex, Triple &TT) {
1706 SmallString<128> ValueName;
1707 if (convertToString(Record, NameIndex, ValueName))
1708 return error("Invalid record");
1709 unsigned ValueID = Record[0];
1710 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1711 return error("Invalid record");
1712 Value *V = ValueList[ValueID];
1714 StringRef NameStr(ValueName.data(), ValueName.size());
1715 if (NameStr.find_first_of(0) != StringRef::npos)
1716 return error("Invalid value name");
1717 V->setName(NameStr);
1718 auto *GO = dyn_cast<GlobalObject>(V);
1720 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1721 if (TT.isOSBinFormatMachO())
1722 GO->setComdat(nullptr);
1724 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1730 /// Parse the value symbol table at either the current parsing location or
1731 /// at the given bit offset if provided.
1732 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1733 uint64_t CurrentBit;
1734 // Pass in the Offset to distinguish between calling for the module-level
1735 // VST (where we want to jump to the VST offset) and the function-level
1736 // VST (where we don't).
1738 // Save the current parsing location so we can jump back at the end
1740 CurrentBit = Stream.GetCurrentBitNo();
1741 Stream.JumpToBit(Offset * 32);
1743 // Do some checking if we are in debug mode.
1744 BitstreamEntry Entry = Stream.advance();
1745 assert(Entry.Kind == BitstreamEntry::SubBlock);
1746 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1748 // In NDEBUG mode ignore the output so we don't get an unused variable
1754 // Compute the delta between the bitcode indices in the VST (the word offset
1755 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1756 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1757 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1758 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1759 // just before entering the VST subblock because: 1) the EnterSubBlock
1760 // changes the AbbrevID width; 2) the VST block is nested within the same
1761 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1762 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1763 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1764 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1765 unsigned FuncBitcodeOffsetDelta =
1766 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1768 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1769 return error("Invalid record");
1771 SmallVector<uint64_t, 64> Record;
1773 Triple TT(TheModule->getTargetTriple());
1775 // Read all the records for this value table.
1776 SmallString<128> ValueName;
1778 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1780 switch (Entry.Kind) {
1781 case BitstreamEntry::SubBlock: // Handled for us already.
1782 case BitstreamEntry::Error:
1783 return error("Malformed block");
1784 case BitstreamEntry::EndBlock:
1786 Stream.JumpToBit(CurrentBit);
1787 return std::error_code();
1788 case BitstreamEntry::Record:
1789 // The interesting case.
1795 switch (Stream.readRecord(Entry.ID, Record)) {
1796 default: // Default behavior: unknown type.
1798 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1799 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1800 if (std::error_code EC = ValOrErr.getError())
1805 case bitc::VST_CODE_FNENTRY: {
1806 // VST_FNENTRY: [valueid, offset, namechar x N]
1807 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1808 if (std::error_code EC = ValOrErr.getError())
1810 Value *V = ValOrErr.get();
1812 auto *GO = dyn_cast<GlobalObject>(V);
1814 // If this is an alias, need to get the actual Function object
1815 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1816 auto *GA = dyn_cast<GlobalAlias>(V);
1818 GO = GA->getBaseObject();
1822 uint64_t FuncWordOffset = Record[1];
1823 Function *F = dyn_cast<Function>(GO);
1825 uint64_t FuncBitOffset = FuncWordOffset * 32;
1826 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1827 // Set the LastFunctionBlockBit to point to the last function block.
1828 // Later when parsing is resumed after function materialization,
1829 // we can simply skip that last function block.
1830 if (FuncBitOffset > LastFunctionBlockBit)
1831 LastFunctionBlockBit = FuncBitOffset;
1834 case bitc::VST_CODE_BBENTRY: {
1835 if (convertToString(Record, 1, ValueName))
1836 return error("Invalid record");
1837 BasicBlock *BB = getBasicBlock(Record[0]);
1839 return error("Invalid record");
1841 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1849 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1851 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1852 if (Record.size() < 2)
1853 return error("Invalid record");
1855 unsigned Kind = Record[0];
1856 SmallString<8> Name(Record.begin() + 1, Record.end());
1858 unsigned NewKind = TheModule->getMDKindID(Name.str());
1859 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1860 return error("Conflicting METADATA_KIND records");
1861 return std::error_code();
1864 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1866 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1867 /// module level metadata.
1868 std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
1869 IsMetadataMaterialized = true;
1870 unsigned NextMetadataNo = MetadataList.size();
1871 if (ModuleLevel && SeenModuleValuesRecord) {
1872 // Now that we are parsing the module level metadata, we want to restart
1873 // the numbering of the MD values, and replace temp MD created earlier
1874 // with their real values. If we saw a METADATA_VALUE record then we
1875 // would have set the MetadataList size to the number specified in that
1876 // record, to support parsing function-level metadata first, and we need
1877 // to reset back to 0 to fill the MetadataList in with the parsed module
1878 // The function-level metadata parsing should have reset the MetadataList
1879 // size back to the value reported by the METADATA_VALUE record, saved in
1881 assert(NumModuleMDs == MetadataList.size() &&
1882 "Expected MetadataList to only contain module level values");
1886 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1887 return error("Invalid record");
1889 SmallVector<uint64_t, 64> Record;
1891 auto getMD = [&](unsigned ID) -> Metadata * {
1892 return MetadataList.getValueFwdRef(ID);
1894 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1896 return getMD(ID - 1);
1899 auto getMDString = [&](unsigned ID) -> MDString *{
1900 // This requires that the ID is not really a forward reference. In
1901 // particular, the MDString must already have been resolved.
1902 return cast_or_null<MDString>(getMDOrNull(ID));
1905 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1906 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1908 // Read all the records.
1910 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1912 switch (Entry.Kind) {
1913 case BitstreamEntry::SubBlock: // Handled for us already.
1914 case BitstreamEntry::Error:
1915 return error("Malformed block");
1916 case BitstreamEntry::EndBlock:
1917 MetadataList.tryToResolveCycles();
1918 assert((!(ModuleLevel && SeenModuleValuesRecord) ||
1919 NumModuleMDs == MetadataList.size()) &&
1920 "Inconsistent bitcode: METADATA_VALUES mismatch");
1921 return std::error_code();
1922 case BitstreamEntry::Record:
1923 // The interesting case.
1929 unsigned Code = Stream.readRecord(Entry.ID, Record);
1930 bool IsDistinct = false;
1932 default: // Default behavior: ignore.
1934 case bitc::METADATA_NAME: {
1935 // Read name of the named metadata.
1936 SmallString<8> Name(Record.begin(), Record.end());
1938 Code = Stream.ReadCode();
1940 unsigned NextBitCode = Stream.readRecord(Code, Record);
1941 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1942 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1944 // Read named metadata elements.
1945 unsigned Size = Record.size();
1946 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1947 for (unsigned i = 0; i != Size; ++i) {
1949 dyn_cast_or_null<MDNode>(MetadataList.getValueFwdRef(Record[i]));
1951 return error("Invalid record");
1952 NMD->addOperand(MD);
1956 case bitc::METADATA_OLD_FN_NODE: {
1957 // FIXME: Remove in 4.0.
1958 // This is a LocalAsMetadata record, the only type of function-local
1960 if (Record.size() % 2 == 1)
1961 return error("Invalid record");
1963 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1964 // to be legal, but there's no upgrade path.
1965 auto dropRecord = [&] {
1966 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
1968 if (Record.size() != 2) {
1973 Type *Ty = getTypeByID(Record[0]);
1974 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1979 MetadataList.assignValue(
1980 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1984 case bitc::METADATA_OLD_NODE: {
1985 // FIXME: Remove in 4.0.
1986 if (Record.size() % 2 == 1)
1987 return error("Invalid record");
1989 unsigned Size = Record.size();
1990 SmallVector<Metadata *, 8> Elts;
1991 for (unsigned i = 0; i != Size; i += 2) {
1992 Type *Ty = getTypeByID(Record[i]);
1994 return error("Invalid record");
1995 if (Ty->isMetadataTy())
1996 Elts.push_back(MetadataList.getValueFwdRef(Record[i + 1]));
1997 else if (!Ty->isVoidTy()) {
1999 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2000 assert(isa<ConstantAsMetadata>(MD) &&
2001 "Expected non-function-local metadata");
2004 Elts.push_back(nullptr);
2006 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
2009 case bitc::METADATA_VALUE: {
2010 if (Record.size() != 2)
2011 return error("Invalid record");
2013 Type *Ty = getTypeByID(Record[0]);
2014 if (Ty->isMetadataTy() || Ty->isVoidTy())
2015 return error("Invalid record");
2017 MetadataList.assignValue(
2018 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2022 case bitc::METADATA_DISTINCT_NODE:
2025 case bitc::METADATA_NODE: {
2026 SmallVector<Metadata *, 8> Elts;
2027 Elts.reserve(Record.size());
2028 for (unsigned ID : Record)
2029 Elts.push_back(ID ? MetadataList.getValueFwdRef(ID - 1) : nullptr);
2030 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2031 : MDNode::get(Context, Elts),
2035 case bitc::METADATA_LOCATION: {
2036 if (Record.size() != 5)
2037 return error("Invalid record");
2039 unsigned Line = Record[1];
2040 unsigned Column = Record[2];
2041 MDNode *Scope = cast<MDNode>(MetadataList.getValueFwdRef(Record[3]));
2042 Metadata *InlinedAt =
2043 Record[4] ? MetadataList.getValueFwdRef(Record[4] - 1) : nullptr;
2044 MetadataList.assignValue(
2045 GET_OR_DISTINCT(DILocation, Record[0],
2046 (Context, Line, Column, Scope, InlinedAt)),
2050 case bitc::METADATA_GENERIC_DEBUG: {
2051 if (Record.size() < 4)
2052 return error("Invalid record");
2054 unsigned Tag = Record[1];
2055 unsigned Version = Record[2];
2057 if (Tag >= 1u << 16 || Version != 0)
2058 return error("Invalid record");
2060 auto *Header = getMDString(Record[3]);
2061 SmallVector<Metadata *, 8> DwarfOps;
2062 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2064 Record[I] ? MetadataList.getValueFwdRef(Record[I] - 1) : nullptr);
2065 MetadataList.assignValue(
2066 GET_OR_DISTINCT(GenericDINode, Record[0],
2067 (Context, Tag, Header, DwarfOps)),
2071 case bitc::METADATA_SUBRANGE: {
2072 if (Record.size() != 3)
2073 return error("Invalid record");
2075 MetadataList.assignValue(
2076 GET_OR_DISTINCT(DISubrange, Record[0],
2077 (Context, Record[1], unrotateSign(Record[2]))),
2081 case bitc::METADATA_ENUMERATOR: {
2082 if (Record.size() != 3)
2083 return error("Invalid record");
2085 MetadataList.assignValue(
2087 DIEnumerator, Record[0],
2088 (Context, unrotateSign(Record[1]), getMDString(Record[2]))),
2092 case bitc::METADATA_BASIC_TYPE: {
2093 if (Record.size() != 6)
2094 return error("Invalid record");
2096 MetadataList.assignValue(
2097 GET_OR_DISTINCT(DIBasicType, Record[0],
2098 (Context, Record[1], getMDString(Record[2]),
2099 Record[3], Record[4], Record[5])),
2103 case bitc::METADATA_DERIVED_TYPE: {
2104 if (Record.size() != 12)
2105 return error("Invalid record");
2107 MetadataList.assignValue(
2108 GET_OR_DISTINCT(DIDerivedType, Record[0],
2109 (Context, Record[1], getMDString(Record[2]),
2110 getMDOrNull(Record[3]), Record[4],
2111 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2112 Record[7], Record[8], Record[9], Record[10],
2113 getMDOrNull(Record[11]))),
2117 case bitc::METADATA_COMPOSITE_TYPE: {
2118 if (Record.size() != 16)
2119 return error("Invalid record");
2121 MetadataList.assignValue(
2122 GET_OR_DISTINCT(DICompositeType, Record[0],
2123 (Context, Record[1], getMDString(Record[2]),
2124 getMDOrNull(Record[3]), Record[4],
2125 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2126 Record[7], Record[8], Record[9], Record[10],
2127 getMDOrNull(Record[11]), Record[12],
2128 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2129 getMDString(Record[15]))),
2133 case bitc::METADATA_SUBROUTINE_TYPE: {
2134 if (Record.size() != 3)
2135 return error("Invalid record");
2137 MetadataList.assignValue(
2138 GET_OR_DISTINCT(DISubroutineType, Record[0],
2139 (Context, Record[1], getMDOrNull(Record[2]))),
2144 case bitc::METADATA_MODULE: {
2145 if (Record.size() != 6)
2146 return error("Invalid record");
2148 MetadataList.assignValue(
2149 GET_OR_DISTINCT(DIModule, Record[0],
2150 (Context, getMDOrNull(Record[1]),
2151 getMDString(Record[2]), getMDString(Record[3]),
2152 getMDString(Record[4]), getMDString(Record[5]))),
2157 case bitc::METADATA_FILE: {
2158 if (Record.size() != 3)
2159 return error("Invalid record");
2161 MetadataList.assignValue(
2162 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2163 getMDString(Record[2]))),
2167 case bitc::METADATA_COMPILE_UNIT: {
2168 if (Record.size() < 14 || Record.size() > 16)
2169 return error("Invalid record");
2171 // Ignore Record[0], which indicates whether this compile unit is
2172 // distinct. It's always distinct.
2173 MetadataList.assignValue(
2174 DICompileUnit::getDistinct(
2175 Context, Record[1], getMDOrNull(Record[2]),
2176 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2177 Record[6], getMDString(Record[7]), Record[8],
2178 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2179 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2180 getMDOrNull(Record[13]),
2181 Record.size() <= 15 ? 0 : getMDOrNull(Record[15]),
2182 Record.size() <= 14 ? 0 : Record[14]),
2186 case bitc::METADATA_SUBPROGRAM: {
2187 if (Record.size() != 18 && Record.size() != 19)
2188 return error("Invalid record");
2190 bool HasFn = Record.size() == 19;
2191 DISubprogram *SP = GET_OR_DISTINCT(
2193 Record[0] || Record[8], // All definitions should be distinct.
2194 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2195 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2196 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2197 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2198 Record[14], getMDOrNull(Record[15 + HasFn]),
2199 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2200 MetadataList.assignValue(SP, NextMetadataNo++);
2202 // Upgrade sp->function mapping to function->sp mapping.
2203 if (HasFn && Record[15]) {
2204 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2205 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2206 if (F->isMaterializable())
2207 // Defer until materialized; unmaterialized functions may not have
2209 FunctionsWithSPs[F] = SP;
2210 else if (!F->empty())
2211 F->setSubprogram(SP);
2216 case bitc::METADATA_LEXICAL_BLOCK: {
2217 if (Record.size() != 5)
2218 return error("Invalid record");
2220 MetadataList.assignValue(
2221 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2222 (Context, getMDOrNull(Record[1]),
2223 getMDOrNull(Record[2]), Record[3], Record[4])),
2227 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2228 if (Record.size() != 4)
2229 return error("Invalid record");
2231 MetadataList.assignValue(
2232 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2233 (Context, getMDOrNull(Record[1]),
2234 getMDOrNull(Record[2]), Record[3])),
2238 case bitc::METADATA_NAMESPACE: {
2239 if (Record.size() != 5)
2240 return error("Invalid record");
2242 MetadataList.assignValue(
2243 GET_OR_DISTINCT(DINamespace, Record[0],
2244 (Context, getMDOrNull(Record[1]),
2245 getMDOrNull(Record[2]), getMDString(Record[3]),
2250 case bitc::METADATA_MACRO: {
2251 if (Record.size() != 5)
2252 return error("Invalid record");
2254 MetadataList.assignValue(
2255 GET_OR_DISTINCT(DIMacro, Record[0],
2256 (Context, Record[1], Record[2],
2257 getMDString(Record[3]), getMDString(Record[4]))),
2261 case bitc::METADATA_MACRO_FILE: {
2262 if (Record.size() != 5)
2263 return error("Invalid record");
2265 MetadataList.assignValue(
2266 GET_OR_DISTINCT(DIMacroFile, Record[0],
2267 (Context, Record[1], Record[2],
2268 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2272 case bitc::METADATA_TEMPLATE_TYPE: {
2273 if (Record.size() != 3)
2274 return error("Invalid record");
2276 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2278 (Context, getMDString(Record[1]),
2279 getMDOrNull(Record[2]))),
2283 case bitc::METADATA_TEMPLATE_VALUE: {
2284 if (Record.size() != 5)
2285 return error("Invalid record");
2287 MetadataList.assignValue(
2288 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2289 (Context, Record[1], getMDString(Record[2]),
2290 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2294 case bitc::METADATA_GLOBAL_VAR: {
2295 if (Record.size() != 11)
2296 return error("Invalid record");
2298 MetadataList.assignValue(
2299 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2300 (Context, getMDOrNull(Record[1]),
2301 getMDString(Record[2]), getMDString(Record[3]),
2302 getMDOrNull(Record[4]), Record[5],
2303 getMDOrNull(Record[6]), Record[7], Record[8],
2304 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2308 case bitc::METADATA_LOCAL_VAR: {
2309 // 10th field is for the obseleted 'inlinedAt:' field.
2310 if (Record.size() < 8 || Record.size() > 10)
2311 return error("Invalid record");
2313 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2314 // DW_TAG_arg_variable.
2315 bool HasTag = Record.size() > 8;
2316 MetadataList.assignValue(
2317 GET_OR_DISTINCT(DILocalVariable, Record[0],
2318 (Context, getMDOrNull(Record[1 + HasTag]),
2319 getMDString(Record[2 + HasTag]),
2320 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2321 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2322 Record[7 + HasTag])),
2326 case bitc::METADATA_EXPRESSION: {
2327 if (Record.size() < 1)
2328 return error("Invalid record");
2330 MetadataList.assignValue(
2331 GET_OR_DISTINCT(DIExpression, Record[0],
2332 (Context, makeArrayRef(Record).slice(1))),
2336 case bitc::METADATA_OBJC_PROPERTY: {
2337 if (Record.size() != 8)
2338 return error("Invalid record");
2340 MetadataList.assignValue(
2341 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2342 (Context, getMDString(Record[1]),
2343 getMDOrNull(Record[2]), Record[3],
2344 getMDString(Record[4]), getMDString(Record[5]),
2345 Record[6], getMDOrNull(Record[7]))),
2349 case bitc::METADATA_IMPORTED_ENTITY: {
2350 if (Record.size() != 6)
2351 return error("Invalid record");
2353 MetadataList.assignValue(
2354 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2355 (Context, Record[1], getMDOrNull(Record[2]),
2356 getMDOrNull(Record[3]), Record[4],
2357 getMDString(Record[5]))),
2361 case bitc::METADATA_STRING: {
2362 std::string String(Record.begin(), Record.end());
2363 llvm::UpgradeMDStringConstant(String);
2364 Metadata *MD = MDString::get(Context, String);
2365 MetadataList.assignValue(MD, NextMetadataNo++);
2368 case bitc::METADATA_KIND: {
2369 // Support older bitcode files that had METADATA_KIND records in a
2370 // block with METADATA_BLOCK_ID.
2371 if (std::error_code EC = parseMetadataKindRecord(Record))
2377 #undef GET_OR_DISTINCT
2380 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2381 std::error_code BitcodeReader::parseMetadataKinds() {
2382 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2383 return error("Invalid record");
2385 SmallVector<uint64_t, 64> Record;
2387 // Read all the records.
2389 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2391 switch (Entry.Kind) {
2392 case BitstreamEntry::SubBlock: // Handled for us already.
2393 case BitstreamEntry::Error:
2394 return error("Malformed block");
2395 case BitstreamEntry::EndBlock:
2396 return std::error_code();
2397 case BitstreamEntry::Record:
2398 // The interesting case.
2404 unsigned Code = Stream.readRecord(Entry.ID, Record);
2406 default: // Default behavior: ignore.
2408 case bitc::METADATA_KIND: {
2409 if (std::error_code EC = parseMetadataKindRecord(Record))
2417 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2419 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2424 // There is no such thing as -0 with integers. "-0" really means MININT.
2428 /// Resolve all of the initializers for global values and aliases that we can.
2429 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2430 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2431 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2432 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2433 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2434 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2436 GlobalInitWorklist.swap(GlobalInits);
2437 AliasInitWorklist.swap(AliasInits);
2438 FunctionPrefixWorklist.swap(FunctionPrefixes);
2439 FunctionPrologueWorklist.swap(FunctionPrologues);
2440 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2442 while (!GlobalInitWorklist.empty()) {
2443 unsigned ValID = GlobalInitWorklist.back().second;
2444 if (ValID >= ValueList.size()) {
2445 // Not ready to resolve this yet, it requires something later in the file.
2446 GlobalInits.push_back(GlobalInitWorklist.back());
2448 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2449 GlobalInitWorklist.back().first->setInitializer(C);
2451 return error("Expected a constant");
2453 GlobalInitWorklist.pop_back();
2456 while (!AliasInitWorklist.empty()) {
2457 unsigned ValID = AliasInitWorklist.back().second;
2458 if (ValID >= ValueList.size()) {
2459 AliasInits.push_back(AliasInitWorklist.back());
2461 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2463 return error("Expected a constant");
2464 GlobalAlias *Alias = AliasInitWorklist.back().first;
2465 if (C->getType() != Alias->getType())
2466 return error("Alias and aliasee types don't match");
2467 Alias->setAliasee(C);
2469 AliasInitWorklist.pop_back();
2472 while (!FunctionPrefixWorklist.empty()) {
2473 unsigned ValID = FunctionPrefixWorklist.back().second;
2474 if (ValID >= ValueList.size()) {
2475 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2477 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2478 FunctionPrefixWorklist.back().first->setPrefixData(C);
2480 return error("Expected a constant");
2482 FunctionPrefixWorklist.pop_back();
2485 while (!FunctionPrologueWorklist.empty()) {
2486 unsigned ValID = FunctionPrologueWorklist.back().second;
2487 if (ValID >= ValueList.size()) {
2488 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2490 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2491 FunctionPrologueWorklist.back().first->setPrologueData(C);
2493 return error("Expected a constant");
2495 FunctionPrologueWorklist.pop_back();
2498 while (!FunctionPersonalityFnWorklist.empty()) {
2499 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2500 if (ValID >= ValueList.size()) {
2501 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2503 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2504 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2506 return error("Expected a constant");
2508 FunctionPersonalityFnWorklist.pop_back();
2511 return std::error_code();
2514 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2515 SmallVector<uint64_t, 8> Words(Vals.size());
2516 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2517 BitcodeReader::decodeSignRotatedValue);
2519 return APInt(TypeBits, Words);
2522 std::error_code BitcodeReader::parseConstants() {
2523 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2524 return error("Invalid record");
2526 SmallVector<uint64_t, 64> Record;
2528 // Read all the records for this value table.
2529 Type *CurTy = Type::getInt32Ty(Context);
2530 unsigned NextCstNo = ValueList.size();
2532 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2534 switch (Entry.Kind) {
2535 case BitstreamEntry::SubBlock: // Handled for us already.
2536 case BitstreamEntry::Error:
2537 return error("Malformed block");
2538 case BitstreamEntry::EndBlock:
2539 if (NextCstNo != ValueList.size())
2540 return error("Invalid ronstant reference");
2542 // Once all the constants have been read, go through and resolve forward
2544 ValueList.resolveConstantForwardRefs();
2545 return std::error_code();
2546 case BitstreamEntry::Record:
2547 // The interesting case.
2554 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2556 default: // Default behavior: unknown constant
2557 case bitc::CST_CODE_UNDEF: // UNDEF
2558 V = UndefValue::get(CurTy);
2560 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2562 return error("Invalid record");
2563 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2564 return error("Invalid record");
2565 CurTy = TypeList[Record[0]];
2566 continue; // Skip the ValueList manipulation.
2567 case bitc::CST_CODE_NULL: // NULL
2568 V = Constant::getNullValue(CurTy);
2570 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2571 if (!CurTy->isIntegerTy() || Record.empty())
2572 return error("Invalid record");
2573 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2575 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2576 if (!CurTy->isIntegerTy() || Record.empty())
2577 return error("Invalid record");
2580 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2581 V = ConstantInt::get(Context, VInt);
2585 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2587 return error("Invalid record");
2588 if (CurTy->isHalfTy())
2589 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2590 APInt(16, (uint16_t)Record[0])));
2591 else if (CurTy->isFloatTy())
2592 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2593 APInt(32, (uint32_t)Record[0])));
2594 else if (CurTy->isDoubleTy())
2595 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2596 APInt(64, Record[0])));
2597 else if (CurTy->isX86_FP80Ty()) {
2598 // Bits are not stored the same way as a normal i80 APInt, compensate.
2599 uint64_t Rearrange[2];
2600 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2601 Rearrange[1] = Record[0] >> 48;
2602 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2603 APInt(80, Rearrange)));
2604 } else if (CurTy->isFP128Ty())
2605 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2606 APInt(128, Record)));
2607 else if (CurTy->isPPC_FP128Ty())
2608 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2609 APInt(128, Record)));
2611 V = UndefValue::get(CurTy);
2615 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2617 return error("Invalid record");
2619 unsigned Size = Record.size();
2620 SmallVector<Constant*, 16> Elts;
2622 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2623 for (unsigned i = 0; i != Size; ++i)
2624 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2625 STy->getElementType(i)));
2626 V = ConstantStruct::get(STy, Elts);
2627 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2628 Type *EltTy = ATy->getElementType();
2629 for (unsigned i = 0; i != Size; ++i)
2630 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2631 V = ConstantArray::get(ATy, Elts);
2632 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2633 Type *EltTy = VTy->getElementType();
2634 for (unsigned i = 0; i != Size; ++i)
2635 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2636 V = ConstantVector::get(Elts);
2638 V = UndefValue::get(CurTy);
2642 case bitc::CST_CODE_STRING: // STRING: [values]
2643 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2645 return error("Invalid record");
2647 SmallString<16> Elts(Record.begin(), Record.end());
2648 V = ConstantDataArray::getString(Context, Elts,
2649 BitCode == bitc::CST_CODE_CSTRING);
2652 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2654 return error("Invalid record");
2656 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2657 if (EltTy->isIntegerTy(8)) {
2658 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2659 if (isa<VectorType>(CurTy))
2660 V = ConstantDataVector::get(Context, Elts);
2662 V = ConstantDataArray::get(Context, Elts);
2663 } else if (EltTy->isIntegerTy(16)) {
2664 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2665 if (isa<VectorType>(CurTy))
2666 V = ConstantDataVector::get(Context, Elts);
2668 V = ConstantDataArray::get(Context, Elts);
2669 } else if (EltTy->isIntegerTy(32)) {
2670 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2671 if (isa<VectorType>(CurTy))
2672 V = ConstantDataVector::get(Context, Elts);
2674 V = ConstantDataArray::get(Context, Elts);
2675 } else if (EltTy->isIntegerTy(64)) {
2676 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2677 if (isa<VectorType>(CurTy))
2678 V = ConstantDataVector::get(Context, Elts);
2680 V = ConstantDataArray::get(Context, Elts);
2681 } else if (EltTy->isHalfTy()) {
2682 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2683 if (isa<VectorType>(CurTy))
2684 V = ConstantDataVector::getFP(Context, Elts);
2686 V = ConstantDataArray::getFP(Context, Elts);
2687 } else if (EltTy->isFloatTy()) {
2688 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2689 if (isa<VectorType>(CurTy))
2690 V = ConstantDataVector::getFP(Context, Elts);
2692 V = ConstantDataArray::getFP(Context, Elts);
2693 } else if (EltTy->isDoubleTy()) {
2694 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2695 if (isa<VectorType>(CurTy))
2696 V = ConstantDataVector::getFP(Context, Elts);
2698 V = ConstantDataArray::getFP(Context, Elts);
2700 return error("Invalid type for value");
2705 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2706 if (Record.size() < 3)
2707 return error("Invalid record");
2708 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2710 V = UndefValue::get(CurTy); // Unknown binop.
2712 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2713 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2715 if (Record.size() >= 4) {
2716 if (Opc == Instruction::Add ||
2717 Opc == Instruction::Sub ||
2718 Opc == Instruction::Mul ||
2719 Opc == Instruction::Shl) {
2720 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2721 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2722 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2723 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2724 } else if (Opc == Instruction::SDiv ||
2725 Opc == Instruction::UDiv ||
2726 Opc == Instruction::LShr ||
2727 Opc == Instruction::AShr) {
2728 if (Record[3] & (1 << bitc::PEO_EXACT))
2729 Flags |= SDivOperator::IsExact;
2732 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2736 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2737 if (Record.size() < 3)
2738 return error("Invalid record");
2739 int Opc = getDecodedCastOpcode(Record[0]);
2741 V = UndefValue::get(CurTy); // Unknown cast.
2743 Type *OpTy = getTypeByID(Record[1]);
2745 return error("Invalid record");
2746 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2747 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2748 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2752 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2753 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2755 Type *PointeeType = nullptr;
2756 if (Record.size() % 2)
2757 PointeeType = getTypeByID(Record[OpNum++]);
2758 SmallVector<Constant*, 16> Elts;
2759 while (OpNum != Record.size()) {
2760 Type *ElTy = getTypeByID(Record[OpNum++]);
2762 return error("Invalid record");
2763 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2768 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2770 return error("Explicit gep operator type does not match pointee type "
2771 "of pointer operand");
2773 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2774 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2776 bitc::CST_CODE_CE_INBOUNDS_GEP);
2779 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2780 if (Record.size() < 3)
2781 return error("Invalid record");
2783 Type *SelectorTy = Type::getInt1Ty(Context);
2785 // The selector might be an i1 or an <n x i1>
2786 // Get the type from the ValueList before getting a forward ref.
2787 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2788 if (Value *V = ValueList[Record[0]])
2789 if (SelectorTy != V->getType())
2790 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2792 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2794 ValueList.getConstantFwdRef(Record[1],CurTy),
2795 ValueList.getConstantFwdRef(Record[2],CurTy));
2798 case bitc::CST_CODE_CE_EXTRACTELT
2799 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2800 if (Record.size() < 3)
2801 return error("Invalid record");
2803 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2805 return error("Invalid record");
2806 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2807 Constant *Op1 = nullptr;
2808 if (Record.size() == 4) {
2809 Type *IdxTy = getTypeByID(Record[2]);
2811 return error("Invalid record");
2812 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2813 } else // TODO: Remove with llvm 4.0
2814 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2816 return error("Invalid record");
2817 V = ConstantExpr::getExtractElement(Op0, Op1);
2820 case bitc::CST_CODE_CE_INSERTELT
2821 : { // CE_INSERTELT: [opval, opval, opty, opval]
2822 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2823 if (Record.size() < 3 || !OpTy)
2824 return error("Invalid record");
2825 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2826 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2827 OpTy->getElementType());
2828 Constant *Op2 = nullptr;
2829 if (Record.size() == 4) {
2830 Type *IdxTy = getTypeByID(Record[2]);
2832 return error("Invalid record");
2833 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2834 } else // TODO: Remove with llvm 4.0
2835 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2837 return error("Invalid record");
2838 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2841 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2842 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2843 if (Record.size() < 3 || !OpTy)
2844 return error("Invalid record");
2845 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2846 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2847 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2848 OpTy->getNumElements());
2849 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2850 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2853 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2854 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2856 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2857 if (Record.size() < 4 || !RTy || !OpTy)
2858 return error("Invalid record");
2859 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2860 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2861 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2862 RTy->getNumElements());
2863 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2864 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2867 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2868 if (Record.size() < 4)
2869 return error("Invalid record");
2870 Type *OpTy = getTypeByID(Record[0]);
2872 return error("Invalid record");
2873 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2874 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2876 if (OpTy->isFPOrFPVectorTy())
2877 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2879 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2882 // This maintains backward compatibility, pre-asm dialect keywords.
2883 // FIXME: Remove with the 4.0 release.
2884 case bitc::CST_CODE_INLINEASM_OLD: {
2885 if (Record.size() < 2)
2886 return error("Invalid record");
2887 std::string AsmStr, ConstrStr;
2888 bool HasSideEffects = Record[0] & 1;
2889 bool IsAlignStack = Record[0] >> 1;
2890 unsigned AsmStrSize = Record[1];
2891 if (2+AsmStrSize >= Record.size())
2892 return error("Invalid record");
2893 unsigned ConstStrSize = Record[2+AsmStrSize];
2894 if (3+AsmStrSize+ConstStrSize > Record.size())
2895 return error("Invalid record");
2897 for (unsigned i = 0; i != AsmStrSize; ++i)
2898 AsmStr += (char)Record[2+i];
2899 for (unsigned i = 0; i != ConstStrSize; ++i)
2900 ConstrStr += (char)Record[3+AsmStrSize+i];
2901 PointerType *PTy = cast<PointerType>(CurTy);
2902 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2903 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2906 // This version adds support for the asm dialect keywords (e.g.,
2908 case bitc::CST_CODE_INLINEASM: {
2909 if (Record.size() < 2)
2910 return error("Invalid record");
2911 std::string AsmStr, ConstrStr;
2912 bool HasSideEffects = Record[0] & 1;
2913 bool IsAlignStack = (Record[0] >> 1) & 1;
2914 unsigned AsmDialect = Record[0] >> 2;
2915 unsigned AsmStrSize = Record[1];
2916 if (2+AsmStrSize >= Record.size())
2917 return error("Invalid record");
2918 unsigned ConstStrSize = Record[2+AsmStrSize];
2919 if (3+AsmStrSize+ConstStrSize > Record.size())
2920 return error("Invalid record");
2922 for (unsigned i = 0; i != AsmStrSize; ++i)
2923 AsmStr += (char)Record[2+i];
2924 for (unsigned i = 0; i != ConstStrSize; ++i)
2925 ConstrStr += (char)Record[3+AsmStrSize+i];
2926 PointerType *PTy = cast<PointerType>(CurTy);
2927 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2928 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2929 InlineAsm::AsmDialect(AsmDialect));
2932 case bitc::CST_CODE_BLOCKADDRESS:{
2933 if (Record.size() < 3)
2934 return error("Invalid record");
2935 Type *FnTy = getTypeByID(Record[0]);
2937 return error("Invalid record");
2939 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2941 return error("Invalid record");
2943 // If the function is already parsed we can insert the block address right
2946 unsigned BBID = Record[2];
2948 // Invalid reference to entry block.
2949 return error("Invalid ID");
2951 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2952 for (size_t I = 0, E = BBID; I != E; ++I) {
2954 return error("Invalid ID");
2959 // Otherwise insert a placeholder and remember it so it can be inserted
2960 // when the function is parsed.
2961 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2963 BasicBlockFwdRefQueue.push_back(Fn);
2964 if (FwdBBs.size() < BBID + 1)
2965 FwdBBs.resize(BBID + 1);
2967 FwdBBs[BBID] = BasicBlock::Create(Context);
2970 V = BlockAddress::get(Fn, BB);
2975 ValueList.assignValue(V, NextCstNo);
2980 std::error_code BitcodeReader::parseUseLists() {
2981 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2982 return error("Invalid record");
2984 // Read all the records.
2985 SmallVector<uint64_t, 64> Record;
2987 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2989 switch (Entry.Kind) {
2990 case BitstreamEntry::SubBlock: // Handled for us already.
2991 case BitstreamEntry::Error:
2992 return error("Malformed block");
2993 case BitstreamEntry::EndBlock:
2994 return std::error_code();
2995 case BitstreamEntry::Record:
2996 // The interesting case.
3000 // Read a use list record.
3003 switch (Stream.readRecord(Entry.ID, Record)) {
3004 default: // Default behavior: unknown type.
3006 case bitc::USELIST_CODE_BB:
3009 case bitc::USELIST_CODE_DEFAULT: {
3010 unsigned RecordLength = Record.size();
3011 if (RecordLength < 3)
3012 // Records should have at least an ID and two indexes.
3013 return error("Invalid record");
3014 unsigned ID = Record.back();
3019 assert(ID < FunctionBBs.size() && "Basic block not found");
3020 V = FunctionBBs[ID];
3023 unsigned NumUses = 0;
3024 SmallDenseMap<const Use *, unsigned, 16> Order;
3025 for (const Use &U : V->materialized_uses()) {
3026 if (++NumUses > Record.size())
3028 Order[&U] = Record[NumUses - 1];
3030 if (Order.size() != Record.size() || NumUses > Record.size())
3031 // Mismatches can happen if the functions are being materialized lazily
3032 // (out-of-order), or a value has been upgraded.
3035 V->sortUseList([&](const Use &L, const Use &R) {
3036 return Order.lookup(&L) < Order.lookup(&R);
3044 /// When we see the block for metadata, remember where it is and then skip it.
3045 /// This lets us lazily deserialize the metadata.
3046 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3047 // Save the current stream state.
3048 uint64_t CurBit = Stream.GetCurrentBitNo();
3049 DeferredMetadataInfo.push_back(CurBit);
3051 // Skip over the block for now.
3052 if (Stream.SkipBlock())
3053 return error("Invalid record");
3054 return std::error_code();
3057 std::error_code BitcodeReader::materializeMetadata() {
3058 for (uint64_t BitPos : DeferredMetadataInfo) {
3059 // Move the bit stream to the saved position.
3060 Stream.JumpToBit(BitPos);
3061 if (std::error_code EC = parseMetadata(true))
3064 DeferredMetadataInfo.clear();
3065 return std::error_code();
3068 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3070 void BitcodeReader::saveMetadataList(
3071 DenseMap<const Metadata *, unsigned> &MetadataToIDs, bool OnlyTempMD) {
3072 for (unsigned ID = 0; ID < MetadataList.size(); ++ID) {
3073 Metadata *MD = MetadataList[ID];
3074 auto *N = dyn_cast_or_null<MDNode>(MD);
3075 assert((!N || (N->isResolved() || N->isTemporary())) &&
3076 "Found non-resolved non-temp MDNode while saving metadata");
3077 // Save all values if !OnlyTempMD, otherwise just the temporary metadata.
3078 // Note that in the !OnlyTempMD case we need to save all Metadata, not
3079 // just MDNode, as we may have references to other types of module-level
3080 // metadata (e.g. ValueAsMetadata) from instructions.
3081 if (!OnlyTempMD || (N && N->isTemporary())) {
3082 // Will call this after materializing each function, in order to
3083 // handle remapping of the function's instructions/metadata.
3084 // See if we already have an entry in that case.
3085 if (OnlyTempMD && MetadataToIDs.count(MD)) {
3086 assert(MetadataToIDs[MD] == ID && "Inconsistent metadata value id");
3089 if (N && N->isTemporary())
3090 // Ensure that we assert if someone tries to RAUW this temporary
3091 // metadata while it is the key of a map. The flag will be set back
3092 // to true when the saved metadata list is destroyed.
3093 N->setCanReplace(false);
3094 MetadataToIDs[MD] = ID;
3099 /// When we see the block for a function body, remember where it is and then
3100 /// skip it. This lets us lazily deserialize the functions.
3101 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3102 // Get the function we are talking about.
3103 if (FunctionsWithBodies.empty())
3104 return error("Insufficient function protos");
3106 Function *Fn = FunctionsWithBodies.back();
3107 FunctionsWithBodies.pop_back();
3109 // Save the current stream state.
3110 uint64_t CurBit = Stream.GetCurrentBitNo();
3112 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3113 "Mismatch between VST and scanned function offsets");
3114 DeferredFunctionInfo[Fn] = CurBit;
3116 // Skip over the function block for now.
3117 if (Stream.SkipBlock())
3118 return error("Invalid record");
3119 return std::error_code();
3122 std::error_code BitcodeReader::globalCleanup() {
3123 // Patch the initializers for globals and aliases up.
3124 resolveGlobalAndAliasInits();
3125 if (!GlobalInits.empty() || !AliasInits.empty())
3126 return error("Malformed global initializer set");
3128 // Look for intrinsic functions which need to be upgraded at some point
3129 for (Function &F : *TheModule) {
3131 if (UpgradeIntrinsicFunction(&F, NewFn))
3132 UpgradedIntrinsics[&F] = NewFn;
3135 // Look for global variables which need to be renamed.
3136 for (GlobalVariable &GV : TheModule->globals())
3137 UpgradeGlobalVariable(&GV);
3139 // Force deallocation of memory for these vectors to favor the client that
3140 // want lazy deserialization.
3141 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3142 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3143 return std::error_code();
3146 /// Support for lazy parsing of function bodies. This is required if we
3147 /// either have an old bitcode file without a VST forward declaration record,
3148 /// or if we have an anonymous function being materialized, since anonymous
3149 /// functions do not have a name and are therefore not in the VST.
3150 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3151 Stream.JumpToBit(NextUnreadBit);
3153 if (Stream.AtEndOfStream())
3154 return error("Could not find function in stream");
3156 if (!SeenFirstFunctionBody)
3157 return error("Trying to materialize functions before seeing function blocks");
3159 // An old bitcode file with the symbol table at the end would have
3160 // finished the parse greedily.
3161 assert(SeenValueSymbolTable);
3163 SmallVector<uint64_t, 64> Record;
3166 BitstreamEntry Entry = Stream.advance();
3167 switch (Entry.Kind) {
3169 return error("Expect SubBlock");
3170 case BitstreamEntry::SubBlock:
3173 return error("Expect function block");
3174 case bitc::FUNCTION_BLOCK_ID:
3175 if (std::error_code EC = rememberAndSkipFunctionBody())
3177 NextUnreadBit = Stream.GetCurrentBitNo();
3178 return std::error_code();
3184 std::error_code BitcodeReader::parseBitcodeVersion() {
3185 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3186 return error("Invalid record");
3188 // Read all the records.
3189 SmallVector<uint64_t, 64> Record;
3191 BitstreamEntry Entry = Stream.advance();
3193 switch (Entry.Kind) {
3195 case BitstreamEntry::Error:
3196 return error("Malformed block");
3197 case BitstreamEntry::EndBlock:
3198 return std::error_code();
3199 case BitstreamEntry::Record:
3200 // The interesting case.
3206 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3208 default: // Default behavior: reject
3209 return error("Invalid value");
3210 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3212 convertToString(Record, 0, ProducerIdentification);
3215 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3216 unsigned epoch = (unsigned)Record[0];
3217 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3219 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3220 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3227 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3228 bool ShouldLazyLoadMetadata) {
3230 Stream.JumpToBit(ResumeBit);
3231 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3232 return error("Invalid record");
3234 SmallVector<uint64_t, 64> Record;
3235 std::vector<std::string> SectionTable;
3236 std::vector<std::string> GCTable;
3238 // Read all the records for this module.
3240 BitstreamEntry Entry = Stream.advance();
3242 switch (Entry.Kind) {
3243 case BitstreamEntry::Error:
3244 return error("Malformed block");
3245 case BitstreamEntry::EndBlock:
3246 return globalCleanup();
3248 case BitstreamEntry::SubBlock:
3250 default: // Skip unknown content.
3251 if (Stream.SkipBlock())
3252 return error("Invalid record");
3254 case bitc::BLOCKINFO_BLOCK_ID:
3255 if (Stream.ReadBlockInfoBlock())
3256 return error("Malformed block");
3258 case bitc::PARAMATTR_BLOCK_ID:
3259 if (std::error_code EC = parseAttributeBlock())
3262 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3263 if (std::error_code EC = parseAttributeGroupBlock())
3266 case bitc::TYPE_BLOCK_ID_NEW:
3267 if (std::error_code EC = parseTypeTable())
3270 case bitc::VALUE_SYMTAB_BLOCK_ID:
3271 if (!SeenValueSymbolTable) {
3272 // Either this is an old form VST without function index and an
3273 // associated VST forward declaration record (which would have caused
3274 // the VST to be jumped to and parsed before it was encountered
3275 // normally in the stream), or there were no function blocks to
3276 // trigger an earlier parsing of the VST.
3277 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3278 if (std::error_code EC = parseValueSymbolTable())
3280 SeenValueSymbolTable = true;
3282 // We must have had a VST forward declaration record, which caused
3283 // the parser to jump to and parse the VST earlier.
3284 assert(VSTOffset > 0);
3285 if (Stream.SkipBlock())
3286 return error("Invalid record");
3289 case bitc::CONSTANTS_BLOCK_ID:
3290 if (std::error_code EC = parseConstants())
3292 if (std::error_code EC = resolveGlobalAndAliasInits())
3295 case bitc::METADATA_BLOCK_ID:
3296 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3297 if (std::error_code EC = rememberAndSkipMetadata())
3301 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3302 if (std::error_code EC = parseMetadata(true))
3305 case bitc::METADATA_KIND_BLOCK_ID:
3306 if (std::error_code EC = parseMetadataKinds())
3309 case bitc::FUNCTION_BLOCK_ID:
3310 // If this is the first function body we've seen, reverse the
3311 // FunctionsWithBodies list.
3312 if (!SeenFirstFunctionBody) {
3313 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3314 if (std::error_code EC = globalCleanup())
3316 SeenFirstFunctionBody = true;
3319 if (VSTOffset > 0) {
3320 // If we have a VST forward declaration record, make sure we
3321 // parse the VST now if we haven't already. It is needed to
3322 // set up the DeferredFunctionInfo vector for lazy reading.
3323 if (!SeenValueSymbolTable) {
3324 if (std::error_code EC =
3325 BitcodeReader::parseValueSymbolTable(VSTOffset))
3327 SeenValueSymbolTable = true;
3328 // Fall through so that we record the NextUnreadBit below.
3329 // This is necessary in case we have an anonymous function that
3330 // is later materialized. Since it will not have a VST entry we
3331 // need to fall back to the lazy parse to find its offset.
3333 // If we have a VST forward declaration record, but have already
3334 // parsed the VST (just above, when the first function body was
3335 // encountered here), then we are resuming the parse after
3336 // materializing functions. The ResumeBit points to the
3337 // start of the last function block recorded in the
3338 // DeferredFunctionInfo map. Skip it.
3339 if (Stream.SkipBlock())
3340 return error("Invalid record");
3345 // Support older bitcode files that did not have the function
3346 // index in the VST, nor a VST forward declaration record, as
3347 // well as anonymous functions that do not have VST entries.
3348 // Build the DeferredFunctionInfo vector on the fly.
3349 if (std::error_code EC = rememberAndSkipFunctionBody())
3352 // Suspend parsing when we reach the function bodies. Subsequent
3353 // materialization calls will resume it when necessary. If the bitcode
3354 // file is old, the symbol table will be at the end instead and will not
3355 // have been seen yet. In this case, just finish the parse now.
3356 if (SeenValueSymbolTable) {
3357 NextUnreadBit = Stream.GetCurrentBitNo();
3358 return std::error_code();
3361 case bitc::USELIST_BLOCK_ID:
3362 if (std::error_code EC = parseUseLists())
3365 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3366 if (std::error_code EC = parseOperandBundleTags())
3372 case BitstreamEntry::Record:
3373 // The interesting case.
3379 auto BitCode = Stream.readRecord(Entry.ID, Record);
3381 default: break; // Default behavior, ignore unknown content.
3382 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3383 if (Record.size() < 1)
3384 return error("Invalid record");
3385 // Only version #0 and #1 are supported so far.
3386 unsigned module_version = Record[0];
3387 switch (module_version) {
3389 return error("Invalid value");
3391 UseRelativeIDs = false;
3394 UseRelativeIDs = true;
3399 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3401 if (convertToString(Record, 0, S))
3402 return error("Invalid record");
3403 TheModule->setTargetTriple(S);
3406 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3408 if (convertToString(Record, 0, S))
3409 return error("Invalid record");
3410 TheModule->setDataLayout(S);
3413 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3415 if (convertToString(Record, 0, S))
3416 return error("Invalid record");
3417 TheModule->setModuleInlineAsm(S);
3420 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3421 // FIXME: Remove in 4.0.
3423 if (convertToString(Record, 0, S))
3424 return error("Invalid record");
3428 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3430 if (convertToString(Record, 0, S))
3431 return error("Invalid record");
3432 SectionTable.push_back(S);
3435 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3437 if (convertToString(Record, 0, S))
3438 return error("Invalid record");
3439 GCTable.push_back(S);
3442 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3443 if (Record.size() < 2)
3444 return error("Invalid record");
3445 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3446 unsigned ComdatNameSize = Record[1];
3447 std::string ComdatName;
3448 ComdatName.reserve(ComdatNameSize);
3449 for (unsigned i = 0; i != ComdatNameSize; ++i)
3450 ComdatName += (char)Record[2 + i];
3451 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3452 C->setSelectionKind(SK);
3453 ComdatList.push_back(C);
3456 // GLOBALVAR: [pointer type, isconst, initid,
3457 // linkage, alignment, section, visibility, threadlocal,
3458 // unnamed_addr, externally_initialized, dllstorageclass,
3460 case bitc::MODULE_CODE_GLOBALVAR: {
3461 if (Record.size() < 6)
3462 return error("Invalid record");
3463 Type *Ty = getTypeByID(Record[0]);
3465 return error("Invalid record");
3466 bool isConstant = Record[1] & 1;
3467 bool explicitType = Record[1] & 2;
3468 unsigned AddressSpace;
3470 AddressSpace = Record[1] >> 2;
3472 if (!Ty->isPointerTy())
3473 return error("Invalid type for value");
3474 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3475 Ty = cast<PointerType>(Ty)->getElementType();
3478 uint64_t RawLinkage = Record[3];
3479 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3481 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3483 std::string Section;
3485 if (Record[5]-1 >= SectionTable.size())
3486 return error("Invalid ID");
3487 Section = SectionTable[Record[5]-1];
3489 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3490 // Local linkage must have default visibility.
3491 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3492 // FIXME: Change to an error if non-default in 4.0.
3493 Visibility = getDecodedVisibility(Record[6]);
3495 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3496 if (Record.size() > 7)
3497 TLM = getDecodedThreadLocalMode(Record[7]);
3499 bool UnnamedAddr = false;
3500 if (Record.size() > 8)
3501 UnnamedAddr = Record[8];
3503 bool ExternallyInitialized = false;
3504 if (Record.size() > 9)
3505 ExternallyInitialized = Record[9];
3507 GlobalVariable *NewGV =
3508 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3509 TLM, AddressSpace, ExternallyInitialized);
3510 NewGV->setAlignment(Alignment);
3511 if (!Section.empty())
3512 NewGV->setSection(Section);
3513 NewGV->setVisibility(Visibility);
3514 NewGV->setUnnamedAddr(UnnamedAddr);
3516 if (Record.size() > 10)
3517 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3519 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3521 ValueList.push_back(NewGV);
3523 // Remember which value to use for the global initializer.
3524 if (unsigned InitID = Record[2])
3525 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3527 if (Record.size() > 11) {
3528 if (unsigned ComdatID = Record[11]) {
3529 if (ComdatID > ComdatList.size())
3530 return error("Invalid global variable comdat ID");
3531 NewGV->setComdat(ComdatList[ComdatID - 1]);
3533 } else if (hasImplicitComdat(RawLinkage)) {
3534 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3538 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3539 // alignment, section, visibility, gc, unnamed_addr,
3540 // prologuedata, dllstorageclass, comdat, prefixdata]
3541 case bitc::MODULE_CODE_FUNCTION: {
3542 if (Record.size() < 8)
3543 return error("Invalid record");
3544 Type *Ty = getTypeByID(Record[0]);
3546 return error("Invalid record");
3547 if (auto *PTy = dyn_cast<PointerType>(Ty))
3548 Ty = PTy->getElementType();
3549 auto *FTy = dyn_cast<FunctionType>(Ty);
3551 return error("Invalid type for value");
3552 auto CC = static_cast<CallingConv::ID>(Record[1]);
3553 if (CC & ~CallingConv::MaxID)
3554 return error("Invalid calling convention ID");
3556 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3559 Func->setCallingConv(CC);
3560 bool isProto = Record[2];
3561 uint64_t RawLinkage = Record[3];
3562 Func->setLinkage(getDecodedLinkage(RawLinkage));
3563 Func->setAttributes(getAttributes(Record[4]));
3566 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3568 Func->setAlignment(Alignment);
3570 if (Record[6]-1 >= SectionTable.size())
3571 return error("Invalid ID");
3572 Func->setSection(SectionTable[Record[6]-1]);
3574 // Local linkage must have default visibility.
3575 if (!Func->hasLocalLinkage())
3576 // FIXME: Change to an error if non-default in 4.0.
3577 Func->setVisibility(getDecodedVisibility(Record[7]));
3578 if (Record.size() > 8 && Record[8]) {
3579 if (Record[8]-1 >= GCTable.size())
3580 return error("Invalid ID");
3581 Func->setGC(GCTable[Record[8]-1].c_str());
3583 bool UnnamedAddr = false;
3584 if (Record.size() > 9)
3585 UnnamedAddr = Record[9];
3586 Func->setUnnamedAddr(UnnamedAddr);
3587 if (Record.size() > 10 && Record[10] != 0)
3588 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3590 if (Record.size() > 11)
3591 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3593 upgradeDLLImportExportLinkage(Func, RawLinkage);
3595 if (Record.size() > 12) {
3596 if (unsigned ComdatID = Record[12]) {
3597 if (ComdatID > ComdatList.size())
3598 return error("Invalid function comdat ID");
3599 Func->setComdat(ComdatList[ComdatID - 1]);
3601 } else if (hasImplicitComdat(RawLinkage)) {
3602 Func->setComdat(reinterpret_cast<Comdat *>(1));
3605 if (Record.size() > 13 && Record[13] != 0)
3606 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3608 if (Record.size() > 14 && Record[14] != 0)
3609 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3611 ValueList.push_back(Func);
3613 // If this is a function with a body, remember the prototype we are
3614 // creating now, so that we can match up the body with them later.
3616 Func->setIsMaterializable(true);
3617 FunctionsWithBodies.push_back(Func);
3618 DeferredFunctionInfo[Func] = 0;
3622 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3623 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3624 case bitc::MODULE_CODE_ALIAS:
3625 case bitc::MODULE_CODE_ALIAS_OLD: {
3626 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3627 if (Record.size() < (3 + (unsigned)NewRecord))
3628 return error("Invalid record");
3630 Type *Ty = getTypeByID(Record[OpNum++]);
3632 return error("Invalid record");
3636 auto *PTy = dyn_cast<PointerType>(Ty);
3638 return error("Invalid type for value");
3639 Ty = PTy->getElementType();
3640 AddrSpace = PTy->getAddressSpace();
3642 AddrSpace = Record[OpNum++];
3645 auto Val = Record[OpNum++];
3646 auto Linkage = Record[OpNum++];
3647 auto *NewGA = GlobalAlias::create(
3648 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3649 // Old bitcode files didn't have visibility field.
3650 // Local linkage must have default visibility.
3651 if (OpNum != Record.size()) {
3652 auto VisInd = OpNum++;
3653 if (!NewGA->hasLocalLinkage())
3654 // FIXME: Change to an error if non-default in 4.0.
3655 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3657 if (OpNum != Record.size())
3658 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3660 upgradeDLLImportExportLinkage(NewGA, Linkage);
3661 if (OpNum != Record.size())
3662 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3663 if (OpNum != Record.size())
3664 NewGA->setUnnamedAddr(Record[OpNum++]);
3665 ValueList.push_back(NewGA);
3666 AliasInits.push_back(std::make_pair(NewGA, Val));
3669 /// MODULE_CODE_PURGEVALS: [numvals]
3670 case bitc::MODULE_CODE_PURGEVALS:
3671 // Trim down the value list to the specified size.
3672 if (Record.size() < 1 || Record[0] > ValueList.size())
3673 return error("Invalid record");
3674 ValueList.shrinkTo(Record[0]);
3676 /// MODULE_CODE_VSTOFFSET: [offset]
3677 case bitc::MODULE_CODE_VSTOFFSET:
3678 if (Record.size() < 1)
3679 return error("Invalid record");
3680 VSTOffset = Record[0];
3682 /// MODULE_CODE_METADATA_VALUES: [numvals]
3683 case bitc::MODULE_CODE_METADATA_VALUES:
3684 if (Record.size() < 1)
3685 return error("Invalid record");
3686 assert(!IsMetadataMaterialized);
3687 // This record contains the number of metadata values in the module-level
3688 // METADATA_BLOCK. It is used to support lazy parsing of metadata as
3689 // a postpass, where we will parse function-level metadata first.
3690 // This is needed because the ids of metadata are assigned implicitly
3691 // based on their ordering in the bitcode, with the function-level
3692 // metadata ids starting after the module-level metadata ids. Otherwise,
3693 // we would have to parse the module-level metadata block to prime the
3694 // MetadataList when we are lazy loading metadata during function
3695 // importing. Initialize the MetadataList size here based on the
3696 // record value, regardless of whether we are doing lazy metadata
3697 // loading, so that we have consistent handling and assertion
3698 // checking in parseMetadata for module-level metadata.
3699 NumModuleMDs = Record[0];
3700 SeenModuleValuesRecord = true;
3701 assert(MetadataList.size() == 0);
3702 MetadataList.resize(NumModuleMDs);
3709 /// Helper to read the header common to all bitcode files.
3710 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3711 // Sniff for the signature.
3712 if (Stream.Read(8) != 'B' ||
3713 Stream.Read(8) != 'C' ||
3714 Stream.Read(4) != 0x0 ||
3715 Stream.Read(4) != 0xC ||
3716 Stream.Read(4) != 0xE ||
3717 Stream.Read(4) != 0xD)
3723 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3724 Module *M, bool ShouldLazyLoadMetadata) {
3727 if (std::error_code EC = initStream(std::move(Streamer)))
3730 // Sniff for the signature.
3731 if (!hasValidBitcodeHeader(Stream))
3732 return error("Invalid bitcode signature");
3734 // We expect a number of well-defined blocks, though we don't necessarily
3735 // need to understand them all.
3737 if (Stream.AtEndOfStream()) {
3738 // We didn't really read a proper Module.
3739 return error("Malformed IR file");
3742 BitstreamEntry Entry =
3743 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3745 if (Entry.Kind != BitstreamEntry::SubBlock)
3746 return error("Malformed block");
3748 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3749 parseBitcodeVersion();
3753 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3754 return parseModule(0, ShouldLazyLoadMetadata);
3756 if (Stream.SkipBlock())
3757 return error("Invalid record");
3761 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3762 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3763 return error("Invalid record");
3765 SmallVector<uint64_t, 64> Record;
3768 // Read all the records for this module.
3770 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3772 switch (Entry.Kind) {
3773 case BitstreamEntry::SubBlock: // Handled for us already.
3774 case BitstreamEntry::Error:
3775 return error("Malformed block");
3776 case BitstreamEntry::EndBlock:
3778 case BitstreamEntry::Record:
3779 // The interesting case.
3784 switch (Stream.readRecord(Entry.ID, Record)) {
3785 default: break; // Default behavior, ignore unknown content.
3786 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3788 if (convertToString(Record, 0, S))
3789 return error("Invalid record");
3796 llvm_unreachable("Exit infinite loop");
3799 ErrorOr<std::string> BitcodeReader::parseTriple() {
3800 if (std::error_code EC = initStream(nullptr))
3803 // Sniff for the signature.
3804 if (!hasValidBitcodeHeader(Stream))
3805 return error("Invalid bitcode signature");
3807 // We expect a number of well-defined blocks, though we don't necessarily
3808 // need to understand them all.
3810 BitstreamEntry Entry = Stream.advance();
3812 switch (Entry.Kind) {
3813 case BitstreamEntry::Error:
3814 return error("Malformed block");
3815 case BitstreamEntry::EndBlock:
3816 return std::error_code();
3818 case BitstreamEntry::SubBlock:
3819 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3820 return parseModuleTriple();
3822 // Ignore other sub-blocks.
3823 if (Stream.SkipBlock())
3824 return error("Malformed block");
3827 case BitstreamEntry::Record:
3828 Stream.skipRecord(Entry.ID);
3834 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3835 if (std::error_code EC = initStream(nullptr))
3838 // Sniff for the signature.
3839 if (!hasValidBitcodeHeader(Stream))
3840 return error("Invalid bitcode signature");
3842 // We expect a number of well-defined blocks, though we don't necessarily
3843 // need to understand them all.
3845 BitstreamEntry Entry = Stream.advance();
3846 switch (Entry.Kind) {
3847 case BitstreamEntry::Error:
3848 return error("Malformed block");
3849 case BitstreamEntry::EndBlock:
3850 return std::error_code();
3852 case BitstreamEntry::SubBlock:
3853 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3854 if (std::error_code EC = parseBitcodeVersion())
3856 return ProducerIdentification;
3858 // Ignore other sub-blocks.
3859 if (Stream.SkipBlock())
3860 return error("Malformed block");
3862 case BitstreamEntry::Record:
3863 Stream.skipRecord(Entry.ID);
3869 /// Parse metadata attachments.
3870 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3871 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3872 return error("Invalid record");
3874 SmallVector<uint64_t, 64> Record;
3876 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3878 switch (Entry.Kind) {
3879 case BitstreamEntry::SubBlock: // Handled for us already.
3880 case BitstreamEntry::Error:
3881 return error("Malformed block");
3882 case BitstreamEntry::EndBlock:
3883 return std::error_code();
3884 case BitstreamEntry::Record:
3885 // The interesting case.
3889 // Read a metadata attachment record.
3891 switch (Stream.readRecord(Entry.ID, Record)) {
3892 default: // Default behavior: ignore.
3894 case bitc::METADATA_ATTACHMENT: {
3895 unsigned RecordLength = Record.size();
3897 return error("Invalid record");
3898 if (RecordLength % 2 == 0) {
3899 // A function attachment.
3900 for (unsigned I = 0; I != RecordLength; I += 2) {
3901 auto K = MDKindMap.find(Record[I]);
3902 if (K == MDKindMap.end())
3903 return error("Invalid ID");
3904 Metadata *MD = MetadataList.getValueFwdRef(Record[I + 1]);
3905 F.setMetadata(K->second, cast<MDNode>(MD));
3910 // An instruction attachment.
3911 Instruction *Inst = InstructionList[Record[0]];
3912 for (unsigned i = 1; i != RecordLength; i = i+2) {
3913 unsigned Kind = Record[i];
3914 DenseMap<unsigned, unsigned>::iterator I =
3915 MDKindMap.find(Kind);
3916 if (I == MDKindMap.end())
3917 return error("Invalid ID");
3918 Metadata *Node = MetadataList.getValueFwdRef(Record[i + 1]);
3919 if (isa<LocalAsMetadata>(Node))
3920 // Drop the attachment. This used to be legal, but there's no
3923 Inst->setMetadata(I->second, cast<MDNode>(Node));
3924 if (I->second == LLVMContext::MD_tbaa)
3925 InstsWithTBAATag.push_back(Inst);
3933 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3934 LLVMContext &Context = PtrType->getContext();
3935 if (!isa<PointerType>(PtrType))
3936 return error(Context, "Load/Store operand is not a pointer type");
3937 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3939 if (ValType && ValType != ElemType)
3940 return error(Context, "Explicit load/store type does not match pointee "
3941 "type of pointer operand");
3942 if (!PointerType::isLoadableOrStorableType(ElemType))
3943 return error(Context, "Cannot load/store from pointer");
3944 return std::error_code();
3947 /// Lazily parse the specified function body block.
3948 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3949 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3950 return error("Invalid record");
3952 InstructionList.clear();
3953 unsigned ModuleValueListSize = ValueList.size();
3954 unsigned ModuleMetadataListSize = MetadataList.size();
3956 // Add all the function arguments to the value table.
3957 for (Argument &I : F->args())
3958 ValueList.push_back(&I);
3960 unsigned NextValueNo = ValueList.size();
3961 BasicBlock *CurBB = nullptr;
3962 unsigned CurBBNo = 0;
3965 auto getLastInstruction = [&]() -> Instruction * {
3966 if (CurBB && !CurBB->empty())
3967 return &CurBB->back();
3968 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3969 !FunctionBBs[CurBBNo - 1]->empty())
3970 return &FunctionBBs[CurBBNo - 1]->back();
3974 std::vector<OperandBundleDef> OperandBundles;
3976 // Read all the records.
3977 SmallVector<uint64_t, 64> Record;
3979 BitstreamEntry Entry = Stream.advance();
3981 switch (Entry.Kind) {
3982 case BitstreamEntry::Error:
3983 return error("Malformed block");
3984 case BitstreamEntry::EndBlock:
3985 goto OutOfRecordLoop;
3987 case BitstreamEntry::SubBlock:
3989 default: // Skip unknown content.
3990 if (Stream.SkipBlock())
3991 return error("Invalid record");
3993 case bitc::CONSTANTS_BLOCK_ID:
3994 if (std::error_code EC = parseConstants())
3996 NextValueNo = ValueList.size();
3998 case bitc::VALUE_SYMTAB_BLOCK_ID:
3999 if (std::error_code EC = parseValueSymbolTable())
4002 case bitc::METADATA_ATTACHMENT_ID:
4003 if (std::error_code EC = parseMetadataAttachment(*F))
4006 case bitc::METADATA_BLOCK_ID:
4007 if (std::error_code EC = parseMetadata())
4010 case bitc::USELIST_BLOCK_ID:
4011 if (std::error_code EC = parseUseLists())
4017 case BitstreamEntry::Record:
4018 // The interesting case.
4024 Instruction *I = nullptr;
4025 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
4027 default: // Default behavior: reject
4028 return error("Invalid value");
4029 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
4030 if (Record.size() < 1 || Record[0] == 0)
4031 return error("Invalid record");
4032 // Create all the basic blocks for the function.
4033 FunctionBBs.resize(Record[0]);
4035 // See if anything took the address of blocks in this function.
4036 auto BBFRI = BasicBlockFwdRefs.find(F);
4037 if (BBFRI == BasicBlockFwdRefs.end()) {
4038 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4039 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4041 auto &BBRefs = BBFRI->second;
4042 // Check for invalid basic block references.
4043 if (BBRefs.size() > FunctionBBs.size())
4044 return error("Invalid ID");
4045 assert(!BBRefs.empty() && "Unexpected empty array");
4046 assert(!BBRefs.front() && "Invalid reference to entry block");
4047 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4049 if (I < RE && BBRefs[I]) {
4050 BBRefs[I]->insertInto(F);
4051 FunctionBBs[I] = BBRefs[I];
4053 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4056 // Erase from the table.
4057 BasicBlockFwdRefs.erase(BBFRI);
4060 CurBB = FunctionBBs[0];
4064 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4065 // This record indicates that the last instruction is at the same
4066 // location as the previous instruction with a location.
4067 I = getLastInstruction();
4070 return error("Invalid record");
4071 I->setDebugLoc(LastLoc);
4075 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4076 I = getLastInstruction();
4077 if (!I || Record.size() < 4)
4078 return error("Invalid record");
4080 unsigned Line = Record[0], Col = Record[1];
4081 unsigned ScopeID = Record[2], IAID = Record[3];
4083 MDNode *Scope = nullptr, *IA = nullptr;
4085 Scope = cast<MDNode>(MetadataList.getValueFwdRef(ScopeID - 1));
4087 IA = cast<MDNode>(MetadataList.getValueFwdRef(IAID - 1));
4088 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4089 I->setDebugLoc(LastLoc);
4094 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4097 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4098 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4099 OpNum+1 > Record.size())
4100 return error("Invalid record");
4102 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4104 return error("Invalid record");
4105 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4106 InstructionList.push_back(I);
4107 if (OpNum < Record.size()) {
4108 if (Opc == Instruction::Add ||
4109 Opc == Instruction::Sub ||
4110 Opc == Instruction::Mul ||
4111 Opc == Instruction::Shl) {
4112 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4113 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4114 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4115 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4116 } else if (Opc == Instruction::SDiv ||
4117 Opc == Instruction::UDiv ||
4118 Opc == Instruction::LShr ||
4119 Opc == Instruction::AShr) {
4120 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4121 cast<BinaryOperator>(I)->setIsExact(true);
4122 } else if (isa<FPMathOperator>(I)) {
4123 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4125 I->setFastMathFlags(FMF);
4131 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4134 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4135 OpNum+2 != Record.size())
4136 return error("Invalid record");
4138 Type *ResTy = getTypeByID(Record[OpNum]);
4139 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4140 if (Opc == -1 || !ResTy)
4141 return error("Invalid record");
4142 Instruction *Temp = nullptr;
4143 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4145 InstructionList.push_back(Temp);
4146 CurBB->getInstList().push_back(Temp);
4149 auto CastOp = (Instruction::CastOps)Opc;
4150 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4151 return error("Invalid cast");
4152 I = CastInst::Create(CastOp, Op, ResTy);
4154 InstructionList.push_back(I);
4157 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4158 case bitc::FUNC_CODE_INST_GEP_OLD:
4159 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4165 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4166 InBounds = Record[OpNum++];
4167 Ty = getTypeByID(Record[OpNum++]);
4169 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4174 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4175 return error("Invalid record");
4178 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4181 cast<SequentialType>(BasePtr->getType()->getScalarType())
4184 "Explicit gep type does not match pointee type of pointer operand");
4186 SmallVector<Value*, 16> GEPIdx;
4187 while (OpNum != Record.size()) {
4189 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4190 return error("Invalid record");
4191 GEPIdx.push_back(Op);
4194 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4196 InstructionList.push_back(I);
4198 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4202 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4203 // EXTRACTVAL: [opty, opval, n x indices]
4206 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4207 return error("Invalid record");
4209 unsigned RecSize = Record.size();
4210 if (OpNum == RecSize)
4211 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4213 SmallVector<unsigned, 4> EXTRACTVALIdx;
4214 Type *CurTy = Agg->getType();
4215 for (; OpNum != RecSize; ++OpNum) {
4216 bool IsArray = CurTy->isArrayTy();
4217 bool IsStruct = CurTy->isStructTy();
4218 uint64_t Index = Record[OpNum];
4220 if (!IsStruct && !IsArray)
4221 return error("EXTRACTVAL: Invalid type");
4222 if ((unsigned)Index != Index)
4223 return error("Invalid value");
4224 if (IsStruct && Index >= CurTy->subtypes().size())
4225 return error("EXTRACTVAL: Invalid struct index");
4226 if (IsArray && Index >= CurTy->getArrayNumElements())
4227 return error("EXTRACTVAL: Invalid array index");
4228 EXTRACTVALIdx.push_back((unsigned)Index);
4231 CurTy = CurTy->subtypes()[Index];
4233 CurTy = CurTy->subtypes()[0];
4236 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4237 InstructionList.push_back(I);
4241 case bitc::FUNC_CODE_INST_INSERTVAL: {
4242 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4245 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4246 return error("Invalid record");
4248 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4249 return error("Invalid record");
4251 unsigned RecSize = Record.size();
4252 if (OpNum == RecSize)
4253 return error("INSERTVAL: Invalid instruction with 0 indices");
4255 SmallVector<unsigned, 4> INSERTVALIdx;
4256 Type *CurTy = Agg->getType();
4257 for (; OpNum != RecSize; ++OpNum) {
4258 bool IsArray = CurTy->isArrayTy();
4259 bool IsStruct = CurTy->isStructTy();
4260 uint64_t Index = Record[OpNum];
4262 if (!IsStruct && !IsArray)
4263 return error("INSERTVAL: Invalid type");
4264 if ((unsigned)Index != Index)
4265 return error("Invalid value");
4266 if (IsStruct && Index >= CurTy->subtypes().size())
4267 return error("INSERTVAL: Invalid struct index");
4268 if (IsArray && Index >= CurTy->getArrayNumElements())
4269 return error("INSERTVAL: Invalid array index");
4271 INSERTVALIdx.push_back((unsigned)Index);
4273 CurTy = CurTy->subtypes()[Index];
4275 CurTy = CurTy->subtypes()[0];
4278 if (CurTy != Val->getType())
4279 return error("Inserted value type doesn't match aggregate type");
4281 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4282 InstructionList.push_back(I);
4286 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4287 // obsolete form of select
4288 // handles select i1 ... in old bitcode
4290 Value *TrueVal, *FalseVal, *Cond;
4291 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4292 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4293 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4294 return error("Invalid record");
4296 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4297 InstructionList.push_back(I);
4301 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4302 // new form of select
4303 // handles select i1 or select [N x i1]
4305 Value *TrueVal, *FalseVal, *Cond;
4306 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4307 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4308 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4309 return error("Invalid record");
4311 // select condition can be either i1 or [N x i1]
4312 if (VectorType* vector_type =
4313 dyn_cast<VectorType>(Cond->getType())) {
4315 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4316 return error("Invalid type for value");
4319 if (Cond->getType() != Type::getInt1Ty(Context))
4320 return error("Invalid type for value");
4323 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4324 InstructionList.push_back(I);
4328 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4331 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4332 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4333 return error("Invalid record");
4334 if (!Vec->getType()->isVectorTy())
4335 return error("Invalid type for value");
4336 I = ExtractElementInst::Create(Vec, Idx);
4337 InstructionList.push_back(I);
4341 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4343 Value *Vec, *Elt, *Idx;
4344 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4345 return error("Invalid record");
4346 if (!Vec->getType()->isVectorTy())
4347 return error("Invalid type for value");
4348 if (popValue(Record, OpNum, NextValueNo,
4349 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4350 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4351 return error("Invalid record");
4352 I = InsertElementInst::Create(Vec, Elt, Idx);
4353 InstructionList.push_back(I);
4357 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4359 Value *Vec1, *Vec2, *Mask;
4360 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4361 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4362 return error("Invalid record");
4364 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4365 return error("Invalid record");
4366 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4367 return error("Invalid type for value");
4368 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4369 InstructionList.push_back(I);
4373 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4374 // Old form of ICmp/FCmp returning bool
4375 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4376 // both legal on vectors but had different behaviour.
4377 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4378 // FCmp/ICmp returning bool or vector of bool
4382 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4383 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4384 return error("Invalid record");
4386 unsigned PredVal = Record[OpNum];
4387 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4389 if (IsFP && Record.size() > OpNum+1)
4390 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4392 if (OpNum+1 != Record.size())
4393 return error("Invalid record");
4395 if (LHS->getType()->isFPOrFPVectorTy())
4396 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4398 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4401 I->setFastMathFlags(FMF);
4402 InstructionList.push_back(I);
4406 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4408 unsigned Size = Record.size();
4410 I = ReturnInst::Create(Context);
4411 InstructionList.push_back(I);
4416 Value *Op = nullptr;
4417 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4418 return error("Invalid record");
4419 if (OpNum != Record.size())
4420 return error("Invalid record");
4422 I = ReturnInst::Create(Context, Op);
4423 InstructionList.push_back(I);
4426 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4427 if (Record.size() != 1 && Record.size() != 3)
4428 return error("Invalid record");
4429 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4431 return error("Invalid record");
4433 if (Record.size() == 1) {
4434 I = BranchInst::Create(TrueDest);
4435 InstructionList.push_back(I);
4438 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4439 Value *Cond = getValue(Record, 2, NextValueNo,
4440 Type::getInt1Ty(Context));
4441 if (!FalseDest || !Cond)
4442 return error("Invalid record");
4443 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4444 InstructionList.push_back(I);
4448 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4449 if (Record.size() != 1 && Record.size() != 2)
4450 return error("Invalid record");
4453 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4455 return error("Invalid record");
4456 BasicBlock *UnwindDest = nullptr;
4457 if (Record.size() == 2) {
4458 UnwindDest = getBasicBlock(Record[Idx++]);
4460 return error("Invalid record");
4463 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4464 InstructionList.push_back(I);
4467 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4468 if (Record.size() != 2)
4469 return error("Invalid record");
4472 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4474 return error("Invalid record");
4475 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4477 return error("Invalid record");
4479 I = CatchReturnInst::Create(CatchPad, BB);
4480 InstructionList.push_back(I);
4483 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4484 // We must have, at minimum, the outer scope and the number of arguments.
4485 if (Record.size() < 2)
4486 return error("Invalid record");
4491 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4493 unsigned NumHandlers = Record[Idx++];
4495 SmallVector<BasicBlock *, 2> Handlers;
4496 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4497 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4499 return error("Invalid record");
4500 Handlers.push_back(BB);
4503 BasicBlock *UnwindDest = nullptr;
4504 if (Idx + 1 == Record.size()) {
4505 UnwindDest = getBasicBlock(Record[Idx++]);
4507 return error("Invalid record");
4510 if (Record.size() != Idx)
4511 return error("Invalid record");
4514 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4515 for (BasicBlock *Handler : Handlers)
4516 CatchSwitch->addHandler(Handler);
4518 InstructionList.push_back(I);
4521 case bitc::FUNC_CODE_INST_CATCHPAD:
4522 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4523 // We must have, at minimum, the outer scope and the number of arguments.
4524 if (Record.size() < 2)
4525 return error("Invalid record");
4530 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4532 unsigned NumArgOperands = Record[Idx++];
4534 SmallVector<Value *, 2> Args;
4535 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4537 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4538 return error("Invalid record");
4539 Args.push_back(Val);
4542 if (Record.size() != Idx)
4543 return error("Invalid record");
4545 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4546 I = CleanupPadInst::Create(ParentPad, Args);
4548 I = CatchPadInst::Create(ParentPad, Args);
4549 InstructionList.push_back(I);
4552 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4554 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4555 // "New" SwitchInst format with case ranges. The changes to write this
4556 // format were reverted but we still recognize bitcode that uses it.
4557 // Hopefully someday we will have support for case ranges and can use
4558 // this format again.
4560 Type *OpTy = getTypeByID(Record[1]);
4561 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4563 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4564 BasicBlock *Default = getBasicBlock(Record[3]);
4565 if (!OpTy || !Cond || !Default)
4566 return error("Invalid record");
4568 unsigned NumCases = Record[4];
4570 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4571 InstructionList.push_back(SI);
4573 unsigned CurIdx = 5;
4574 for (unsigned i = 0; i != NumCases; ++i) {
4575 SmallVector<ConstantInt*, 1> CaseVals;
4576 unsigned NumItems = Record[CurIdx++];
4577 for (unsigned ci = 0; ci != NumItems; ++ci) {
4578 bool isSingleNumber = Record[CurIdx++];
4581 unsigned ActiveWords = 1;
4582 if (ValueBitWidth > 64)
4583 ActiveWords = Record[CurIdx++];
4584 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4586 CurIdx += ActiveWords;
4588 if (!isSingleNumber) {
4590 if (ValueBitWidth > 64)
4591 ActiveWords = Record[CurIdx++];
4592 APInt High = readWideAPInt(
4593 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4594 CurIdx += ActiveWords;
4596 // FIXME: It is not clear whether values in the range should be
4597 // compared as signed or unsigned values. The partially
4598 // implemented changes that used this format in the past used
4599 // unsigned comparisons.
4600 for ( ; Low.ule(High); ++Low)
4601 CaseVals.push_back(ConstantInt::get(Context, Low));
4603 CaseVals.push_back(ConstantInt::get(Context, Low));
4605 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4606 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4607 cve = CaseVals.end(); cvi != cve; ++cvi)
4608 SI->addCase(*cvi, DestBB);
4614 // Old SwitchInst format without case ranges.
4616 if (Record.size() < 3 || (Record.size() & 1) == 0)
4617 return error("Invalid record");
4618 Type *OpTy = getTypeByID(Record[0]);
4619 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4620 BasicBlock *Default = getBasicBlock(Record[2]);
4621 if (!OpTy || !Cond || !Default)
4622 return error("Invalid record");
4623 unsigned NumCases = (Record.size()-3)/2;
4624 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4625 InstructionList.push_back(SI);
4626 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4627 ConstantInt *CaseVal =
4628 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4629 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4630 if (!CaseVal || !DestBB) {
4632 return error("Invalid record");
4634 SI->addCase(CaseVal, DestBB);
4639 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4640 if (Record.size() < 2)
4641 return error("Invalid record");
4642 Type *OpTy = getTypeByID(Record[0]);
4643 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4644 if (!OpTy || !Address)
4645 return error("Invalid record");
4646 unsigned NumDests = Record.size()-2;
4647 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4648 InstructionList.push_back(IBI);
4649 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4650 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4651 IBI->addDestination(DestBB);
4654 return error("Invalid record");
4661 case bitc::FUNC_CODE_INST_INVOKE: {
4662 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4663 if (Record.size() < 4)
4664 return error("Invalid record");
4666 AttributeSet PAL = getAttributes(Record[OpNum++]);
4667 unsigned CCInfo = Record[OpNum++];
4668 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4669 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4671 FunctionType *FTy = nullptr;
4672 if (CCInfo >> 13 & 1 &&
4673 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4674 return error("Explicit invoke type is not a function type");
4677 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4678 return error("Invalid record");
4680 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4682 return error("Callee is not a pointer");
4684 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4686 return error("Callee is not of pointer to function type");
4687 } else if (CalleeTy->getElementType() != FTy)
4688 return error("Explicit invoke type does not match pointee type of "
4690 if (Record.size() < FTy->getNumParams() + OpNum)
4691 return error("Insufficient operands to call");
4693 SmallVector<Value*, 16> Ops;
4694 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4695 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4696 FTy->getParamType(i)));
4698 return error("Invalid record");
4701 if (!FTy->isVarArg()) {
4702 if (Record.size() != OpNum)
4703 return error("Invalid record");
4705 // Read type/value pairs for varargs params.
4706 while (OpNum != Record.size()) {
4708 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4709 return error("Invalid record");
4714 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4715 OperandBundles.clear();
4716 InstructionList.push_back(I);
4717 cast<InvokeInst>(I)->setCallingConv(
4718 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4719 cast<InvokeInst>(I)->setAttributes(PAL);
4722 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4724 Value *Val = nullptr;
4725 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4726 return error("Invalid record");
4727 I = ResumeInst::Create(Val);
4728 InstructionList.push_back(I);
4731 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4732 I = new UnreachableInst(Context);
4733 InstructionList.push_back(I);
4735 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4736 if (Record.size() < 1 || ((Record.size()-1)&1))
4737 return error("Invalid record");
4738 Type *Ty = getTypeByID(Record[0]);
4740 return error("Invalid record");
4742 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4743 InstructionList.push_back(PN);
4745 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4747 // With the new function encoding, it is possible that operands have
4748 // negative IDs (for forward references). Use a signed VBR
4749 // representation to keep the encoding small.
4751 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4753 V = getValue(Record, 1+i, NextValueNo, Ty);
4754 BasicBlock *BB = getBasicBlock(Record[2+i]);
4756 return error("Invalid record");
4757 PN->addIncoming(V, BB);
4763 case bitc::FUNC_CODE_INST_LANDINGPAD:
4764 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4765 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4767 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4768 if (Record.size() < 3)
4769 return error("Invalid record");
4771 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4772 if (Record.size() < 4)
4773 return error("Invalid record");
4775 Type *Ty = getTypeByID(Record[Idx++]);
4777 return error("Invalid record");
4778 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4779 Value *PersFn = nullptr;
4780 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4781 return error("Invalid record");
4783 if (!F->hasPersonalityFn())
4784 F->setPersonalityFn(cast<Constant>(PersFn));
4785 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4786 return error("Personality function mismatch");
4789 bool IsCleanup = !!Record[Idx++];
4790 unsigned NumClauses = Record[Idx++];
4791 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4792 LP->setCleanup(IsCleanup);
4793 for (unsigned J = 0; J != NumClauses; ++J) {
4794 LandingPadInst::ClauseType CT =
4795 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4798 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4800 return error("Invalid record");
4803 assert((CT != LandingPadInst::Catch ||
4804 !isa<ArrayType>(Val->getType())) &&
4805 "Catch clause has a invalid type!");
4806 assert((CT != LandingPadInst::Filter ||
4807 isa<ArrayType>(Val->getType())) &&
4808 "Filter clause has invalid type!");
4809 LP->addClause(cast<Constant>(Val));
4813 InstructionList.push_back(I);
4817 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4818 if (Record.size() != 4)
4819 return error("Invalid record");
4820 uint64_t AlignRecord = Record[3];
4821 const uint64_t InAllocaMask = uint64_t(1) << 5;
4822 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4823 // Reserve bit 7 for SwiftError flag.
4824 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4825 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4826 bool InAlloca = AlignRecord & InAllocaMask;
4827 Type *Ty = getTypeByID(Record[0]);
4828 if ((AlignRecord & ExplicitTypeMask) == 0) {
4829 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4831 return error("Old-style alloca with a non-pointer type");
4832 Ty = PTy->getElementType();
4834 Type *OpTy = getTypeByID(Record[1]);
4835 Value *Size = getFnValueByID(Record[2], OpTy);
4837 if (std::error_code EC =
4838 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4842 return error("Invalid record");
4843 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4844 AI->setUsedWithInAlloca(InAlloca);
4846 InstructionList.push_back(I);
4849 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4852 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4853 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4854 return error("Invalid record");
4857 if (OpNum + 3 == Record.size())
4858 Ty = getTypeByID(Record[OpNum++]);
4859 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4862 Ty = cast<PointerType>(Op->getType())->getElementType();
4865 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4867 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4869 InstructionList.push_back(I);
4872 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4873 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4876 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4877 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4878 return error("Invalid record");
4881 if (OpNum + 5 == Record.size())
4882 Ty = getTypeByID(Record[OpNum++]);
4883 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4886 Ty = cast<PointerType>(Op->getType())->getElementType();
4888 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4889 if (Ordering == NotAtomic || Ordering == Release ||
4890 Ordering == AcquireRelease)
4891 return error("Invalid record");
4892 if (Ordering != NotAtomic && Record[OpNum] == 0)
4893 return error("Invalid record");
4894 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4897 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4899 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4901 InstructionList.push_back(I);
4904 case bitc::FUNC_CODE_INST_STORE:
4905 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4908 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4909 (BitCode == bitc::FUNC_CODE_INST_STORE
4910 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4911 : popValue(Record, OpNum, NextValueNo,
4912 cast<PointerType>(Ptr->getType())->getElementType(),
4914 OpNum + 2 != Record.size())
4915 return error("Invalid record");
4917 if (std::error_code EC =
4918 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4921 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4923 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4924 InstructionList.push_back(I);
4927 case bitc::FUNC_CODE_INST_STOREATOMIC:
4928 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4929 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4932 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4933 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4934 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4935 : popValue(Record, OpNum, NextValueNo,
4936 cast<PointerType>(Ptr->getType())->getElementType(),
4938 OpNum + 4 != Record.size())
4939 return error("Invalid record");
4941 if (std::error_code EC =
4942 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4944 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4945 if (Ordering == NotAtomic || Ordering == Acquire ||
4946 Ordering == AcquireRelease)
4947 return error("Invalid record");
4948 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4949 if (Ordering != NotAtomic && Record[OpNum] == 0)
4950 return error("Invalid record");
4953 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4955 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4956 InstructionList.push_back(I);
4959 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4960 case bitc::FUNC_CODE_INST_CMPXCHG: {
4961 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4962 // failureordering?, isweak?]
4964 Value *Ptr, *Cmp, *New;
4965 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4966 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4967 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4968 : popValue(Record, OpNum, NextValueNo,
4969 cast<PointerType>(Ptr->getType())->getElementType(),
4971 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4972 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4973 return error("Invalid record");
4974 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4975 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4976 return error("Invalid record");
4977 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4979 if (std::error_code EC =
4980 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4982 AtomicOrdering FailureOrdering;
4983 if (Record.size() < 7)
4985 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4987 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4989 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4991 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4993 if (Record.size() < 8) {
4994 // Before weak cmpxchgs existed, the instruction simply returned the
4995 // value loaded from memory, so bitcode files from that era will be
4996 // expecting the first component of a modern cmpxchg.
4997 CurBB->getInstList().push_back(I);
4998 I = ExtractValueInst::Create(I, 0);
5000 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5003 InstructionList.push_back(I);
5006 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5007 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5010 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5011 popValue(Record, OpNum, NextValueNo,
5012 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5013 OpNum+4 != Record.size())
5014 return error("Invalid record");
5015 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5016 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5017 Operation > AtomicRMWInst::LAST_BINOP)
5018 return error("Invalid record");
5019 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5020 if (Ordering == NotAtomic || Ordering == Unordered)
5021 return error("Invalid record");
5022 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5023 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5024 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5025 InstructionList.push_back(I);
5028 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5029 if (2 != Record.size())
5030 return error("Invalid record");
5031 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5032 if (Ordering == NotAtomic || Ordering == Unordered ||
5033 Ordering == Monotonic)
5034 return error("Invalid record");
5035 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5036 I = new FenceInst(Context, Ordering, SynchScope);
5037 InstructionList.push_back(I);
5040 case bitc::FUNC_CODE_INST_CALL: {
5041 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5042 if (Record.size() < 3)
5043 return error("Invalid record");
5046 AttributeSet PAL = getAttributes(Record[OpNum++]);
5047 unsigned CCInfo = Record[OpNum++];
5050 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5051 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5053 return error("Fast math flags indicator set for call with no FMF");
5056 FunctionType *FTy = nullptr;
5057 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5058 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5059 return error("Explicit call type is not a function type");
5062 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5063 return error("Invalid record");
5065 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5067 return error("Callee is not a pointer type");
5069 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5071 return error("Callee is not of pointer to function type");
5072 } else if (OpTy->getElementType() != FTy)
5073 return error("Explicit call type does not match pointee type of "
5075 if (Record.size() < FTy->getNumParams() + OpNum)
5076 return error("Insufficient operands to call");
5078 SmallVector<Value*, 16> Args;
5079 // Read the fixed params.
5080 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5081 if (FTy->getParamType(i)->isLabelTy())
5082 Args.push_back(getBasicBlock(Record[OpNum]));
5084 Args.push_back(getValue(Record, OpNum, NextValueNo,
5085 FTy->getParamType(i)));
5087 return error("Invalid record");
5090 // Read type/value pairs for varargs params.
5091 if (!FTy->isVarArg()) {
5092 if (OpNum != Record.size())
5093 return error("Invalid record");
5095 while (OpNum != Record.size()) {
5097 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5098 return error("Invalid record");
5103 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5104 OperandBundles.clear();
5105 InstructionList.push_back(I);
5106 cast<CallInst>(I)->setCallingConv(
5107 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5108 CallInst::TailCallKind TCK = CallInst::TCK_None;
5109 if (CCInfo & 1 << bitc::CALL_TAIL)
5110 TCK = CallInst::TCK_Tail;
5111 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5112 TCK = CallInst::TCK_MustTail;
5113 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5114 TCK = CallInst::TCK_NoTail;
5115 cast<CallInst>(I)->setTailCallKind(TCK);
5116 cast<CallInst>(I)->setAttributes(PAL);
5118 if (!isa<FPMathOperator>(I))
5119 return error("Fast-math-flags specified for call without "
5120 "floating-point scalar or vector return type");
5121 I->setFastMathFlags(FMF);
5125 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5126 if (Record.size() < 3)
5127 return error("Invalid record");
5128 Type *OpTy = getTypeByID(Record[0]);
5129 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5130 Type *ResTy = getTypeByID(Record[2]);
5131 if (!OpTy || !Op || !ResTy)
5132 return error("Invalid record");
5133 I = new VAArgInst(Op, ResTy);
5134 InstructionList.push_back(I);
5138 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5139 // A call or an invoke can be optionally prefixed with some variable
5140 // number of operand bundle blocks. These blocks are read into
5141 // OperandBundles and consumed at the next call or invoke instruction.
5143 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5144 return error("Invalid record");
5146 std::vector<Value *> Inputs;
5149 while (OpNum != Record.size()) {
5151 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5152 return error("Invalid record");
5153 Inputs.push_back(Op);
5156 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5161 // Add instruction to end of current BB. If there is no current BB, reject
5165 return error("Invalid instruction with no BB");
5167 if (!OperandBundles.empty()) {
5169 return error("Operand bundles found with no consumer");
5171 CurBB->getInstList().push_back(I);
5173 // If this was a terminator instruction, move to the next block.
5174 if (isa<TerminatorInst>(I)) {
5176 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5179 // Non-void values get registered in the value table for future use.
5180 if (I && !I->getType()->isVoidTy())
5181 ValueList.assignValue(I, NextValueNo++);
5186 if (!OperandBundles.empty())
5187 return error("Operand bundles found with no consumer");
5189 // Check the function list for unresolved values.
5190 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5191 if (!A->getParent()) {
5192 // We found at least one unresolved value. Nuke them all to avoid leaks.
5193 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5194 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5195 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5199 return error("Never resolved value found in function");
5203 // FIXME: Check for unresolved forward-declared metadata references
5204 // and clean up leaks.
5206 // Trim the value list down to the size it was before we parsed this function.
5207 ValueList.shrinkTo(ModuleValueListSize);
5208 MetadataList.shrinkTo(ModuleMetadataListSize);
5209 std::vector<BasicBlock*>().swap(FunctionBBs);
5210 return std::error_code();
5213 /// Find the function body in the bitcode stream
5214 std::error_code BitcodeReader::findFunctionInStream(
5216 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5217 while (DeferredFunctionInfoIterator->second == 0) {
5218 // This is the fallback handling for the old format bitcode that
5219 // didn't contain the function index in the VST, or when we have
5220 // an anonymous function which would not have a VST entry.
5221 // Assert that we have one of those two cases.
5222 assert(VSTOffset == 0 || !F->hasName());
5223 // Parse the next body in the stream and set its position in the
5224 // DeferredFunctionInfo map.
5225 if (std::error_code EC = rememberAndSkipFunctionBodies())
5228 return std::error_code();
5231 //===----------------------------------------------------------------------===//
5232 // GVMaterializer implementation
5233 //===----------------------------------------------------------------------===//
5235 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5237 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5238 // In older bitcode we must materialize the metadata before parsing
5239 // any functions, in order to set up the MetadataList properly.
5240 if (!SeenModuleValuesRecord) {
5241 if (std::error_code EC = materializeMetadata())
5245 Function *F = dyn_cast<Function>(GV);
5246 // If it's not a function or is already material, ignore the request.
5247 if (!F || !F->isMaterializable())
5248 return std::error_code();
5250 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5251 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5252 // If its position is recorded as 0, its body is somewhere in the stream
5253 // but we haven't seen it yet.
5254 if (DFII->second == 0)
5255 if (std::error_code EC = findFunctionInStream(F, DFII))
5258 // Move the bit stream to the saved position of the deferred function body.
5259 Stream.JumpToBit(DFII->second);
5261 if (std::error_code EC = parseFunctionBody(F))
5263 F->setIsMaterializable(false);
5268 // Upgrade any old intrinsic calls in the function.
5269 for (auto &I : UpgradedIntrinsics) {
5270 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5274 if (CallInst *CI = dyn_cast<CallInst>(U))
5275 UpgradeIntrinsicCall(CI, I.second);
5279 // Finish fn->subprogram upgrade for materialized functions.
5280 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5281 F->setSubprogram(SP);
5283 // Bring in any functions that this function forward-referenced via
5285 return materializeForwardReferencedFunctions();
5288 std::error_code BitcodeReader::materializeModule() {
5289 if (std::error_code EC = materializeMetadata())
5292 // Promise to materialize all forward references.
5293 WillMaterializeAllForwardRefs = true;
5295 // Iterate over the module, deserializing any functions that are still on
5297 for (Function &F : *TheModule) {
5298 if (std::error_code EC = materialize(&F))
5301 // At this point, if there are any function bodies, parse the rest of
5302 // the bits in the module past the last function block we have recorded
5303 // through either lazy scanning or the VST.
5304 if (LastFunctionBlockBit || NextUnreadBit)
5305 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5308 // Check that all block address forward references got resolved (as we
5310 if (!BasicBlockFwdRefs.empty())
5311 return error("Never resolved function from blockaddress");
5313 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5314 // delete the old functions to clean up. We can't do this unless the entire
5315 // module is materialized because there could always be another function body
5316 // with calls to the old function.
5317 for (auto &I : UpgradedIntrinsics) {
5318 for (auto *U : I.first->users()) {
5319 if (CallInst *CI = dyn_cast<CallInst>(U))
5320 UpgradeIntrinsicCall(CI, I.second);
5322 if (!I.first->use_empty())
5323 I.first->replaceAllUsesWith(I.second);
5324 I.first->eraseFromParent();
5326 UpgradedIntrinsics.clear();
5328 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5329 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5331 UpgradeDebugInfo(*TheModule);
5332 return std::error_code();
5335 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5336 return IdentifiedStructTypes;
5340 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5342 return initLazyStream(std::move(Streamer));
5343 return initStreamFromBuffer();
5346 std::error_code BitcodeReader::initStreamFromBuffer() {
5347 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5348 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5350 if (Buffer->getBufferSize() & 3)
5351 return error("Invalid bitcode signature");
5353 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5354 // The magic number is 0x0B17C0DE stored in little endian.
5355 if (isBitcodeWrapper(BufPtr, BufEnd))
5356 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5357 return error("Invalid bitcode wrapper header");
5359 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5360 Stream.init(&*StreamFile);
5362 return std::error_code();
5366 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5367 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5370 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5371 StreamingMemoryObject &Bytes = *OwnedBytes;
5372 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5373 Stream.init(&*StreamFile);
5375 unsigned char buf[16];
5376 if (Bytes.readBytes(buf, 16, 0) != 16)
5377 return error("Invalid bitcode signature");
5379 if (!isBitcode(buf, buf + 16))
5380 return error("Invalid bitcode signature");
5382 if (isBitcodeWrapper(buf, buf + 4)) {
5383 const unsigned char *bitcodeStart = buf;
5384 const unsigned char *bitcodeEnd = buf + 16;
5385 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5386 Bytes.dropLeadingBytes(bitcodeStart - buf);
5387 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5389 return std::error_code();
5392 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5393 const Twine &Message) {
5394 return ::error(DiagnosticHandler, make_error_code(E), Message);
5397 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5398 return ::error(DiagnosticHandler,
5399 make_error_code(BitcodeError::CorruptedBitcode), Message);
5402 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5403 return ::error(DiagnosticHandler, make_error_code(E));
5406 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5407 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5408 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5409 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
5410 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5412 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5413 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5414 bool CheckFuncSummaryPresenceOnly)
5415 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
5416 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5418 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5420 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5422 // Specialized value symbol table parser used when reading function index
5423 // blocks where we don't actually create global values.
5424 // At the end of this routine the function index is populated with a map
5425 // from function name to FunctionInfo. The function info contains
5426 // the function block's bitcode offset as well as the offset into the
5427 // function summary section.
5428 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5429 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5430 return error("Invalid record");
5432 SmallVector<uint64_t, 64> Record;
5434 // Read all the records for this value table.
5435 SmallString<128> ValueName;
5437 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5439 switch (Entry.Kind) {
5440 case BitstreamEntry::SubBlock: // Handled for us already.
5441 case BitstreamEntry::Error:
5442 return error("Malformed block");
5443 case BitstreamEntry::EndBlock:
5444 return std::error_code();
5445 case BitstreamEntry::Record:
5446 // The interesting case.
5452 switch (Stream.readRecord(Entry.ID, Record)) {
5453 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5455 case bitc::VST_CODE_FNENTRY: {
5456 // VST_FNENTRY: [valueid, offset, namechar x N]
5457 if (convertToString(Record, 2, ValueName))
5458 return error("Invalid record");
5459 unsigned ValueID = Record[0];
5460 uint64_t FuncOffset = Record[1];
5461 std::unique_ptr<FunctionInfo> FuncInfo =
5462 llvm::make_unique<FunctionInfo>(FuncOffset);
5463 if (foundFuncSummary() && !IsLazy) {
5464 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5465 SummaryMap.find(ValueID);
5466 assert(SMI != SummaryMap.end() && "Summary info not found");
5467 FuncInfo->setFunctionSummary(std::move(SMI->second));
5469 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5474 case bitc::VST_CODE_COMBINED_FNENTRY: {
5475 // VST_FNENTRY: [offset, namechar x N]
5476 if (convertToString(Record, 1, ValueName))
5477 return error("Invalid record");
5478 uint64_t FuncSummaryOffset = Record[0];
5479 std::unique_ptr<FunctionInfo> FuncInfo =
5480 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5481 if (foundFuncSummary() && !IsLazy) {
5482 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5483 SummaryMap.find(FuncSummaryOffset);
5484 assert(SMI != SummaryMap.end() && "Summary info not found");
5485 FuncInfo->setFunctionSummary(std::move(SMI->second));
5487 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5496 // Parse just the blocks needed for function index building out of the module.
5497 // At the end of this routine the function Index is populated with a map
5498 // from function name to FunctionInfo. The function info contains
5499 // either the parsed function summary information (when parsing summaries
5500 // eagerly), or just to the function summary record's offset
5501 // if parsing lazily (IsLazy).
5502 std::error_code FunctionIndexBitcodeReader::parseModule() {
5503 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5504 return error("Invalid record");
5506 // Read the function index for this module.
5508 BitstreamEntry Entry = Stream.advance();
5510 switch (Entry.Kind) {
5511 case BitstreamEntry::Error:
5512 return error("Malformed block");
5513 case BitstreamEntry::EndBlock:
5514 return std::error_code();
5516 case BitstreamEntry::SubBlock:
5517 if (CheckFuncSummaryPresenceOnly) {
5518 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) {
5519 SeenFuncSummary = true;
5520 // No need to parse the rest since we found the summary.
5521 return std::error_code();
5523 if (Stream.SkipBlock())
5524 return error("Invalid record");
5528 default: // Skip unknown content.
5529 if (Stream.SkipBlock())
5530 return error("Invalid record");
5532 case bitc::BLOCKINFO_BLOCK_ID:
5533 // Need to parse these to get abbrev ids (e.g. for VST)
5534 if (Stream.ReadBlockInfoBlock())
5535 return error("Malformed block");
5537 case bitc::VALUE_SYMTAB_BLOCK_ID:
5538 if (std::error_code EC = parseValueSymbolTable())
5541 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5542 SeenFuncSummary = true;
5544 // Lazy parsing of summary info, skip it.
5545 if (Stream.SkipBlock())
5546 return error("Invalid record");
5547 } else if (std::error_code EC = parseEntireSummary())
5550 case bitc::MODULE_STRTAB_BLOCK_ID:
5551 if (std::error_code EC = parseModuleStringTable())
5557 case BitstreamEntry::Record:
5558 Stream.skipRecord(Entry.ID);
5564 // Eagerly parse the entire function summary block (i.e. for all functions
5565 // in the index). This populates the FunctionSummary objects in
5567 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5568 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5569 return error("Invalid record");
5571 SmallVector<uint64_t, 64> Record;
5574 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5576 switch (Entry.Kind) {
5577 case BitstreamEntry::SubBlock: // Handled for us already.
5578 case BitstreamEntry::Error:
5579 return error("Malformed block");
5580 case BitstreamEntry::EndBlock:
5581 return std::error_code();
5582 case BitstreamEntry::Record:
5583 // The interesting case.
5587 // Read a record. The record format depends on whether this
5588 // is a per-module index or a combined index file. In the per-module
5589 // case the records contain the associated value's ID for correlation
5590 // with VST entries. In the combined index the correlation is done
5591 // via the bitcode offset of the summary records (which were saved
5592 // in the combined index VST entries). The records also contain
5593 // information used for ThinLTO renaming and importing.
5595 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5596 switch (Stream.readRecord(Entry.ID, Record)) {
5597 default: // Default behavior: ignore.
5599 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5600 case bitc::FS_CODE_PERMODULE_ENTRY: {
5601 unsigned ValueID = Record[0];
5602 bool IsLocal = Record[1];
5603 unsigned InstCount = Record[2];
5604 std::unique_ptr<FunctionSummary> FS =
5605 llvm::make_unique<FunctionSummary>(InstCount);
5606 FS->setLocalFunction(IsLocal);
5607 // The module path string ref set in the summary must be owned by the
5608 // index's module string table. Since we don't have a module path
5609 // string table section in the per-module index, we create a single
5610 // module path string table entry with an empty (0) ID to take
5613 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5614 SummaryMap[ValueID] = std::move(FS);
5616 // FS_COMBINED_ENTRY: [modid, instcount]
5617 case bitc::FS_CODE_COMBINED_ENTRY: {
5618 uint64_t ModuleId = Record[0];
5619 unsigned InstCount = Record[1];
5620 std::unique_ptr<FunctionSummary> FS =
5621 llvm::make_unique<FunctionSummary>(InstCount);
5622 FS->setModulePath(ModuleIdMap[ModuleId]);
5623 SummaryMap[CurRecordBit] = std::move(FS);
5627 llvm_unreachable("Exit infinite loop");
5630 // Parse the module string table block into the Index.
5631 // This populates the ModulePathStringTable map in the index.
5632 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5633 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5634 return error("Invalid record");
5636 SmallVector<uint64_t, 64> Record;
5638 SmallString<128> ModulePath;
5640 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5642 switch (Entry.Kind) {
5643 case BitstreamEntry::SubBlock: // Handled for us already.
5644 case BitstreamEntry::Error:
5645 return error("Malformed block");
5646 case BitstreamEntry::EndBlock:
5647 return std::error_code();
5648 case BitstreamEntry::Record:
5649 // The interesting case.
5654 switch (Stream.readRecord(Entry.ID, Record)) {
5655 default: // Default behavior: ignore.
5657 case bitc::MST_CODE_ENTRY: {
5658 // MST_ENTRY: [modid, namechar x N]
5659 if (convertToString(Record, 1, ModulePath))
5660 return error("Invalid record");
5661 uint64_t ModuleId = Record[0];
5662 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5663 ModuleIdMap[ModuleId] = ModulePathInMap;
5669 llvm_unreachable("Exit infinite loop");
5672 // Parse the function info index from the bitcode streamer into the given index.
5673 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5674 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5677 if (std::error_code EC = initStream(std::move(Streamer)))
5680 // Sniff for the signature.
5681 if (!hasValidBitcodeHeader(Stream))
5682 return error("Invalid bitcode signature");
5684 // We expect a number of well-defined blocks, though we don't necessarily
5685 // need to understand them all.
5687 if (Stream.AtEndOfStream()) {
5688 // We didn't really read a proper Module block.
5689 return error("Malformed block");
5692 BitstreamEntry Entry =
5693 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5695 if (Entry.Kind != BitstreamEntry::SubBlock)
5696 return error("Malformed block");
5698 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5699 // building the function summary index.
5700 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5701 return parseModule();
5703 if (Stream.SkipBlock())
5704 return error("Invalid record");
5708 // Parse the function information at the given offset in the buffer into
5709 // the index. Used to support lazy parsing of function summaries from the
5710 // combined index during importing.
5711 // TODO: This function is not yet complete as it won't have a consumer
5712 // until ThinLTO function importing is added.
5713 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5714 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5715 size_t FunctionSummaryOffset) {
5718 if (std::error_code EC = initStream(std::move(Streamer)))
5721 // Sniff for the signature.
5722 if (!hasValidBitcodeHeader(Stream))
5723 return error("Invalid bitcode signature");
5725 Stream.JumpToBit(FunctionSummaryOffset);
5727 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5729 switch (Entry.Kind) {
5731 return error("Malformed block");
5732 case BitstreamEntry::Record:
5733 // The expected case.
5737 // TODO: Read a record. This interface will be completed when ThinLTO
5738 // importing is added so that it can be tested.
5739 SmallVector<uint64_t, 64> Record;
5740 switch (Stream.readRecord(Entry.ID, Record)) {
5741 case bitc::FS_CODE_COMBINED_ENTRY:
5743 return error("Invalid record");
5746 return std::error_code();
5750 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5752 return initLazyStream(std::move(Streamer));
5753 return initStreamFromBuffer();
5756 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5757 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5758 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5760 if (Buffer->getBufferSize() & 3)
5761 return error("Invalid bitcode signature");
5763 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5764 // The magic number is 0x0B17C0DE stored in little endian.
5765 if (isBitcodeWrapper(BufPtr, BufEnd))
5766 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5767 return error("Invalid bitcode wrapper header");
5769 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5770 Stream.init(&*StreamFile);
5772 return std::error_code();
5775 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5776 std::unique_ptr<DataStreamer> Streamer) {
5777 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5780 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5781 StreamingMemoryObject &Bytes = *OwnedBytes;
5782 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5783 Stream.init(&*StreamFile);
5785 unsigned char buf[16];
5786 if (Bytes.readBytes(buf, 16, 0) != 16)
5787 return error("Invalid bitcode signature");
5789 if (!isBitcode(buf, buf + 16))
5790 return error("Invalid bitcode signature");
5792 if (isBitcodeWrapper(buf, buf + 4)) {
5793 const unsigned char *bitcodeStart = buf;
5794 const unsigned char *bitcodeEnd = buf + 16;
5795 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5796 Bytes.dropLeadingBytes(bitcodeStart - buf);
5797 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5799 return std::error_code();
5803 class BitcodeErrorCategoryType : public std::error_category {
5804 const char *name() const LLVM_NOEXCEPT override {
5805 return "llvm.bitcode";
5807 std::string message(int IE) const override {
5808 BitcodeError E = static_cast<BitcodeError>(IE);
5810 case BitcodeError::InvalidBitcodeSignature:
5811 return "Invalid bitcode signature";
5812 case BitcodeError::CorruptedBitcode:
5813 return "Corrupted bitcode";
5815 llvm_unreachable("Unknown error type!");
5820 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5822 const std::error_category &llvm::BitcodeErrorCategory() {
5823 return *ErrorCategory;
5826 //===----------------------------------------------------------------------===//
5827 // External interface
5828 //===----------------------------------------------------------------------===//
5830 static ErrorOr<std::unique_ptr<Module>>
5831 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5832 BitcodeReader *R, LLVMContext &Context,
5833 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5834 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5835 M->setMaterializer(R);
5837 auto cleanupOnError = [&](std::error_code EC) {
5838 R->releaseBuffer(); // Never take ownership on error.
5842 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5843 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5844 ShouldLazyLoadMetadata))
5845 return cleanupOnError(EC);
5847 if (MaterializeAll) {
5848 // Read in the entire module, and destroy the BitcodeReader.
5849 if (std::error_code EC = M->materializeAll())
5850 return cleanupOnError(EC);
5852 // Resolve forward references from blockaddresses.
5853 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5854 return cleanupOnError(EC);
5856 return std::move(M);
5859 /// \brief Get a lazy one-at-time loading module from bitcode.
5861 /// This isn't always used in a lazy context. In particular, it's also used by
5862 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5863 /// in forward-referenced functions from block address references.
5865 /// \param[in] MaterializeAll Set to \c true if we should materialize
5867 static ErrorOr<std::unique_ptr<Module>>
5868 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5869 LLVMContext &Context, bool MaterializeAll,
5870 bool ShouldLazyLoadMetadata = false) {
5871 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
5873 ErrorOr<std::unique_ptr<Module>> Ret =
5874 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5875 MaterializeAll, ShouldLazyLoadMetadata);
5879 Buffer.release(); // The BitcodeReader owns it now.
5883 ErrorOr<std::unique_ptr<Module>>
5884 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
5885 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
5886 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5887 ShouldLazyLoadMetadata);
5890 ErrorOr<std::unique_ptr<Module>>
5891 llvm::getStreamedBitcodeModule(StringRef Name,
5892 std::unique_ptr<DataStreamer> Streamer,
5893 LLVMContext &Context) {
5894 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5895 BitcodeReader *R = new BitcodeReader(Context);
5897 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5901 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5902 LLVMContext &Context) {
5903 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5904 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
5905 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5906 // written. We must defer until the Module has been fully materialized.
5909 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
5910 LLVMContext &Context) {
5911 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5912 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
5913 ErrorOr<std::string> Triple = R->parseTriple();
5914 if (Triple.getError())
5916 return Triple.get();
5919 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
5920 LLVMContext &Context) {
5921 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5922 BitcodeReader R(Buf.release(), Context);
5923 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5924 if (ProducerString.getError())
5926 return ProducerString.get();
5929 // Parse the specified bitcode buffer, returning the function info index.
5930 // If IsLazy is false, parse the entire function summary into
5931 // the index. Otherwise skip the function summary section, and only create
5932 // an index object with a map from function name to function summary offset.
5933 // The index is used to perform lazy function summary reading later.
5934 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5935 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer,
5936 DiagnosticHandlerFunction DiagnosticHandler,
5938 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5939 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
5941 auto Index = llvm::make_unique<FunctionInfoIndex>();
5943 auto cleanupOnError = [&](std::error_code EC) {
5944 R.releaseBuffer(); // Never take ownership on error.
5948 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5949 return cleanupOnError(EC);
5951 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5952 return std::move(Index);
5955 // Check if the given bitcode buffer contains a function summary block.
5956 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer,
5957 DiagnosticHandlerFunction DiagnosticHandler) {
5958 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5959 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
5961 auto cleanupOnError = [&](std::error_code EC) {
5962 R.releaseBuffer(); // Never take ownership on error.
5966 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5967 return cleanupOnError(EC);
5969 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5970 return R.foundFuncSummary();
5973 // This method supports lazy reading of function summary data from the combined
5974 // index during ThinLTO function importing. When reading the combined index
5975 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5976 // Then this method is called for each function considered for importing,
5977 // to parse the summary information for the given function name into
5979 std::error_code llvm::readFunctionSummary(
5980 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5981 StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) {
5982 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5983 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
5985 auto cleanupOnError = [&](std::error_code EC) {
5986 R.releaseBuffer(); // Never take ownership on error.
5990 // Lookup the given function name in the FunctionMap, which may
5991 // contain a list of function infos in the case of a COMDAT. Walk through
5992 // and parse each function summary info at the function summary offset
5993 // recorded when parsing the value symbol table.
5994 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5995 size_t FunctionSummaryOffset = FI->bitcodeIndex();
5996 if (std::error_code EC =
5997 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5998 return cleanupOnError(EC);
6001 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
6002 return std::error_code();