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 /// Indicates which operator an operand allows (for the few operands that may
46 /// only reference a certain operator).
47 enum OperatorConstraint {
48 OC_None = 0, // No constraint
49 OC_CatchPad, // Must be CatchPadInst
50 OC_CleanupPad // Must be CleanupPadInst
53 class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
56 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
59 /// ResolveConstantForwardRefs for more information about this.
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
75 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
78 assert(ResolveConstants.empty() && "Constants not resolved?");
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
87 Value *back() const { return ValuePtrs.back(); }
88 void pop_back() { ValuePtrs.pop_back(); }
89 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
96 Value *getValueFwdRef(unsigned Idx, Type *Ty,
97 OperatorConstraint OC = OC_None);
99 bool assignValue(Value *V, unsigned Idx);
101 /// Once all constants are read, this method bulk resolves any forward
103 void resolveConstantForwardRefs();
106 class BitcodeReaderMDValueList {
111 std::vector<TrackingMDRef> MDValuePtrs;
113 LLVMContext &Context;
115 BitcodeReaderMDValueList(LLVMContext &C)
116 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
118 // vector compatibility methods
119 unsigned size() const { return MDValuePtrs.size(); }
120 void resize(unsigned N) { MDValuePtrs.resize(N); }
121 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
122 void clear() { MDValuePtrs.clear(); }
123 Metadata *back() const { return MDValuePtrs.back(); }
124 void pop_back() { MDValuePtrs.pop_back(); }
125 bool empty() const { return MDValuePtrs.empty(); }
127 Metadata *operator[](unsigned i) const {
128 assert(i < MDValuePtrs.size());
129 return MDValuePtrs[i];
132 void shrinkTo(unsigned N) {
133 assert(N <= size() && "Invalid shrinkTo request!");
134 MDValuePtrs.resize(N);
137 Metadata *getValueFwdRef(unsigned Idx);
138 void assignValue(Metadata *MD, unsigned Idx);
139 void tryToResolveCycles();
142 class BitcodeReader : public GVMaterializer {
143 LLVMContext &Context;
144 DiagnosticHandlerFunction DiagnosticHandler;
145 Module *TheModule = nullptr;
146 std::unique_ptr<MemoryBuffer> Buffer;
147 std::unique_ptr<BitstreamReader> StreamFile;
148 BitstreamCursor Stream;
149 // Next offset to start scanning for lazy parsing of function bodies.
150 uint64_t NextUnreadBit = 0;
151 // Last function offset found in the VST.
152 uint64_t LastFunctionBlockBit = 0;
153 bool SeenValueSymbolTable = false;
154 uint64_t VSTOffset = 0;
155 // Contains an arbitrary and optional string identifying the bitcode producer
156 std::string ProducerIdentification;
157 // Number of module level metadata records specified by the
158 // MODULE_CODE_METADATA_VALUES record.
159 unsigned NumModuleMDs = 0;
160 // Support older bitcode without the MODULE_CODE_METADATA_VALUES record.
161 bool SeenModuleValuesRecord = false;
163 std::vector<Type*> TypeList;
164 BitcodeReaderValueList ValueList;
165 BitcodeReaderMDValueList MDValueList;
166 std::vector<Comdat *> ComdatList;
167 SmallVector<Instruction *, 64> InstructionList;
169 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
170 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
171 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
172 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
173 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
175 SmallVector<Instruction*, 64> InstsWithTBAATag;
177 /// The set of attributes by index. Index zero in the file is for null, and
178 /// is thus not represented here. As such all indices are off by one.
179 std::vector<AttributeSet> MAttributes;
181 /// The set of attribute groups.
182 std::map<unsigned, AttributeSet> MAttributeGroups;
184 /// While parsing a function body, this is a list of the basic blocks for the
186 std::vector<BasicBlock*> FunctionBBs;
188 // When reading the module header, this list is populated with functions that
189 // have bodies later in the file.
190 std::vector<Function*> FunctionsWithBodies;
192 // When intrinsic functions are encountered which require upgrading they are
193 // stored here with their replacement function.
194 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
195 UpgradedIntrinsicMap UpgradedIntrinsics;
197 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
198 DenseMap<unsigned, unsigned> MDKindMap;
200 // Several operations happen after the module header has been read, but
201 // before function bodies are processed. This keeps track of whether
202 // we've done this yet.
203 bool SeenFirstFunctionBody = false;
205 /// When function bodies are initially scanned, this map contains info about
206 /// where to find deferred function body in the stream.
207 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
209 /// When Metadata block is initially scanned when parsing the module, we may
210 /// choose to defer parsing of the metadata. This vector contains info about
211 /// which Metadata blocks are deferred.
212 std::vector<uint64_t> DeferredMetadataInfo;
214 /// These are basic blocks forward-referenced by block addresses. They are
215 /// inserted lazily into functions when they're loaded. The basic block ID is
216 /// its index into the vector.
217 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
218 std::deque<Function *> BasicBlockFwdRefQueue;
220 /// Indicates that we are using a new encoding for instruction operands where
221 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
222 /// instruction number, for a more compact encoding. Some instruction
223 /// operands are not relative to the instruction ID: basic block numbers, and
224 /// types. Once the old style function blocks have been phased out, we would
225 /// not need this flag.
226 bool UseRelativeIDs = false;
228 /// True if all functions will be materialized, negating the need to process
229 /// (e.g.) blockaddress forward references.
230 bool WillMaterializeAllForwardRefs = false;
232 /// Functions that have block addresses taken. This is usually empty.
233 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
235 /// True if any Metadata block has been materialized.
236 bool IsMetadataMaterialized = false;
238 bool StripDebugInfo = false;
240 /// Functions that need to be matched with subprograms when upgrading old
242 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
244 std::vector<std::string> BundleTags;
247 std::error_code error(BitcodeError E, const Twine &Message);
248 std::error_code error(BitcodeError E);
249 std::error_code error(const Twine &Message);
251 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
252 DiagnosticHandlerFunction DiagnosticHandler);
253 BitcodeReader(LLVMContext &Context,
254 DiagnosticHandlerFunction DiagnosticHandler);
255 ~BitcodeReader() override { freeState(); }
257 std::error_code materializeForwardReferencedFunctions();
261 void releaseBuffer();
263 bool isDematerializable(const GlobalValue *GV) const override;
264 std::error_code materialize(GlobalValue *GV) override;
265 std::error_code materializeModule(Module *M) override;
266 std::vector<StructType *> getIdentifiedStructTypes() const override;
267 void dematerialize(GlobalValue *GV) override;
269 /// \brief Main interface to parsing a bitcode buffer.
270 /// \returns true if an error occurred.
271 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
273 bool ShouldLazyLoadMetadata = false);
275 /// \brief Cheap mechanism to just extract module triple
276 /// \returns true if an error occurred.
277 ErrorOr<std::string> parseTriple();
279 /// Cheap mechanism to just extract the identification block out of bitcode.
280 ErrorOr<std::string> parseIdentificationBlock();
282 static uint64_t decodeSignRotatedValue(uint64_t V);
284 /// Materialize any deferred Metadata block.
285 std::error_code materializeMetadata() override;
287 void setStripDebugInfo() override;
290 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
291 // ProducerIdentification data member, and do some basic enforcement on the
292 // "epoch" encoded in the bitcode.
293 std::error_code parseBitcodeVersion();
295 std::vector<StructType *> IdentifiedStructTypes;
296 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
297 StructType *createIdentifiedStructType(LLVMContext &Context);
299 Type *getTypeByID(unsigned ID);
300 Value *getFnValueByID(unsigned ID, Type *Ty,
301 OperatorConstraint OC = OC_None) {
302 if (Ty && Ty->isMetadataTy())
303 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
304 return ValueList.getValueFwdRef(ID, Ty, OC);
306 Metadata *getFnMetadataByID(unsigned ID) {
307 return MDValueList.getValueFwdRef(ID);
309 BasicBlock *getBasicBlock(unsigned ID) const {
310 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
311 return FunctionBBs[ID];
313 AttributeSet getAttributes(unsigned i) const {
314 if (i-1 < MAttributes.size())
315 return MAttributes[i-1];
316 return AttributeSet();
319 /// Read a value/type pair out of the specified record from slot 'Slot'.
320 /// Increment Slot past the number of slots used in the record. Return true on
322 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
323 unsigned InstNum, Value *&ResVal) {
324 if (Slot == Record.size()) return true;
325 unsigned ValNo = (unsigned)Record[Slot++];
326 // Adjust the ValNo, if it was encoded relative to the InstNum.
328 ValNo = InstNum - ValNo;
329 if (ValNo < InstNum) {
330 // If this is not a forward reference, just return the value we already
332 ResVal = getFnValueByID(ValNo, nullptr);
333 return ResVal == nullptr;
335 if (Slot == Record.size())
338 unsigned TypeNo = (unsigned)Record[Slot++];
339 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
340 return ResVal == nullptr;
343 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
344 /// past the number of slots used by the value in the record. Return true if
345 /// there is an error.
346 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
347 unsigned InstNum, Type *Ty, Value *&ResVal,
348 OperatorConstraint OC = OC_None) {
349 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
351 // All values currently take a single record slot.
356 /// Like popValue, but does not increment the Slot number.
357 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
358 unsigned InstNum, Type *Ty, Value *&ResVal,
359 OperatorConstraint OC = OC_None) {
360 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
361 return ResVal == nullptr;
364 /// Version of getValue that returns ResVal directly, or 0 if there is an
366 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
367 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
368 if (Slot == Record.size()) return nullptr;
369 unsigned ValNo = (unsigned)Record[Slot];
370 // Adjust the ValNo, if it was encoded relative to the InstNum.
372 ValNo = InstNum - ValNo;
373 return getFnValueByID(ValNo, Ty, OC);
376 /// Like getValue, but decodes signed VBRs.
377 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
378 unsigned InstNum, Type *Ty,
379 OperatorConstraint OC = OC_None) {
380 if (Slot == Record.size()) return nullptr;
381 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
382 // Adjust the ValNo, if it was encoded relative to the InstNum.
384 ValNo = InstNum - ValNo;
385 return getFnValueByID(ValNo, Ty, OC);
388 /// Converts alignment exponent (i.e. power of two (or zero)) to the
389 /// corresponding alignment to use. If alignment is too large, returns
390 /// a corresponding error code.
391 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
392 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
393 std::error_code parseModule(uint64_t ResumeBit,
394 bool ShouldLazyLoadMetadata = false);
395 std::error_code parseAttributeBlock();
396 std::error_code parseAttributeGroupBlock();
397 std::error_code parseTypeTable();
398 std::error_code parseTypeTableBody();
399 std::error_code parseOperandBundleTags();
401 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
402 unsigned NameIndex, Triple &TT);
403 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
404 std::error_code parseConstants();
405 std::error_code rememberAndSkipFunctionBodies();
406 std::error_code rememberAndSkipFunctionBody();
407 /// Save the positions of the Metadata blocks and skip parsing the blocks.
408 std::error_code rememberAndSkipMetadata();
409 std::error_code parseFunctionBody(Function *F);
410 std::error_code globalCleanup();
411 std::error_code resolveGlobalAndAliasInits();
412 std::error_code parseMetadata(bool ModuleLevel = false);
413 std::error_code parseMetadataKinds();
414 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
415 std::error_code parseMetadataAttachment(Function &F);
416 ErrorOr<std::string> parseModuleTriple();
417 std::error_code parseUseLists();
418 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
419 std::error_code initStreamFromBuffer();
420 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
421 std::error_code findFunctionInStream(
423 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
426 /// Class to manage reading and parsing function summary index bitcode
428 class FunctionIndexBitcodeReader {
429 DiagnosticHandlerFunction DiagnosticHandler;
431 /// Eventually points to the function index built during parsing.
432 FunctionInfoIndex *TheIndex = nullptr;
434 std::unique_ptr<MemoryBuffer> Buffer;
435 std::unique_ptr<BitstreamReader> StreamFile;
436 BitstreamCursor Stream;
438 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
440 /// If false, the summary section is fully parsed into the index during
441 /// the initial parse. Otherwise, if true, the caller is expected to
442 /// invoke \a readFunctionSummary for each summary needed, and the summary
443 /// section is thus parsed lazily.
446 /// Used to indicate whether caller only wants to check for the presence
447 /// of the function summary bitcode section. All blocks are skipped,
448 /// but the SeenFuncSummary boolean is set.
449 bool CheckFuncSummaryPresenceOnly = false;
451 /// Indicates whether we have encountered a function summary section
452 /// yet during parsing, used when checking if file contains function
454 bool SeenFuncSummary = false;
456 /// \brief Map populated during function summary section parsing, and
457 /// consumed during ValueSymbolTable parsing.
459 /// Used to correlate summary records with VST entries. For the per-module
460 /// index this maps the ValueID to the parsed function summary, and
461 /// for the combined index this maps the summary record's bitcode
462 /// offset to the function summary (since in the combined index the
463 /// VST records do not hold value IDs but rather hold the function
464 /// summary record offset).
465 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
467 /// Map populated during module path string table parsing, from the
468 /// module ID to a string reference owned by the index's module
469 /// path string table, used to correlate with combined index function
471 DenseMap<uint64_t, StringRef> ModuleIdMap;
474 std::error_code error(BitcodeError E, const Twine &Message);
475 std::error_code error(BitcodeError E);
476 std::error_code error(const Twine &Message);
478 FunctionIndexBitcodeReader(MemoryBuffer *Buffer,
479 DiagnosticHandlerFunction DiagnosticHandler,
481 bool CheckFuncSummaryPresenceOnly = false);
482 FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler,
484 bool CheckFuncSummaryPresenceOnly = false);
485 ~FunctionIndexBitcodeReader() { freeState(); }
489 void releaseBuffer();
491 /// Check if the parser has encountered a function summary section.
492 bool foundFuncSummary() { return SeenFuncSummary; }
494 /// \brief Main interface to parsing a bitcode buffer.
495 /// \returns true if an error occurred.
496 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
497 FunctionInfoIndex *I);
499 /// \brief Interface for parsing a function summary lazily.
500 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
501 FunctionInfoIndex *I,
502 size_t FunctionSummaryOffset);
505 std::error_code parseModule();
506 std::error_code parseValueSymbolTable();
507 std::error_code parseEntireSummary();
508 std::error_code parseModuleStringTable();
509 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
510 std::error_code initStreamFromBuffer();
511 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
515 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
516 DiagnosticSeverity Severity,
518 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
520 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
522 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
523 std::error_code EC, const Twine &Message) {
524 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
525 DiagnosticHandler(DI);
529 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
530 std::error_code EC) {
531 return error(DiagnosticHandler, EC, EC.message());
534 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
535 const Twine &Message) {
536 return error(DiagnosticHandler,
537 make_error_code(BitcodeError::CorruptedBitcode), Message);
540 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
541 if (!ProducerIdentification.empty()) {
542 return ::error(DiagnosticHandler, make_error_code(E),
543 Message + " (Producer: '" + ProducerIdentification +
544 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
546 return ::error(DiagnosticHandler, make_error_code(E), Message);
549 std::error_code BitcodeReader::error(const Twine &Message) {
550 if (!ProducerIdentification.empty()) {
551 return ::error(DiagnosticHandler,
552 make_error_code(BitcodeError::CorruptedBitcode),
553 Message + " (Producer: '" + ProducerIdentification +
554 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
556 return ::error(DiagnosticHandler,
557 make_error_code(BitcodeError::CorruptedBitcode), Message);
560 std::error_code BitcodeReader::error(BitcodeError E) {
561 return ::error(DiagnosticHandler, make_error_code(E));
564 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
568 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
571 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
572 DiagnosticHandlerFunction DiagnosticHandler)
574 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
575 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
577 BitcodeReader::BitcodeReader(LLVMContext &Context,
578 DiagnosticHandlerFunction DiagnosticHandler)
580 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
581 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
583 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
584 if (WillMaterializeAllForwardRefs)
585 return std::error_code();
587 // Prevent recursion.
588 WillMaterializeAllForwardRefs = true;
590 while (!BasicBlockFwdRefQueue.empty()) {
591 Function *F = BasicBlockFwdRefQueue.front();
592 BasicBlockFwdRefQueue.pop_front();
593 assert(F && "Expected valid function");
594 if (!BasicBlockFwdRefs.count(F))
595 // Already materialized.
598 // Check for a function that isn't materializable to prevent an infinite
599 // loop. When parsing a blockaddress stored in a global variable, there
600 // isn't a trivial way to check if a function will have a body without a
601 // linear search through FunctionsWithBodies, so just check it here.
602 if (!F->isMaterializable())
603 return error("Never resolved function from blockaddress");
605 // Try to materialize F.
606 if (std::error_code EC = materialize(F))
609 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
612 WillMaterializeAllForwardRefs = false;
613 return std::error_code();
616 void BitcodeReader::freeState() {
618 std::vector<Type*>().swap(TypeList);
621 std::vector<Comdat *>().swap(ComdatList);
623 std::vector<AttributeSet>().swap(MAttributes);
624 std::vector<BasicBlock*>().swap(FunctionBBs);
625 std::vector<Function*>().swap(FunctionsWithBodies);
626 DeferredFunctionInfo.clear();
627 DeferredMetadataInfo.clear();
630 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
631 BasicBlockFwdRefQueue.clear();
634 //===----------------------------------------------------------------------===//
635 // Helper functions to implement forward reference resolution, etc.
636 //===----------------------------------------------------------------------===//
638 /// Convert a string from a record into an std::string, return true on failure.
639 template <typename StrTy>
640 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
642 if (Idx > Record.size())
645 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
646 Result += (char)Record[i];
650 static bool hasImplicitComdat(size_t Val) {
654 case 1: // Old WeakAnyLinkage
655 case 4: // Old LinkOnceAnyLinkage
656 case 10: // Old WeakODRLinkage
657 case 11: // Old LinkOnceODRLinkage
662 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
664 default: // Map unknown/new linkages to external
666 return GlobalValue::ExternalLinkage;
668 return GlobalValue::AppendingLinkage;
670 return GlobalValue::InternalLinkage;
672 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
674 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
676 return GlobalValue::ExternalWeakLinkage;
678 return GlobalValue::CommonLinkage;
680 return GlobalValue::PrivateLinkage;
682 return GlobalValue::AvailableExternallyLinkage;
684 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
686 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
688 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
689 case 1: // Old value with implicit comdat.
691 return GlobalValue::WeakAnyLinkage;
692 case 10: // Old value with implicit comdat.
694 return GlobalValue::WeakODRLinkage;
695 case 4: // Old value with implicit comdat.
697 return GlobalValue::LinkOnceAnyLinkage;
698 case 11: // Old value with implicit comdat.
700 return GlobalValue::LinkOnceODRLinkage;
704 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
706 default: // Map unknown visibilities to default.
707 case 0: return GlobalValue::DefaultVisibility;
708 case 1: return GlobalValue::HiddenVisibility;
709 case 2: return GlobalValue::ProtectedVisibility;
713 static GlobalValue::DLLStorageClassTypes
714 getDecodedDLLStorageClass(unsigned Val) {
716 default: // Map unknown values to default.
717 case 0: return GlobalValue::DefaultStorageClass;
718 case 1: return GlobalValue::DLLImportStorageClass;
719 case 2: return GlobalValue::DLLExportStorageClass;
723 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
725 case 0: return GlobalVariable::NotThreadLocal;
726 default: // Map unknown non-zero value to general dynamic.
727 case 1: return GlobalVariable::GeneralDynamicTLSModel;
728 case 2: return GlobalVariable::LocalDynamicTLSModel;
729 case 3: return GlobalVariable::InitialExecTLSModel;
730 case 4: return GlobalVariable::LocalExecTLSModel;
734 static int getDecodedCastOpcode(unsigned Val) {
737 case bitc::CAST_TRUNC : return Instruction::Trunc;
738 case bitc::CAST_ZEXT : return Instruction::ZExt;
739 case bitc::CAST_SEXT : return Instruction::SExt;
740 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
741 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
742 case bitc::CAST_UITOFP : return Instruction::UIToFP;
743 case bitc::CAST_SITOFP : return Instruction::SIToFP;
744 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
745 case bitc::CAST_FPEXT : return Instruction::FPExt;
746 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
747 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
748 case bitc::CAST_BITCAST : return Instruction::BitCast;
749 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
753 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
754 bool IsFP = Ty->isFPOrFPVectorTy();
755 // BinOps are only valid for int/fp or vector of int/fp types
756 if (!IsFP && !Ty->isIntOrIntVectorTy())
762 case bitc::BINOP_ADD:
763 return IsFP ? Instruction::FAdd : Instruction::Add;
764 case bitc::BINOP_SUB:
765 return IsFP ? Instruction::FSub : Instruction::Sub;
766 case bitc::BINOP_MUL:
767 return IsFP ? Instruction::FMul : Instruction::Mul;
768 case bitc::BINOP_UDIV:
769 return IsFP ? -1 : Instruction::UDiv;
770 case bitc::BINOP_SDIV:
771 return IsFP ? Instruction::FDiv : Instruction::SDiv;
772 case bitc::BINOP_UREM:
773 return IsFP ? -1 : Instruction::URem;
774 case bitc::BINOP_SREM:
775 return IsFP ? Instruction::FRem : Instruction::SRem;
776 case bitc::BINOP_SHL:
777 return IsFP ? -1 : Instruction::Shl;
778 case bitc::BINOP_LSHR:
779 return IsFP ? -1 : Instruction::LShr;
780 case bitc::BINOP_ASHR:
781 return IsFP ? -1 : Instruction::AShr;
782 case bitc::BINOP_AND:
783 return IsFP ? -1 : Instruction::And;
785 return IsFP ? -1 : Instruction::Or;
786 case bitc::BINOP_XOR:
787 return IsFP ? -1 : Instruction::Xor;
791 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
793 default: return AtomicRMWInst::BAD_BINOP;
794 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
795 case bitc::RMW_ADD: return AtomicRMWInst::Add;
796 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
797 case bitc::RMW_AND: return AtomicRMWInst::And;
798 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
799 case bitc::RMW_OR: return AtomicRMWInst::Or;
800 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
801 case bitc::RMW_MAX: return AtomicRMWInst::Max;
802 case bitc::RMW_MIN: return AtomicRMWInst::Min;
803 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
804 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
808 static AtomicOrdering getDecodedOrdering(unsigned Val) {
810 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
811 case bitc::ORDERING_UNORDERED: return Unordered;
812 case bitc::ORDERING_MONOTONIC: return Monotonic;
813 case bitc::ORDERING_ACQUIRE: return Acquire;
814 case bitc::ORDERING_RELEASE: return Release;
815 case bitc::ORDERING_ACQREL: return AcquireRelease;
816 default: // Map unknown orderings to sequentially-consistent.
817 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
821 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
823 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
824 default: // Map unknown scopes to cross-thread.
825 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
829 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
831 default: // Map unknown selection kinds to any.
832 case bitc::COMDAT_SELECTION_KIND_ANY:
834 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
835 return Comdat::ExactMatch;
836 case bitc::COMDAT_SELECTION_KIND_LARGEST:
837 return Comdat::Largest;
838 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
839 return Comdat::NoDuplicates;
840 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
841 return Comdat::SameSize;
845 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
847 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
848 FMF.setUnsafeAlgebra();
849 if (0 != (Val & FastMathFlags::NoNaNs))
851 if (0 != (Val & FastMathFlags::NoInfs))
853 if (0 != (Val & FastMathFlags::NoSignedZeros))
854 FMF.setNoSignedZeros();
855 if (0 != (Val & FastMathFlags::AllowReciprocal))
856 FMF.setAllowReciprocal();
860 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
862 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
863 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
869 /// \brief A class for maintaining the slot number definition
870 /// as a placeholder for the actual definition for forward constants defs.
871 class ConstantPlaceHolder : public ConstantExpr {
872 void operator=(const ConstantPlaceHolder &) = delete;
875 // allocate space for exactly one operand
876 void *operator new(size_t s) { return User::operator new(s, 1); }
877 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
878 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
879 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
882 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
883 static bool classof(const Value *V) {
884 return isa<ConstantExpr>(V) &&
885 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
888 /// Provide fast operand accessors
889 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
893 // FIXME: can we inherit this from ConstantExpr?
895 struct OperandTraits<ConstantPlaceHolder> :
896 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
898 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
901 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
910 WeakVH &OldV = ValuePtrs[Idx];
916 // Handle constants and non-constants (e.g. instrs) differently for
918 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
919 ResolveConstants.push_back(std::make_pair(PHC, Idx));
922 // If there was a forward reference to this value, replace it.
923 Value *PrevVal = OldV;
924 // Check operator constraints. We only put cleanuppads or catchpads in
925 // the forward value map if the value is constrained to match.
926 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
927 if (!isa<CatchPadInst>(V))
929 // Delete the dummy basic block that was created with the sentinel
931 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
932 assert(DummyBlock == CatchPad->getNormalDest());
933 CatchPad->dropAllReferences();
935 } else if (isa<CleanupPadInst>(PrevVal)) {
936 if (!isa<CleanupPadInst>(V))
939 OldV->replaceAllUsesWith(V);
947 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
952 if (Value *V = ValuePtrs[Idx]) {
953 if (Ty != V->getType())
954 report_fatal_error("Type mismatch in constant table!");
955 return cast<Constant>(V);
958 // Create and return a placeholder, which will later be RAUW'd.
959 Constant *C = new ConstantPlaceHolder(Ty, Context);
964 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
965 OperatorConstraint OC) {
966 // Bail out for a clearly invalid value. This would make us call resize(0)
973 if (Value *V = ValuePtrs[Idx]) {
974 // If the types don't match, it's invalid.
975 if (Ty && Ty != V->getType())
979 // Use dyn_cast to enforce operator constraints
982 return dyn_cast<CatchPadInst>(V);
984 return dyn_cast<CleanupPadInst>(V);
986 llvm_unreachable("Unexpected operator constraint");
990 // No type specified, must be invalid reference.
991 if (!Ty) return nullptr;
993 // Create and return a placeholder, which will later be RAUW'd.
997 V = new Argument(Ty);
1000 BasicBlock *BB = BasicBlock::Create(Context);
1001 V = CatchPadInst::Create(BB, BB, {});
1005 assert(OC == OC_CleanupPad && "unexpected operator constraint");
1006 V = CleanupPadInst::Create(Context, {});
1014 /// Once all constants are read, this method bulk resolves any forward
1015 /// references. The idea behind this is that we sometimes get constants (such
1016 /// as large arrays) which reference *many* forward ref constants. Replacing
1017 /// each of these causes a lot of thrashing when building/reuniquing the
1018 /// constant. Instead of doing this, we look at all the uses and rewrite all
1019 /// the place holders at once for any constant that uses a placeholder.
1020 void BitcodeReaderValueList::resolveConstantForwardRefs() {
1021 // Sort the values by-pointer so that they are efficient to look up with a
1023 std::sort(ResolveConstants.begin(), ResolveConstants.end());
1025 SmallVector<Constant*, 64> NewOps;
1027 while (!ResolveConstants.empty()) {
1028 Value *RealVal = operator[](ResolveConstants.back().second);
1029 Constant *Placeholder = ResolveConstants.back().first;
1030 ResolveConstants.pop_back();
1032 // Loop over all users of the placeholder, updating them to reference the
1033 // new value. If they reference more than one placeholder, update them all
1035 while (!Placeholder->use_empty()) {
1036 auto UI = Placeholder->user_begin();
1039 // If the using object isn't uniqued, just update the operands. This
1040 // handles instructions and initializers for global variables.
1041 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1042 UI.getUse().set(RealVal);
1046 // Otherwise, we have a constant that uses the placeholder. Replace that
1047 // constant with a new constant that has *all* placeholder uses updated.
1048 Constant *UserC = cast<Constant>(U);
1049 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1052 if (!isa<ConstantPlaceHolder>(*I)) {
1053 // Not a placeholder reference.
1055 } else if (*I == Placeholder) {
1056 // Common case is that it just references this one placeholder.
1059 // Otherwise, look up the placeholder in ResolveConstants.
1060 ResolveConstantsTy::iterator It =
1061 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1062 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1064 assert(It != ResolveConstants.end() && It->first == *I);
1065 NewOp = operator[](It->second);
1068 NewOps.push_back(cast<Constant>(NewOp));
1071 // Make the new constant.
1073 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1074 NewC = ConstantArray::get(UserCA->getType(), NewOps);
1075 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1076 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1077 } else if (isa<ConstantVector>(UserC)) {
1078 NewC = ConstantVector::get(NewOps);
1080 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1081 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1084 UserC->replaceAllUsesWith(NewC);
1085 UserC->destroyConstant();
1089 // Update all ValueHandles, they should be the only users at this point.
1090 Placeholder->replaceAllUsesWith(RealVal);
1095 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
1096 if (Idx == size()) {
1104 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1110 // If there was a forward reference to this value, replace it.
1111 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1112 PrevMD->replaceAllUsesWith(MD);
1116 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
1120 if (Metadata *MD = MDValuePtrs[Idx])
1123 // Track forward refs to be resolved later.
1125 MinFwdRef = std::min(MinFwdRef, Idx);
1126 MaxFwdRef = std::max(MaxFwdRef, Idx);
1129 MinFwdRef = MaxFwdRef = Idx;
1133 // Create and return a placeholder, which will later be RAUW'd.
1134 Metadata *MD = MDNode::getTemporary(Context, None).release();
1135 MDValuePtrs[Idx].reset(MD);
1139 void BitcodeReaderMDValueList::tryToResolveCycles() {
1145 // Still forward references... can't resolve cycles.
1148 // Resolve any cycles.
1149 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1150 auto &MD = MDValuePtrs[I];
1151 auto *N = dyn_cast_or_null<MDNode>(MD);
1155 assert(!N->isTemporary() && "Unexpected forward reference");
1159 // Make sure we return early again until there's another forward ref.
1163 Type *BitcodeReader::getTypeByID(unsigned ID) {
1164 // The type table size is always specified correctly.
1165 if (ID >= TypeList.size())
1168 if (Type *Ty = TypeList[ID])
1171 // If we have a forward reference, the only possible case is when it is to a
1172 // named struct. Just create a placeholder for now.
1173 return TypeList[ID] = createIdentifiedStructType(Context);
1176 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1178 auto *Ret = StructType::create(Context, Name);
1179 IdentifiedStructTypes.push_back(Ret);
1183 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1184 auto *Ret = StructType::create(Context);
1185 IdentifiedStructTypes.push_back(Ret);
1190 //===----------------------------------------------------------------------===//
1191 // Functions for parsing blocks from the bitcode file
1192 //===----------------------------------------------------------------------===//
1195 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1196 /// been decoded from the given integer. This function must stay in sync with
1197 /// 'encodeLLVMAttributesForBitcode'.
1198 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1199 uint64_t EncodedAttrs) {
1200 // FIXME: Remove in 4.0.
1202 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1203 // the bits above 31 down by 11 bits.
1204 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1205 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1206 "Alignment must be a power of two.");
1209 B.addAlignmentAttr(Alignment);
1210 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1211 (EncodedAttrs & 0xffff));
1214 std::error_code BitcodeReader::parseAttributeBlock() {
1215 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1216 return error("Invalid record");
1218 if (!MAttributes.empty())
1219 return error("Invalid multiple blocks");
1221 SmallVector<uint64_t, 64> Record;
1223 SmallVector<AttributeSet, 8> Attrs;
1225 // Read all the records.
1227 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1229 switch (Entry.Kind) {
1230 case BitstreamEntry::SubBlock: // Handled for us already.
1231 case BitstreamEntry::Error:
1232 return error("Malformed block");
1233 case BitstreamEntry::EndBlock:
1234 return std::error_code();
1235 case BitstreamEntry::Record:
1236 // The interesting case.
1242 switch (Stream.readRecord(Entry.ID, Record)) {
1243 default: // Default behavior: ignore.
1245 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1246 // FIXME: Remove in 4.0.
1247 if (Record.size() & 1)
1248 return error("Invalid record");
1250 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1252 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1253 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1256 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1260 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1261 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1262 Attrs.push_back(MAttributeGroups[Record[i]]);
1264 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1272 // Returns Attribute::None on unrecognized codes.
1273 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1276 return Attribute::None;
1277 case bitc::ATTR_KIND_ALIGNMENT:
1278 return Attribute::Alignment;
1279 case bitc::ATTR_KIND_ALWAYS_INLINE:
1280 return Attribute::AlwaysInline;
1281 case bitc::ATTR_KIND_ARGMEMONLY:
1282 return Attribute::ArgMemOnly;
1283 case bitc::ATTR_KIND_BUILTIN:
1284 return Attribute::Builtin;
1285 case bitc::ATTR_KIND_BY_VAL:
1286 return Attribute::ByVal;
1287 case bitc::ATTR_KIND_IN_ALLOCA:
1288 return Attribute::InAlloca;
1289 case bitc::ATTR_KIND_COLD:
1290 return Attribute::Cold;
1291 case bitc::ATTR_KIND_CONVERGENT:
1292 return Attribute::Convergent;
1293 case bitc::ATTR_KIND_INLINE_HINT:
1294 return Attribute::InlineHint;
1295 case bitc::ATTR_KIND_IN_REG:
1296 return Attribute::InReg;
1297 case bitc::ATTR_KIND_JUMP_TABLE:
1298 return Attribute::JumpTable;
1299 case bitc::ATTR_KIND_MIN_SIZE:
1300 return Attribute::MinSize;
1301 case bitc::ATTR_KIND_NAKED:
1302 return Attribute::Naked;
1303 case bitc::ATTR_KIND_NEST:
1304 return Attribute::Nest;
1305 case bitc::ATTR_KIND_NO_ALIAS:
1306 return Attribute::NoAlias;
1307 case bitc::ATTR_KIND_NO_BUILTIN:
1308 return Attribute::NoBuiltin;
1309 case bitc::ATTR_KIND_NO_CAPTURE:
1310 return Attribute::NoCapture;
1311 case bitc::ATTR_KIND_NO_DUPLICATE:
1312 return Attribute::NoDuplicate;
1313 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1314 return Attribute::NoImplicitFloat;
1315 case bitc::ATTR_KIND_NO_INLINE:
1316 return Attribute::NoInline;
1317 case bitc::ATTR_KIND_NO_RECURSE:
1318 return Attribute::NoRecurse;
1319 case bitc::ATTR_KIND_NON_LAZY_BIND:
1320 return Attribute::NonLazyBind;
1321 case bitc::ATTR_KIND_NON_NULL:
1322 return Attribute::NonNull;
1323 case bitc::ATTR_KIND_DEREFERENCEABLE:
1324 return Attribute::Dereferenceable;
1325 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1326 return Attribute::DereferenceableOrNull;
1327 case bitc::ATTR_KIND_NO_RED_ZONE:
1328 return Attribute::NoRedZone;
1329 case bitc::ATTR_KIND_NO_RETURN:
1330 return Attribute::NoReturn;
1331 case bitc::ATTR_KIND_NO_UNWIND:
1332 return Attribute::NoUnwind;
1333 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1334 return Attribute::OptimizeForSize;
1335 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1336 return Attribute::OptimizeNone;
1337 case bitc::ATTR_KIND_READ_NONE:
1338 return Attribute::ReadNone;
1339 case bitc::ATTR_KIND_READ_ONLY:
1340 return Attribute::ReadOnly;
1341 case bitc::ATTR_KIND_RETURNED:
1342 return Attribute::Returned;
1343 case bitc::ATTR_KIND_RETURNS_TWICE:
1344 return Attribute::ReturnsTwice;
1345 case bitc::ATTR_KIND_S_EXT:
1346 return Attribute::SExt;
1347 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1348 return Attribute::StackAlignment;
1349 case bitc::ATTR_KIND_STACK_PROTECT:
1350 return Attribute::StackProtect;
1351 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1352 return Attribute::StackProtectReq;
1353 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1354 return Attribute::StackProtectStrong;
1355 case bitc::ATTR_KIND_SAFESTACK:
1356 return Attribute::SafeStack;
1357 case bitc::ATTR_KIND_STRUCT_RET:
1358 return Attribute::StructRet;
1359 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1360 return Attribute::SanitizeAddress;
1361 case bitc::ATTR_KIND_SANITIZE_THREAD:
1362 return Attribute::SanitizeThread;
1363 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1364 return Attribute::SanitizeMemory;
1365 case bitc::ATTR_KIND_UW_TABLE:
1366 return Attribute::UWTable;
1367 case bitc::ATTR_KIND_Z_EXT:
1368 return Attribute::ZExt;
1372 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1373 unsigned &Alignment) {
1374 // Note: Alignment in bitcode files is incremented by 1, so that zero
1375 // can be used for default alignment.
1376 if (Exponent > Value::MaxAlignmentExponent + 1)
1377 return error("Invalid alignment value");
1378 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1379 return std::error_code();
1382 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1383 Attribute::AttrKind *Kind) {
1384 *Kind = getAttrFromCode(Code);
1385 if (*Kind == Attribute::None)
1386 return error(BitcodeError::CorruptedBitcode,
1387 "Unknown attribute kind (" + Twine(Code) + ")");
1388 return std::error_code();
1391 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1392 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1393 return error("Invalid record");
1395 if (!MAttributeGroups.empty())
1396 return error("Invalid multiple blocks");
1398 SmallVector<uint64_t, 64> Record;
1400 // Read all the records.
1402 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1404 switch (Entry.Kind) {
1405 case BitstreamEntry::SubBlock: // Handled for us already.
1406 case BitstreamEntry::Error:
1407 return error("Malformed block");
1408 case BitstreamEntry::EndBlock:
1409 return std::error_code();
1410 case BitstreamEntry::Record:
1411 // The interesting case.
1417 switch (Stream.readRecord(Entry.ID, Record)) {
1418 default: // Default behavior: ignore.
1420 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1421 if (Record.size() < 3)
1422 return error("Invalid record");
1424 uint64_t GrpID = Record[0];
1425 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1428 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1429 if (Record[i] == 0) { // Enum attribute
1430 Attribute::AttrKind Kind;
1431 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1434 B.addAttribute(Kind);
1435 } else if (Record[i] == 1) { // Integer attribute
1436 Attribute::AttrKind Kind;
1437 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1439 if (Kind == Attribute::Alignment)
1440 B.addAlignmentAttr(Record[++i]);
1441 else if (Kind == Attribute::StackAlignment)
1442 B.addStackAlignmentAttr(Record[++i]);
1443 else if (Kind == Attribute::Dereferenceable)
1444 B.addDereferenceableAttr(Record[++i]);
1445 else if (Kind == Attribute::DereferenceableOrNull)
1446 B.addDereferenceableOrNullAttr(Record[++i]);
1447 } else { // String attribute
1448 assert((Record[i] == 3 || Record[i] == 4) &&
1449 "Invalid attribute group entry");
1450 bool HasValue = (Record[i++] == 4);
1451 SmallString<64> KindStr;
1452 SmallString<64> ValStr;
1454 while (Record[i] != 0 && i != e)
1455 KindStr += Record[i++];
1456 assert(Record[i] == 0 && "Kind string not null terminated");
1459 // Has a value associated with it.
1460 ++i; // Skip the '0' that terminates the "kind" string.
1461 while (Record[i] != 0 && i != e)
1462 ValStr += Record[i++];
1463 assert(Record[i] == 0 && "Value string not null terminated");
1466 B.addAttribute(KindStr.str(), ValStr.str());
1470 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1477 std::error_code BitcodeReader::parseTypeTable() {
1478 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1479 return error("Invalid record");
1481 return parseTypeTableBody();
1484 std::error_code BitcodeReader::parseTypeTableBody() {
1485 if (!TypeList.empty())
1486 return error("Invalid multiple blocks");
1488 SmallVector<uint64_t, 64> Record;
1489 unsigned NumRecords = 0;
1491 SmallString<64> TypeName;
1493 // Read all the records for this type table.
1495 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1497 switch (Entry.Kind) {
1498 case BitstreamEntry::SubBlock: // Handled for us already.
1499 case BitstreamEntry::Error:
1500 return error("Malformed block");
1501 case BitstreamEntry::EndBlock:
1502 if (NumRecords != TypeList.size())
1503 return error("Malformed block");
1504 return std::error_code();
1505 case BitstreamEntry::Record:
1506 // The interesting case.
1512 Type *ResultTy = nullptr;
1513 switch (Stream.readRecord(Entry.ID, Record)) {
1515 return error("Invalid value");
1516 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1517 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1518 // type list. This allows us to reserve space.
1519 if (Record.size() < 1)
1520 return error("Invalid record");
1521 TypeList.resize(Record[0]);
1523 case bitc::TYPE_CODE_VOID: // VOID
1524 ResultTy = Type::getVoidTy(Context);
1526 case bitc::TYPE_CODE_HALF: // HALF
1527 ResultTy = Type::getHalfTy(Context);
1529 case bitc::TYPE_CODE_FLOAT: // FLOAT
1530 ResultTy = Type::getFloatTy(Context);
1532 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1533 ResultTy = Type::getDoubleTy(Context);
1535 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1536 ResultTy = Type::getX86_FP80Ty(Context);
1538 case bitc::TYPE_CODE_FP128: // FP128
1539 ResultTy = Type::getFP128Ty(Context);
1541 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1542 ResultTy = Type::getPPC_FP128Ty(Context);
1544 case bitc::TYPE_CODE_LABEL: // LABEL
1545 ResultTy = Type::getLabelTy(Context);
1547 case bitc::TYPE_CODE_METADATA: // METADATA
1548 ResultTy = Type::getMetadataTy(Context);
1550 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1551 ResultTy = Type::getX86_MMXTy(Context);
1553 case bitc::TYPE_CODE_TOKEN: // TOKEN
1554 ResultTy = Type::getTokenTy(Context);
1556 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1557 if (Record.size() < 1)
1558 return error("Invalid record");
1560 uint64_t NumBits = Record[0];
1561 if (NumBits < IntegerType::MIN_INT_BITS ||
1562 NumBits > IntegerType::MAX_INT_BITS)
1563 return error("Bitwidth for integer type out of range");
1564 ResultTy = IntegerType::get(Context, NumBits);
1567 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1568 // [pointee type, address space]
1569 if (Record.size() < 1)
1570 return error("Invalid record");
1571 unsigned AddressSpace = 0;
1572 if (Record.size() == 2)
1573 AddressSpace = Record[1];
1574 ResultTy = getTypeByID(Record[0]);
1576 !PointerType::isValidElementType(ResultTy))
1577 return error("Invalid type");
1578 ResultTy = PointerType::get(ResultTy, AddressSpace);
1581 case bitc::TYPE_CODE_FUNCTION_OLD: {
1582 // FIXME: attrid is dead, remove it in LLVM 4.0
1583 // FUNCTION: [vararg, attrid, retty, paramty x N]
1584 if (Record.size() < 3)
1585 return error("Invalid record");
1586 SmallVector<Type*, 8> ArgTys;
1587 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1588 if (Type *T = getTypeByID(Record[i]))
1589 ArgTys.push_back(T);
1594 ResultTy = getTypeByID(Record[2]);
1595 if (!ResultTy || ArgTys.size() < Record.size()-3)
1596 return error("Invalid type");
1598 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1601 case bitc::TYPE_CODE_FUNCTION: {
1602 // FUNCTION: [vararg, retty, paramty x N]
1603 if (Record.size() < 2)
1604 return error("Invalid record");
1605 SmallVector<Type*, 8> ArgTys;
1606 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1607 if (Type *T = getTypeByID(Record[i])) {
1608 if (!FunctionType::isValidArgumentType(T))
1609 return error("Invalid function argument type");
1610 ArgTys.push_back(T);
1616 ResultTy = getTypeByID(Record[1]);
1617 if (!ResultTy || ArgTys.size() < Record.size()-2)
1618 return error("Invalid type");
1620 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1623 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1624 if (Record.size() < 1)
1625 return error("Invalid record");
1626 SmallVector<Type*, 8> EltTys;
1627 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1628 if (Type *T = getTypeByID(Record[i]))
1629 EltTys.push_back(T);
1633 if (EltTys.size() != Record.size()-1)
1634 return error("Invalid type");
1635 ResultTy = StructType::get(Context, EltTys, Record[0]);
1638 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1639 if (convertToString(Record, 0, TypeName))
1640 return error("Invalid record");
1643 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1644 if (Record.size() < 1)
1645 return error("Invalid record");
1647 if (NumRecords >= TypeList.size())
1648 return error("Invalid TYPE table");
1650 // Check to see if this was forward referenced, if so fill in the temp.
1651 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1653 Res->setName(TypeName);
1654 TypeList[NumRecords] = nullptr;
1655 } else // Otherwise, create a new struct.
1656 Res = createIdentifiedStructType(Context, TypeName);
1659 SmallVector<Type*, 8> EltTys;
1660 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1661 if (Type *T = getTypeByID(Record[i]))
1662 EltTys.push_back(T);
1666 if (EltTys.size() != Record.size()-1)
1667 return error("Invalid record");
1668 Res->setBody(EltTys, Record[0]);
1672 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1673 if (Record.size() != 1)
1674 return error("Invalid record");
1676 if (NumRecords >= TypeList.size())
1677 return error("Invalid TYPE table");
1679 // Check to see if this was forward referenced, if so fill in the temp.
1680 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1682 Res->setName(TypeName);
1683 TypeList[NumRecords] = nullptr;
1684 } else // Otherwise, create a new struct with no body.
1685 Res = createIdentifiedStructType(Context, TypeName);
1690 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1691 if (Record.size() < 2)
1692 return error("Invalid record");
1693 ResultTy = getTypeByID(Record[1]);
1694 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1695 return error("Invalid type");
1696 ResultTy = ArrayType::get(ResultTy, Record[0]);
1698 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1699 if (Record.size() < 2)
1700 return error("Invalid record");
1702 return error("Invalid vector length");
1703 ResultTy = getTypeByID(Record[1]);
1704 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1705 return error("Invalid type");
1706 ResultTy = VectorType::get(ResultTy, Record[0]);
1710 if (NumRecords >= TypeList.size())
1711 return error("Invalid TYPE table");
1712 if (TypeList[NumRecords])
1714 "Invalid TYPE table: Only named structs can be forward referenced");
1715 assert(ResultTy && "Didn't read a type?");
1716 TypeList[NumRecords++] = ResultTy;
1720 std::error_code BitcodeReader::parseOperandBundleTags() {
1721 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1722 return error("Invalid record");
1724 if (!BundleTags.empty())
1725 return error("Invalid multiple blocks");
1727 SmallVector<uint64_t, 64> Record;
1730 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1732 switch (Entry.Kind) {
1733 case BitstreamEntry::SubBlock: // Handled for us already.
1734 case BitstreamEntry::Error:
1735 return error("Malformed block");
1736 case BitstreamEntry::EndBlock:
1737 return std::error_code();
1738 case BitstreamEntry::Record:
1739 // The interesting case.
1743 // Tags are implicitly mapped to integers by their order.
1745 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1746 return error("Invalid record");
1748 // OPERAND_BUNDLE_TAG: [strchr x N]
1749 BundleTags.emplace_back();
1750 if (convertToString(Record, 0, BundleTags.back()))
1751 return error("Invalid record");
1756 /// Associate a value with its name from the given index in the provided record.
1757 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1758 unsigned NameIndex, Triple &TT) {
1759 SmallString<128> ValueName;
1760 if (convertToString(Record, NameIndex, ValueName))
1761 return error("Invalid record");
1762 unsigned ValueID = Record[0];
1763 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1764 return error("Invalid record");
1765 Value *V = ValueList[ValueID];
1767 StringRef NameStr(ValueName.data(), ValueName.size());
1768 if (NameStr.find_first_of(0) != StringRef::npos)
1769 return error("Invalid value name");
1770 V->setName(NameStr);
1771 auto *GO = dyn_cast<GlobalObject>(V);
1773 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1774 if (TT.isOSBinFormatMachO())
1775 GO->setComdat(nullptr);
1777 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1783 /// Parse the value symbol table at either the current parsing location or
1784 /// at the given bit offset if provided.
1785 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1786 uint64_t CurrentBit;
1787 // Pass in the Offset to distinguish between calling for the module-level
1788 // VST (where we want to jump to the VST offset) and the function-level
1789 // VST (where we don't).
1791 // Save the current parsing location so we can jump back at the end
1793 CurrentBit = Stream.GetCurrentBitNo();
1794 Stream.JumpToBit(Offset * 32);
1796 // Do some checking if we are in debug mode.
1797 BitstreamEntry Entry = Stream.advance();
1798 assert(Entry.Kind == BitstreamEntry::SubBlock);
1799 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1801 // In NDEBUG mode ignore the output so we don't get an unused variable
1807 // Compute the delta between the bitcode indices in the VST (the word offset
1808 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1809 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1810 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1811 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1812 // just before entering the VST subblock because: 1) the EnterSubBlock
1813 // changes the AbbrevID width; 2) the VST block is nested within the same
1814 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1815 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1816 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1817 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1818 unsigned FuncBitcodeOffsetDelta =
1819 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1821 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1822 return error("Invalid record");
1824 SmallVector<uint64_t, 64> Record;
1826 Triple TT(TheModule->getTargetTriple());
1828 // Read all the records for this value table.
1829 SmallString<128> ValueName;
1831 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1833 switch (Entry.Kind) {
1834 case BitstreamEntry::SubBlock: // Handled for us already.
1835 case BitstreamEntry::Error:
1836 return error("Malformed block");
1837 case BitstreamEntry::EndBlock:
1839 Stream.JumpToBit(CurrentBit);
1840 return std::error_code();
1841 case BitstreamEntry::Record:
1842 // The interesting case.
1848 switch (Stream.readRecord(Entry.ID, Record)) {
1849 default: // Default behavior: unknown type.
1851 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
1852 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1853 if (std::error_code EC = ValOrErr.getError())
1858 case bitc::VST_CODE_FNENTRY: {
1859 // VST_FNENTRY: [valueid, offset, namechar x N]
1860 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1861 if (std::error_code EC = ValOrErr.getError())
1863 Value *V = ValOrErr.get();
1865 auto *GO = dyn_cast<GlobalObject>(V);
1867 // If this is an alias, need to get the actual Function object
1868 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1869 auto *GA = dyn_cast<GlobalAlias>(V);
1871 GO = GA->getBaseObject();
1875 uint64_t FuncWordOffset = Record[1];
1876 Function *F = dyn_cast<Function>(GO);
1878 uint64_t FuncBitOffset = FuncWordOffset * 32;
1879 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1880 // Set the LastFunctionBlockBit to point to the last function block.
1881 // Later when parsing is resumed after function materialization,
1882 // we can simply skip that last function block.
1883 if (FuncBitOffset > LastFunctionBlockBit)
1884 LastFunctionBlockBit = FuncBitOffset;
1887 case bitc::VST_CODE_BBENTRY: {
1888 if (convertToString(Record, 1, ValueName))
1889 return error("Invalid record");
1890 BasicBlock *BB = getBasicBlock(Record[0]);
1892 return error("Invalid record");
1894 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1902 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1904 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1905 if (Record.size() < 2)
1906 return error("Invalid record");
1908 unsigned Kind = Record[0];
1909 SmallString<8> Name(Record.begin() + 1, Record.end());
1911 unsigned NewKind = TheModule->getMDKindID(Name.str());
1912 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1913 return error("Conflicting METADATA_KIND records");
1914 return std::error_code();
1917 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1919 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1920 /// module level metadata.
1921 std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
1922 IsMetadataMaterialized = true;
1923 unsigned NextMDValueNo = MDValueList.size();
1924 if (ModuleLevel && SeenModuleValuesRecord) {
1925 // Now that we are parsing the module level metadata, we want to restart
1926 // the numbering of the MD values, and replace temp MD created earlier
1927 // with their real values. If we saw a METADATA_VALUE record then we
1928 // would have set the MDValueList size to the number specified in that
1929 // record, to support parsing function-level metadata first, and we need
1930 // to reset back to 0 to fill the MDValueList in with the parsed module
1931 // The function-level metadata parsing should have reset the MDValueList
1932 // size back to the value reported by the METADATA_VALUE record, saved in
1934 assert(NumModuleMDs == MDValueList.size() &&
1935 "Expected MDValueList to only contain module level values");
1939 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1940 return error("Invalid record");
1942 SmallVector<uint64_t, 64> Record;
1945 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1946 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1948 return getMD(ID - 1);
1951 auto getMDString = [&](unsigned ID) -> MDString *{
1952 // This requires that the ID is not really a forward reference. In
1953 // particular, the MDString must already have been resolved.
1954 return cast_or_null<MDString>(getMDOrNull(ID));
1957 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1958 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1960 // Read all the records.
1962 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1964 switch (Entry.Kind) {
1965 case BitstreamEntry::SubBlock: // Handled for us already.
1966 case BitstreamEntry::Error:
1967 return error("Malformed block");
1968 case BitstreamEntry::EndBlock:
1969 MDValueList.tryToResolveCycles();
1970 return std::error_code();
1971 case BitstreamEntry::Record:
1972 // The interesting case.
1978 unsigned Code = Stream.readRecord(Entry.ID, Record);
1979 bool IsDistinct = false;
1981 default: // Default behavior: ignore.
1983 case bitc::METADATA_NAME: {
1984 // Read name of the named metadata.
1985 SmallString<8> Name(Record.begin(), Record.end());
1987 Code = Stream.ReadCode();
1989 unsigned NextBitCode = Stream.readRecord(Code, Record);
1990 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1991 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1993 // Read named metadata elements.
1994 unsigned Size = Record.size();
1995 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1996 for (unsigned i = 0; i != Size; ++i) {
1997 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1999 return error("Invalid record");
2000 NMD->addOperand(MD);
2004 case bitc::METADATA_OLD_FN_NODE: {
2005 // FIXME: Remove in 4.0.
2006 // This is a LocalAsMetadata record, the only type of function-local
2008 if (Record.size() % 2 == 1)
2009 return error("Invalid record");
2011 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2012 // to be legal, but there's no upgrade path.
2013 auto dropRecord = [&] {
2014 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
2016 if (Record.size() != 2) {
2021 Type *Ty = getTypeByID(Record[0]);
2022 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2027 MDValueList.assignValue(
2028 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2032 case bitc::METADATA_OLD_NODE: {
2033 // FIXME: Remove in 4.0.
2034 if (Record.size() % 2 == 1)
2035 return error("Invalid record");
2037 unsigned Size = Record.size();
2038 SmallVector<Metadata *, 8> Elts;
2039 for (unsigned i = 0; i != Size; i += 2) {
2040 Type *Ty = getTypeByID(Record[i]);
2042 return error("Invalid record");
2043 if (Ty->isMetadataTy())
2044 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
2045 else if (!Ty->isVoidTy()) {
2047 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2048 assert(isa<ConstantAsMetadata>(MD) &&
2049 "Expected non-function-local metadata");
2052 Elts.push_back(nullptr);
2054 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2057 case bitc::METADATA_VALUE: {
2058 if (Record.size() != 2)
2059 return error("Invalid record");
2061 Type *Ty = getTypeByID(Record[0]);
2062 if (Ty->isMetadataTy() || Ty->isVoidTy())
2063 return error("Invalid record");
2065 MDValueList.assignValue(
2066 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2070 case bitc::METADATA_DISTINCT_NODE:
2073 case bitc::METADATA_NODE: {
2074 SmallVector<Metadata *, 8> Elts;
2075 Elts.reserve(Record.size());
2076 for (unsigned ID : Record)
2077 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2078 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2079 : MDNode::get(Context, Elts),
2083 case bitc::METADATA_LOCATION: {
2084 if (Record.size() != 5)
2085 return error("Invalid record");
2087 unsigned Line = Record[1];
2088 unsigned Column = Record[2];
2089 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2090 Metadata *InlinedAt =
2091 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2092 MDValueList.assignValue(
2093 GET_OR_DISTINCT(DILocation, Record[0],
2094 (Context, Line, Column, Scope, InlinedAt)),
2098 case bitc::METADATA_GENERIC_DEBUG: {
2099 if (Record.size() < 4)
2100 return error("Invalid record");
2102 unsigned Tag = Record[1];
2103 unsigned Version = Record[2];
2105 if (Tag >= 1u << 16 || Version != 0)
2106 return error("Invalid record");
2108 auto *Header = getMDString(Record[3]);
2109 SmallVector<Metadata *, 8> DwarfOps;
2110 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2111 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2113 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2114 (Context, Tag, Header, DwarfOps)),
2118 case bitc::METADATA_SUBRANGE: {
2119 if (Record.size() != 3)
2120 return error("Invalid record");
2122 MDValueList.assignValue(
2123 GET_OR_DISTINCT(DISubrange, Record[0],
2124 (Context, Record[1], unrotateSign(Record[2]))),
2128 case bitc::METADATA_ENUMERATOR: {
2129 if (Record.size() != 3)
2130 return error("Invalid record");
2132 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2133 (Context, unrotateSign(Record[1]),
2134 getMDString(Record[2]))),
2138 case bitc::METADATA_BASIC_TYPE: {
2139 if (Record.size() != 6)
2140 return error("Invalid record");
2142 MDValueList.assignValue(
2143 GET_OR_DISTINCT(DIBasicType, Record[0],
2144 (Context, Record[1], getMDString(Record[2]),
2145 Record[3], Record[4], Record[5])),
2149 case bitc::METADATA_DERIVED_TYPE: {
2150 if (Record.size() != 12)
2151 return error("Invalid record");
2153 MDValueList.assignValue(
2154 GET_OR_DISTINCT(DIDerivedType, Record[0],
2155 (Context, Record[1], getMDString(Record[2]),
2156 getMDOrNull(Record[3]), Record[4],
2157 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2158 Record[7], Record[8], Record[9], Record[10],
2159 getMDOrNull(Record[11]))),
2163 case bitc::METADATA_COMPOSITE_TYPE: {
2164 if (Record.size() != 16)
2165 return error("Invalid record");
2167 MDValueList.assignValue(
2168 GET_OR_DISTINCT(DICompositeType, Record[0],
2169 (Context, Record[1], getMDString(Record[2]),
2170 getMDOrNull(Record[3]), Record[4],
2171 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2172 Record[7], Record[8], Record[9], Record[10],
2173 getMDOrNull(Record[11]), Record[12],
2174 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2175 getMDString(Record[15]))),
2179 case bitc::METADATA_SUBROUTINE_TYPE: {
2180 if (Record.size() != 3)
2181 return error("Invalid record");
2183 MDValueList.assignValue(
2184 GET_OR_DISTINCT(DISubroutineType, Record[0],
2185 (Context, Record[1], getMDOrNull(Record[2]))),
2190 case bitc::METADATA_MODULE: {
2191 if (Record.size() != 6)
2192 return error("Invalid record");
2194 MDValueList.assignValue(
2195 GET_OR_DISTINCT(DIModule, Record[0],
2196 (Context, getMDOrNull(Record[1]),
2197 getMDString(Record[2]), getMDString(Record[3]),
2198 getMDString(Record[4]), getMDString(Record[5]))),
2203 case bitc::METADATA_FILE: {
2204 if (Record.size() != 3)
2205 return error("Invalid record");
2207 MDValueList.assignValue(
2208 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2209 getMDString(Record[2]))),
2213 case bitc::METADATA_COMPILE_UNIT: {
2214 if (Record.size() < 14 || Record.size() > 15)
2215 return error("Invalid record");
2217 // Ignore Record[1], which indicates whether this compile unit is
2218 // distinct. It's always distinct.
2219 MDValueList.assignValue(
2220 DICompileUnit::getDistinct(
2221 Context, Record[1], getMDOrNull(Record[2]),
2222 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2223 Record[6], getMDString(Record[7]), Record[8],
2224 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2225 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2226 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2230 case bitc::METADATA_SUBPROGRAM: {
2231 if (Record.size() != 18 && Record.size() != 19)
2232 return error("Invalid record");
2234 bool HasFn = Record.size() == 19;
2235 DISubprogram *SP = GET_OR_DISTINCT(
2237 Record[0] || Record[8], // All definitions should be distinct.
2238 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2239 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2240 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2241 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2242 Record[14], getMDOrNull(Record[15 + HasFn]),
2243 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2244 MDValueList.assignValue(SP, NextMDValueNo++);
2246 // Upgrade sp->function mapping to function->sp mapping.
2247 if (HasFn && Record[15]) {
2248 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2249 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2250 if (F->isMaterializable())
2251 // Defer until materialized; unmaterialized functions may not have
2253 FunctionsWithSPs[F] = SP;
2254 else if (!F->empty())
2255 F->setSubprogram(SP);
2260 case bitc::METADATA_LEXICAL_BLOCK: {
2261 if (Record.size() != 5)
2262 return error("Invalid record");
2264 MDValueList.assignValue(
2265 GET_OR_DISTINCT(DILexicalBlock, Record[0],
2266 (Context, getMDOrNull(Record[1]),
2267 getMDOrNull(Record[2]), Record[3], Record[4])),
2271 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2272 if (Record.size() != 4)
2273 return error("Invalid record");
2275 MDValueList.assignValue(
2276 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2277 (Context, getMDOrNull(Record[1]),
2278 getMDOrNull(Record[2]), Record[3])),
2282 case bitc::METADATA_NAMESPACE: {
2283 if (Record.size() != 5)
2284 return error("Invalid record");
2286 MDValueList.assignValue(
2287 GET_OR_DISTINCT(DINamespace, Record[0],
2288 (Context, getMDOrNull(Record[1]),
2289 getMDOrNull(Record[2]), getMDString(Record[3]),
2294 case bitc::METADATA_TEMPLATE_TYPE: {
2295 if (Record.size() != 3)
2296 return error("Invalid record");
2298 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2300 (Context, getMDString(Record[1]),
2301 getMDOrNull(Record[2]))),
2305 case bitc::METADATA_TEMPLATE_VALUE: {
2306 if (Record.size() != 5)
2307 return error("Invalid record");
2309 MDValueList.assignValue(
2310 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2311 (Context, Record[1], getMDString(Record[2]),
2312 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2316 case bitc::METADATA_GLOBAL_VAR: {
2317 if (Record.size() != 11)
2318 return error("Invalid record");
2320 MDValueList.assignValue(
2321 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2322 (Context, getMDOrNull(Record[1]),
2323 getMDString(Record[2]), getMDString(Record[3]),
2324 getMDOrNull(Record[4]), Record[5],
2325 getMDOrNull(Record[6]), Record[7], Record[8],
2326 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2330 case bitc::METADATA_LOCAL_VAR: {
2331 // 10th field is for the obseleted 'inlinedAt:' field.
2332 if (Record.size() < 8 || Record.size() > 10)
2333 return error("Invalid record");
2335 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2336 // DW_TAG_arg_variable.
2337 bool HasTag = Record.size() > 8;
2338 MDValueList.assignValue(
2339 GET_OR_DISTINCT(DILocalVariable, Record[0],
2340 (Context, getMDOrNull(Record[1 + HasTag]),
2341 getMDString(Record[2 + HasTag]),
2342 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2343 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2344 Record[7 + HasTag])),
2348 case bitc::METADATA_EXPRESSION: {
2349 if (Record.size() < 1)
2350 return error("Invalid record");
2352 MDValueList.assignValue(
2353 GET_OR_DISTINCT(DIExpression, Record[0],
2354 (Context, makeArrayRef(Record).slice(1))),
2358 case bitc::METADATA_OBJC_PROPERTY: {
2359 if (Record.size() != 8)
2360 return error("Invalid record");
2362 MDValueList.assignValue(
2363 GET_OR_DISTINCT(DIObjCProperty, Record[0],
2364 (Context, getMDString(Record[1]),
2365 getMDOrNull(Record[2]), Record[3],
2366 getMDString(Record[4]), getMDString(Record[5]),
2367 Record[6], getMDOrNull(Record[7]))),
2371 case bitc::METADATA_IMPORTED_ENTITY: {
2372 if (Record.size() != 6)
2373 return error("Invalid record");
2375 MDValueList.assignValue(
2376 GET_OR_DISTINCT(DIImportedEntity, Record[0],
2377 (Context, Record[1], getMDOrNull(Record[2]),
2378 getMDOrNull(Record[3]), Record[4],
2379 getMDString(Record[5]))),
2383 case bitc::METADATA_STRING: {
2384 std::string String(Record.begin(), Record.end());
2385 llvm::UpgradeMDStringConstant(String);
2386 Metadata *MD = MDString::get(Context, String);
2387 MDValueList.assignValue(MD, NextMDValueNo++);
2390 case bitc::METADATA_KIND: {
2391 // Support older bitcode files that had METADATA_KIND records in a
2392 // block with METADATA_BLOCK_ID.
2393 if (std::error_code EC = parseMetadataKindRecord(Record))
2399 assert((!(ModuleLevel && SeenModuleValuesRecord) ||
2400 NumModuleMDs == MDValueList.size()) &&
2401 "Inconsistent bitcode: METADATA_VALUES mismatch");
2402 #undef GET_OR_DISTINCT
2405 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2406 std::error_code BitcodeReader::parseMetadataKinds() {
2407 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2408 return error("Invalid record");
2410 SmallVector<uint64_t, 64> Record;
2412 // Read all the records.
2414 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2416 switch (Entry.Kind) {
2417 case BitstreamEntry::SubBlock: // Handled for us already.
2418 case BitstreamEntry::Error:
2419 return error("Malformed block");
2420 case BitstreamEntry::EndBlock:
2421 return std::error_code();
2422 case BitstreamEntry::Record:
2423 // The interesting case.
2429 unsigned Code = Stream.readRecord(Entry.ID, Record);
2431 default: // Default behavior: ignore.
2433 case bitc::METADATA_KIND: {
2434 if (std::error_code EC = parseMetadataKindRecord(Record))
2442 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2444 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2449 // There is no such thing as -0 with integers. "-0" really means MININT.
2453 /// Resolve all of the initializers for global values and aliases that we can.
2454 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2455 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2456 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2457 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2458 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2459 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2461 GlobalInitWorklist.swap(GlobalInits);
2462 AliasInitWorklist.swap(AliasInits);
2463 FunctionPrefixWorklist.swap(FunctionPrefixes);
2464 FunctionPrologueWorklist.swap(FunctionPrologues);
2465 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2467 while (!GlobalInitWorklist.empty()) {
2468 unsigned ValID = GlobalInitWorklist.back().second;
2469 if (ValID >= ValueList.size()) {
2470 // Not ready to resolve this yet, it requires something later in the file.
2471 GlobalInits.push_back(GlobalInitWorklist.back());
2473 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2474 GlobalInitWorklist.back().first->setInitializer(C);
2476 return error("Expected a constant");
2478 GlobalInitWorklist.pop_back();
2481 while (!AliasInitWorklist.empty()) {
2482 unsigned ValID = AliasInitWorklist.back().second;
2483 if (ValID >= ValueList.size()) {
2484 AliasInits.push_back(AliasInitWorklist.back());
2486 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2488 return error("Expected a constant");
2489 GlobalAlias *Alias = AliasInitWorklist.back().first;
2490 if (C->getType() != Alias->getType())
2491 return error("Alias and aliasee types don't match");
2492 Alias->setAliasee(C);
2494 AliasInitWorklist.pop_back();
2497 while (!FunctionPrefixWorklist.empty()) {
2498 unsigned ValID = FunctionPrefixWorklist.back().second;
2499 if (ValID >= ValueList.size()) {
2500 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2502 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2503 FunctionPrefixWorklist.back().first->setPrefixData(C);
2505 return error("Expected a constant");
2507 FunctionPrefixWorklist.pop_back();
2510 while (!FunctionPrologueWorklist.empty()) {
2511 unsigned ValID = FunctionPrologueWorklist.back().second;
2512 if (ValID >= ValueList.size()) {
2513 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2515 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2516 FunctionPrologueWorklist.back().first->setPrologueData(C);
2518 return error("Expected a constant");
2520 FunctionPrologueWorklist.pop_back();
2523 while (!FunctionPersonalityFnWorklist.empty()) {
2524 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2525 if (ValID >= ValueList.size()) {
2526 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2528 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2529 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2531 return error("Expected a constant");
2533 FunctionPersonalityFnWorklist.pop_back();
2536 return std::error_code();
2539 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2540 SmallVector<uint64_t, 8> Words(Vals.size());
2541 std::transform(Vals.begin(), Vals.end(), Words.begin(),
2542 BitcodeReader::decodeSignRotatedValue);
2544 return APInt(TypeBits, Words);
2547 std::error_code BitcodeReader::parseConstants() {
2548 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2549 return error("Invalid record");
2551 SmallVector<uint64_t, 64> Record;
2553 // Read all the records for this value table.
2554 Type *CurTy = Type::getInt32Ty(Context);
2555 unsigned NextCstNo = ValueList.size();
2557 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2559 switch (Entry.Kind) {
2560 case BitstreamEntry::SubBlock: // Handled for us already.
2561 case BitstreamEntry::Error:
2562 return error("Malformed block");
2563 case BitstreamEntry::EndBlock:
2564 if (NextCstNo != ValueList.size())
2565 return error("Invalid ronstant reference");
2567 // Once all the constants have been read, go through and resolve forward
2569 ValueList.resolveConstantForwardRefs();
2570 return std::error_code();
2571 case BitstreamEntry::Record:
2572 // The interesting case.
2579 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2581 default: // Default behavior: unknown constant
2582 case bitc::CST_CODE_UNDEF: // UNDEF
2583 V = UndefValue::get(CurTy);
2585 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2587 return error("Invalid record");
2588 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2589 return error("Invalid record");
2590 CurTy = TypeList[Record[0]];
2591 continue; // Skip the ValueList manipulation.
2592 case bitc::CST_CODE_NULL: // NULL
2593 V = Constant::getNullValue(CurTy);
2595 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2596 if (!CurTy->isIntegerTy() || Record.empty())
2597 return error("Invalid record");
2598 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2600 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2601 if (!CurTy->isIntegerTy() || Record.empty())
2602 return error("Invalid record");
2605 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2606 V = ConstantInt::get(Context, VInt);
2610 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2612 return error("Invalid record");
2613 if (CurTy->isHalfTy())
2614 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2615 APInt(16, (uint16_t)Record[0])));
2616 else if (CurTy->isFloatTy())
2617 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2618 APInt(32, (uint32_t)Record[0])));
2619 else if (CurTy->isDoubleTy())
2620 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2621 APInt(64, Record[0])));
2622 else if (CurTy->isX86_FP80Ty()) {
2623 // Bits are not stored the same way as a normal i80 APInt, compensate.
2624 uint64_t Rearrange[2];
2625 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2626 Rearrange[1] = Record[0] >> 48;
2627 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2628 APInt(80, Rearrange)));
2629 } else if (CurTy->isFP128Ty())
2630 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2631 APInt(128, Record)));
2632 else if (CurTy->isPPC_FP128Ty())
2633 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2634 APInt(128, Record)));
2636 V = UndefValue::get(CurTy);
2640 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2642 return error("Invalid record");
2644 unsigned Size = Record.size();
2645 SmallVector<Constant*, 16> Elts;
2647 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2648 for (unsigned i = 0; i != Size; ++i)
2649 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2650 STy->getElementType(i)));
2651 V = ConstantStruct::get(STy, Elts);
2652 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2653 Type *EltTy = ATy->getElementType();
2654 for (unsigned i = 0; i != Size; ++i)
2655 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2656 V = ConstantArray::get(ATy, Elts);
2657 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2658 Type *EltTy = VTy->getElementType();
2659 for (unsigned i = 0; i != Size; ++i)
2660 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2661 V = ConstantVector::get(Elts);
2663 V = UndefValue::get(CurTy);
2667 case bitc::CST_CODE_STRING: // STRING: [values]
2668 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2670 return error("Invalid record");
2672 SmallString<16> Elts(Record.begin(), Record.end());
2673 V = ConstantDataArray::getString(Context, Elts,
2674 BitCode == bitc::CST_CODE_CSTRING);
2677 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2679 return error("Invalid record");
2681 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2682 unsigned Size = Record.size();
2684 if (EltTy->isIntegerTy(8)) {
2685 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2686 if (isa<VectorType>(CurTy))
2687 V = ConstantDataVector::get(Context, Elts);
2689 V = ConstantDataArray::get(Context, Elts);
2690 } else if (EltTy->isIntegerTy(16)) {
2691 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2692 if (isa<VectorType>(CurTy))
2693 V = ConstantDataVector::get(Context, Elts);
2695 V = ConstantDataArray::get(Context, Elts);
2696 } else if (EltTy->isIntegerTy(32)) {
2697 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2698 if (isa<VectorType>(CurTy))
2699 V = ConstantDataVector::get(Context, Elts);
2701 V = ConstantDataArray::get(Context, Elts);
2702 } else if (EltTy->isIntegerTy(64)) {
2703 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2704 if (isa<VectorType>(CurTy))
2705 V = ConstantDataVector::get(Context, Elts);
2707 V = ConstantDataArray::get(Context, Elts);
2708 } else if (EltTy->isFloatTy()) {
2709 SmallVector<float, 16> Elts(Size);
2710 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2711 if (isa<VectorType>(CurTy))
2712 V = ConstantDataVector::get(Context, Elts);
2714 V = ConstantDataArray::get(Context, Elts);
2715 } else if (EltTy->isDoubleTy()) {
2716 SmallVector<double, 16> Elts(Size);
2717 std::transform(Record.begin(), Record.end(), Elts.begin(),
2719 if (isa<VectorType>(CurTy))
2720 V = ConstantDataVector::get(Context, Elts);
2722 V = ConstantDataArray::get(Context, Elts);
2724 return error("Invalid type for value");
2729 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2730 if (Record.size() < 3)
2731 return error("Invalid record");
2732 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2734 V = UndefValue::get(CurTy); // Unknown binop.
2736 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2737 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2739 if (Record.size() >= 4) {
2740 if (Opc == Instruction::Add ||
2741 Opc == Instruction::Sub ||
2742 Opc == Instruction::Mul ||
2743 Opc == Instruction::Shl) {
2744 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2745 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2746 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2747 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2748 } else if (Opc == Instruction::SDiv ||
2749 Opc == Instruction::UDiv ||
2750 Opc == Instruction::LShr ||
2751 Opc == Instruction::AShr) {
2752 if (Record[3] & (1 << bitc::PEO_EXACT))
2753 Flags |= SDivOperator::IsExact;
2756 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2760 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2761 if (Record.size() < 3)
2762 return error("Invalid record");
2763 int Opc = getDecodedCastOpcode(Record[0]);
2765 V = UndefValue::get(CurTy); // Unknown cast.
2767 Type *OpTy = getTypeByID(Record[1]);
2769 return error("Invalid record");
2770 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2771 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2772 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2776 case bitc::CST_CODE_CE_INBOUNDS_GEP:
2777 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
2779 Type *PointeeType = nullptr;
2780 if (Record.size() % 2)
2781 PointeeType = getTypeByID(Record[OpNum++]);
2782 SmallVector<Constant*, 16> Elts;
2783 while (OpNum != Record.size()) {
2784 Type *ElTy = getTypeByID(Record[OpNum++]);
2786 return error("Invalid record");
2787 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2792 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2794 return error("Explicit gep operator type does not match pointee type "
2795 "of pointer operand");
2797 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2798 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2800 bitc::CST_CODE_CE_INBOUNDS_GEP);
2803 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2804 if (Record.size() < 3)
2805 return error("Invalid record");
2807 Type *SelectorTy = Type::getInt1Ty(Context);
2809 // The selector might be an i1 or an <n x i1>
2810 // Get the type from the ValueList before getting a forward ref.
2811 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2812 if (Value *V = ValueList[Record[0]])
2813 if (SelectorTy != V->getType())
2814 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2816 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2818 ValueList.getConstantFwdRef(Record[1],CurTy),
2819 ValueList.getConstantFwdRef(Record[2],CurTy));
2822 case bitc::CST_CODE_CE_EXTRACTELT
2823 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2824 if (Record.size() < 3)
2825 return error("Invalid record");
2827 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2829 return error("Invalid record");
2830 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2831 Constant *Op1 = nullptr;
2832 if (Record.size() == 4) {
2833 Type *IdxTy = getTypeByID(Record[2]);
2835 return error("Invalid record");
2836 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2837 } else // TODO: Remove with llvm 4.0
2838 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2840 return error("Invalid record");
2841 V = ConstantExpr::getExtractElement(Op0, Op1);
2844 case bitc::CST_CODE_CE_INSERTELT
2845 : { // CE_INSERTELT: [opval, opval, opty, opval]
2846 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2847 if (Record.size() < 3 || !OpTy)
2848 return error("Invalid record");
2849 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2850 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2851 OpTy->getElementType());
2852 Constant *Op2 = nullptr;
2853 if (Record.size() == 4) {
2854 Type *IdxTy = getTypeByID(Record[2]);
2856 return error("Invalid record");
2857 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2858 } else // TODO: Remove with llvm 4.0
2859 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2861 return error("Invalid record");
2862 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2865 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2866 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2867 if (Record.size() < 3 || !OpTy)
2868 return error("Invalid record");
2869 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2870 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2871 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2872 OpTy->getNumElements());
2873 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2874 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2877 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2878 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2880 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2881 if (Record.size() < 4 || !RTy || !OpTy)
2882 return error("Invalid record");
2883 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2884 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2885 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2886 RTy->getNumElements());
2887 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2888 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2891 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2892 if (Record.size() < 4)
2893 return error("Invalid record");
2894 Type *OpTy = getTypeByID(Record[0]);
2896 return error("Invalid record");
2897 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2898 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2900 if (OpTy->isFPOrFPVectorTy())
2901 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2903 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2906 // This maintains backward compatibility, pre-asm dialect keywords.
2907 // FIXME: Remove with the 4.0 release.
2908 case bitc::CST_CODE_INLINEASM_OLD: {
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;
2914 unsigned AsmStrSize = Record[1];
2915 if (2+AsmStrSize >= Record.size())
2916 return error("Invalid record");
2917 unsigned ConstStrSize = Record[2+AsmStrSize];
2918 if (3+AsmStrSize+ConstStrSize > Record.size())
2919 return error("Invalid record");
2921 for (unsigned i = 0; i != AsmStrSize; ++i)
2922 AsmStr += (char)Record[2+i];
2923 for (unsigned i = 0; i != ConstStrSize; ++i)
2924 ConstrStr += (char)Record[3+AsmStrSize+i];
2925 PointerType *PTy = cast<PointerType>(CurTy);
2926 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2927 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2930 // This version adds support for the asm dialect keywords (e.g.,
2932 case bitc::CST_CODE_INLINEASM: {
2933 if (Record.size() < 2)
2934 return error("Invalid record");
2935 std::string AsmStr, ConstrStr;
2936 bool HasSideEffects = Record[0] & 1;
2937 bool IsAlignStack = (Record[0] >> 1) & 1;
2938 unsigned AsmDialect = Record[0] >> 2;
2939 unsigned AsmStrSize = Record[1];
2940 if (2+AsmStrSize >= Record.size())
2941 return error("Invalid record");
2942 unsigned ConstStrSize = Record[2+AsmStrSize];
2943 if (3+AsmStrSize+ConstStrSize > Record.size())
2944 return error("Invalid record");
2946 for (unsigned i = 0; i != AsmStrSize; ++i)
2947 AsmStr += (char)Record[2+i];
2948 for (unsigned i = 0; i != ConstStrSize; ++i)
2949 ConstrStr += (char)Record[3+AsmStrSize+i];
2950 PointerType *PTy = cast<PointerType>(CurTy);
2951 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2952 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2953 InlineAsm::AsmDialect(AsmDialect));
2956 case bitc::CST_CODE_BLOCKADDRESS:{
2957 if (Record.size() < 3)
2958 return error("Invalid record");
2959 Type *FnTy = getTypeByID(Record[0]);
2961 return error("Invalid record");
2963 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2965 return error("Invalid record");
2967 // Don't let Fn get dematerialized.
2968 BlockAddressesTaken.insert(Fn);
2970 // If the function is already parsed we can insert the block address right
2973 unsigned BBID = Record[2];
2975 // Invalid reference to entry block.
2976 return error("Invalid ID");
2978 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2979 for (size_t I = 0, E = BBID; I != E; ++I) {
2981 return error("Invalid ID");
2986 // Otherwise insert a placeholder and remember it so it can be inserted
2987 // when the function is parsed.
2988 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2990 BasicBlockFwdRefQueue.push_back(Fn);
2991 if (FwdBBs.size() < BBID + 1)
2992 FwdBBs.resize(BBID + 1);
2994 FwdBBs[BBID] = BasicBlock::Create(Context);
2997 V = BlockAddress::get(Fn, BB);
3002 if (ValueList.assignValue(V, NextCstNo))
3003 return error("Invalid forward reference");
3008 std::error_code BitcodeReader::parseUseLists() {
3009 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3010 return error("Invalid record");
3012 // Read all the records.
3013 SmallVector<uint64_t, 64> Record;
3015 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3017 switch (Entry.Kind) {
3018 case BitstreamEntry::SubBlock: // Handled for us already.
3019 case BitstreamEntry::Error:
3020 return error("Malformed block");
3021 case BitstreamEntry::EndBlock:
3022 return std::error_code();
3023 case BitstreamEntry::Record:
3024 // The interesting case.
3028 // Read a use list record.
3031 switch (Stream.readRecord(Entry.ID, Record)) {
3032 default: // Default behavior: unknown type.
3034 case bitc::USELIST_CODE_BB:
3037 case bitc::USELIST_CODE_DEFAULT: {
3038 unsigned RecordLength = Record.size();
3039 if (RecordLength < 3)
3040 // Records should have at least an ID and two indexes.
3041 return error("Invalid record");
3042 unsigned ID = Record.back();
3047 assert(ID < FunctionBBs.size() && "Basic block not found");
3048 V = FunctionBBs[ID];
3051 unsigned NumUses = 0;
3052 SmallDenseMap<const Use *, unsigned, 16> Order;
3053 for (const Use &U : V->uses()) {
3054 if (++NumUses > Record.size())
3056 Order[&U] = Record[NumUses - 1];
3058 if (Order.size() != Record.size() || NumUses > Record.size())
3059 // Mismatches can happen if the functions are being materialized lazily
3060 // (out-of-order), or a value has been upgraded.
3063 V->sortUseList([&](const Use &L, const Use &R) {
3064 return Order.lookup(&L) < Order.lookup(&R);
3072 /// When we see the block for metadata, remember where it is and then skip it.
3073 /// This lets us lazily deserialize the metadata.
3074 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3075 // Save the current stream state.
3076 uint64_t CurBit = Stream.GetCurrentBitNo();
3077 DeferredMetadataInfo.push_back(CurBit);
3079 // Skip over the block for now.
3080 if (Stream.SkipBlock())
3081 return error("Invalid record");
3082 return std::error_code();
3085 std::error_code BitcodeReader::materializeMetadata() {
3086 for (uint64_t BitPos : DeferredMetadataInfo) {
3087 // Move the bit stream to the saved position.
3088 Stream.JumpToBit(BitPos);
3089 if (std::error_code EC = parseMetadata(true))
3092 DeferredMetadataInfo.clear();
3093 return std::error_code();
3096 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3098 /// When we see the block for a function body, remember where it is and then
3099 /// skip it. This lets us lazily deserialize the functions.
3100 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3101 // Get the function we are talking about.
3102 if (FunctionsWithBodies.empty())
3103 return error("Insufficient function protos");
3105 Function *Fn = FunctionsWithBodies.back();
3106 FunctionsWithBodies.pop_back();
3108 // Save the current stream state.
3109 uint64_t CurBit = Stream.GetCurrentBitNo();
3111 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3112 "Mismatch between VST and scanned function offsets");
3113 DeferredFunctionInfo[Fn] = CurBit;
3115 // Skip over the function block for now.
3116 if (Stream.SkipBlock())
3117 return error("Invalid record");
3118 return std::error_code();
3121 std::error_code BitcodeReader::globalCleanup() {
3122 // Patch the initializers for globals and aliases up.
3123 resolveGlobalAndAliasInits();
3124 if (!GlobalInits.empty() || !AliasInits.empty())
3125 return error("Malformed global initializer set");
3127 // Look for intrinsic functions which need to be upgraded at some point
3128 for (Function &F : *TheModule) {
3130 if (UpgradeIntrinsicFunction(&F, NewFn))
3131 UpgradedIntrinsics[&F] = NewFn;
3134 // Look for global variables which need to be renamed.
3135 for (GlobalVariable &GV : TheModule->globals())
3136 UpgradeGlobalVariable(&GV);
3138 // Force deallocation of memory for these vectors to favor the client that
3139 // want lazy deserialization.
3140 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3141 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3142 return std::error_code();
3145 /// Support for lazy parsing of function bodies. This is required if we
3146 /// either have an old bitcode file without a VST forward declaration record,
3147 /// or if we have an anonymous function being materialized, since anonymous
3148 /// functions do not have a name and are therefore not in the VST.
3149 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3150 Stream.JumpToBit(NextUnreadBit);
3152 if (Stream.AtEndOfStream())
3153 return error("Could not find function in stream");
3155 if (!SeenFirstFunctionBody)
3156 return error("Trying to materialize functions before seeing function blocks");
3158 // An old bitcode file with the symbol table at the end would have
3159 // finished the parse greedily.
3160 assert(SeenValueSymbolTable);
3162 SmallVector<uint64_t, 64> Record;
3165 BitstreamEntry Entry = Stream.advance();
3166 switch (Entry.Kind) {
3168 return error("Expect SubBlock");
3169 case BitstreamEntry::SubBlock:
3172 return error("Expect function block");
3173 case bitc::FUNCTION_BLOCK_ID:
3174 if (std::error_code EC = rememberAndSkipFunctionBody())
3176 NextUnreadBit = Stream.GetCurrentBitNo();
3177 return std::error_code();
3183 std::error_code BitcodeReader::parseBitcodeVersion() {
3184 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3185 return error("Invalid record");
3187 // Read all the records.
3188 SmallVector<uint64_t, 64> Record;
3190 BitstreamEntry Entry = Stream.advance();
3192 switch (Entry.Kind) {
3194 case BitstreamEntry::Error:
3195 return error("Malformed block");
3196 case BitstreamEntry::EndBlock:
3197 return std::error_code();
3198 case BitstreamEntry::Record:
3199 // The interesting case.
3205 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3207 default: // Default behavior: reject
3208 return error("Invalid value");
3209 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3211 convertToString(Record, 0, ProducerIdentification);
3214 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3215 unsigned epoch = (unsigned)Record[0];
3216 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3218 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3219 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3226 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3227 bool ShouldLazyLoadMetadata) {
3229 Stream.JumpToBit(ResumeBit);
3230 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3231 return error("Invalid record");
3233 SmallVector<uint64_t, 64> Record;
3234 std::vector<std::string> SectionTable;
3235 std::vector<std::string> GCTable;
3237 // Read all the records for this module.
3239 BitstreamEntry Entry = Stream.advance();
3241 switch (Entry.Kind) {
3242 case BitstreamEntry::Error:
3243 return error("Malformed block");
3244 case BitstreamEntry::EndBlock:
3245 return globalCleanup();
3247 case BitstreamEntry::SubBlock:
3249 default: // Skip unknown content.
3250 if (Stream.SkipBlock())
3251 return error("Invalid record");
3253 case bitc::BLOCKINFO_BLOCK_ID:
3254 if (Stream.ReadBlockInfoBlock())
3255 return error("Malformed block");
3257 case bitc::PARAMATTR_BLOCK_ID:
3258 if (std::error_code EC = parseAttributeBlock())
3261 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3262 if (std::error_code EC = parseAttributeGroupBlock())
3265 case bitc::TYPE_BLOCK_ID_NEW:
3266 if (std::error_code EC = parseTypeTable())
3269 case bitc::VALUE_SYMTAB_BLOCK_ID:
3270 if (!SeenValueSymbolTable) {
3271 // Either this is an old form VST without function index and an
3272 // associated VST forward declaration record (which would have caused
3273 // the VST to be jumped to and parsed before it was encountered
3274 // normally in the stream), or there were no function blocks to
3275 // trigger an earlier parsing of the VST.
3276 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3277 if (std::error_code EC = parseValueSymbolTable())
3279 SeenValueSymbolTable = true;
3281 // We must have had a VST forward declaration record, which caused
3282 // the parser to jump to and parse the VST earlier.
3283 assert(VSTOffset > 0);
3284 if (Stream.SkipBlock())
3285 return error("Invalid record");
3288 case bitc::CONSTANTS_BLOCK_ID:
3289 if (std::error_code EC = parseConstants())
3291 if (std::error_code EC = resolveGlobalAndAliasInits())
3294 case bitc::METADATA_BLOCK_ID:
3295 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3296 if (std::error_code EC = rememberAndSkipMetadata())
3300 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3301 if (std::error_code EC = parseMetadata(true))
3304 case bitc::METADATA_KIND_BLOCK_ID:
3305 if (std::error_code EC = parseMetadataKinds())
3308 case bitc::FUNCTION_BLOCK_ID:
3309 // If this is the first function body we've seen, reverse the
3310 // FunctionsWithBodies list.
3311 if (!SeenFirstFunctionBody) {
3312 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3313 if (std::error_code EC = globalCleanup())
3315 SeenFirstFunctionBody = true;
3318 if (VSTOffset > 0) {
3319 // If we have a VST forward declaration record, make sure we
3320 // parse the VST now if we haven't already. It is needed to
3321 // set up the DeferredFunctionInfo vector for lazy reading.
3322 if (!SeenValueSymbolTable) {
3323 if (std::error_code EC =
3324 BitcodeReader::parseValueSymbolTable(VSTOffset))
3326 SeenValueSymbolTable = true;
3327 // Fall through so that we record the NextUnreadBit below.
3328 // This is necessary in case we have an anonymous function that
3329 // is later materialized. Since it will not have a VST entry we
3330 // need to fall back to the lazy parse to find its offset.
3332 // If we have a VST forward declaration record, but have already
3333 // parsed the VST (just above, when the first function body was
3334 // encountered here), then we are resuming the parse after
3335 // materializing functions. The ResumeBit points to the
3336 // start of the last function block recorded in the
3337 // DeferredFunctionInfo map. Skip it.
3338 if (Stream.SkipBlock())
3339 return error("Invalid record");
3344 // Support older bitcode files that did not have the function
3345 // index in the VST, nor a VST forward declaration record, as
3346 // well as anonymous functions that do not have VST entries.
3347 // Build the DeferredFunctionInfo vector on the fly.
3348 if (std::error_code EC = rememberAndSkipFunctionBody())
3351 // Suspend parsing when we reach the function bodies. Subsequent
3352 // materialization calls will resume it when necessary. If the bitcode
3353 // file is old, the symbol table will be at the end instead and will not
3354 // have been seen yet. In this case, just finish the parse now.
3355 if (SeenValueSymbolTable) {
3356 NextUnreadBit = Stream.GetCurrentBitNo();
3357 return std::error_code();
3360 case bitc::USELIST_BLOCK_ID:
3361 if (std::error_code EC = parseUseLists())
3364 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3365 if (std::error_code EC = parseOperandBundleTags())
3371 case BitstreamEntry::Record:
3372 // The interesting case.
3378 auto BitCode = Stream.readRecord(Entry.ID, Record);
3380 default: break; // Default behavior, ignore unknown content.
3381 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
3382 if (Record.size() < 1)
3383 return error("Invalid record");
3384 // Only version #0 and #1 are supported so far.
3385 unsigned module_version = Record[0];
3386 switch (module_version) {
3388 return error("Invalid value");
3390 UseRelativeIDs = false;
3393 UseRelativeIDs = true;
3398 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3400 if (convertToString(Record, 0, S))
3401 return error("Invalid record");
3402 TheModule->setTargetTriple(S);
3405 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3407 if (convertToString(Record, 0, S))
3408 return error("Invalid record");
3409 TheModule->setDataLayout(S);
3412 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3414 if (convertToString(Record, 0, S))
3415 return error("Invalid record");
3416 TheModule->setModuleInlineAsm(S);
3419 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3420 // FIXME: Remove in 4.0.
3422 if (convertToString(Record, 0, S))
3423 return error("Invalid record");
3427 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3429 if (convertToString(Record, 0, S))
3430 return error("Invalid record");
3431 SectionTable.push_back(S);
3434 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3436 if (convertToString(Record, 0, S))
3437 return error("Invalid record");
3438 GCTable.push_back(S);
3441 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3442 if (Record.size() < 2)
3443 return error("Invalid record");
3444 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3445 unsigned ComdatNameSize = Record[1];
3446 std::string ComdatName;
3447 ComdatName.reserve(ComdatNameSize);
3448 for (unsigned i = 0; i != ComdatNameSize; ++i)
3449 ComdatName += (char)Record[2 + i];
3450 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3451 C->setSelectionKind(SK);
3452 ComdatList.push_back(C);
3455 // GLOBALVAR: [pointer type, isconst, initid,
3456 // linkage, alignment, section, visibility, threadlocal,
3457 // unnamed_addr, externally_initialized, dllstorageclass,
3459 case bitc::MODULE_CODE_GLOBALVAR: {
3460 if (Record.size() < 6)
3461 return error("Invalid record");
3462 Type *Ty = getTypeByID(Record[0]);
3464 return error("Invalid record");
3465 bool isConstant = Record[1] & 1;
3466 bool explicitType = Record[1] & 2;
3467 unsigned AddressSpace;
3469 AddressSpace = Record[1] >> 2;
3471 if (!Ty->isPointerTy())
3472 return error("Invalid type for value");
3473 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3474 Ty = cast<PointerType>(Ty)->getElementType();
3477 uint64_t RawLinkage = Record[3];
3478 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3480 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3482 std::string Section;
3484 if (Record[5]-1 >= SectionTable.size())
3485 return error("Invalid ID");
3486 Section = SectionTable[Record[5]-1];
3488 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3489 // Local linkage must have default visibility.
3490 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3491 // FIXME: Change to an error if non-default in 4.0.
3492 Visibility = getDecodedVisibility(Record[6]);
3494 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3495 if (Record.size() > 7)
3496 TLM = getDecodedThreadLocalMode(Record[7]);
3498 bool UnnamedAddr = false;
3499 if (Record.size() > 8)
3500 UnnamedAddr = Record[8];
3502 bool ExternallyInitialized = false;
3503 if (Record.size() > 9)
3504 ExternallyInitialized = Record[9];
3506 GlobalVariable *NewGV =
3507 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3508 TLM, AddressSpace, ExternallyInitialized);
3509 NewGV->setAlignment(Alignment);
3510 if (!Section.empty())
3511 NewGV->setSection(Section);
3512 NewGV->setVisibility(Visibility);
3513 NewGV->setUnnamedAddr(UnnamedAddr);
3515 if (Record.size() > 10)
3516 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3518 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3520 ValueList.push_back(NewGV);
3522 // Remember which value to use for the global initializer.
3523 if (unsigned InitID = Record[2])
3524 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3526 if (Record.size() > 11) {
3527 if (unsigned ComdatID = Record[11]) {
3528 if (ComdatID > ComdatList.size())
3529 return error("Invalid global variable comdat ID");
3530 NewGV->setComdat(ComdatList[ComdatID - 1]);
3532 } else if (hasImplicitComdat(RawLinkage)) {
3533 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3537 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
3538 // alignment, section, visibility, gc, unnamed_addr,
3539 // prologuedata, dllstorageclass, comdat, prefixdata]
3540 case bitc::MODULE_CODE_FUNCTION: {
3541 if (Record.size() < 8)
3542 return error("Invalid record");
3543 Type *Ty = getTypeByID(Record[0]);
3545 return error("Invalid record");
3546 if (auto *PTy = dyn_cast<PointerType>(Ty))
3547 Ty = PTy->getElementType();
3548 auto *FTy = dyn_cast<FunctionType>(Ty);
3550 return error("Invalid type for value");
3551 auto CC = static_cast<CallingConv::ID>(Record[1]);
3552 if (CC & ~CallingConv::MaxID)
3553 return error("Invalid calling convention ID");
3555 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3558 Func->setCallingConv(CC);
3559 bool isProto = Record[2];
3560 uint64_t RawLinkage = Record[3];
3561 Func->setLinkage(getDecodedLinkage(RawLinkage));
3562 Func->setAttributes(getAttributes(Record[4]));
3565 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3567 Func->setAlignment(Alignment);
3569 if (Record[6]-1 >= SectionTable.size())
3570 return error("Invalid ID");
3571 Func->setSection(SectionTable[Record[6]-1]);
3573 // Local linkage must have default visibility.
3574 if (!Func->hasLocalLinkage())
3575 // FIXME: Change to an error if non-default in 4.0.
3576 Func->setVisibility(getDecodedVisibility(Record[7]));
3577 if (Record.size() > 8 && Record[8]) {
3578 if (Record[8]-1 >= GCTable.size())
3579 return error("Invalid ID");
3580 Func->setGC(GCTable[Record[8]-1].c_str());
3582 bool UnnamedAddr = false;
3583 if (Record.size() > 9)
3584 UnnamedAddr = Record[9];
3585 Func->setUnnamedAddr(UnnamedAddr);
3586 if (Record.size() > 10 && Record[10] != 0)
3587 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3589 if (Record.size() > 11)
3590 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3592 upgradeDLLImportExportLinkage(Func, RawLinkage);
3594 if (Record.size() > 12) {
3595 if (unsigned ComdatID = Record[12]) {
3596 if (ComdatID > ComdatList.size())
3597 return error("Invalid function comdat ID");
3598 Func->setComdat(ComdatList[ComdatID - 1]);
3600 } else if (hasImplicitComdat(RawLinkage)) {
3601 Func->setComdat(reinterpret_cast<Comdat *>(1));
3604 if (Record.size() > 13 && Record[13] != 0)
3605 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3607 if (Record.size() > 14 && Record[14] != 0)
3608 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3610 ValueList.push_back(Func);
3612 // If this is a function with a body, remember the prototype we are
3613 // creating now, so that we can match up the body with them later.
3615 Func->setIsMaterializable(true);
3616 FunctionsWithBodies.push_back(Func);
3617 DeferredFunctionInfo[Func] = 0;
3621 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3622 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3623 case bitc::MODULE_CODE_ALIAS:
3624 case bitc::MODULE_CODE_ALIAS_OLD: {
3625 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3626 if (Record.size() < (3 + (unsigned)NewRecord))
3627 return error("Invalid record");
3629 Type *Ty = getTypeByID(Record[OpNum++]);
3631 return error("Invalid record");
3635 auto *PTy = dyn_cast<PointerType>(Ty);
3637 return error("Invalid type for value");
3638 Ty = PTy->getElementType();
3639 AddrSpace = PTy->getAddressSpace();
3641 AddrSpace = Record[OpNum++];
3644 auto Val = Record[OpNum++];
3645 auto Linkage = Record[OpNum++];
3646 auto *NewGA = GlobalAlias::create(
3647 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3648 // Old bitcode files didn't have visibility field.
3649 // Local linkage must have default visibility.
3650 if (OpNum != Record.size()) {
3651 auto VisInd = OpNum++;
3652 if (!NewGA->hasLocalLinkage())
3653 // FIXME: Change to an error if non-default in 4.0.
3654 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3656 if (OpNum != Record.size())
3657 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3659 upgradeDLLImportExportLinkage(NewGA, Linkage);
3660 if (OpNum != Record.size())
3661 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3662 if (OpNum != Record.size())
3663 NewGA->setUnnamedAddr(Record[OpNum++]);
3664 ValueList.push_back(NewGA);
3665 AliasInits.push_back(std::make_pair(NewGA, Val));
3668 /// MODULE_CODE_PURGEVALS: [numvals]
3669 case bitc::MODULE_CODE_PURGEVALS:
3670 // Trim down the value list to the specified size.
3671 if (Record.size() < 1 || Record[0] > ValueList.size())
3672 return error("Invalid record");
3673 ValueList.shrinkTo(Record[0]);
3675 /// MODULE_CODE_VSTOFFSET: [offset]
3676 case bitc::MODULE_CODE_VSTOFFSET:
3677 if (Record.size() < 1)
3678 return error("Invalid record");
3679 VSTOffset = Record[0];
3681 /// MODULE_CODE_METADATA_VALUES: [numvals]
3682 case bitc::MODULE_CODE_METADATA_VALUES:
3683 if (Record.size() < 1)
3684 return error("Invalid record");
3685 assert(!IsMetadataMaterialized);
3686 // This record contains the number of metadata values in the module-level
3687 // METADATA_BLOCK. It is used to support lazy parsing of metadata as
3688 // a postpass, where we will parse function-level metadata first.
3689 // This is needed because the ids of metadata are assigned implicitly
3690 // based on their ordering in the bitcode, with the function-level
3691 // metadata ids starting after the module-level metadata ids. Otherwise,
3692 // we would have to parse the module-level metadata block to prime the
3693 // MDValueList when we are lazy loading metadata during function
3694 // importing. Initialize the MDValueList size here based on the
3695 // record value, regardless of whether we are doing lazy metadata
3696 // loading, so that we have consistent handling and assertion
3697 // checking in parseMetadata for module-level metadata.
3698 NumModuleMDs = Record[0];
3699 SeenModuleValuesRecord = true;
3700 assert(MDValueList.size() == 0);
3701 MDValueList.resize(NumModuleMDs);
3708 /// Helper to read the header common to all bitcode files.
3709 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3710 // Sniff for the signature.
3711 if (Stream.Read(8) != 'B' ||
3712 Stream.Read(8) != 'C' ||
3713 Stream.Read(4) != 0x0 ||
3714 Stream.Read(4) != 0xC ||
3715 Stream.Read(4) != 0xE ||
3716 Stream.Read(4) != 0xD)
3722 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3723 Module *M, bool ShouldLazyLoadMetadata) {
3726 if (std::error_code EC = initStream(std::move(Streamer)))
3729 // Sniff for the signature.
3730 if (!hasValidBitcodeHeader(Stream))
3731 return error("Invalid bitcode signature");
3733 // We expect a number of well-defined blocks, though we don't necessarily
3734 // need to understand them all.
3736 if (Stream.AtEndOfStream()) {
3737 // We didn't really read a proper Module.
3738 return error("Malformed IR file");
3741 BitstreamEntry Entry =
3742 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3744 if (Entry.Kind != BitstreamEntry::SubBlock)
3745 return error("Malformed block");
3747 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3748 parseBitcodeVersion();
3752 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3753 return parseModule(0, ShouldLazyLoadMetadata);
3755 if (Stream.SkipBlock())
3756 return error("Invalid record");
3760 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3761 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3762 return error("Invalid record");
3764 SmallVector<uint64_t, 64> Record;
3767 // Read all the records for this module.
3769 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3771 switch (Entry.Kind) {
3772 case BitstreamEntry::SubBlock: // Handled for us already.
3773 case BitstreamEntry::Error:
3774 return error("Malformed block");
3775 case BitstreamEntry::EndBlock:
3777 case BitstreamEntry::Record:
3778 // The interesting case.
3783 switch (Stream.readRecord(Entry.ID, Record)) {
3784 default: break; // Default behavior, ignore unknown content.
3785 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3787 if (convertToString(Record, 0, S))
3788 return error("Invalid record");
3795 llvm_unreachable("Exit infinite loop");
3798 ErrorOr<std::string> BitcodeReader::parseTriple() {
3799 if (std::error_code EC = initStream(nullptr))
3802 // Sniff for the signature.
3803 if (!hasValidBitcodeHeader(Stream))
3804 return error("Invalid bitcode signature");
3806 // We expect a number of well-defined blocks, though we don't necessarily
3807 // need to understand them all.
3809 BitstreamEntry Entry = Stream.advance();
3811 switch (Entry.Kind) {
3812 case BitstreamEntry::Error:
3813 return error("Malformed block");
3814 case BitstreamEntry::EndBlock:
3815 return std::error_code();
3817 case BitstreamEntry::SubBlock:
3818 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3819 return parseModuleTriple();
3821 // Ignore other sub-blocks.
3822 if (Stream.SkipBlock())
3823 return error("Malformed block");
3826 case BitstreamEntry::Record:
3827 Stream.skipRecord(Entry.ID);
3833 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3834 if (std::error_code EC = initStream(nullptr))
3837 // Sniff for the signature.
3838 if (!hasValidBitcodeHeader(Stream))
3839 return error("Invalid bitcode signature");
3841 // We expect a number of well-defined blocks, though we don't necessarily
3842 // need to understand them all.
3844 BitstreamEntry Entry = Stream.advance();
3845 switch (Entry.Kind) {
3846 case BitstreamEntry::Error:
3847 return error("Malformed block");
3848 case BitstreamEntry::EndBlock:
3849 return std::error_code();
3851 case BitstreamEntry::SubBlock:
3852 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3853 if (std::error_code EC = parseBitcodeVersion())
3855 return ProducerIdentification;
3857 // Ignore other sub-blocks.
3858 if (Stream.SkipBlock())
3859 return error("Malformed block");
3861 case BitstreamEntry::Record:
3862 Stream.skipRecord(Entry.ID);
3868 /// Parse metadata attachments.
3869 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3870 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3871 return error("Invalid record");
3873 SmallVector<uint64_t, 64> Record;
3875 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3877 switch (Entry.Kind) {
3878 case BitstreamEntry::SubBlock: // Handled for us already.
3879 case BitstreamEntry::Error:
3880 return error("Malformed block");
3881 case BitstreamEntry::EndBlock:
3882 return std::error_code();
3883 case BitstreamEntry::Record:
3884 // The interesting case.
3888 // Read a metadata attachment record.
3890 switch (Stream.readRecord(Entry.ID, Record)) {
3891 default: // Default behavior: ignore.
3893 case bitc::METADATA_ATTACHMENT: {
3894 unsigned RecordLength = Record.size();
3896 return error("Invalid record");
3897 if (RecordLength % 2 == 0) {
3898 // A function attachment.
3899 for (unsigned I = 0; I != RecordLength; I += 2) {
3900 auto K = MDKindMap.find(Record[I]);
3901 if (K == MDKindMap.end())
3902 return error("Invalid ID");
3903 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3904 F.setMetadata(K->second, cast<MDNode>(MD));
3909 // An instruction attachment.
3910 Instruction *Inst = InstructionList[Record[0]];
3911 for (unsigned i = 1; i != RecordLength; i = i+2) {
3912 unsigned Kind = Record[i];
3913 DenseMap<unsigned, unsigned>::iterator I =
3914 MDKindMap.find(Kind);
3915 if (I == MDKindMap.end())
3916 return error("Invalid ID");
3917 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3918 if (isa<LocalAsMetadata>(Node))
3919 // Drop the attachment. This used to be legal, but there's no
3922 Inst->setMetadata(I->second, cast<MDNode>(Node));
3923 if (I->second == LLVMContext::MD_tbaa)
3924 InstsWithTBAATag.push_back(Inst);
3932 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3933 Type *ValType, Type *PtrType) {
3934 if (!isa<PointerType>(PtrType))
3935 return error(DH, "Load/Store operand is not a pointer type");
3936 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3938 if (ValType && ValType != ElemType)
3939 return error(DH, "Explicit load/store type does not match pointee type of "
3941 if (!PointerType::isLoadableOrStorableType(ElemType))
3942 return error(DH, "Cannot load/store from pointer");
3943 return std::error_code();
3946 /// Lazily parse the specified function body block.
3947 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3948 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3949 return error("Invalid record");
3951 InstructionList.clear();
3952 unsigned ModuleValueListSize = ValueList.size();
3953 unsigned ModuleMDValueListSize = MDValueList.size();
3955 // Add all the function arguments to the value table.
3956 for (Argument &I : F->args())
3957 ValueList.push_back(&I);
3959 unsigned NextValueNo = ValueList.size();
3960 BasicBlock *CurBB = nullptr;
3961 unsigned CurBBNo = 0;
3964 auto getLastInstruction = [&]() -> Instruction * {
3965 if (CurBB && !CurBB->empty())
3966 return &CurBB->back();
3967 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3968 !FunctionBBs[CurBBNo - 1]->empty())
3969 return &FunctionBBs[CurBBNo - 1]->back();
3973 std::vector<OperandBundleDef> OperandBundles;
3975 // Read all the records.
3976 SmallVector<uint64_t, 64> Record;
3978 BitstreamEntry Entry = Stream.advance();
3980 switch (Entry.Kind) {
3981 case BitstreamEntry::Error:
3982 return error("Malformed block");
3983 case BitstreamEntry::EndBlock:
3984 goto OutOfRecordLoop;
3986 case BitstreamEntry::SubBlock:
3988 default: // Skip unknown content.
3989 if (Stream.SkipBlock())
3990 return error("Invalid record");
3992 case bitc::CONSTANTS_BLOCK_ID:
3993 if (std::error_code EC = parseConstants())
3995 NextValueNo = ValueList.size();
3997 case bitc::VALUE_SYMTAB_BLOCK_ID:
3998 if (std::error_code EC = parseValueSymbolTable())
4001 case bitc::METADATA_ATTACHMENT_ID:
4002 if (std::error_code EC = parseMetadataAttachment(*F))
4005 case bitc::METADATA_BLOCK_ID:
4006 if (std::error_code EC = parseMetadata())
4009 case bitc::USELIST_BLOCK_ID:
4010 if (std::error_code EC = parseUseLists())
4016 case BitstreamEntry::Record:
4017 // The interesting case.
4023 Instruction *I = nullptr;
4024 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
4026 default: // Default behavior: reject
4027 return error("Invalid value");
4028 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
4029 if (Record.size() < 1 || Record[0] == 0)
4030 return error("Invalid record");
4031 // Create all the basic blocks for the function.
4032 FunctionBBs.resize(Record[0]);
4034 // See if anything took the address of blocks in this function.
4035 auto BBFRI = BasicBlockFwdRefs.find(F);
4036 if (BBFRI == BasicBlockFwdRefs.end()) {
4037 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4038 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4040 auto &BBRefs = BBFRI->second;
4041 // Check for invalid basic block references.
4042 if (BBRefs.size() > FunctionBBs.size())
4043 return error("Invalid ID");
4044 assert(!BBRefs.empty() && "Unexpected empty array");
4045 assert(!BBRefs.front() && "Invalid reference to entry block");
4046 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4048 if (I < RE && BBRefs[I]) {
4049 BBRefs[I]->insertInto(F);
4050 FunctionBBs[I] = BBRefs[I];
4052 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4055 // Erase from the table.
4056 BasicBlockFwdRefs.erase(BBFRI);
4059 CurBB = FunctionBBs[0];
4063 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4064 // This record indicates that the last instruction is at the same
4065 // location as the previous instruction with a location.
4066 I = getLastInstruction();
4069 return error("Invalid record");
4070 I->setDebugLoc(LastLoc);
4074 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4075 I = getLastInstruction();
4076 if (!I || Record.size() < 4)
4077 return error("Invalid record");
4079 unsigned Line = Record[0], Col = Record[1];
4080 unsigned ScopeID = Record[2], IAID = Record[3];
4082 MDNode *Scope = nullptr, *IA = nullptr;
4083 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
4084 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
4085 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4086 I->setDebugLoc(LastLoc);
4091 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4094 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4095 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4096 OpNum+1 > Record.size())
4097 return error("Invalid record");
4099 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4101 return error("Invalid record");
4102 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4103 InstructionList.push_back(I);
4104 if (OpNum < Record.size()) {
4105 if (Opc == Instruction::Add ||
4106 Opc == Instruction::Sub ||
4107 Opc == Instruction::Mul ||
4108 Opc == Instruction::Shl) {
4109 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4110 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4111 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4112 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4113 } else if (Opc == Instruction::SDiv ||
4114 Opc == Instruction::UDiv ||
4115 Opc == Instruction::LShr ||
4116 Opc == Instruction::AShr) {
4117 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4118 cast<BinaryOperator>(I)->setIsExact(true);
4119 } else if (isa<FPMathOperator>(I)) {
4120 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4122 I->setFastMathFlags(FMF);
4128 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4131 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4132 OpNum+2 != Record.size())
4133 return error("Invalid record");
4135 Type *ResTy = getTypeByID(Record[OpNum]);
4136 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4137 if (Opc == -1 || !ResTy)
4138 return error("Invalid record");
4139 Instruction *Temp = nullptr;
4140 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4142 InstructionList.push_back(Temp);
4143 CurBB->getInstList().push_back(Temp);
4146 auto CastOp = (Instruction::CastOps)Opc;
4147 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4148 return error("Invalid cast");
4149 I = CastInst::Create(CastOp, Op, ResTy);
4151 InstructionList.push_back(I);
4154 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4155 case bitc::FUNC_CODE_INST_GEP_OLD:
4156 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4162 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4163 InBounds = Record[OpNum++];
4164 Ty = getTypeByID(Record[OpNum++]);
4166 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4171 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4172 return error("Invalid record");
4175 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4178 cast<SequentialType>(BasePtr->getType()->getScalarType())
4181 "Explicit gep type does not match pointee type of pointer operand");
4183 SmallVector<Value*, 16> GEPIdx;
4184 while (OpNum != Record.size()) {
4186 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4187 return error("Invalid record");
4188 GEPIdx.push_back(Op);
4191 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4193 InstructionList.push_back(I);
4195 cast<GetElementPtrInst>(I)->setIsInBounds(true);
4199 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4200 // EXTRACTVAL: [opty, opval, n x indices]
4203 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4204 return error("Invalid record");
4206 unsigned RecSize = Record.size();
4207 if (OpNum == RecSize)
4208 return error("EXTRACTVAL: Invalid instruction with 0 indices");
4210 SmallVector<unsigned, 4> EXTRACTVALIdx;
4211 Type *CurTy = Agg->getType();
4212 for (; OpNum != RecSize; ++OpNum) {
4213 bool IsArray = CurTy->isArrayTy();
4214 bool IsStruct = CurTy->isStructTy();
4215 uint64_t Index = Record[OpNum];
4217 if (!IsStruct && !IsArray)
4218 return error("EXTRACTVAL: Invalid type");
4219 if ((unsigned)Index != Index)
4220 return error("Invalid value");
4221 if (IsStruct && Index >= CurTy->subtypes().size())
4222 return error("EXTRACTVAL: Invalid struct index");
4223 if (IsArray && Index >= CurTy->getArrayNumElements())
4224 return error("EXTRACTVAL: Invalid array index");
4225 EXTRACTVALIdx.push_back((unsigned)Index);
4228 CurTy = CurTy->subtypes()[Index];
4230 CurTy = CurTy->subtypes()[0];
4233 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4234 InstructionList.push_back(I);
4238 case bitc::FUNC_CODE_INST_INSERTVAL: {
4239 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4242 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4243 return error("Invalid record");
4245 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4246 return error("Invalid record");
4248 unsigned RecSize = Record.size();
4249 if (OpNum == RecSize)
4250 return error("INSERTVAL: Invalid instruction with 0 indices");
4252 SmallVector<unsigned, 4> INSERTVALIdx;
4253 Type *CurTy = Agg->getType();
4254 for (; OpNum != RecSize; ++OpNum) {
4255 bool IsArray = CurTy->isArrayTy();
4256 bool IsStruct = CurTy->isStructTy();
4257 uint64_t Index = Record[OpNum];
4259 if (!IsStruct && !IsArray)
4260 return error("INSERTVAL: Invalid type");
4261 if ((unsigned)Index != Index)
4262 return error("Invalid value");
4263 if (IsStruct && Index >= CurTy->subtypes().size())
4264 return error("INSERTVAL: Invalid struct index");
4265 if (IsArray && Index >= CurTy->getArrayNumElements())
4266 return error("INSERTVAL: Invalid array index");
4268 INSERTVALIdx.push_back((unsigned)Index);
4270 CurTy = CurTy->subtypes()[Index];
4272 CurTy = CurTy->subtypes()[0];
4275 if (CurTy != Val->getType())
4276 return error("Inserted value type doesn't match aggregate type");
4278 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4279 InstructionList.push_back(I);
4283 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4284 // obsolete form of select
4285 // handles select i1 ... in old bitcode
4287 Value *TrueVal, *FalseVal, *Cond;
4288 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4289 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4290 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4291 return error("Invalid record");
4293 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4294 InstructionList.push_back(I);
4298 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4299 // new form of select
4300 // handles select i1 or select [N x i1]
4302 Value *TrueVal, *FalseVal, *Cond;
4303 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4304 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4305 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4306 return error("Invalid record");
4308 // select condition can be either i1 or [N x i1]
4309 if (VectorType* vector_type =
4310 dyn_cast<VectorType>(Cond->getType())) {
4312 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4313 return error("Invalid type for value");
4316 if (Cond->getType() != Type::getInt1Ty(Context))
4317 return error("Invalid type for value");
4320 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4321 InstructionList.push_back(I);
4325 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4328 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4329 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4330 return error("Invalid record");
4331 if (!Vec->getType()->isVectorTy())
4332 return error("Invalid type for value");
4333 I = ExtractElementInst::Create(Vec, Idx);
4334 InstructionList.push_back(I);
4338 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4340 Value *Vec, *Elt, *Idx;
4341 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4342 return error("Invalid record");
4343 if (!Vec->getType()->isVectorTy())
4344 return error("Invalid type for value");
4345 if (popValue(Record, OpNum, NextValueNo,
4346 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4347 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4348 return error("Invalid record");
4349 I = InsertElementInst::Create(Vec, Elt, Idx);
4350 InstructionList.push_back(I);
4354 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4356 Value *Vec1, *Vec2, *Mask;
4357 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4358 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4359 return error("Invalid record");
4361 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4362 return error("Invalid record");
4363 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4364 return error("Invalid type for value");
4365 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4366 InstructionList.push_back(I);
4370 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4371 // Old form of ICmp/FCmp returning bool
4372 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4373 // both legal on vectors but had different behaviour.
4374 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4375 // FCmp/ICmp returning bool or vector of bool
4379 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4380 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4381 return error("Invalid record");
4383 unsigned PredVal = Record[OpNum];
4384 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4386 if (IsFP && Record.size() > OpNum+1)
4387 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4389 if (OpNum+1 != Record.size())
4390 return error("Invalid record");
4392 if (LHS->getType()->isFPOrFPVectorTy())
4393 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4395 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4398 I->setFastMathFlags(FMF);
4399 InstructionList.push_back(I);
4403 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4405 unsigned Size = Record.size();
4407 I = ReturnInst::Create(Context);
4408 InstructionList.push_back(I);
4413 Value *Op = nullptr;
4414 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4415 return error("Invalid record");
4416 if (OpNum != Record.size())
4417 return error("Invalid record");
4419 I = ReturnInst::Create(Context, Op);
4420 InstructionList.push_back(I);
4423 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4424 if (Record.size() != 1 && Record.size() != 3)
4425 return error("Invalid record");
4426 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4428 return error("Invalid record");
4430 if (Record.size() == 1) {
4431 I = BranchInst::Create(TrueDest);
4432 InstructionList.push_back(I);
4435 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4436 Value *Cond = getValue(Record, 2, NextValueNo,
4437 Type::getInt1Ty(Context));
4438 if (!FalseDest || !Cond)
4439 return error("Invalid record");
4440 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4441 InstructionList.push_back(I);
4445 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4446 if (Record.size() != 1 && Record.size() != 2)
4447 return error("Invalid record");
4449 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4450 Type::getTokenTy(Context), OC_CleanupPad);
4452 return error("Invalid record");
4453 BasicBlock *UnwindDest = nullptr;
4454 if (Record.size() == 2) {
4455 UnwindDest = getBasicBlock(Record[Idx++]);
4457 return error("Invalid record");
4460 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4462 InstructionList.push_back(I);
4465 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4466 if (Record.size() != 2)
4467 return error("Invalid record");
4469 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4470 Type::getTokenTy(Context), OC_CatchPad);
4472 return error("Invalid record");
4473 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4475 return error("Invalid record");
4477 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4478 InstructionList.push_back(I);
4481 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4482 if (Record.size() < 3)
4483 return error("Invalid record");
4485 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4487 return error("Invalid record");
4488 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4490 return error("Invalid record");
4491 unsigned NumArgOperands = Record[Idx++];
4492 SmallVector<Value *, 2> Args;
4493 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4495 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4496 return error("Invalid record");
4497 Args.push_back(Val);
4499 if (Record.size() != Idx)
4500 return error("Invalid record");
4502 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4503 InstructionList.push_back(I);
4506 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4507 if (Record.size() < 1)
4508 return error("Invalid record");
4510 bool HasUnwindDest = !!Record[Idx++];
4511 BasicBlock *UnwindDest = nullptr;
4512 if (HasUnwindDest) {
4513 if (Idx == Record.size())
4514 return error("Invalid record");
4515 UnwindDest = getBasicBlock(Record[Idx++]);
4517 return error("Invalid record");
4519 unsigned NumArgOperands = Record[Idx++];
4520 SmallVector<Value *, 2> Args;
4521 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4523 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4524 return error("Invalid record");
4525 Args.push_back(Val);
4527 if (Record.size() != Idx)
4528 return error("Invalid record");
4530 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4531 InstructionList.push_back(I);
4534 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4535 if (Record.size() < 1)
4536 return error("Invalid record");
4538 unsigned NumArgOperands = Record[Idx++];
4539 SmallVector<Value *, 2> Args;
4540 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4542 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4543 return error("Invalid record");
4544 Args.push_back(Val);
4546 if (Record.size() != Idx)
4547 return error("Invalid record");
4549 I = CleanupPadInst::Create(Context, Args);
4550 InstructionList.push_back(I);
4553 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4554 if (Record.size() > 1)
4555 return error("Invalid record");
4556 BasicBlock *BB = nullptr;
4557 if (Record.size() == 1) {
4558 BB = getBasicBlock(Record[0]);
4560 return error("Invalid record");
4562 I = CatchEndPadInst::Create(Context, BB);
4563 InstructionList.push_back(I);
4566 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4567 if (Record.size() != 1 && Record.size() != 2)
4568 return error("Invalid record");
4570 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4571 Type::getTokenTy(Context), OC_CleanupPad);
4573 return error("Invalid record");
4575 BasicBlock *BB = nullptr;
4576 if (Record.size() == 2) {
4577 BB = getBasicBlock(Record[Idx++]);
4579 return error("Invalid record");
4581 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4582 InstructionList.push_back(I);
4585 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4587 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4588 // "New" SwitchInst format with case ranges. The changes to write this
4589 // format were reverted but we still recognize bitcode that uses it.
4590 // Hopefully someday we will have support for case ranges and can use
4591 // this format again.
4593 Type *OpTy = getTypeByID(Record[1]);
4594 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4596 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4597 BasicBlock *Default = getBasicBlock(Record[3]);
4598 if (!OpTy || !Cond || !Default)
4599 return error("Invalid record");
4601 unsigned NumCases = Record[4];
4603 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4604 InstructionList.push_back(SI);
4606 unsigned CurIdx = 5;
4607 for (unsigned i = 0; i != NumCases; ++i) {
4608 SmallVector<ConstantInt*, 1> CaseVals;
4609 unsigned NumItems = Record[CurIdx++];
4610 for (unsigned ci = 0; ci != NumItems; ++ci) {
4611 bool isSingleNumber = Record[CurIdx++];
4614 unsigned ActiveWords = 1;
4615 if (ValueBitWidth > 64)
4616 ActiveWords = Record[CurIdx++];
4617 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4619 CurIdx += ActiveWords;
4621 if (!isSingleNumber) {
4623 if (ValueBitWidth > 64)
4624 ActiveWords = Record[CurIdx++];
4625 APInt High = readWideAPInt(
4626 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4627 CurIdx += ActiveWords;
4629 // FIXME: It is not clear whether values in the range should be
4630 // compared as signed or unsigned values. The partially
4631 // implemented changes that used this format in the past used
4632 // unsigned comparisons.
4633 for ( ; Low.ule(High); ++Low)
4634 CaseVals.push_back(ConstantInt::get(Context, Low));
4636 CaseVals.push_back(ConstantInt::get(Context, Low));
4638 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4639 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4640 cve = CaseVals.end(); cvi != cve; ++cvi)
4641 SI->addCase(*cvi, DestBB);
4647 // Old SwitchInst format without case ranges.
4649 if (Record.size() < 3 || (Record.size() & 1) == 0)
4650 return error("Invalid record");
4651 Type *OpTy = getTypeByID(Record[0]);
4652 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4653 BasicBlock *Default = getBasicBlock(Record[2]);
4654 if (!OpTy || !Cond || !Default)
4655 return error("Invalid record");
4656 unsigned NumCases = (Record.size()-3)/2;
4657 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4658 InstructionList.push_back(SI);
4659 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4660 ConstantInt *CaseVal =
4661 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4662 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4663 if (!CaseVal || !DestBB) {
4665 return error("Invalid record");
4667 SI->addCase(CaseVal, DestBB);
4672 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4673 if (Record.size() < 2)
4674 return error("Invalid record");
4675 Type *OpTy = getTypeByID(Record[0]);
4676 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4677 if (!OpTy || !Address)
4678 return error("Invalid record");
4679 unsigned NumDests = Record.size()-2;
4680 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4681 InstructionList.push_back(IBI);
4682 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4683 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4684 IBI->addDestination(DestBB);
4687 return error("Invalid record");
4694 case bitc::FUNC_CODE_INST_INVOKE: {
4695 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4696 if (Record.size() < 4)
4697 return error("Invalid record");
4699 AttributeSet PAL = getAttributes(Record[OpNum++]);
4700 unsigned CCInfo = Record[OpNum++];
4701 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4702 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4704 FunctionType *FTy = nullptr;
4705 if (CCInfo >> 13 & 1 &&
4706 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4707 return error("Explicit invoke type is not a function type");
4710 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4711 return error("Invalid record");
4713 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4715 return error("Callee is not a pointer");
4717 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4719 return error("Callee is not of pointer to function type");
4720 } else if (CalleeTy->getElementType() != FTy)
4721 return error("Explicit invoke type does not match pointee type of "
4723 if (Record.size() < FTy->getNumParams() + OpNum)
4724 return error("Insufficient operands to call");
4726 SmallVector<Value*, 16> Ops;
4727 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4728 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4729 FTy->getParamType(i)));
4731 return error("Invalid record");
4734 if (!FTy->isVarArg()) {
4735 if (Record.size() != OpNum)
4736 return error("Invalid record");
4738 // Read type/value pairs for varargs params.
4739 while (OpNum != Record.size()) {
4741 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4742 return error("Invalid record");
4747 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4748 OperandBundles.clear();
4749 InstructionList.push_back(I);
4750 cast<InvokeInst>(I)->setCallingConv(
4751 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4752 cast<InvokeInst>(I)->setAttributes(PAL);
4755 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4757 Value *Val = nullptr;
4758 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4759 return error("Invalid record");
4760 I = ResumeInst::Create(Val);
4761 InstructionList.push_back(I);
4764 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4765 I = new UnreachableInst(Context);
4766 InstructionList.push_back(I);
4768 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4769 if (Record.size() < 1 || ((Record.size()-1)&1))
4770 return error("Invalid record");
4771 Type *Ty = getTypeByID(Record[0]);
4773 return error("Invalid record");
4775 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4776 InstructionList.push_back(PN);
4778 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4780 // With the new function encoding, it is possible that operands have
4781 // negative IDs (for forward references). Use a signed VBR
4782 // representation to keep the encoding small.
4784 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4786 V = getValue(Record, 1+i, NextValueNo, Ty);
4787 BasicBlock *BB = getBasicBlock(Record[2+i]);
4789 return error("Invalid record");
4790 PN->addIncoming(V, BB);
4796 case bitc::FUNC_CODE_INST_LANDINGPAD:
4797 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4798 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4800 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4801 if (Record.size() < 3)
4802 return error("Invalid record");
4804 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4805 if (Record.size() < 4)
4806 return error("Invalid record");
4808 Type *Ty = getTypeByID(Record[Idx++]);
4810 return error("Invalid record");
4811 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4812 Value *PersFn = nullptr;
4813 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4814 return error("Invalid record");
4816 if (!F->hasPersonalityFn())
4817 F->setPersonalityFn(cast<Constant>(PersFn));
4818 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4819 return error("Personality function mismatch");
4822 bool IsCleanup = !!Record[Idx++];
4823 unsigned NumClauses = Record[Idx++];
4824 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4825 LP->setCleanup(IsCleanup);
4826 for (unsigned J = 0; J != NumClauses; ++J) {
4827 LandingPadInst::ClauseType CT =
4828 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4831 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4833 return error("Invalid record");
4836 assert((CT != LandingPadInst::Catch ||
4837 !isa<ArrayType>(Val->getType())) &&
4838 "Catch clause has a invalid type!");
4839 assert((CT != LandingPadInst::Filter ||
4840 isa<ArrayType>(Val->getType())) &&
4841 "Filter clause has invalid type!");
4842 LP->addClause(cast<Constant>(Val));
4846 InstructionList.push_back(I);
4850 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4851 if (Record.size() != 4)
4852 return error("Invalid record");
4853 uint64_t AlignRecord = Record[3];
4854 const uint64_t InAllocaMask = uint64_t(1) << 5;
4855 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4856 // Reserve bit 7 for SwiftError flag.
4857 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4858 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4859 bool InAlloca = AlignRecord & InAllocaMask;
4860 Type *Ty = getTypeByID(Record[0]);
4861 if ((AlignRecord & ExplicitTypeMask) == 0) {
4862 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4864 return error("Old-style alloca with a non-pointer type");
4865 Ty = PTy->getElementType();
4867 Type *OpTy = getTypeByID(Record[1]);
4868 Value *Size = getFnValueByID(Record[2], OpTy);
4870 if (std::error_code EC =
4871 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4875 return error("Invalid record");
4876 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4877 AI->setUsedWithInAlloca(InAlloca);
4879 InstructionList.push_back(I);
4882 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4885 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4886 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4887 return error("Invalid record");
4890 if (OpNum + 3 == Record.size())
4891 Ty = getTypeByID(Record[OpNum++]);
4892 if (std::error_code EC =
4893 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4896 Ty = cast<PointerType>(Op->getType())->getElementType();
4899 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4901 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4903 InstructionList.push_back(I);
4906 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4907 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4910 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4911 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4912 return error("Invalid record");
4915 if (OpNum + 5 == Record.size())
4916 Ty = getTypeByID(Record[OpNum++]);
4917 if (std::error_code EC =
4918 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4921 Ty = cast<PointerType>(Op->getType())->getElementType();
4923 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4924 if (Ordering == NotAtomic || Ordering == Release ||
4925 Ordering == AcquireRelease)
4926 return error("Invalid record");
4927 if (Ordering != NotAtomic && Record[OpNum] == 0)
4928 return error("Invalid record");
4929 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4932 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4934 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4936 InstructionList.push_back(I);
4939 case bitc::FUNC_CODE_INST_STORE:
4940 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4943 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4944 (BitCode == bitc::FUNC_CODE_INST_STORE
4945 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4946 : popValue(Record, OpNum, NextValueNo,
4947 cast<PointerType>(Ptr->getType())->getElementType(),
4949 OpNum + 2 != Record.size())
4950 return error("Invalid record");
4952 if (std::error_code EC = typeCheckLoadStoreInst(
4953 DiagnosticHandler, Val->getType(), Ptr->getType()))
4956 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4958 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4959 InstructionList.push_back(I);
4962 case bitc::FUNC_CODE_INST_STOREATOMIC:
4963 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4964 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4967 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4968 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4969 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4970 : popValue(Record, OpNum, NextValueNo,
4971 cast<PointerType>(Ptr->getType())->getElementType(),
4973 OpNum + 4 != Record.size())
4974 return error("Invalid record");
4976 if (std::error_code EC = typeCheckLoadStoreInst(
4977 DiagnosticHandler, Val->getType(), Ptr->getType()))
4979 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4980 if (Ordering == NotAtomic || Ordering == Acquire ||
4981 Ordering == AcquireRelease)
4982 return error("Invalid record");
4983 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4984 if (Ordering != NotAtomic && Record[OpNum] == 0)
4985 return error("Invalid record");
4988 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4990 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4991 InstructionList.push_back(I);
4994 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4995 case bitc::FUNC_CODE_INST_CMPXCHG: {
4996 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4997 // failureordering?, isweak?]
4999 Value *Ptr, *Cmp, *New;
5000 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5001 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5002 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5003 : popValue(Record, OpNum, NextValueNo,
5004 cast<PointerType>(Ptr->getType())->getElementType(),
5006 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5007 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
5008 return error("Invalid record");
5009 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
5010 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
5011 return error("Invalid record");
5012 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
5014 if (std::error_code EC = typeCheckLoadStoreInst(
5015 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
5017 AtomicOrdering FailureOrdering;
5018 if (Record.size() < 7)
5020 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5022 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
5024 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5026 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5028 if (Record.size() < 8) {
5029 // Before weak cmpxchgs existed, the instruction simply returned the
5030 // value loaded from memory, so bitcode files from that era will be
5031 // expecting the first component of a modern cmpxchg.
5032 CurBB->getInstList().push_back(I);
5033 I = ExtractValueInst::Create(I, 0);
5035 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5038 InstructionList.push_back(I);
5041 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5042 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5045 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5046 popValue(Record, OpNum, NextValueNo,
5047 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5048 OpNum+4 != Record.size())
5049 return error("Invalid record");
5050 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5051 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5052 Operation > AtomicRMWInst::LAST_BINOP)
5053 return error("Invalid record");
5054 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5055 if (Ordering == NotAtomic || Ordering == Unordered)
5056 return error("Invalid record");
5057 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5058 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5059 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5060 InstructionList.push_back(I);
5063 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5064 if (2 != Record.size())
5065 return error("Invalid record");
5066 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5067 if (Ordering == NotAtomic || Ordering == Unordered ||
5068 Ordering == Monotonic)
5069 return error("Invalid record");
5070 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5071 I = new FenceInst(Context, Ordering, SynchScope);
5072 InstructionList.push_back(I);
5075 case bitc::FUNC_CODE_INST_CALL: {
5076 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
5077 if (Record.size() < 3)
5078 return error("Invalid record");
5081 AttributeSet PAL = getAttributes(Record[OpNum++]);
5082 unsigned CCInfo = Record[OpNum++];
5084 FunctionType *FTy = nullptr;
5085 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5086 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5087 return error("Explicit call type is not a function type");
5090 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5091 return error("Invalid record");
5093 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5095 return error("Callee is not a pointer type");
5097 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5099 return error("Callee is not of pointer to function type");
5100 } else if (OpTy->getElementType() != FTy)
5101 return error("Explicit call type does not match pointee type of "
5103 if (Record.size() < FTy->getNumParams() + OpNum)
5104 return error("Insufficient operands to call");
5106 SmallVector<Value*, 16> Args;
5107 // Read the fixed params.
5108 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5109 if (FTy->getParamType(i)->isLabelTy())
5110 Args.push_back(getBasicBlock(Record[OpNum]));
5112 Args.push_back(getValue(Record, OpNum, NextValueNo,
5113 FTy->getParamType(i)));
5115 return error("Invalid record");
5118 // Read type/value pairs for varargs params.
5119 if (!FTy->isVarArg()) {
5120 if (OpNum != Record.size())
5121 return error("Invalid record");
5123 while (OpNum != Record.size()) {
5125 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5126 return error("Invalid record");
5131 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5132 OperandBundles.clear();
5133 InstructionList.push_back(I);
5134 cast<CallInst>(I)->setCallingConv(
5135 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5136 CallInst::TailCallKind TCK = CallInst::TCK_None;
5137 if (CCInfo & 1 << bitc::CALL_TAIL)
5138 TCK = CallInst::TCK_Tail;
5139 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5140 TCK = CallInst::TCK_MustTail;
5141 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5142 TCK = CallInst::TCK_NoTail;
5143 cast<CallInst>(I)->setTailCallKind(TCK);
5144 cast<CallInst>(I)->setAttributes(PAL);
5147 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5148 if (Record.size() < 3)
5149 return error("Invalid record");
5150 Type *OpTy = getTypeByID(Record[0]);
5151 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5152 Type *ResTy = getTypeByID(Record[2]);
5153 if (!OpTy || !Op || !ResTy)
5154 return error("Invalid record");
5155 I = new VAArgInst(Op, ResTy);
5156 InstructionList.push_back(I);
5160 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5161 // A call or an invoke can be optionally prefixed with some variable
5162 // number of operand bundle blocks. These blocks are read into
5163 // OperandBundles and consumed at the next call or invoke instruction.
5165 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5166 return error("Invalid record");
5168 std::vector<Value *> Inputs;
5171 while (OpNum != Record.size()) {
5173 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5174 return error("Invalid record");
5175 Inputs.push_back(Op);
5178 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5183 // Add instruction to end of current BB. If there is no current BB, reject
5187 return error("Invalid instruction with no BB");
5189 if (!OperandBundles.empty()) {
5191 return error("Operand bundles found with no consumer");
5193 CurBB->getInstList().push_back(I);
5195 // If this was a terminator instruction, move to the next block.
5196 if (isa<TerminatorInst>(I)) {
5198 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5201 // Non-void values get registered in the value table for future use.
5202 if (I && !I->getType()->isVoidTy())
5203 if (ValueList.assignValue(I, NextValueNo++))
5204 return error("Invalid forward reference");
5209 if (!OperandBundles.empty())
5210 return error("Operand bundles found with no consumer");
5212 // Check the function list for unresolved values.
5213 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5214 if (!A->getParent()) {
5215 // We found at least one unresolved value. Nuke them all to avoid leaks.
5216 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5217 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5218 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5222 return error("Never resolved value found in function");
5226 // FIXME: Check for unresolved forward-declared metadata references
5227 // and clean up leaks.
5229 // Trim the value list down to the size it was before we parsed this function.
5230 ValueList.shrinkTo(ModuleValueListSize);
5231 MDValueList.shrinkTo(ModuleMDValueListSize);
5232 std::vector<BasicBlock*>().swap(FunctionBBs);
5233 return std::error_code();
5236 /// Find the function body in the bitcode stream
5237 std::error_code BitcodeReader::findFunctionInStream(
5239 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5240 while (DeferredFunctionInfoIterator->second == 0) {
5241 // This is the fallback handling for the old format bitcode that
5242 // didn't contain the function index in the VST, or when we have
5243 // an anonymous function which would not have a VST entry.
5244 // Assert that we have one of those two cases.
5245 assert(VSTOffset == 0 || !F->hasName());
5246 // Parse the next body in the stream and set its position in the
5247 // DeferredFunctionInfo map.
5248 if (std::error_code EC = rememberAndSkipFunctionBodies())
5251 return std::error_code();
5254 //===----------------------------------------------------------------------===//
5255 // GVMaterializer implementation
5256 //===----------------------------------------------------------------------===//
5258 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5260 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5261 // In older bitcode we must materialize the metadata before parsing
5262 // any functions, in order to set up the MDValueList properly.
5263 if (!SeenModuleValuesRecord) {
5264 if (std::error_code EC = materializeMetadata())
5268 Function *F = dyn_cast<Function>(GV);
5269 // If it's not a function or is already material, ignore the request.
5270 if (!F || !F->isMaterializable())
5271 return std::error_code();
5273 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5274 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5275 // If its position is recorded as 0, its body is somewhere in the stream
5276 // but we haven't seen it yet.
5277 if (DFII->second == 0)
5278 if (std::error_code EC = findFunctionInStream(F, DFII))
5281 // Move the bit stream to the saved position of the deferred function body.
5282 Stream.JumpToBit(DFII->second);
5284 if (std::error_code EC = parseFunctionBody(F))
5286 F->setIsMaterializable(false);
5291 // Upgrade any old intrinsic calls in the function.
5292 for (auto &I : UpgradedIntrinsics) {
5293 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5296 if (CallInst *CI = dyn_cast<CallInst>(U))
5297 UpgradeIntrinsicCall(CI, I.second);
5301 // Finish fn->subprogram upgrade for materialized functions.
5302 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5303 F->setSubprogram(SP);
5305 // Bring in any functions that this function forward-referenced via
5307 return materializeForwardReferencedFunctions();
5310 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5311 const Function *F = dyn_cast<Function>(GV);
5312 if (!F || F->isDeclaration())
5315 // Dematerializing F would leave dangling references that wouldn't be
5316 // reconnected on re-materialization.
5317 if (BlockAddressesTaken.count(F))
5320 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5323 void BitcodeReader::dematerialize(GlobalValue *GV) {
5324 Function *F = dyn_cast<Function>(GV);
5325 // If this function isn't dematerializable, this is a noop.
5326 if (!F || !isDematerializable(F))
5329 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5331 // Just forget the function body, we can remat it later.
5332 F->dropAllReferences();
5333 F->setIsMaterializable(true);
5336 std::error_code BitcodeReader::materializeModule(Module *M) {
5337 assert(M == TheModule &&
5338 "Can only Materialize the Module this BitcodeReader is attached to.");
5340 if (std::error_code EC = materializeMetadata())
5343 // Promise to materialize all forward references.
5344 WillMaterializeAllForwardRefs = true;
5346 // Iterate over the module, deserializing any functions that are still on
5348 for (Function &F : *TheModule) {
5349 if (std::error_code EC = materialize(&F))
5352 // At this point, if there are any function bodies, parse the rest of
5353 // the bits in the module past the last function block we have recorded
5354 // through either lazy scanning or the VST.
5355 if (LastFunctionBlockBit || NextUnreadBit)
5356 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5359 // Check that all block address forward references got resolved (as we
5361 if (!BasicBlockFwdRefs.empty())
5362 return error("Never resolved function from blockaddress");
5364 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5365 // delete the old functions to clean up. We can't do this unless the entire
5366 // module is materialized because there could always be another function body
5367 // with calls to the old function.
5368 for (auto &I : UpgradedIntrinsics) {
5369 for (auto *U : I.first->users()) {
5370 if (CallInst *CI = dyn_cast<CallInst>(U))
5371 UpgradeIntrinsicCall(CI, I.second);
5373 if (!I.first->use_empty())
5374 I.first->replaceAllUsesWith(I.second);
5375 I.first->eraseFromParent();
5377 UpgradedIntrinsics.clear();
5379 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5380 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5382 UpgradeDebugInfo(*M);
5383 return std::error_code();
5386 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5387 return IdentifiedStructTypes;
5391 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5393 return initLazyStream(std::move(Streamer));
5394 return initStreamFromBuffer();
5397 std::error_code BitcodeReader::initStreamFromBuffer() {
5398 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5399 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5401 if (Buffer->getBufferSize() & 3)
5402 return error("Invalid bitcode signature");
5404 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5405 // The magic number is 0x0B17C0DE stored in little endian.
5406 if (isBitcodeWrapper(BufPtr, BufEnd))
5407 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5408 return error("Invalid bitcode wrapper header");
5410 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5411 Stream.init(&*StreamFile);
5413 return std::error_code();
5417 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5418 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5421 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5422 StreamingMemoryObject &Bytes = *OwnedBytes;
5423 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5424 Stream.init(&*StreamFile);
5426 unsigned char buf[16];
5427 if (Bytes.readBytes(buf, 16, 0) != 16)
5428 return error("Invalid bitcode signature");
5430 if (!isBitcode(buf, buf + 16))
5431 return error("Invalid bitcode signature");
5433 if (isBitcodeWrapper(buf, buf + 4)) {
5434 const unsigned char *bitcodeStart = buf;
5435 const unsigned char *bitcodeEnd = buf + 16;
5436 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5437 Bytes.dropLeadingBytes(bitcodeStart - buf);
5438 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5440 return std::error_code();
5443 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5444 const Twine &Message) {
5445 return ::error(DiagnosticHandler, make_error_code(E), Message);
5448 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5449 return ::error(DiagnosticHandler,
5450 make_error_code(BitcodeError::CorruptedBitcode), Message);
5453 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5454 return ::error(DiagnosticHandler, make_error_code(E));
5457 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5458 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5459 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5460 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
5461 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5463 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5464 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5465 bool CheckFuncSummaryPresenceOnly)
5466 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
5467 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5469 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5471 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5473 // Specialized value symbol table parser used when reading function index
5474 // blocks where we don't actually create global values.
5475 // At the end of this routine the function index is populated with a map
5476 // from function name to FunctionInfo. The function info contains
5477 // the function block's bitcode offset as well as the offset into the
5478 // function summary section.
5479 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5480 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5481 return error("Invalid record");
5483 SmallVector<uint64_t, 64> Record;
5485 // Read all the records for this value table.
5486 SmallString<128> ValueName;
5488 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5490 switch (Entry.Kind) {
5491 case BitstreamEntry::SubBlock: // Handled for us already.
5492 case BitstreamEntry::Error:
5493 return error("Malformed block");
5494 case BitstreamEntry::EndBlock:
5495 return std::error_code();
5496 case BitstreamEntry::Record:
5497 // The interesting case.
5503 switch (Stream.readRecord(Entry.ID, Record)) {
5504 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5506 case bitc::VST_CODE_FNENTRY: {
5507 // VST_FNENTRY: [valueid, offset, namechar x N]
5508 if (convertToString(Record, 2, ValueName))
5509 return error("Invalid record");
5510 unsigned ValueID = Record[0];
5511 uint64_t FuncOffset = Record[1];
5512 std::unique_ptr<FunctionInfo> FuncInfo =
5513 llvm::make_unique<FunctionInfo>(FuncOffset);
5514 if (foundFuncSummary() && !IsLazy) {
5515 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5516 SummaryMap.find(ValueID);
5517 assert(SMI != SummaryMap.end() && "Summary info not found");
5518 FuncInfo->setFunctionSummary(std::move(SMI->second));
5520 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5525 case bitc::VST_CODE_COMBINED_FNENTRY: {
5526 // VST_FNENTRY: [offset, namechar x N]
5527 if (convertToString(Record, 1, ValueName))
5528 return error("Invalid record");
5529 uint64_t FuncSummaryOffset = Record[0];
5530 std::unique_ptr<FunctionInfo> FuncInfo =
5531 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5532 if (foundFuncSummary() && !IsLazy) {
5533 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5534 SummaryMap.find(FuncSummaryOffset);
5535 assert(SMI != SummaryMap.end() && "Summary info not found");
5536 FuncInfo->setFunctionSummary(std::move(SMI->second));
5538 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5547 // Parse just the blocks needed for function index building out of the module.
5548 // At the end of this routine the function Index is populated with a map
5549 // from function name to FunctionInfo. The function info contains
5550 // either the parsed function summary information (when parsing summaries
5551 // eagerly), or just to the function summary record's offset
5552 // if parsing lazily (IsLazy).
5553 std::error_code FunctionIndexBitcodeReader::parseModule() {
5554 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5555 return error("Invalid record");
5557 // Read the function index for this module.
5559 BitstreamEntry Entry = Stream.advance();
5561 switch (Entry.Kind) {
5562 case BitstreamEntry::Error:
5563 return error("Malformed block");
5564 case BitstreamEntry::EndBlock:
5565 return std::error_code();
5567 case BitstreamEntry::SubBlock:
5568 if (CheckFuncSummaryPresenceOnly) {
5569 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5570 SeenFuncSummary = true;
5571 if (Stream.SkipBlock())
5572 return error("Invalid record");
5573 // No need to parse the rest since we found the summary.
5574 return std::error_code();
5577 default: // Skip unknown content.
5578 if (Stream.SkipBlock())
5579 return error("Invalid record");
5581 case bitc::BLOCKINFO_BLOCK_ID:
5582 // Need to parse these to get abbrev ids (e.g. for VST)
5583 if (Stream.ReadBlockInfoBlock())
5584 return error("Malformed block");
5586 case bitc::VALUE_SYMTAB_BLOCK_ID:
5587 if (std::error_code EC = parseValueSymbolTable())
5590 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5591 SeenFuncSummary = true;
5593 // Lazy parsing of summary info, skip it.
5594 if (Stream.SkipBlock())
5595 return error("Invalid record");
5596 } else if (std::error_code EC = parseEntireSummary())
5599 case bitc::MODULE_STRTAB_BLOCK_ID:
5600 if (std::error_code EC = parseModuleStringTable())
5606 case BitstreamEntry::Record:
5607 Stream.skipRecord(Entry.ID);
5613 // Eagerly parse the entire function summary block (i.e. for all functions
5614 // in the index). This populates the FunctionSummary objects in
5616 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5617 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5618 return error("Invalid record");
5620 SmallVector<uint64_t, 64> Record;
5623 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5625 switch (Entry.Kind) {
5626 case BitstreamEntry::SubBlock: // Handled for us already.
5627 case BitstreamEntry::Error:
5628 return error("Malformed block");
5629 case BitstreamEntry::EndBlock:
5630 return std::error_code();
5631 case BitstreamEntry::Record:
5632 // The interesting case.
5636 // Read a record. The record format depends on whether this
5637 // is a per-module index or a combined index file. In the per-module
5638 // case the records contain the associated value's ID for correlation
5639 // with VST entries. In the combined index the correlation is done
5640 // via the bitcode offset of the summary records (which were saved
5641 // in the combined index VST entries). The records also contain
5642 // information used for ThinLTO renaming and importing.
5644 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5645 switch (Stream.readRecord(Entry.ID, Record)) {
5646 default: // Default behavior: ignore.
5648 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5649 case bitc::FS_CODE_PERMODULE_ENTRY: {
5650 unsigned ValueID = Record[0];
5651 bool IsLocal = Record[1];
5652 unsigned InstCount = Record[2];
5653 std::unique_ptr<FunctionSummary> FS =
5654 llvm::make_unique<FunctionSummary>(InstCount);
5655 FS->setLocalFunction(IsLocal);
5656 // The module path string ref set in the summary must be owned by the
5657 // index's module string table. Since we don't have a module path
5658 // string table section in the per-module index, we create a single
5659 // module path string table entry with an empty (0) ID to take
5662 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5663 SummaryMap[ValueID] = std::move(FS);
5665 // FS_COMBINED_ENTRY: [modid, instcount]
5666 case bitc::FS_CODE_COMBINED_ENTRY: {
5667 uint64_t ModuleId = Record[0];
5668 unsigned InstCount = Record[1];
5669 std::unique_ptr<FunctionSummary> FS =
5670 llvm::make_unique<FunctionSummary>(InstCount);
5671 FS->setModulePath(ModuleIdMap[ModuleId]);
5672 SummaryMap[CurRecordBit] = std::move(FS);
5676 llvm_unreachable("Exit infinite loop");
5679 // Parse the module string table block into the Index.
5680 // This populates the ModulePathStringTable map in the index.
5681 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5682 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5683 return error("Invalid record");
5685 SmallVector<uint64_t, 64> Record;
5687 SmallString<128> ModulePath;
5689 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5691 switch (Entry.Kind) {
5692 case BitstreamEntry::SubBlock: // Handled for us already.
5693 case BitstreamEntry::Error:
5694 return error("Malformed block");
5695 case BitstreamEntry::EndBlock:
5696 return std::error_code();
5697 case BitstreamEntry::Record:
5698 // The interesting case.
5703 switch (Stream.readRecord(Entry.ID, Record)) {
5704 default: // Default behavior: ignore.
5706 case bitc::MST_CODE_ENTRY: {
5707 // MST_ENTRY: [modid, namechar x N]
5708 if (convertToString(Record, 1, ModulePath))
5709 return error("Invalid record");
5710 uint64_t ModuleId = Record[0];
5711 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5712 ModuleIdMap[ModuleId] = ModulePathInMap;
5718 llvm_unreachable("Exit infinite loop");
5721 // Parse the function info index from the bitcode streamer into the given index.
5722 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5723 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5726 if (std::error_code EC = initStream(std::move(Streamer)))
5729 // Sniff for the signature.
5730 if (!hasValidBitcodeHeader(Stream))
5731 return error("Invalid bitcode signature");
5733 // We expect a number of well-defined blocks, though we don't necessarily
5734 // need to understand them all.
5736 if (Stream.AtEndOfStream()) {
5737 // We didn't really read a proper Module block.
5738 return error("Malformed block");
5741 BitstreamEntry Entry =
5742 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5744 if (Entry.Kind != BitstreamEntry::SubBlock)
5745 return error("Malformed block");
5747 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5748 // building the function summary index.
5749 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5750 return parseModule();
5752 if (Stream.SkipBlock())
5753 return error("Invalid record");
5757 // Parse the function information at the given offset in the buffer into
5758 // the index. Used to support lazy parsing of function summaries from the
5759 // combined index during importing.
5760 // TODO: This function is not yet complete as it won't have a consumer
5761 // until ThinLTO function importing is added.
5762 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5763 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5764 size_t FunctionSummaryOffset) {
5767 if (std::error_code EC = initStream(std::move(Streamer)))
5770 // Sniff for the signature.
5771 if (!hasValidBitcodeHeader(Stream))
5772 return error("Invalid bitcode signature");
5774 Stream.JumpToBit(FunctionSummaryOffset);
5776 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5778 switch (Entry.Kind) {
5780 return error("Malformed block");
5781 case BitstreamEntry::Record:
5782 // The expected case.
5786 // TODO: Read a record. This interface will be completed when ThinLTO
5787 // importing is added so that it can be tested.
5788 SmallVector<uint64_t, 64> Record;
5789 switch (Stream.readRecord(Entry.ID, Record)) {
5790 case bitc::FS_CODE_COMBINED_ENTRY:
5792 return error("Invalid record");
5795 return std::error_code();
5799 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5801 return initLazyStream(std::move(Streamer));
5802 return initStreamFromBuffer();
5805 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5806 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5807 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5809 if (Buffer->getBufferSize() & 3)
5810 return error("Invalid bitcode signature");
5812 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5813 // The magic number is 0x0B17C0DE stored in little endian.
5814 if (isBitcodeWrapper(BufPtr, BufEnd))
5815 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5816 return error("Invalid bitcode wrapper header");
5818 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5819 Stream.init(&*StreamFile);
5821 return std::error_code();
5824 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5825 std::unique_ptr<DataStreamer> Streamer) {
5826 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5829 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5830 StreamingMemoryObject &Bytes = *OwnedBytes;
5831 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5832 Stream.init(&*StreamFile);
5834 unsigned char buf[16];
5835 if (Bytes.readBytes(buf, 16, 0) != 16)
5836 return error("Invalid bitcode signature");
5838 if (!isBitcode(buf, buf + 16))
5839 return error("Invalid bitcode signature");
5841 if (isBitcodeWrapper(buf, buf + 4)) {
5842 const unsigned char *bitcodeStart = buf;
5843 const unsigned char *bitcodeEnd = buf + 16;
5844 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5845 Bytes.dropLeadingBytes(bitcodeStart - buf);
5846 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5848 return std::error_code();
5852 class BitcodeErrorCategoryType : public std::error_category {
5853 const char *name() const LLVM_NOEXCEPT override {
5854 return "llvm.bitcode";
5856 std::string message(int IE) const override {
5857 BitcodeError E = static_cast<BitcodeError>(IE);
5859 case BitcodeError::InvalidBitcodeSignature:
5860 return "Invalid bitcode signature";
5861 case BitcodeError::CorruptedBitcode:
5862 return "Corrupted bitcode";
5864 llvm_unreachable("Unknown error type!");
5869 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5871 const std::error_category &llvm::BitcodeErrorCategory() {
5872 return *ErrorCategory;
5875 //===----------------------------------------------------------------------===//
5876 // External interface
5877 //===----------------------------------------------------------------------===//
5879 static ErrorOr<std::unique_ptr<Module>>
5880 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5881 BitcodeReader *R, LLVMContext &Context,
5882 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5883 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5884 M->setMaterializer(R);
5886 auto cleanupOnError = [&](std::error_code EC) {
5887 R->releaseBuffer(); // Never take ownership on error.
5891 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5892 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5893 ShouldLazyLoadMetadata))
5894 return cleanupOnError(EC);
5896 if (MaterializeAll) {
5897 // Read in the entire module, and destroy the BitcodeReader.
5898 if (std::error_code EC = M->materializeAllPermanently())
5899 return cleanupOnError(EC);
5901 // Resolve forward references from blockaddresses.
5902 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5903 return cleanupOnError(EC);
5905 return std::move(M);
5908 /// \brief Get a lazy one-at-time loading module from bitcode.
5910 /// This isn't always used in a lazy context. In particular, it's also used by
5911 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5912 /// in forward-referenced functions from block address references.
5914 /// \param[in] MaterializeAll Set to \c true if we should materialize
5916 static ErrorOr<std::unique_ptr<Module>>
5917 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5918 LLVMContext &Context, bool MaterializeAll,
5919 DiagnosticHandlerFunction DiagnosticHandler,
5920 bool ShouldLazyLoadMetadata = false) {
5922 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5924 ErrorOr<std::unique_ptr<Module>> Ret =
5925 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5926 MaterializeAll, ShouldLazyLoadMetadata);
5930 Buffer.release(); // The BitcodeReader owns it now.
5934 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5935 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5936 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5937 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5938 DiagnosticHandler, ShouldLazyLoadMetadata);
5941 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5942 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5943 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5944 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5945 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5947 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5951 ErrorOr<std::unique_ptr<Module>>
5952 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5953 DiagnosticHandlerFunction DiagnosticHandler) {
5954 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5955 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5957 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5958 // written. We must defer until the Module has been fully materialized.
5962 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5963 DiagnosticHandlerFunction DiagnosticHandler) {
5964 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5965 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5967 ErrorOr<std::string> Triple = R->parseTriple();
5968 if (Triple.getError())
5970 return Triple.get();
5974 llvm::getBitcodeProducerString(MemoryBufferRef Buffer, LLVMContext &Context,
5975 DiagnosticHandlerFunction DiagnosticHandler) {
5976 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5977 BitcodeReader R(Buf.release(), Context, DiagnosticHandler);
5978 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5979 if (ProducerString.getError())
5981 return ProducerString.get();
5984 // Parse the specified bitcode buffer, returning the function info index.
5985 // If IsLazy is false, parse the entire function summary into
5986 // the index. Otherwise skip the function summary section, and only create
5987 // an index object with a map from function name to function summary offset.
5988 // The index is used to perform lazy function summary reading later.
5989 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5990 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer,
5991 DiagnosticHandlerFunction DiagnosticHandler,
5992 const Module *ExportingModule, bool IsLazy) {
5993 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5994 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
5996 std::unique_ptr<FunctionInfoIndex> Index =
5997 llvm::make_unique<FunctionInfoIndex>(ExportingModule);
5999 auto cleanupOnError = [&](std::error_code EC) {
6000 R.releaseBuffer(); // Never take ownership on error.
6004 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6005 return cleanupOnError(EC);
6007 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
6008 return std::move(Index);
6011 // Check if the given bitcode buffer contains a function summary block.
6012 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer,
6013 DiagnosticHandlerFunction DiagnosticHandler) {
6014 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6015 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
6017 auto cleanupOnError = [&](std::error_code EC) {
6018 R.releaseBuffer(); // Never take ownership on error.
6022 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6023 return cleanupOnError(EC);
6025 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
6026 return R.foundFuncSummary();
6029 // This method supports lazy reading of function summary data from the combined
6030 // index during ThinLTO function importing. When reading the combined index
6031 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
6032 // Then this method is called for each function considered for importing,
6033 // to parse the summary information for the given function name into
6035 std::error_code llvm::readFunctionSummary(
6036 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
6037 StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) {
6038 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6039 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
6041 auto cleanupOnError = [&](std::error_code EC) {
6042 R.releaseBuffer(); // Never take ownership on error.
6046 // Lookup the given function name in the FunctionMap, which may
6047 // contain a list of function infos in the case of a COMDAT. Walk through
6048 // and parse each function summary info at the function summary offset
6049 // recorded when parsing the value symbol table.
6050 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
6051 size_t FunctionSummaryOffset = FI->bitcodeIndex();
6052 if (std::error_code EC =
6053 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
6054 return cleanupOnError(EC);
6057 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
6058 return std::error_code();