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/BitcodeReader.h"
11 #include "MetadataLoader.h"
12 #include "ValueList.h"
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Bitcode/BitstreamReader.h"
25 #include "llvm/Bitcode/LLVMBitCodes.h"
26 #include "llvm/IR/Argument.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/AutoUpgrade.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Comdat.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DebugInfo.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GVMaterializer.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalIFunc.h"
44 #include "llvm/IR/GlobalIndirectSymbol.h"
45 #include "llvm/IR/GlobalObject.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/InlineAsm.h"
49 #include "llvm/IR/InstIterator.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/IR/ModuleSummaryIndex.h"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/IR/Type.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/IR/Verifier.h"
62 #include "llvm/Support/AtomicOrdering.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Compiler.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/Error.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/ErrorOr.h"
70 #include "llvm/Support/ManagedStatic.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/MemoryBuffer.h"
73 #include "llvm/Support/raw_ostream.h"
83 #include <system_error>
90 static cl::opt<bool> PrintSummaryGUIDs(
91 "print-summary-global-ids", cl::init(false), cl::Hidden,
93 "Print the global id for each value when reading the module summary"));
98 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
101 } // end anonymous namespace
103 static Error error(const Twine &Message) {
104 return make_error<StringError>(
105 Message, make_error_code(BitcodeError::CorruptedBitcode));
108 /// Helper to read the header common to all bitcode files.
109 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
110 // Sniff for the signature.
111 if (!Stream.canSkipToPos(4) ||
112 Stream.Read(8) != 'B' ||
113 Stream.Read(8) != 'C' ||
114 Stream.Read(4) != 0x0 ||
115 Stream.Read(4) != 0xC ||
116 Stream.Read(4) != 0xE ||
117 Stream.Read(4) != 0xD)
122 static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
123 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
124 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
126 if (Buffer.getBufferSize() & 3)
127 return error("Invalid bitcode signature");
129 // If we have a wrapper header, parse it and ignore the non-bc file contents.
130 // The magic number is 0x0B17C0DE stored in little endian.
131 if (isBitcodeWrapper(BufPtr, BufEnd))
132 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
133 return error("Invalid bitcode wrapper header");
135 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
136 if (!hasValidBitcodeHeader(Stream))
137 return error("Invalid bitcode signature");
139 return std::move(Stream);
142 /// Convert a string from a record into an std::string, return true on failure.
143 template <typename StrTy>
144 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
146 if (Idx > Record.size())
149 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
150 Result += (char)Record[i];
154 // Strip all the TBAA attachment for the module.
155 static void stripTBAA(Module *M) {
157 if (F.isMaterializable())
159 for (auto &I : instructions(F))
160 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
164 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
165 /// "epoch" encoded in the bitcode, and return the producer name if any.
166 static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
167 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
168 return error("Invalid record");
170 // Read all the records.
171 SmallVector<uint64_t, 64> Record;
173 std::string ProducerIdentification;
176 BitstreamEntry Entry = Stream.advance();
178 switch (Entry.Kind) {
180 case BitstreamEntry::Error:
181 return error("Malformed block");
182 case BitstreamEntry::EndBlock:
183 return ProducerIdentification;
184 case BitstreamEntry::Record:
185 // The interesting case.
191 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
193 default: // Default behavior: reject
194 return error("Invalid value");
195 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
196 convertToString(Record, 0, ProducerIdentification);
198 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
199 unsigned epoch = (unsigned)Record[0];
200 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
202 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
203 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
210 static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
211 // We expect a number of well-defined blocks, though we don't necessarily
212 // need to understand them all.
214 if (Stream.AtEndOfStream())
217 BitstreamEntry Entry = Stream.advance();
218 switch (Entry.Kind) {
219 case BitstreamEntry::EndBlock:
220 case BitstreamEntry::Error:
221 return error("Malformed block");
223 case BitstreamEntry::SubBlock:
224 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
225 return readIdentificationBlock(Stream);
227 // Ignore other sub-blocks.
228 if (Stream.SkipBlock())
229 return error("Malformed block");
231 case BitstreamEntry::Record:
232 Stream.skipRecord(Entry.ID);
238 static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
239 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
240 return error("Invalid record");
242 SmallVector<uint64_t, 64> Record;
243 // Read all the records for this module.
246 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
248 switch (Entry.Kind) {
249 case BitstreamEntry::SubBlock: // Handled for us already.
250 case BitstreamEntry::Error:
251 return error("Malformed block");
252 case BitstreamEntry::EndBlock:
254 case BitstreamEntry::Record:
255 // The interesting case.
260 switch (Stream.readRecord(Entry.ID, Record)) {
262 break; // Default behavior, ignore unknown content.
263 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
265 if (convertToString(Record, 0, S))
266 return error("Invalid record");
267 // Check for the i386 and other (x86_64, ARM) conventions
268 if (S.find("__DATA,__objc_catlist") != std::string::npos ||
269 S.find("__OBJC,__category") != std::string::npos)
276 llvm_unreachable("Exit infinite loop");
279 static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
280 // We expect a number of well-defined blocks, though we don't necessarily
281 // need to understand them all.
283 BitstreamEntry Entry = Stream.advance();
285 switch (Entry.Kind) {
286 case BitstreamEntry::Error:
287 return error("Malformed block");
288 case BitstreamEntry::EndBlock:
291 case BitstreamEntry::SubBlock:
292 if (Entry.ID == bitc::MODULE_BLOCK_ID)
293 return hasObjCCategoryInModule(Stream);
295 // Ignore other sub-blocks.
296 if (Stream.SkipBlock())
297 return error("Malformed block");
300 case BitstreamEntry::Record:
301 Stream.skipRecord(Entry.ID);
307 static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
308 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
309 return error("Invalid record");
311 SmallVector<uint64_t, 64> Record;
315 // Read all the records for this module.
317 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
319 switch (Entry.Kind) {
320 case BitstreamEntry::SubBlock: // Handled for us already.
321 case BitstreamEntry::Error:
322 return error("Malformed block");
323 case BitstreamEntry::EndBlock:
325 case BitstreamEntry::Record:
326 // The interesting case.
331 switch (Stream.readRecord(Entry.ID, Record)) {
332 default: break; // Default behavior, ignore unknown content.
333 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
335 if (convertToString(Record, 0, S))
336 return error("Invalid record");
343 llvm_unreachable("Exit infinite loop");
346 static Expected<std::string> readTriple(BitstreamCursor &Stream) {
347 // We expect a number of well-defined blocks, though we don't necessarily
348 // need to understand them all.
350 BitstreamEntry Entry = Stream.advance();
352 switch (Entry.Kind) {
353 case BitstreamEntry::Error:
354 return error("Malformed block");
355 case BitstreamEntry::EndBlock:
358 case BitstreamEntry::SubBlock:
359 if (Entry.ID == bitc::MODULE_BLOCK_ID)
360 return readModuleTriple(Stream);
362 // Ignore other sub-blocks.
363 if (Stream.SkipBlock())
364 return error("Malformed block");
367 case BitstreamEntry::Record:
368 Stream.skipRecord(Entry.ID);
376 class BitcodeReaderBase {
378 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
379 : Stream(std::move(Stream)), Strtab(Strtab) {
380 this->Stream.setBlockInfo(&BlockInfo);
383 BitstreamBlockInfo BlockInfo;
384 BitstreamCursor Stream;
387 /// In version 2 of the bitcode we store names of global values and comdats in
388 /// a string table rather than in the VST.
389 bool UseStrtab = false;
391 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
393 /// If this module uses a string table, pop the reference to the string table
394 /// and return the referenced string and the rest of the record. Otherwise
395 /// just return the record itself.
396 std::pair<StringRef, ArrayRef<uint64_t>>
397 readNameFromStrtab(ArrayRef<uint64_t> Record);
399 bool readBlockInfo();
401 // Contains an arbitrary and optional string identifying the bitcode producer
402 std::string ProducerIdentification;
404 Error error(const Twine &Message);
407 } // end anonymous namespace
409 Error BitcodeReaderBase::error(const Twine &Message) {
410 std::string FullMsg = Message.str();
411 if (!ProducerIdentification.empty())
412 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
413 LLVM_VERSION_STRING "')";
414 return ::error(FullMsg);
418 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
420 return error("Invalid record");
421 unsigned ModuleVersion = Record[0];
422 if (ModuleVersion > 2)
423 return error("Invalid value");
424 UseStrtab = ModuleVersion >= 2;
425 return ModuleVersion;
428 std::pair<StringRef, ArrayRef<uint64_t>>
429 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
432 // Invalid reference. Let the caller complain about the record being empty.
433 if (Record[0] + Record[1] > Strtab.size())
435 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
440 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
441 LLVMContext &Context;
442 Module *TheModule = nullptr;
443 // Next offset to start scanning for lazy parsing of function bodies.
444 uint64_t NextUnreadBit = 0;
445 // Last function offset found in the VST.
446 uint64_t LastFunctionBlockBit = 0;
447 bool SeenValueSymbolTable = false;
448 uint64_t VSTOffset = 0;
450 std::vector<std::string> SectionTable;
451 std::vector<std::string> GCTable;
453 std::vector<Type*> TypeList;
454 BitcodeReaderValueList ValueList;
455 Optional<MetadataLoader> MDLoader;
456 std::vector<Comdat *> ComdatList;
457 SmallVector<Instruction *, 64> InstructionList;
459 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
460 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
461 std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
462 std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
463 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
465 /// The set of attributes by index. Index zero in the file is for null, and
466 /// is thus not represented here. As such all indices are off by one.
467 std::vector<AttributeList> MAttributes;
469 /// The set of attribute groups.
470 std::map<unsigned, AttributeList> MAttributeGroups;
472 /// While parsing a function body, this is a list of the basic blocks for the
474 std::vector<BasicBlock*> FunctionBBs;
476 // When reading the module header, this list is populated with functions that
477 // have bodies later in the file.
478 std::vector<Function*> FunctionsWithBodies;
480 // When intrinsic functions are encountered which require upgrading they are
481 // stored here with their replacement function.
482 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
483 UpdatedIntrinsicMap UpgradedIntrinsics;
484 // Intrinsics which were remangled because of types rename
485 UpdatedIntrinsicMap RemangledIntrinsics;
487 // Several operations happen after the module header has been read, but
488 // before function bodies are processed. This keeps track of whether
489 // we've done this yet.
490 bool SeenFirstFunctionBody = false;
492 /// When function bodies are initially scanned, this map contains info about
493 /// where to find deferred function body in the stream.
494 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
496 /// When Metadata block is initially scanned when parsing the module, we may
497 /// choose to defer parsing of the metadata. This vector contains info about
498 /// which Metadata blocks are deferred.
499 std::vector<uint64_t> DeferredMetadataInfo;
501 /// These are basic blocks forward-referenced by block addresses. They are
502 /// inserted lazily into functions when they're loaded. The basic block ID is
503 /// its index into the vector.
504 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
505 std::deque<Function *> BasicBlockFwdRefQueue;
507 /// Indicates that we are using a new encoding for instruction operands where
508 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
509 /// instruction number, for a more compact encoding. Some instruction
510 /// operands are not relative to the instruction ID: basic block numbers, and
511 /// types. Once the old style function blocks have been phased out, we would
512 /// not need this flag.
513 bool UseRelativeIDs = false;
515 /// True if all functions will be materialized, negating the need to process
516 /// (e.g.) blockaddress forward references.
517 bool WillMaterializeAllForwardRefs = false;
519 bool StripDebugInfo = false;
520 TBAAVerifier TBAAVerifyHelper;
522 std::vector<std::string> BundleTags;
523 SmallVector<SyncScope::ID, 8> SSIDs;
526 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
527 StringRef ProducerIdentification, LLVMContext &Context);
529 Error materializeForwardReferencedFunctions();
531 Error materialize(GlobalValue *GV) override;
532 Error materializeModule() override;
533 std::vector<StructType *> getIdentifiedStructTypes() const override;
535 /// \brief Main interface to parsing a bitcode buffer.
536 /// \returns true if an error occurred.
537 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
538 bool IsImporting = false);
540 static uint64_t decodeSignRotatedValue(uint64_t V);
542 /// Materialize any deferred Metadata block.
543 Error materializeMetadata() override;
545 void setStripDebugInfo() override;
548 std::vector<StructType *> IdentifiedStructTypes;
549 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
550 StructType *createIdentifiedStructType(LLVMContext &Context);
552 Type *getTypeByID(unsigned ID);
554 Value *getFnValueByID(unsigned ID, Type *Ty) {
555 if (Ty && Ty->isMetadataTy())
556 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
557 return ValueList.getValueFwdRef(ID, Ty);
560 Metadata *getFnMetadataByID(unsigned ID) {
561 return MDLoader->getMetadataFwdRefOrLoad(ID);
564 BasicBlock *getBasicBlock(unsigned ID) const {
565 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
566 return FunctionBBs[ID];
569 AttributeList getAttributes(unsigned i) const {
570 if (i-1 < MAttributes.size())
571 return MAttributes[i-1];
572 return AttributeList();
575 /// Read a value/type pair out of the specified record from slot 'Slot'.
576 /// Increment Slot past the number of slots used in the record. Return true on
578 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
579 unsigned InstNum, Value *&ResVal) {
580 if (Slot == Record.size()) return true;
581 unsigned ValNo = (unsigned)Record[Slot++];
582 // Adjust the ValNo, if it was encoded relative to the InstNum.
584 ValNo = InstNum - ValNo;
585 if (ValNo < InstNum) {
586 // If this is not a forward reference, just return the value we already
588 ResVal = getFnValueByID(ValNo, nullptr);
589 return ResVal == nullptr;
591 if (Slot == Record.size())
594 unsigned TypeNo = (unsigned)Record[Slot++];
595 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
596 return ResVal == nullptr;
599 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
600 /// past the number of slots used by the value in the record. Return true if
601 /// there is an error.
602 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
603 unsigned InstNum, Type *Ty, Value *&ResVal) {
604 if (getValue(Record, Slot, InstNum, Ty, ResVal))
606 // All values currently take a single record slot.
611 /// Like popValue, but does not increment the Slot number.
612 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
613 unsigned InstNum, Type *Ty, Value *&ResVal) {
614 ResVal = getValue(Record, Slot, InstNum, Ty);
615 return ResVal == nullptr;
618 /// Version of getValue that returns ResVal directly, or 0 if there is an
620 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
621 unsigned InstNum, Type *Ty) {
622 if (Slot == Record.size()) return nullptr;
623 unsigned ValNo = (unsigned)Record[Slot];
624 // Adjust the ValNo, if it was encoded relative to the InstNum.
626 ValNo = InstNum - ValNo;
627 return getFnValueByID(ValNo, Ty);
630 /// Like getValue, but decodes signed VBRs.
631 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
632 unsigned InstNum, Type *Ty) {
633 if (Slot == Record.size()) return nullptr;
634 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
635 // Adjust the ValNo, if it was encoded relative to the InstNum.
637 ValNo = InstNum - ValNo;
638 return getFnValueByID(ValNo, Ty);
641 /// Converts alignment exponent (i.e. power of two (or zero)) to the
642 /// corresponding alignment to use. If alignment is too large, returns
643 /// a corresponding error code.
644 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
645 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
646 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
648 Error parseComdatRecord(ArrayRef<uint64_t> Record);
649 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
650 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
651 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
652 ArrayRef<uint64_t> Record);
654 Error parseAttributeBlock();
655 Error parseAttributeGroupBlock();
656 Error parseTypeTable();
657 Error parseTypeTableBody();
658 Error parseOperandBundleTags();
659 Error parseSyncScopeNames();
661 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
662 unsigned NameIndex, Triple &TT);
663 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
664 ArrayRef<uint64_t> Record);
665 Error parseValueSymbolTable(uint64_t Offset = 0);
666 Error parseGlobalValueSymbolTable();
667 Error parseConstants();
668 Error rememberAndSkipFunctionBodies();
669 Error rememberAndSkipFunctionBody();
670 /// Save the positions of the Metadata blocks and skip parsing the blocks.
671 Error rememberAndSkipMetadata();
672 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
673 Error parseFunctionBody(Function *F);
674 Error globalCleanup();
675 Error resolveGlobalAndIndirectSymbolInits();
676 Error parseUseLists();
677 Error findFunctionInStream(
679 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
681 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
684 /// Class to manage reading and parsing function summary index bitcode
686 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
687 /// The module index built during parsing.
688 ModuleSummaryIndex &TheIndex;
690 /// Indicates whether we have encountered a global value summary section
691 /// yet during parsing.
692 bool SeenGlobalValSummary = false;
694 /// Indicates whether we have already parsed the VST, used for error checking.
695 bool SeenValueSymbolTable = false;
697 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
698 /// Used to enable on-demand parsing of the VST.
699 uint64_t VSTOffset = 0;
701 // Map to save ValueId to ValueInfo association that was recorded in the
702 // ValueSymbolTable. It is used after the VST is parsed to convert
703 // call graph edges read from the function summary from referencing
704 // callees by their ValueId to using the ValueInfo instead, which is how
705 // they are recorded in the summary index being built.
706 // We save a GUID which refers to the same global as the ValueInfo, but
707 // ignoring the linkage, i.e. for values other than local linkage they are
709 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
710 ValueIdToValueInfoMap;
712 /// Map populated during module path string table parsing, from the
713 /// module ID to a string reference owned by the index's module
714 /// path string table, used to correlate with combined index
716 DenseMap<uint64_t, StringRef> ModuleIdMap;
718 /// Original source file name recorded in a bitcode record.
719 std::string SourceFileName;
721 /// The string identifier given to this module by the client, normally the
722 /// path to the bitcode file.
723 StringRef ModulePath;
725 /// For per-module summary indexes, the unique numerical identifier given to
726 /// this module by the client.
730 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
731 ModuleSummaryIndex &TheIndex,
732 StringRef ModulePath, unsigned ModuleId);
737 void setValueGUID(uint64_t ValueID, StringRef ValueName,
738 GlobalValue::LinkageTypes Linkage,
739 StringRef SourceFileName);
740 Error parseValueSymbolTable(
742 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
743 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
744 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
745 bool IsOldProfileFormat,
747 Error parseEntireSummary(unsigned ID);
748 Error parseModuleStringTable();
750 std::pair<ValueInfo, GlobalValue::GUID>
751 getValueInfoFromValueId(unsigned ValueId);
753 ModuleSummaryIndex::ModuleInfo *addThisModule();
756 } // end anonymous namespace
758 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
762 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
763 EC = EIB.convertToErrorCode();
764 Ctx.emitError(EIB.message());
768 return std::error_code();
771 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
772 StringRef ProducerIdentification,
773 LLVMContext &Context)
774 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
776 this->ProducerIdentification = ProducerIdentification;
779 Error BitcodeReader::materializeForwardReferencedFunctions() {
780 if (WillMaterializeAllForwardRefs)
781 return Error::success();
783 // Prevent recursion.
784 WillMaterializeAllForwardRefs = true;
786 while (!BasicBlockFwdRefQueue.empty()) {
787 Function *F = BasicBlockFwdRefQueue.front();
788 BasicBlockFwdRefQueue.pop_front();
789 assert(F && "Expected valid function");
790 if (!BasicBlockFwdRefs.count(F))
791 // Already materialized.
794 // Check for a function that isn't materializable to prevent an infinite
795 // loop. When parsing a blockaddress stored in a global variable, there
796 // isn't a trivial way to check if a function will have a body without a
797 // linear search through FunctionsWithBodies, so just check it here.
798 if (!F->isMaterializable())
799 return error("Never resolved function from blockaddress");
801 // Try to materialize F.
802 if (Error Err = materialize(F))
805 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
808 WillMaterializeAllForwardRefs = false;
809 return Error::success();
812 //===----------------------------------------------------------------------===//
813 // Helper functions to implement forward reference resolution, etc.
814 //===----------------------------------------------------------------------===//
816 static bool hasImplicitComdat(size_t Val) {
820 case 1: // Old WeakAnyLinkage
821 case 4: // Old LinkOnceAnyLinkage
822 case 10: // Old WeakODRLinkage
823 case 11: // Old LinkOnceODRLinkage
828 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
830 default: // Map unknown/new linkages to external
832 return GlobalValue::ExternalLinkage;
834 return GlobalValue::AppendingLinkage;
836 return GlobalValue::InternalLinkage;
838 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
840 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
842 return GlobalValue::ExternalWeakLinkage;
844 return GlobalValue::CommonLinkage;
846 return GlobalValue::PrivateLinkage;
848 return GlobalValue::AvailableExternallyLinkage;
850 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
852 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
854 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
855 case 1: // Old value with implicit comdat.
857 return GlobalValue::WeakAnyLinkage;
858 case 10: // Old value with implicit comdat.
860 return GlobalValue::WeakODRLinkage;
861 case 4: // Old value with implicit comdat.
863 return GlobalValue::LinkOnceAnyLinkage;
864 case 11: // Old value with implicit comdat.
866 return GlobalValue::LinkOnceODRLinkage;
870 static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
871 FunctionSummary::FFlags Flags;
872 Flags.ReadNone = RawFlags & 0x1;
873 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
874 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
875 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
879 /// Decode the flags for GlobalValue in the summary.
880 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
882 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
883 // like getDecodedLinkage() above. Any future change to the linkage enum and
884 // to getDecodedLinkage() will need to be taken into account here as above.
885 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
886 RawFlags = RawFlags >> 4;
887 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
888 // The Live flag wasn't introduced until version 3. For dead stripping
889 // to work correctly on earlier versions, we must conservatively treat all
891 bool Live = (RawFlags & 0x2) || Version < 3;
892 bool Local = (RawFlags & 0x4);
894 return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local);
897 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
899 default: // Map unknown visibilities to default.
900 case 0: return GlobalValue::DefaultVisibility;
901 case 1: return GlobalValue::HiddenVisibility;
902 case 2: return GlobalValue::ProtectedVisibility;
906 static GlobalValue::DLLStorageClassTypes
907 getDecodedDLLStorageClass(unsigned Val) {
909 default: // Map unknown values to default.
910 case 0: return GlobalValue::DefaultStorageClass;
911 case 1: return GlobalValue::DLLImportStorageClass;
912 case 2: return GlobalValue::DLLExportStorageClass;
916 static bool getDecodedDSOLocal(unsigned Val) {
918 default: // Map unknown values to preemptable.
919 case 0: return false;
924 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
926 case 0: return GlobalVariable::NotThreadLocal;
927 default: // Map unknown non-zero value to general dynamic.
928 case 1: return GlobalVariable::GeneralDynamicTLSModel;
929 case 2: return GlobalVariable::LocalDynamicTLSModel;
930 case 3: return GlobalVariable::InitialExecTLSModel;
931 case 4: return GlobalVariable::LocalExecTLSModel;
935 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
937 default: // Map unknown to UnnamedAddr::None.
938 case 0: return GlobalVariable::UnnamedAddr::None;
939 case 1: return GlobalVariable::UnnamedAddr::Global;
940 case 2: return GlobalVariable::UnnamedAddr::Local;
944 static int getDecodedCastOpcode(unsigned Val) {
947 case bitc::CAST_TRUNC : return Instruction::Trunc;
948 case bitc::CAST_ZEXT : return Instruction::ZExt;
949 case bitc::CAST_SEXT : return Instruction::SExt;
950 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
951 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
952 case bitc::CAST_UITOFP : return Instruction::UIToFP;
953 case bitc::CAST_SITOFP : return Instruction::SIToFP;
954 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
955 case bitc::CAST_FPEXT : return Instruction::FPExt;
956 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
957 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
958 case bitc::CAST_BITCAST : return Instruction::BitCast;
959 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
963 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
964 bool IsFP = Ty->isFPOrFPVectorTy();
965 // BinOps are only valid for int/fp or vector of int/fp types
966 if (!IsFP && !Ty->isIntOrIntVectorTy())
972 case bitc::BINOP_ADD:
973 return IsFP ? Instruction::FAdd : Instruction::Add;
974 case bitc::BINOP_SUB:
975 return IsFP ? Instruction::FSub : Instruction::Sub;
976 case bitc::BINOP_MUL:
977 return IsFP ? Instruction::FMul : Instruction::Mul;
978 case bitc::BINOP_UDIV:
979 return IsFP ? -1 : Instruction::UDiv;
980 case bitc::BINOP_SDIV:
981 return IsFP ? Instruction::FDiv : Instruction::SDiv;
982 case bitc::BINOP_UREM:
983 return IsFP ? -1 : Instruction::URem;
984 case bitc::BINOP_SREM:
985 return IsFP ? Instruction::FRem : Instruction::SRem;
986 case bitc::BINOP_SHL:
987 return IsFP ? -1 : Instruction::Shl;
988 case bitc::BINOP_LSHR:
989 return IsFP ? -1 : Instruction::LShr;
990 case bitc::BINOP_ASHR:
991 return IsFP ? -1 : Instruction::AShr;
992 case bitc::BINOP_AND:
993 return IsFP ? -1 : Instruction::And;
995 return IsFP ? -1 : Instruction::Or;
996 case bitc::BINOP_XOR:
997 return IsFP ? -1 : Instruction::Xor;
1001 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1003 default: return AtomicRMWInst::BAD_BINOP;
1004 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1005 case bitc::RMW_ADD: return AtomicRMWInst::Add;
1006 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1007 case bitc::RMW_AND: return AtomicRMWInst::And;
1008 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1009 case bitc::RMW_OR: return AtomicRMWInst::Or;
1010 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1011 case bitc::RMW_MAX: return AtomicRMWInst::Max;
1012 case bitc::RMW_MIN: return AtomicRMWInst::Min;
1013 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1014 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1018 static AtomicOrdering getDecodedOrdering(unsigned Val) {
1020 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1021 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1022 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1023 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1024 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1025 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1026 default: // Map unknown orderings to sequentially-consistent.
1027 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1031 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1033 default: // Map unknown selection kinds to any.
1034 case bitc::COMDAT_SELECTION_KIND_ANY:
1036 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1037 return Comdat::ExactMatch;
1038 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1039 return Comdat::Largest;
1040 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1041 return Comdat::NoDuplicates;
1042 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1043 return Comdat::SameSize;
1047 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1049 if (0 != (Val & bitc::UnsafeAlgebra))
1051 if (0 != (Val & bitc::AllowReassoc))
1052 FMF.setAllowReassoc();
1053 if (0 != (Val & bitc::NoNaNs))
1055 if (0 != (Val & bitc::NoInfs))
1057 if (0 != (Val & bitc::NoSignedZeros))
1058 FMF.setNoSignedZeros();
1059 if (0 != (Val & bitc::AllowReciprocal))
1060 FMF.setAllowReciprocal();
1061 if (0 != (Val & bitc::AllowContract))
1062 FMF.setAllowContract(true);
1063 if (0 != (Val & bitc::ApproxFunc))
1064 FMF.setApproxFunc();
1068 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1070 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1071 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1075 Type *BitcodeReader::getTypeByID(unsigned ID) {
1076 // The type table size is always specified correctly.
1077 if (ID >= TypeList.size())
1080 if (Type *Ty = TypeList[ID])
1083 // If we have a forward reference, the only possible case is when it is to a
1084 // named struct. Just create a placeholder for now.
1085 return TypeList[ID] = createIdentifiedStructType(Context);
1088 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1090 auto *Ret = StructType::create(Context, Name);
1091 IdentifiedStructTypes.push_back(Ret);
1095 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1096 auto *Ret = StructType::create(Context);
1097 IdentifiedStructTypes.push_back(Ret);
1101 //===----------------------------------------------------------------------===//
1102 // Functions for parsing blocks from the bitcode file
1103 //===----------------------------------------------------------------------===//
1105 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1107 case Attribute::EndAttrKinds:
1108 llvm_unreachable("Synthetic enumerators which should never get here");
1110 case Attribute::None: return 0;
1111 case Attribute::ZExt: return 1 << 0;
1112 case Attribute::SExt: return 1 << 1;
1113 case Attribute::NoReturn: return 1 << 2;
1114 case Attribute::InReg: return 1 << 3;
1115 case Attribute::StructRet: return 1 << 4;
1116 case Attribute::NoUnwind: return 1 << 5;
1117 case Attribute::NoAlias: return 1 << 6;
1118 case Attribute::ByVal: return 1 << 7;
1119 case Attribute::Nest: return 1 << 8;
1120 case Attribute::ReadNone: return 1 << 9;
1121 case Attribute::ReadOnly: return 1 << 10;
1122 case Attribute::NoInline: return 1 << 11;
1123 case Attribute::AlwaysInline: return 1 << 12;
1124 case Attribute::OptimizeForSize: return 1 << 13;
1125 case Attribute::StackProtect: return 1 << 14;
1126 case Attribute::StackProtectReq: return 1 << 15;
1127 case Attribute::Alignment: return 31 << 16;
1128 case Attribute::NoCapture: return 1 << 21;
1129 case Attribute::NoRedZone: return 1 << 22;
1130 case Attribute::NoImplicitFloat: return 1 << 23;
1131 case Attribute::Naked: return 1 << 24;
1132 case Attribute::InlineHint: return 1 << 25;
1133 case Attribute::StackAlignment: return 7 << 26;
1134 case Attribute::ReturnsTwice: return 1 << 29;
1135 case Attribute::UWTable: return 1 << 30;
1136 case Attribute::NonLazyBind: return 1U << 31;
1137 case Attribute::SanitizeAddress: return 1ULL << 32;
1138 case Attribute::MinSize: return 1ULL << 33;
1139 case Attribute::NoDuplicate: return 1ULL << 34;
1140 case Attribute::StackProtectStrong: return 1ULL << 35;
1141 case Attribute::SanitizeThread: return 1ULL << 36;
1142 case Attribute::SanitizeMemory: return 1ULL << 37;
1143 case Attribute::NoBuiltin: return 1ULL << 38;
1144 case Attribute::Returned: return 1ULL << 39;
1145 case Attribute::Cold: return 1ULL << 40;
1146 case Attribute::Builtin: return 1ULL << 41;
1147 case Attribute::OptimizeNone: return 1ULL << 42;
1148 case Attribute::InAlloca: return 1ULL << 43;
1149 case Attribute::NonNull: return 1ULL << 44;
1150 case Attribute::JumpTable: return 1ULL << 45;
1151 case Attribute::Convergent: return 1ULL << 46;
1152 case Attribute::SafeStack: return 1ULL << 47;
1153 case Attribute::NoRecurse: return 1ULL << 48;
1154 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1155 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1156 case Attribute::SwiftSelf: return 1ULL << 51;
1157 case Attribute::SwiftError: return 1ULL << 52;
1158 case Attribute::WriteOnly: return 1ULL << 53;
1159 case Attribute::Speculatable: return 1ULL << 54;
1160 case Attribute::StrictFP: return 1ULL << 55;
1161 case Attribute::SanitizeHWAddress: return 1ULL << 56;
1162 case Attribute::Dereferenceable:
1163 llvm_unreachable("dereferenceable attribute not supported in raw format");
1165 case Attribute::DereferenceableOrNull:
1166 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1169 case Attribute::ArgMemOnly:
1170 llvm_unreachable("argmemonly attribute not supported in raw format");
1172 case Attribute::AllocSize:
1173 llvm_unreachable("allocsize not supported in raw format");
1176 llvm_unreachable("Unsupported attribute type");
1179 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1182 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1183 I = Attribute::AttrKind(I + 1)) {
1184 if (I == Attribute::Dereferenceable ||
1185 I == Attribute::DereferenceableOrNull ||
1186 I == Attribute::ArgMemOnly ||
1187 I == Attribute::AllocSize)
1189 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1190 if (I == Attribute::Alignment)
1191 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1192 else if (I == Attribute::StackAlignment)
1193 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1200 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1201 /// been decoded from the given integer. This function must stay in sync with
1202 /// 'encodeLLVMAttributesForBitcode'.
1203 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1204 uint64_t EncodedAttrs) {
1205 // FIXME: Remove in 4.0.
1207 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1208 // the bits above 31 down by 11 bits.
1209 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1210 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1211 "Alignment must be a power of two.");
1214 B.addAlignmentAttr(Alignment);
1215 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1216 (EncodedAttrs & 0xffff));
1219 Error BitcodeReader::parseAttributeBlock() {
1220 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1221 return error("Invalid record");
1223 if (!MAttributes.empty())
1224 return error("Invalid multiple blocks");
1226 SmallVector<uint64_t, 64> Record;
1228 SmallVector<AttributeList, 8> Attrs;
1230 // Read all the records.
1232 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1234 switch (Entry.Kind) {
1235 case BitstreamEntry::SubBlock: // Handled for us already.
1236 case BitstreamEntry::Error:
1237 return error("Malformed block");
1238 case BitstreamEntry::EndBlock:
1239 return Error::success();
1240 case BitstreamEntry::Record:
1241 // The interesting case.
1247 switch (Stream.readRecord(Entry.ID, Record)) {
1248 default: // Default behavior: ignore.
1250 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1251 // FIXME: Remove in 4.0.
1252 if (Record.size() & 1)
1253 return error("Invalid record");
1255 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1257 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1258 Attrs.push_back(AttributeList::get(Context, Record[i], B));
1261 MAttributes.push_back(AttributeList::get(Context, Attrs));
1264 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1265 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1266 Attrs.push_back(MAttributeGroups[Record[i]]);
1268 MAttributes.push_back(AttributeList::get(Context, Attrs));
1275 // Returns Attribute::None on unrecognized codes.
1276 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1279 return Attribute::None;
1280 case bitc::ATTR_KIND_ALIGNMENT:
1281 return Attribute::Alignment;
1282 case bitc::ATTR_KIND_ALWAYS_INLINE:
1283 return Attribute::AlwaysInline;
1284 case bitc::ATTR_KIND_ARGMEMONLY:
1285 return Attribute::ArgMemOnly;
1286 case bitc::ATTR_KIND_BUILTIN:
1287 return Attribute::Builtin;
1288 case bitc::ATTR_KIND_BY_VAL:
1289 return Attribute::ByVal;
1290 case bitc::ATTR_KIND_IN_ALLOCA:
1291 return Attribute::InAlloca;
1292 case bitc::ATTR_KIND_COLD:
1293 return Attribute::Cold;
1294 case bitc::ATTR_KIND_CONVERGENT:
1295 return Attribute::Convergent;
1296 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1297 return Attribute::InaccessibleMemOnly;
1298 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1299 return Attribute::InaccessibleMemOrArgMemOnly;
1300 case bitc::ATTR_KIND_INLINE_HINT:
1301 return Attribute::InlineHint;
1302 case bitc::ATTR_KIND_IN_REG:
1303 return Attribute::InReg;
1304 case bitc::ATTR_KIND_JUMP_TABLE:
1305 return Attribute::JumpTable;
1306 case bitc::ATTR_KIND_MIN_SIZE:
1307 return Attribute::MinSize;
1308 case bitc::ATTR_KIND_NAKED:
1309 return Attribute::Naked;
1310 case bitc::ATTR_KIND_NEST:
1311 return Attribute::Nest;
1312 case bitc::ATTR_KIND_NO_ALIAS:
1313 return Attribute::NoAlias;
1314 case bitc::ATTR_KIND_NO_BUILTIN:
1315 return Attribute::NoBuiltin;
1316 case bitc::ATTR_KIND_NO_CAPTURE:
1317 return Attribute::NoCapture;
1318 case bitc::ATTR_KIND_NO_DUPLICATE:
1319 return Attribute::NoDuplicate;
1320 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1321 return Attribute::NoImplicitFloat;
1322 case bitc::ATTR_KIND_NO_INLINE:
1323 return Attribute::NoInline;
1324 case bitc::ATTR_KIND_NO_RECURSE:
1325 return Attribute::NoRecurse;
1326 case bitc::ATTR_KIND_NON_LAZY_BIND:
1327 return Attribute::NonLazyBind;
1328 case bitc::ATTR_KIND_NON_NULL:
1329 return Attribute::NonNull;
1330 case bitc::ATTR_KIND_DEREFERENCEABLE:
1331 return Attribute::Dereferenceable;
1332 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1333 return Attribute::DereferenceableOrNull;
1334 case bitc::ATTR_KIND_ALLOC_SIZE:
1335 return Attribute::AllocSize;
1336 case bitc::ATTR_KIND_NO_RED_ZONE:
1337 return Attribute::NoRedZone;
1338 case bitc::ATTR_KIND_NO_RETURN:
1339 return Attribute::NoReturn;
1340 case bitc::ATTR_KIND_NO_UNWIND:
1341 return Attribute::NoUnwind;
1342 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1343 return Attribute::OptimizeForSize;
1344 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1345 return Attribute::OptimizeNone;
1346 case bitc::ATTR_KIND_READ_NONE:
1347 return Attribute::ReadNone;
1348 case bitc::ATTR_KIND_READ_ONLY:
1349 return Attribute::ReadOnly;
1350 case bitc::ATTR_KIND_RETURNED:
1351 return Attribute::Returned;
1352 case bitc::ATTR_KIND_RETURNS_TWICE:
1353 return Attribute::ReturnsTwice;
1354 case bitc::ATTR_KIND_S_EXT:
1355 return Attribute::SExt;
1356 case bitc::ATTR_KIND_SPECULATABLE:
1357 return Attribute::Speculatable;
1358 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1359 return Attribute::StackAlignment;
1360 case bitc::ATTR_KIND_STACK_PROTECT:
1361 return Attribute::StackProtect;
1362 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1363 return Attribute::StackProtectReq;
1364 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1365 return Attribute::StackProtectStrong;
1366 case bitc::ATTR_KIND_SAFESTACK:
1367 return Attribute::SafeStack;
1368 case bitc::ATTR_KIND_STRICT_FP:
1369 return Attribute::StrictFP;
1370 case bitc::ATTR_KIND_STRUCT_RET:
1371 return Attribute::StructRet;
1372 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1373 return Attribute::SanitizeAddress;
1374 case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1375 return Attribute::SanitizeHWAddress;
1376 case bitc::ATTR_KIND_SANITIZE_THREAD:
1377 return Attribute::SanitizeThread;
1378 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1379 return Attribute::SanitizeMemory;
1380 case bitc::ATTR_KIND_SWIFT_ERROR:
1381 return Attribute::SwiftError;
1382 case bitc::ATTR_KIND_SWIFT_SELF:
1383 return Attribute::SwiftSelf;
1384 case bitc::ATTR_KIND_UW_TABLE:
1385 return Attribute::UWTable;
1386 case bitc::ATTR_KIND_WRITEONLY:
1387 return Attribute::WriteOnly;
1388 case bitc::ATTR_KIND_Z_EXT:
1389 return Attribute::ZExt;
1393 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1394 unsigned &Alignment) {
1395 // Note: Alignment in bitcode files is incremented by 1, so that zero
1396 // can be used for default alignment.
1397 if (Exponent > Value::MaxAlignmentExponent + 1)
1398 return error("Invalid alignment value");
1399 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1400 return Error::success();
1403 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1404 *Kind = getAttrFromCode(Code);
1405 if (*Kind == Attribute::None)
1406 return error("Unknown attribute kind (" + Twine(Code) + ")");
1407 return Error::success();
1410 Error BitcodeReader::parseAttributeGroupBlock() {
1411 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1412 return error("Invalid record");
1414 if (!MAttributeGroups.empty())
1415 return error("Invalid multiple blocks");
1417 SmallVector<uint64_t, 64> Record;
1419 // Read all the records.
1421 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1423 switch (Entry.Kind) {
1424 case BitstreamEntry::SubBlock: // Handled for us already.
1425 case BitstreamEntry::Error:
1426 return error("Malformed block");
1427 case BitstreamEntry::EndBlock:
1428 return Error::success();
1429 case BitstreamEntry::Record:
1430 // The interesting case.
1436 switch (Stream.readRecord(Entry.ID, Record)) {
1437 default: // Default behavior: ignore.
1439 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1440 if (Record.size() < 3)
1441 return error("Invalid record");
1443 uint64_t GrpID = Record[0];
1444 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1447 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1448 if (Record[i] == 0) { // Enum attribute
1449 Attribute::AttrKind Kind;
1450 if (Error Err = parseAttrKind(Record[++i], &Kind))
1453 B.addAttribute(Kind);
1454 } else if (Record[i] == 1) { // Integer attribute
1455 Attribute::AttrKind Kind;
1456 if (Error Err = parseAttrKind(Record[++i], &Kind))
1458 if (Kind == Attribute::Alignment)
1459 B.addAlignmentAttr(Record[++i]);
1460 else if (Kind == Attribute::StackAlignment)
1461 B.addStackAlignmentAttr(Record[++i]);
1462 else if (Kind == Attribute::Dereferenceable)
1463 B.addDereferenceableAttr(Record[++i]);
1464 else if (Kind == Attribute::DereferenceableOrNull)
1465 B.addDereferenceableOrNullAttr(Record[++i]);
1466 else if (Kind == Attribute::AllocSize)
1467 B.addAllocSizeAttrFromRawRepr(Record[++i]);
1468 } else { // String attribute
1469 assert((Record[i] == 3 || Record[i] == 4) &&
1470 "Invalid attribute group entry");
1471 bool HasValue = (Record[i++] == 4);
1472 SmallString<64> KindStr;
1473 SmallString<64> ValStr;
1475 while (Record[i] != 0 && i != e)
1476 KindStr += Record[i++];
1477 assert(Record[i] == 0 && "Kind string not null terminated");
1480 // Has a value associated with it.
1481 ++i; // Skip the '0' that terminates the "kind" string.
1482 while (Record[i] != 0 && i != e)
1483 ValStr += Record[i++];
1484 assert(Record[i] == 0 && "Value string not null terminated");
1487 B.addAttribute(KindStr.str(), ValStr.str());
1491 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1498 Error BitcodeReader::parseTypeTable() {
1499 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1500 return error("Invalid record");
1502 return parseTypeTableBody();
1505 Error BitcodeReader::parseTypeTableBody() {
1506 if (!TypeList.empty())
1507 return error("Invalid multiple blocks");
1509 SmallVector<uint64_t, 64> Record;
1510 unsigned NumRecords = 0;
1512 SmallString<64> TypeName;
1514 // Read all the records for this type table.
1516 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1518 switch (Entry.Kind) {
1519 case BitstreamEntry::SubBlock: // Handled for us already.
1520 case BitstreamEntry::Error:
1521 return error("Malformed block");
1522 case BitstreamEntry::EndBlock:
1523 if (NumRecords != TypeList.size())
1524 return error("Malformed block");
1525 return Error::success();
1526 case BitstreamEntry::Record:
1527 // The interesting case.
1533 Type *ResultTy = nullptr;
1534 switch (Stream.readRecord(Entry.ID, Record)) {
1536 return error("Invalid value");
1537 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1538 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1539 // type list. This allows us to reserve space.
1540 if (Record.size() < 1)
1541 return error("Invalid record");
1542 TypeList.resize(Record[0]);
1544 case bitc::TYPE_CODE_VOID: // VOID
1545 ResultTy = Type::getVoidTy(Context);
1547 case bitc::TYPE_CODE_HALF: // HALF
1548 ResultTy = Type::getHalfTy(Context);
1550 case bitc::TYPE_CODE_FLOAT: // FLOAT
1551 ResultTy = Type::getFloatTy(Context);
1553 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1554 ResultTy = Type::getDoubleTy(Context);
1556 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1557 ResultTy = Type::getX86_FP80Ty(Context);
1559 case bitc::TYPE_CODE_FP128: // FP128
1560 ResultTy = Type::getFP128Ty(Context);
1562 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1563 ResultTy = Type::getPPC_FP128Ty(Context);
1565 case bitc::TYPE_CODE_LABEL: // LABEL
1566 ResultTy = Type::getLabelTy(Context);
1568 case bitc::TYPE_CODE_METADATA: // METADATA
1569 ResultTy = Type::getMetadataTy(Context);
1571 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1572 ResultTy = Type::getX86_MMXTy(Context);
1574 case bitc::TYPE_CODE_TOKEN: // TOKEN
1575 ResultTy = Type::getTokenTy(Context);
1577 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1578 if (Record.size() < 1)
1579 return error("Invalid record");
1581 uint64_t NumBits = Record[0];
1582 if (NumBits < IntegerType::MIN_INT_BITS ||
1583 NumBits > IntegerType::MAX_INT_BITS)
1584 return error("Bitwidth for integer type out of range");
1585 ResultTy = IntegerType::get(Context, NumBits);
1588 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1589 // [pointee type, address space]
1590 if (Record.size() < 1)
1591 return error("Invalid record");
1592 unsigned AddressSpace = 0;
1593 if (Record.size() == 2)
1594 AddressSpace = Record[1];
1595 ResultTy = getTypeByID(Record[0]);
1597 !PointerType::isValidElementType(ResultTy))
1598 return error("Invalid type");
1599 ResultTy = PointerType::get(ResultTy, AddressSpace);
1602 case bitc::TYPE_CODE_FUNCTION_OLD: {
1603 // FIXME: attrid is dead, remove it in LLVM 4.0
1604 // FUNCTION: [vararg, attrid, retty, paramty x N]
1605 if (Record.size() < 3)
1606 return error("Invalid record");
1607 SmallVector<Type*, 8> ArgTys;
1608 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1609 if (Type *T = getTypeByID(Record[i]))
1610 ArgTys.push_back(T);
1615 ResultTy = getTypeByID(Record[2]);
1616 if (!ResultTy || ArgTys.size() < Record.size()-3)
1617 return error("Invalid type");
1619 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1622 case bitc::TYPE_CODE_FUNCTION: {
1623 // FUNCTION: [vararg, retty, paramty x N]
1624 if (Record.size() < 2)
1625 return error("Invalid record");
1626 SmallVector<Type*, 8> ArgTys;
1627 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1628 if (Type *T = getTypeByID(Record[i])) {
1629 if (!FunctionType::isValidArgumentType(T))
1630 return error("Invalid function argument type");
1631 ArgTys.push_back(T);
1637 ResultTy = getTypeByID(Record[1]);
1638 if (!ResultTy || ArgTys.size() < Record.size()-2)
1639 return error("Invalid type");
1641 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1644 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1645 if (Record.size() < 1)
1646 return error("Invalid record");
1647 SmallVector<Type*, 8> EltTys;
1648 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1649 if (Type *T = getTypeByID(Record[i]))
1650 EltTys.push_back(T);
1654 if (EltTys.size() != Record.size()-1)
1655 return error("Invalid type");
1656 ResultTy = StructType::get(Context, EltTys, Record[0]);
1659 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1660 if (convertToString(Record, 0, TypeName))
1661 return error("Invalid record");
1664 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1665 if (Record.size() < 1)
1666 return error("Invalid record");
1668 if (NumRecords >= TypeList.size())
1669 return error("Invalid TYPE table");
1671 // Check to see if this was forward referenced, if so fill in the temp.
1672 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1674 Res->setName(TypeName);
1675 TypeList[NumRecords] = nullptr;
1676 } else // Otherwise, create a new struct.
1677 Res = createIdentifiedStructType(Context, TypeName);
1680 SmallVector<Type*, 8> EltTys;
1681 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1682 if (Type *T = getTypeByID(Record[i]))
1683 EltTys.push_back(T);
1687 if (EltTys.size() != Record.size()-1)
1688 return error("Invalid record");
1689 Res->setBody(EltTys, Record[0]);
1693 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1694 if (Record.size() != 1)
1695 return error("Invalid record");
1697 if (NumRecords >= TypeList.size())
1698 return error("Invalid TYPE table");
1700 // Check to see if this was forward referenced, if so fill in the temp.
1701 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1703 Res->setName(TypeName);
1704 TypeList[NumRecords] = nullptr;
1705 } else // Otherwise, create a new struct with no body.
1706 Res = createIdentifiedStructType(Context, TypeName);
1711 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1712 if (Record.size() < 2)
1713 return error("Invalid record");
1714 ResultTy = getTypeByID(Record[1]);
1715 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1716 return error("Invalid type");
1717 ResultTy = ArrayType::get(ResultTy, Record[0]);
1719 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1720 if (Record.size() < 2)
1721 return error("Invalid record");
1723 return error("Invalid vector length");
1724 ResultTy = getTypeByID(Record[1]);
1725 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1726 return error("Invalid type");
1727 ResultTy = VectorType::get(ResultTy, Record[0]);
1731 if (NumRecords >= TypeList.size())
1732 return error("Invalid TYPE table");
1733 if (TypeList[NumRecords])
1735 "Invalid TYPE table: Only named structs can be forward referenced");
1736 assert(ResultTy && "Didn't read a type?");
1737 TypeList[NumRecords++] = ResultTy;
1741 Error BitcodeReader::parseOperandBundleTags() {
1742 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1743 return error("Invalid record");
1745 if (!BundleTags.empty())
1746 return error("Invalid multiple blocks");
1748 SmallVector<uint64_t, 64> Record;
1751 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1753 switch (Entry.Kind) {
1754 case BitstreamEntry::SubBlock: // Handled for us already.
1755 case BitstreamEntry::Error:
1756 return error("Malformed block");
1757 case BitstreamEntry::EndBlock:
1758 return Error::success();
1759 case BitstreamEntry::Record:
1760 // The interesting case.
1764 // Tags are implicitly mapped to integers by their order.
1766 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1767 return error("Invalid record");
1769 // OPERAND_BUNDLE_TAG: [strchr x N]
1770 BundleTags.emplace_back();
1771 if (convertToString(Record, 0, BundleTags.back()))
1772 return error("Invalid record");
1777 Error BitcodeReader::parseSyncScopeNames() {
1778 if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1779 return error("Invalid record");
1782 return error("Invalid multiple synchronization scope names blocks");
1784 SmallVector<uint64_t, 64> Record;
1786 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1787 switch (Entry.Kind) {
1788 case BitstreamEntry::SubBlock: // Handled for us already.
1789 case BitstreamEntry::Error:
1790 return error("Malformed block");
1791 case BitstreamEntry::EndBlock:
1793 return error("Invalid empty synchronization scope names block");
1794 return Error::success();
1795 case BitstreamEntry::Record:
1796 // The interesting case.
1800 // Synchronization scope names are implicitly mapped to synchronization
1801 // scope IDs by their order.
1803 if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1804 return error("Invalid record");
1806 SmallString<16> SSN;
1807 if (convertToString(Record, 0, SSN))
1808 return error("Invalid record");
1810 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1815 /// Associate a value with its name from the given index in the provided record.
1816 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1817 unsigned NameIndex, Triple &TT) {
1818 SmallString<128> ValueName;
1819 if (convertToString(Record, NameIndex, ValueName))
1820 return error("Invalid record");
1821 unsigned ValueID = Record[0];
1822 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1823 return error("Invalid record");
1824 Value *V = ValueList[ValueID];
1826 StringRef NameStr(ValueName.data(), ValueName.size());
1827 if (NameStr.find_first_of(0) != StringRef::npos)
1828 return error("Invalid value name");
1829 V->setName(NameStr);
1830 auto *GO = dyn_cast<GlobalObject>(V);
1832 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1833 if (TT.supportsCOMDAT())
1834 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1836 GO->setComdat(nullptr);
1842 /// Helper to note and return the current location, and jump to the given
1844 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1845 BitstreamCursor &Stream) {
1846 // Save the current parsing location so we can jump back at the end
1848 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1849 Stream.JumpToBit(Offset * 32);
1851 // Do some checking if we are in debug mode.
1852 BitstreamEntry Entry = Stream.advance();
1853 assert(Entry.Kind == BitstreamEntry::SubBlock);
1854 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1856 // In NDEBUG mode ignore the output so we don't get an unused variable
1863 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1865 ArrayRef<uint64_t> Record) {
1866 // Note that we subtract 1 here because the offset is relative to one word
1867 // before the start of the identification or module block, which was
1868 // historically always the start of the regular bitcode header.
1869 uint64_t FuncWordOffset = Record[1] - 1;
1870 uint64_t FuncBitOffset = FuncWordOffset * 32;
1871 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1872 // Set the LastFunctionBlockBit to point to the last function block.
1873 // Later when parsing is resumed after function materialization,
1874 // we can simply skip that last function block.
1875 if (FuncBitOffset > LastFunctionBlockBit)
1876 LastFunctionBlockBit = FuncBitOffset;
1879 /// Read a new-style GlobalValue symbol table.
1880 Error BitcodeReader::parseGlobalValueSymbolTable() {
1881 unsigned FuncBitcodeOffsetDelta =
1882 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1884 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1885 return error("Invalid record");
1887 SmallVector<uint64_t, 64> Record;
1889 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1891 switch (Entry.Kind) {
1892 case BitstreamEntry::SubBlock:
1893 case BitstreamEntry::Error:
1894 return error("Malformed block");
1895 case BitstreamEntry::EndBlock:
1896 return Error::success();
1897 case BitstreamEntry::Record:
1902 switch (Stream.readRecord(Entry.ID, Record)) {
1903 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1904 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1905 cast<Function>(ValueList[Record[0]]), Record);
1911 /// Parse the value symbol table at either the current parsing location or
1912 /// at the given bit offset if provided.
1913 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1914 uint64_t CurrentBit;
1915 // Pass in the Offset to distinguish between calling for the module-level
1916 // VST (where we want to jump to the VST offset) and the function-level
1917 // VST (where we don't).
1919 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
1920 // If this module uses a string table, read this as a module-level VST.
1922 if (Error Err = parseGlobalValueSymbolTable())
1924 Stream.JumpToBit(CurrentBit);
1925 return Error::success();
1927 // Otherwise, the VST will be in a similar format to a function-level VST,
1928 // and will contain symbol names.
1931 // Compute the delta between the bitcode indices in the VST (the word offset
1932 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1933 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1934 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1935 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1936 // just before entering the VST subblock because: 1) the EnterSubBlock
1937 // changes the AbbrevID width; 2) the VST block is nested within the same
1938 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1939 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1940 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1941 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1942 unsigned FuncBitcodeOffsetDelta =
1943 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1945 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1946 return error("Invalid record");
1948 SmallVector<uint64_t, 64> Record;
1950 Triple TT(TheModule->getTargetTriple());
1952 // Read all the records for this value table.
1953 SmallString<128> ValueName;
1956 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1958 switch (Entry.Kind) {
1959 case BitstreamEntry::SubBlock: // Handled for us already.
1960 case BitstreamEntry::Error:
1961 return error("Malformed block");
1962 case BitstreamEntry::EndBlock:
1964 Stream.JumpToBit(CurrentBit);
1965 return Error::success();
1966 case BitstreamEntry::Record:
1967 // The interesting case.
1973 switch (Stream.readRecord(Entry.ID, Record)) {
1974 default: // Default behavior: unknown type.
1976 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
1977 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1978 if (Error Err = ValOrErr.takeError())
1983 case bitc::VST_CODE_FNENTRY: {
1984 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
1985 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1986 if (Error Err = ValOrErr.takeError())
1988 Value *V = ValOrErr.get();
1990 // Ignore function offsets emitted for aliases of functions in older
1991 // versions of LLVM.
1992 if (auto *F = dyn_cast<Function>(V))
1993 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
1996 case bitc::VST_CODE_BBENTRY: {
1997 if (convertToString(Record, 1, ValueName))
1998 return error("Invalid record");
1999 BasicBlock *BB = getBasicBlock(Record[0]);
2001 return error("Invalid record");
2003 BB->setName(StringRef(ValueName.data(), ValueName.size()));
2011 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2013 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2018 // There is no such thing as -0 with integers. "-0" really means MININT.
2022 /// Resolve all of the initializers for global values and aliases that we can.
2023 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2024 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2025 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2026 IndirectSymbolInitWorklist;
2027 std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2028 std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2029 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2031 GlobalInitWorklist.swap(GlobalInits);
2032 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2033 FunctionPrefixWorklist.swap(FunctionPrefixes);
2034 FunctionPrologueWorklist.swap(FunctionPrologues);
2035 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2037 while (!GlobalInitWorklist.empty()) {
2038 unsigned ValID = GlobalInitWorklist.back().second;
2039 if (ValID >= ValueList.size()) {
2040 // Not ready to resolve this yet, it requires something later in the file.
2041 GlobalInits.push_back(GlobalInitWorklist.back());
2043 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2044 GlobalInitWorklist.back().first->setInitializer(C);
2046 return error("Expected a constant");
2048 GlobalInitWorklist.pop_back();
2051 while (!IndirectSymbolInitWorklist.empty()) {
2052 unsigned ValID = IndirectSymbolInitWorklist.back().second;
2053 if (ValID >= ValueList.size()) {
2054 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2056 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2058 return error("Expected a constant");
2059 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2060 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2061 return error("Alias and aliasee types don't match");
2062 GIS->setIndirectSymbol(C);
2064 IndirectSymbolInitWorklist.pop_back();
2067 while (!FunctionPrefixWorklist.empty()) {
2068 unsigned ValID = FunctionPrefixWorklist.back().second;
2069 if (ValID >= ValueList.size()) {
2070 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2072 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2073 FunctionPrefixWorklist.back().first->setPrefixData(C);
2075 return error("Expected a constant");
2077 FunctionPrefixWorklist.pop_back();
2080 while (!FunctionPrologueWorklist.empty()) {
2081 unsigned ValID = FunctionPrologueWorklist.back().second;
2082 if (ValID >= ValueList.size()) {
2083 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2085 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2086 FunctionPrologueWorklist.back().first->setPrologueData(C);
2088 return error("Expected a constant");
2090 FunctionPrologueWorklist.pop_back();
2093 while (!FunctionPersonalityFnWorklist.empty()) {
2094 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2095 if (ValID >= ValueList.size()) {
2096 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2098 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2099 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2101 return error("Expected a constant");
2103 FunctionPersonalityFnWorklist.pop_back();
2106 return Error::success();
2109 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2110 SmallVector<uint64_t, 8> Words(Vals.size());
2111 transform(Vals, Words.begin(),
2112 BitcodeReader::decodeSignRotatedValue);
2114 return APInt(TypeBits, Words);
2117 Error BitcodeReader::parseConstants() {
2118 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2119 return error("Invalid record");
2121 SmallVector<uint64_t, 64> Record;
2123 // Read all the records for this value table.
2124 Type *CurTy = Type::getInt32Ty(Context);
2125 unsigned NextCstNo = ValueList.size();
2128 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2130 switch (Entry.Kind) {
2131 case BitstreamEntry::SubBlock: // Handled for us already.
2132 case BitstreamEntry::Error:
2133 return error("Malformed block");
2134 case BitstreamEntry::EndBlock:
2135 if (NextCstNo != ValueList.size())
2136 return error("Invalid constant reference");
2138 // Once all the constants have been read, go through and resolve forward
2140 ValueList.resolveConstantForwardRefs();
2141 return Error::success();
2142 case BitstreamEntry::Record:
2143 // The interesting case.
2149 Type *VoidType = Type::getVoidTy(Context);
2151 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2153 default: // Default behavior: unknown constant
2154 case bitc::CST_CODE_UNDEF: // UNDEF
2155 V = UndefValue::get(CurTy);
2157 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2159 return error("Invalid record");
2160 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2161 return error("Invalid record");
2162 if (TypeList[Record[0]] == VoidType)
2163 return error("Invalid constant type");
2164 CurTy = TypeList[Record[0]];
2165 continue; // Skip the ValueList manipulation.
2166 case bitc::CST_CODE_NULL: // NULL
2167 V = Constant::getNullValue(CurTy);
2169 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2170 if (!CurTy->isIntegerTy() || Record.empty())
2171 return error("Invalid record");
2172 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2174 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2175 if (!CurTy->isIntegerTy() || Record.empty())
2176 return error("Invalid record");
2179 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2180 V = ConstantInt::get(Context, VInt);
2184 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2186 return error("Invalid record");
2187 if (CurTy->isHalfTy())
2188 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2189 APInt(16, (uint16_t)Record[0])));
2190 else if (CurTy->isFloatTy())
2191 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2192 APInt(32, (uint32_t)Record[0])));
2193 else if (CurTy->isDoubleTy())
2194 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2195 APInt(64, Record[0])));
2196 else if (CurTy->isX86_FP80Ty()) {
2197 // Bits are not stored the same way as a normal i80 APInt, compensate.
2198 uint64_t Rearrange[2];
2199 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2200 Rearrange[1] = Record[0] >> 48;
2201 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2202 APInt(80, Rearrange)));
2203 } else if (CurTy->isFP128Ty())
2204 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2205 APInt(128, Record)));
2206 else if (CurTy->isPPC_FP128Ty())
2207 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2208 APInt(128, Record)));
2210 V = UndefValue::get(CurTy);
2214 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2216 return error("Invalid record");
2218 unsigned Size = Record.size();
2219 SmallVector<Constant*, 16> Elts;
2221 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2222 for (unsigned i = 0; i != Size; ++i)
2223 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2224 STy->getElementType(i)));
2225 V = ConstantStruct::get(STy, Elts);
2226 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2227 Type *EltTy = ATy->getElementType();
2228 for (unsigned i = 0; i != Size; ++i)
2229 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2230 V = ConstantArray::get(ATy, Elts);
2231 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2232 Type *EltTy = VTy->getElementType();
2233 for (unsigned i = 0; i != Size; ++i)
2234 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2235 V = ConstantVector::get(Elts);
2237 V = UndefValue::get(CurTy);
2241 case bitc::CST_CODE_STRING: // STRING: [values]
2242 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2244 return error("Invalid record");
2246 SmallString<16> Elts(Record.begin(), Record.end());
2247 V = ConstantDataArray::getString(Context, Elts,
2248 BitCode == bitc::CST_CODE_CSTRING);
2251 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2253 return error("Invalid record");
2255 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2256 if (EltTy->isIntegerTy(8)) {
2257 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2258 if (isa<VectorType>(CurTy))
2259 V = ConstantDataVector::get(Context, Elts);
2261 V = ConstantDataArray::get(Context, Elts);
2262 } else if (EltTy->isIntegerTy(16)) {
2263 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2264 if (isa<VectorType>(CurTy))
2265 V = ConstantDataVector::get(Context, Elts);
2267 V = ConstantDataArray::get(Context, Elts);
2268 } else if (EltTy->isIntegerTy(32)) {
2269 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2270 if (isa<VectorType>(CurTy))
2271 V = ConstantDataVector::get(Context, Elts);
2273 V = ConstantDataArray::get(Context, Elts);
2274 } else if (EltTy->isIntegerTy(64)) {
2275 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2276 if (isa<VectorType>(CurTy))
2277 V = ConstantDataVector::get(Context, Elts);
2279 V = ConstantDataArray::get(Context, Elts);
2280 } else if (EltTy->isHalfTy()) {
2281 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2282 if (isa<VectorType>(CurTy))
2283 V = ConstantDataVector::getFP(Context, Elts);
2285 V = ConstantDataArray::getFP(Context, Elts);
2286 } else if (EltTy->isFloatTy()) {
2287 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2288 if (isa<VectorType>(CurTy))
2289 V = ConstantDataVector::getFP(Context, Elts);
2291 V = ConstantDataArray::getFP(Context, Elts);
2292 } else if (EltTy->isDoubleTy()) {
2293 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2294 if (isa<VectorType>(CurTy))
2295 V = ConstantDataVector::getFP(Context, Elts);
2297 V = ConstantDataArray::getFP(Context, Elts);
2299 return error("Invalid type for value");
2303 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2304 if (Record.size() < 3)
2305 return error("Invalid record");
2306 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2308 V = UndefValue::get(CurTy); // Unknown binop.
2310 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2311 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2313 if (Record.size() >= 4) {
2314 if (Opc == Instruction::Add ||
2315 Opc == Instruction::Sub ||
2316 Opc == Instruction::Mul ||
2317 Opc == Instruction::Shl) {
2318 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2319 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2320 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2321 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2322 } else if (Opc == Instruction::SDiv ||
2323 Opc == Instruction::UDiv ||
2324 Opc == Instruction::LShr ||
2325 Opc == Instruction::AShr) {
2326 if (Record[3] & (1 << bitc::PEO_EXACT))
2327 Flags |= SDivOperator::IsExact;
2330 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2334 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2335 if (Record.size() < 3)
2336 return error("Invalid record");
2337 int Opc = getDecodedCastOpcode(Record[0]);
2339 V = UndefValue::get(CurTy); // Unknown cast.
2341 Type *OpTy = getTypeByID(Record[1]);
2343 return error("Invalid record");
2344 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2345 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2346 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2350 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2351 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2352 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2355 Type *PointeeType = nullptr;
2356 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2358 PointeeType = getTypeByID(Record[OpNum++]);
2360 bool InBounds = false;
2361 Optional<unsigned> InRangeIndex;
2362 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2363 uint64_t Op = Record[OpNum++];
2365 InRangeIndex = Op >> 1;
2366 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2369 SmallVector<Constant*, 16> Elts;
2370 while (OpNum != Record.size()) {
2371 Type *ElTy = getTypeByID(Record[OpNum++]);
2373 return error("Invalid record");
2374 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2379 cast<PointerType>(Elts[0]->getType()->getScalarType())
2381 return error("Explicit gep operator type does not match pointee type "
2382 "of pointer operand");
2384 if (Elts.size() < 1)
2385 return error("Invalid gep with no operands");
2387 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2388 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2389 InBounds, InRangeIndex);
2392 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2393 if (Record.size() < 3)
2394 return error("Invalid record");
2396 Type *SelectorTy = Type::getInt1Ty(Context);
2398 // The selector might be an i1 or an <n x i1>
2399 // Get the type from the ValueList before getting a forward ref.
2400 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2401 if (Value *V = ValueList[Record[0]])
2402 if (SelectorTy != V->getType())
2403 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2405 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2407 ValueList.getConstantFwdRef(Record[1],CurTy),
2408 ValueList.getConstantFwdRef(Record[2],CurTy));
2411 case bitc::CST_CODE_CE_EXTRACTELT
2412 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2413 if (Record.size() < 3)
2414 return error("Invalid record");
2416 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2418 return error("Invalid record");
2419 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2420 Constant *Op1 = nullptr;
2421 if (Record.size() == 4) {
2422 Type *IdxTy = getTypeByID(Record[2]);
2424 return error("Invalid record");
2425 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2426 } else // TODO: Remove with llvm 4.0
2427 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2429 return error("Invalid record");
2430 V = ConstantExpr::getExtractElement(Op0, Op1);
2433 case bitc::CST_CODE_CE_INSERTELT
2434 : { // CE_INSERTELT: [opval, opval, opty, opval]
2435 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2436 if (Record.size() < 3 || !OpTy)
2437 return error("Invalid record");
2438 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2439 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2440 OpTy->getElementType());
2441 Constant *Op2 = nullptr;
2442 if (Record.size() == 4) {
2443 Type *IdxTy = getTypeByID(Record[2]);
2445 return error("Invalid record");
2446 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2447 } else // TODO: Remove with llvm 4.0
2448 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2450 return error("Invalid record");
2451 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2454 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2455 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2456 if (Record.size() < 3 || !OpTy)
2457 return error("Invalid record");
2458 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2459 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2460 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2461 OpTy->getNumElements());
2462 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2463 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2466 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2467 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2469 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2470 if (Record.size() < 4 || !RTy || !OpTy)
2471 return error("Invalid record");
2472 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2473 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2474 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2475 RTy->getNumElements());
2476 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2477 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2480 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2481 if (Record.size() < 4)
2482 return error("Invalid record");
2483 Type *OpTy = getTypeByID(Record[0]);
2485 return error("Invalid record");
2486 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2487 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2489 if (OpTy->isFPOrFPVectorTy())
2490 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2492 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2495 // This maintains backward compatibility, pre-asm dialect keywords.
2496 // FIXME: Remove with the 4.0 release.
2497 case bitc::CST_CODE_INLINEASM_OLD: {
2498 if (Record.size() < 2)
2499 return error("Invalid record");
2500 std::string AsmStr, ConstrStr;
2501 bool HasSideEffects = Record[0] & 1;
2502 bool IsAlignStack = Record[0] >> 1;
2503 unsigned AsmStrSize = Record[1];
2504 if (2+AsmStrSize >= Record.size())
2505 return error("Invalid record");
2506 unsigned ConstStrSize = Record[2+AsmStrSize];
2507 if (3+AsmStrSize+ConstStrSize > Record.size())
2508 return error("Invalid record");
2510 for (unsigned i = 0; i != AsmStrSize; ++i)
2511 AsmStr += (char)Record[2+i];
2512 for (unsigned i = 0; i != ConstStrSize; ++i)
2513 ConstrStr += (char)Record[3+AsmStrSize+i];
2514 PointerType *PTy = cast<PointerType>(CurTy);
2515 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2516 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2519 // This version adds support for the asm dialect keywords (e.g.,
2521 case bitc::CST_CODE_INLINEASM: {
2522 if (Record.size() < 2)
2523 return error("Invalid record");
2524 std::string AsmStr, ConstrStr;
2525 bool HasSideEffects = Record[0] & 1;
2526 bool IsAlignStack = (Record[0] >> 1) & 1;
2527 unsigned AsmDialect = Record[0] >> 2;
2528 unsigned AsmStrSize = Record[1];
2529 if (2+AsmStrSize >= Record.size())
2530 return error("Invalid record");
2531 unsigned ConstStrSize = Record[2+AsmStrSize];
2532 if (3+AsmStrSize+ConstStrSize > Record.size())
2533 return error("Invalid record");
2535 for (unsigned i = 0; i != AsmStrSize; ++i)
2536 AsmStr += (char)Record[2+i];
2537 for (unsigned i = 0; i != ConstStrSize; ++i)
2538 ConstrStr += (char)Record[3+AsmStrSize+i];
2539 PointerType *PTy = cast<PointerType>(CurTy);
2540 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2541 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2542 InlineAsm::AsmDialect(AsmDialect));
2545 case bitc::CST_CODE_BLOCKADDRESS:{
2546 if (Record.size() < 3)
2547 return error("Invalid record");
2548 Type *FnTy = getTypeByID(Record[0]);
2550 return error("Invalid record");
2552 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2554 return error("Invalid record");
2556 // If the function is already parsed we can insert the block address right
2559 unsigned BBID = Record[2];
2561 // Invalid reference to entry block.
2562 return error("Invalid ID");
2564 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2565 for (size_t I = 0, E = BBID; I != E; ++I) {
2567 return error("Invalid ID");
2572 // Otherwise insert a placeholder and remember it so it can be inserted
2573 // when the function is parsed.
2574 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2576 BasicBlockFwdRefQueue.push_back(Fn);
2577 if (FwdBBs.size() < BBID + 1)
2578 FwdBBs.resize(BBID + 1);
2580 FwdBBs[BBID] = BasicBlock::Create(Context);
2583 V = BlockAddress::get(Fn, BB);
2588 ValueList.assignValue(V, NextCstNo);
2593 Error BitcodeReader::parseUseLists() {
2594 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2595 return error("Invalid record");
2597 // Read all the records.
2598 SmallVector<uint64_t, 64> Record;
2601 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2603 switch (Entry.Kind) {
2604 case BitstreamEntry::SubBlock: // Handled for us already.
2605 case BitstreamEntry::Error:
2606 return error("Malformed block");
2607 case BitstreamEntry::EndBlock:
2608 return Error::success();
2609 case BitstreamEntry::Record:
2610 // The interesting case.
2614 // Read a use list record.
2617 switch (Stream.readRecord(Entry.ID, Record)) {
2618 default: // Default behavior: unknown type.
2620 case bitc::USELIST_CODE_BB:
2623 case bitc::USELIST_CODE_DEFAULT: {
2624 unsigned RecordLength = Record.size();
2625 if (RecordLength < 3)
2626 // Records should have at least an ID and two indexes.
2627 return error("Invalid record");
2628 unsigned ID = Record.back();
2633 assert(ID < FunctionBBs.size() && "Basic block not found");
2634 V = FunctionBBs[ID];
2637 unsigned NumUses = 0;
2638 SmallDenseMap<const Use *, unsigned, 16> Order;
2639 for (const Use &U : V->materialized_uses()) {
2640 if (++NumUses > Record.size())
2642 Order[&U] = Record[NumUses - 1];
2644 if (Order.size() != Record.size() || NumUses > Record.size())
2645 // Mismatches can happen if the functions are being materialized lazily
2646 // (out-of-order), or a value has been upgraded.
2649 V->sortUseList([&](const Use &L, const Use &R) {
2650 return Order.lookup(&L) < Order.lookup(&R);
2658 /// When we see the block for metadata, remember where it is and then skip it.
2659 /// This lets us lazily deserialize the metadata.
2660 Error BitcodeReader::rememberAndSkipMetadata() {
2661 // Save the current stream state.
2662 uint64_t CurBit = Stream.GetCurrentBitNo();
2663 DeferredMetadataInfo.push_back(CurBit);
2665 // Skip over the block for now.
2666 if (Stream.SkipBlock())
2667 return error("Invalid record");
2668 return Error::success();
2671 Error BitcodeReader::materializeMetadata() {
2672 for (uint64_t BitPos : DeferredMetadataInfo) {
2673 // Move the bit stream to the saved position.
2674 Stream.JumpToBit(BitPos);
2675 if (Error Err = MDLoader->parseModuleMetadata())
2679 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2681 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2682 NamedMDNode *LinkerOpts =
2683 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2684 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2685 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2688 DeferredMetadataInfo.clear();
2689 return Error::success();
2692 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2694 /// When we see the block for a function body, remember where it is and then
2695 /// skip it. This lets us lazily deserialize the functions.
2696 Error BitcodeReader::rememberAndSkipFunctionBody() {
2697 // Get the function we are talking about.
2698 if (FunctionsWithBodies.empty())
2699 return error("Insufficient function protos");
2701 Function *Fn = FunctionsWithBodies.back();
2702 FunctionsWithBodies.pop_back();
2704 // Save the current stream state.
2705 uint64_t CurBit = Stream.GetCurrentBitNo();
2707 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2708 "Mismatch between VST and scanned function offsets");
2709 DeferredFunctionInfo[Fn] = CurBit;
2711 // Skip over the function block for now.
2712 if (Stream.SkipBlock())
2713 return error("Invalid record");
2714 return Error::success();
2717 Error BitcodeReader::globalCleanup() {
2718 // Patch the initializers for globals and aliases up.
2719 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2721 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2722 return error("Malformed global initializer set");
2724 // Look for intrinsic functions which need to be upgraded at some point
2725 for (Function &F : *TheModule) {
2726 MDLoader->upgradeDebugIntrinsics(F);
2728 if (UpgradeIntrinsicFunction(&F, NewFn))
2729 UpgradedIntrinsics[&F] = NewFn;
2730 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2731 // Some types could be renamed during loading if several modules are
2732 // loaded in the same LLVMContext (LTO scenario). In this case we should
2733 // remangle intrinsics names as well.
2734 RemangledIntrinsics[&F] = Remangled.getValue();
2737 // Look for global variables which need to be renamed.
2738 for (GlobalVariable &GV : TheModule->globals())
2739 UpgradeGlobalVariable(&GV);
2741 // Force deallocation of memory for these vectors to favor the client that
2742 // want lazy deserialization.
2743 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
2744 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
2745 IndirectSymbolInits);
2746 return Error::success();
2749 /// Support for lazy parsing of function bodies. This is required if we
2750 /// either have an old bitcode file without a VST forward declaration record,
2751 /// or if we have an anonymous function being materialized, since anonymous
2752 /// functions do not have a name and are therefore not in the VST.
2753 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2754 Stream.JumpToBit(NextUnreadBit);
2756 if (Stream.AtEndOfStream())
2757 return error("Could not find function in stream");
2759 if (!SeenFirstFunctionBody)
2760 return error("Trying to materialize functions before seeing function blocks");
2762 // An old bitcode file with the symbol table at the end would have
2763 // finished the parse greedily.
2764 assert(SeenValueSymbolTable);
2766 SmallVector<uint64_t, 64> Record;
2769 BitstreamEntry Entry = Stream.advance();
2770 switch (Entry.Kind) {
2772 return error("Expect SubBlock");
2773 case BitstreamEntry::SubBlock:
2776 return error("Expect function block");
2777 case bitc::FUNCTION_BLOCK_ID:
2778 if (Error Err = rememberAndSkipFunctionBody())
2780 NextUnreadBit = Stream.GetCurrentBitNo();
2781 return Error::success();
2787 bool BitcodeReaderBase::readBlockInfo() {
2788 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2791 BlockInfo = std::move(*NewBlockInfo);
2795 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
2796 // v1: [selection_kind, name]
2797 // v2: [strtab_offset, strtab_size, selection_kind]
2799 std::tie(Name, Record) = readNameFromStrtab(Record);
2802 return error("Invalid record");
2803 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2804 std::string OldFormatName;
2806 if (Record.size() < 2)
2807 return error("Invalid record");
2808 unsigned ComdatNameSize = Record[1];
2809 OldFormatName.reserve(ComdatNameSize);
2810 for (unsigned i = 0; i != ComdatNameSize; ++i)
2811 OldFormatName += (char)Record[2 + i];
2812 Name = OldFormatName;
2814 Comdat *C = TheModule->getOrInsertComdat(Name);
2815 C->setSelectionKind(SK);
2816 ComdatList.push_back(C);
2817 return Error::success();
2820 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
2821 // v1: [pointer type, isconst, initid, linkage, alignment, section,
2822 // visibility, threadlocal, unnamed_addr, externally_initialized,
2823 // dllstorageclass, comdat, attributes, preemption specifier] (name in VST)
2824 // v2: [strtab_offset, strtab_size, v1]
2826 std::tie(Name, Record) = readNameFromStrtab(Record);
2828 if (Record.size() < 6)
2829 return error("Invalid record");
2830 Type *Ty = getTypeByID(Record[0]);
2832 return error("Invalid record");
2833 bool isConstant = Record[1] & 1;
2834 bool explicitType = Record[1] & 2;
2835 unsigned AddressSpace;
2837 AddressSpace = Record[1] >> 2;
2839 if (!Ty->isPointerTy())
2840 return error("Invalid type for value");
2841 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2842 Ty = cast<PointerType>(Ty)->getElementType();
2845 uint64_t RawLinkage = Record[3];
2846 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2848 if (Error Err = parseAlignmentValue(Record[4], Alignment))
2850 std::string Section;
2852 if (Record[5] - 1 >= SectionTable.size())
2853 return error("Invalid ID");
2854 Section = SectionTable[Record[5] - 1];
2856 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2857 // Local linkage must have default visibility.
2858 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2859 // FIXME: Change to an error if non-default in 4.0.
2860 Visibility = getDecodedVisibility(Record[6]);
2862 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2863 if (Record.size() > 7)
2864 TLM = getDecodedThreadLocalMode(Record[7]);
2866 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2867 if (Record.size() > 8)
2868 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2870 bool ExternallyInitialized = false;
2871 if (Record.size() > 9)
2872 ExternallyInitialized = Record[9];
2874 GlobalVariable *NewGV =
2875 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
2876 nullptr, TLM, AddressSpace, ExternallyInitialized);
2877 NewGV->setAlignment(Alignment);
2878 if (!Section.empty())
2879 NewGV->setSection(Section);
2880 NewGV->setVisibility(Visibility);
2881 NewGV->setUnnamedAddr(UnnamedAddr);
2883 if (Record.size() > 10)
2884 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2886 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2888 ValueList.push_back(NewGV);
2890 // Remember which value to use for the global initializer.
2891 if (unsigned InitID = Record[2])
2892 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2894 if (Record.size() > 11) {
2895 if (unsigned ComdatID = Record[11]) {
2896 if (ComdatID > ComdatList.size())
2897 return error("Invalid global variable comdat ID");
2898 NewGV->setComdat(ComdatList[ComdatID - 1]);
2900 } else if (hasImplicitComdat(RawLinkage)) {
2901 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2904 if (Record.size() > 12) {
2905 auto AS = getAttributes(Record[12]).getFnAttributes();
2906 NewGV->setAttributes(AS);
2909 if (Record.size() > 13) {
2910 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
2913 return Error::success();
2916 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
2917 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
2918 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
2919 // prefixdata, personalityfn, preemption specifier] (name in VST)
2920 // v2: [strtab_offset, strtab_size, v1]
2922 std::tie(Name, Record) = readNameFromStrtab(Record);
2924 if (Record.size() < 8)
2925 return error("Invalid record");
2926 Type *Ty = getTypeByID(Record[0]);
2928 return error("Invalid record");
2929 if (auto *PTy = dyn_cast<PointerType>(Ty))
2930 Ty = PTy->getElementType();
2931 auto *FTy = dyn_cast<FunctionType>(Ty);
2933 return error("Invalid type for value");
2934 auto CC = static_cast<CallingConv::ID>(Record[1]);
2935 if (CC & ~CallingConv::MaxID)
2936 return error("Invalid calling convention ID");
2939 Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule);
2941 Func->setCallingConv(CC);
2942 bool isProto = Record[2];
2943 uint64_t RawLinkage = Record[3];
2944 Func->setLinkage(getDecodedLinkage(RawLinkage));
2945 Func->setAttributes(getAttributes(Record[4]));
2948 if (Error Err = parseAlignmentValue(Record[5], Alignment))
2950 Func->setAlignment(Alignment);
2952 if (Record[6] - 1 >= SectionTable.size())
2953 return error("Invalid ID");
2954 Func->setSection(SectionTable[Record[6] - 1]);
2956 // Local linkage must have default visibility.
2957 if (!Func->hasLocalLinkage())
2958 // FIXME: Change to an error if non-default in 4.0.
2959 Func->setVisibility(getDecodedVisibility(Record[7]));
2960 if (Record.size() > 8 && Record[8]) {
2961 if (Record[8] - 1 >= GCTable.size())
2962 return error("Invalid ID");
2963 Func->setGC(GCTable[Record[8] - 1]);
2965 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2966 if (Record.size() > 9)
2967 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2968 Func->setUnnamedAddr(UnnamedAddr);
2969 if (Record.size() > 10 && Record[10] != 0)
2970 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2972 if (Record.size() > 11)
2973 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2975 upgradeDLLImportExportLinkage(Func, RawLinkage);
2977 if (Record.size() > 12) {
2978 if (unsigned ComdatID = Record[12]) {
2979 if (ComdatID > ComdatList.size())
2980 return error("Invalid function comdat ID");
2981 Func->setComdat(ComdatList[ComdatID - 1]);
2983 } else if (hasImplicitComdat(RawLinkage)) {
2984 Func->setComdat(reinterpret_cast<Comdat *>(1));
2987 if (Record.size() > 13 && Record[13] != 0)
2988 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
2990 if (Record.size() > 14 && Record[14] != 0)
2991 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2993 if (Record.size() > 15) {
2994 Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
2997 ValueList.push_back(Func);
2999 // If this is a function with a body, remember the prototype we are
3000 // creating now, so that we can match up the body with them later.
3002 Func->setIsMaterializable(true);
3003 FunctionsWithBodies.push_back(Func);
3004 DeferredFunctionInfo[Func] = 0;
3006 return Error::success();
3009 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3010 unsigned BitCode, ArrayRef<uint64_t> Record) {
3011 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3012 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3013 // dllstorageclass, threadlocal, unnamed_addr,
3014 // preemption specifier] (name in VST)
3015 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3016 // visibility, dllstorageclass, threadlocal, unnamed_addr,
3017 // preemption specifier] (name in VST)
3018 // v2: [strtab_offset, strtab_size, v1]
3020 std::tie(Name, Record) = readNameFromStrtab(Record);
3022 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3023 if (Record.size() < (3 + (unsigned)NewRecord))
3024 return error("Invalid record");
3026 Type *Ty = getTypeByID(Record[OpNum++]);
3028 return error("Invalid record");
3032 auto *PTy = dyn_cast<PointerType>(Ty);
3034 return error("Invalid type for value");
3035 Ty = PTy->getElementType();
3036 AddrSpace = PTy->getAddressSpace();
3038 AddrSpace = Record[OpNum++];
3041 auto Val = Record[OpNum++];
3042 auto Linkage = Record[OpNum++];
3043 GlobalIndirectSymbol *NewGA;
3044 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3045 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3046 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3049 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3050 nullptr, TheModule);
3051 // Old bitcode files didn't have visibility field.
3052 // Local linkage must have default visibility.
3053 if (OpNum != Record.size()) {
3054 auto VisInd = OpNum++;
3055 if (!NewGA->hasLocalLinkage())
3056 // FIXME: Change to an error if non-default in 4.0.
3057 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3059 if (OpNum != Record.size())
3060 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3062 upgradeDLLImportExportLinkage(NewGA, Linkage);
3063 if (OpNum != Record.size())
3064 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3065 if (OpNum != Record.size())
3066 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3067 if (OpNum != Record.size())
3068 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3069 ValueList.push_back(NewGA);
3070 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3071 return Error::success();
3074 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3075 bool ShouldLazyLoadMetadata) {
3077 Stream.JumpToBit(ResumeBit);
3078 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3079 return error("Invalid record");
3081 SmallVector<uint64_t, 64> Record;
3083 // Read all the records for this module.
3085 BitstreamEntry Entry = Stream.advance();
3087 switch (Entry.Kind) {
3088 case BitstreamEntry::Error:
3089 return error("Malformed block");
3090 case BitstreamEntry::EndBlock:
3091 return globalCleanup();
3093 case BitstreamEntry::SubBlock:
3095 default: // Skip unknown content.
3096 if (Stream.SkipBlock())
3097 return error("Invalid record");
3099 case bitc::BLOCKINFO_BLOCK_ID:
3100 if (readBlockInfo())
3101 return error("Malformed block");
3103 case bitc::PARAMATTR_BLOCK_ID:
3104 if (Error Err = parseAttributeBlock())
3107 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3108 if (Error Err = parseAttributeGroupBlock())
3111 case bitc::TYPE_BLOCK_ID_NEW:
3112 if (Error Err = parseTypeTable())
3115 case bitc::VALUE_SYMTAB_BLOCK_ID:
3116 if (!SeenValueSymbolTable) {
3117 // Either this is an old form VST without function index and an
3118 // associated VST forward declaration record (which would have caused
3119 // the VST to be jumped to and parsed before it was encountered
3120 // normally in the stream), or there were no function blocks to
3121 // trigger an earlier parsing of the VST.
3122 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3123 if (Error Err = parseValueSymbolTable())
3125 SeenValueSymbolTable = true;
3127 // We must have had a VST forward declaration record, which caused
3128 // the parser to jump to and parse the VST earlier.
3129 assert(VSTOffset > 0);
3130 if (Stream.SkipBlock())
3131 return error("Invalid record");
3134 case bitc::CONSTANTS_BLOCK_ID:
3135 if (Error Err = parseConstants())
3137 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3140 case bitc::METADATA_BLOCK_ID:
3141 if (ShouldLazyLoadMetadata) {
3142 if (Error Err = rememberAndSkipMetadata())
3146 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3147 if (Error Err = MDLoader->parseModuleMetadata())
3150 case bitc::METADATA_KIND_BLOCK_ID:
3151 if (Error Err = MDLoader->parseMetadataKinds())
3154 case bitc::FUNCTION_BLOCK_ID:
3155 // If this is the first function body we've seen, reverse the
3156 // FunctionsWithBodies list.
3157 if (!SeenFirstFunctionBody) {
3158 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3159 if (Error Err = globalCleanup())
3161 SeenFirstFunctionBody = true;
3164 if (VSTOffset > 0) {
3165 // If we have a VST forward declaration record, make sure we
3166 // parse the VST now if we haven't already. It is needed to
3167 // set up the DeferredFunctionInfo vector for lazy reading.
3168 if (!SeenValueSymbolTable) {
3169 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3171 SeenValueSymbolTable = true;
3172 // Fall through so that we record the NextUnreadBit below.
3173 // This is necessary in case we have an anonymous function that
3174 // is later materialized. Since it will not have a VST entry we
3175 // need to fall back to the lazy parse to find its offset.
3177 // If we have a VST forward declaration record, but have already
3178 // parsed the VST (just above, when the first function body was
3179 // encountered here), then we are resuming the parse after
3180 // materializing functions. The ResumeBit points to the
3181 // start of the last function block recorded in the
3182 // DeferredFunctionInfo map. Skip it.
3183 if (Stream.SkipBlock())
3184 return error("Invalid record");
3189 // Support older bitcode files that did not have the function
3190 // index in the VST, nor a VST forward declaration record, as
3191 // well as anonymous functions that do not have VST entries.
3192 // Build the DeferredFunctionInfo vector on the fly.
3193 if (Error Err = rememberAndSkipFunctionBody())
3196 // Suspend parsing when we reach the function bodies. Subsequent
3197 // materialization calls will resume it when necessary. If the bitcode
3198 // file is old, the symbol table will be at the end instead and will not
3199 // have been seen yet. In this case, just finish the parse now.
3200 if (SeenValueSymbolTable) {
3201 NextUnreadBit = Stream.GetCurrentBitNo();
3202 // After the VST has been parsed, we need to make sure intrinsic name
3203 // are auto-upgraded.
3204 return globalCleanup();
3207 case bitc::USELIST_BLOCK_ID:
3208 if (Error Err = parseUseLists())
3211 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3212 if (Error Err = parseOperandBundleTags())
3215 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3216 if (Error Err = parseSyncScopeNames())
3222 case BitstreamEntry::Record:
3223 // The interesting case.
3228 auto BitCode = Stream.readRecord(Entry.ID, Record);
3230 default: break; // Default behavior, ignore unknown content.
3231 case bitc::MODULE_CODE_VERSION: {
3232 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3234 return VersionOrErr.takeError();
3235 UseRelativeIDs = *VersionOrErr >= 1;
3238 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3240 if (convertToString(Record, 0, S))
3241 return error("Invalid record");
3242 TheModule->setTargetTriple(S);
3245 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3247 if (convertToString(Record, 0, S))
3248 return error("Invalid record");
3249 TheModule->setDataLayout(S);
3252 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3254 if (convertToString(Record, 0, S))
3255 return error("Invalid record");
3256 TheModule->setModuleInlineAsm(S);
3259 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3260 // FIXME: Remove in 4.0.
3262 if (convertToString(Record, 0, S))
3263 return error("Invalid record");
3267 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3269 if (convertToString(Record, 0, S))
3270 return error("Invalid record");
3271 SectionTable.push_back(S);
3274 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3276 if (convertToString(Record, 0, S))
3277 return error("Invalid record");
3278 GCTable.push_back(S);
3281 case bitc::MODULE_CODE_COMDAT:
3282 if (Error Err = parseComdatRecord(Record))
3285 case bitc::MODULE_CODE_GLOBALVAR:
3286 if (Error Err = parseGlobalVarRecord(Record))
3289 case bitc::MODULE_CODE_FUNCTION:
3290 if (Error Err = parseFunctionRecord(Record))
3293 case bitc::MODULE_CODE_IFUNC:
3294 case bitc::MODULE_CODE_ALIAS:
3295 case bitc::MODULE_CODE_ALIAS_OLD:
3296 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3299 /// MODULE_CODE_VSTOFFSET: [offset]
3300 case bitc::MODULE_CODE_VSTOFFSET:
3301 if (Record.size() < 1)
3302 return error("Invalid record");
3303 // Note that we subtract 1 here because the offset is relative to one word
3304 // before the start of the identification or module block, which was
3305 // historically always the start of the regular bitcode header.
3306 VSTOffset = Record[0] - 1;
3308 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3309 case bitc::MODULE_CODE_SOURCE_FILENAME:
3310 SmallString<128> ValueName;
3311 if (convertToString(Record, 0, ValueName))
3312 return error("Invalid record");
3313 TheModule->setSourceFileName(ValueName);
3320 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3323 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3324 [&](unsigned ID) { return getTypeByID(ID); });
3325 return parseModule(0, ShouldLazyLoadMetadata);
3328 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3329 if (!isa<PointerType>(PtrType))
3330 return error("Load/Store operand is not a pointer type");
3331 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3333 if (ValType && ValType != ElemType)
3334 return error("Explicit load/store type does not match pointee "
3335 "type of pointer operand");
3336 if (!PointerType::isLoadableOrStorableType(ElemType))
3337 return error("Cannot load/store from pointer");
3338 return Error::success();
3341 /// Lazily parse the specified function body block.
3342 Error BitcodeReader::parseFunctionBody(Function *F) {
3343 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3344 return error("Invalid record");
3346 // Unexpected unresolved metadata when parsing function.
3347 if (MDLoader->hasFwdRefs())
3348 return error("Invalid function metadata: incoming forward references");
3350 InstructionList.clear();
3351 unsigned ModuleValueListSize = ValueList.size();
3352 unsigned ModuleMDLoaderSize = MDLoader->size();
3354 // Add all the function arguments to the value table.
3355 for (Argument &I : F->args())
3356 ValueList.push_back(&I);
3358 unsigned NextValueNo = ValueList.size();
3359 BasicBlock *CurBB = nullptr;
3360 unsigned CurBBNo = 0;
3363 auto getLastInstruction = [&]() -> Instruction * {
3364 if (CurBB && !CurBB->empty())
3365 return &CurBB->back();
3366 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3367 !FunctionBBs[CurBBNo - 1]->empty())
3368 return &FunctionBBs[CurBBNo - 1]->back();
3372 std::vector<OperandBundleDef> OperandBundles;
3374 // Read all the records.
3375 SmallVector<uint64_t, 64> Record;
3378 BitstreamEntry Entry = Stream.advance();
3380 switch (Entry.Kind) {
3381 case BitstreamEntry::Error:
3382 return error("Malformed block");
3383 case BitstreamEntry::EndBlock:
3384 goto OutOfRecordLoop;
3386 case BitstreamEntry::SubBlock:
3388 default: // Skip unknown content.
3389 if (Stream.SkipBlock())
3390 return error("Invalid record");
3392 case bitc::CONSTANTS_BLOCK_ID:
3393 if (Error Err = parseConstants())
3395 NextValueNo = ValueList.size();
3397 case bitc::VALUE_SYMTAB_BLOCK_ID:
3398 if (Error Err = parseValueSymbolTable())
3401 case bitc::METADATA_ATTACHMENT_ID:
3402 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3405 case bitc::METADATA_BLOCK_ID:
3406 assert(DeferredMetadataInfo.empty() &&
3407 "Must read all module-level metadata before function-level");
3408 if (Error Err = MDLoader->parseFunctionMetadata())
3411 case bitc::USELIST_BLOCK_ID:
3412 if (Error Err = parseUseLists())
3418 case BitstreamEntry::Record:
3419 // The interesting case.
3425 Instruction *I = nullptr;
3426 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3428 default: // Default behavior: reject
3429 return error("Invalid value");
3430 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3431 if (Record.size() < 1 || Record[0] == 0)
3432 return error("Invalid record");
3433 // Create all the basic blocks for the function.
3434 FunctionBBs.resize(Record[0]);
3436 // See if anything took the address of blocks in this function.
3437 auto BBFRI = BasicBlockFwdRefs.find(F);
3438 if (BBFRI == BasicBlockFwdRefs.end()) {
3439 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3440 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3442 auto &BBRefs = BBFRI->second;
3443 // Check for invalid basic block references.
3444 if (BBRefs.size() > FunctionBBs.size())
3445 return error("Invalid ID");
3446 assert(!BBRefs.empty() && "Unexpected empty array");
3447 assert(!BBRefs.front() && "Invalid reference to entry block");
3448 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3450 if (I < RE && BBRefs[I]) {
3451 BBRefs[I]->insertInto(F);
3452 FunctionBBs[I] = BBRefs[I];
3454 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3457 // Erase from the table.
3458 BasicBlockFwdRefs.erase(BBFRI);
3461 CurBB = FunctionBBs[0];
3465 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3466 // This record indicates that the last instruction is at the same
3467 // location as the previous instruction with a location.
3468 I = getLastInstruction();
3471 return error("Invalid record");
3472 I->setDebugLoc(LastLoc);
3476 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3477 I = getLastInstruction();
3478 if (!I || Record.size() < 4)
3479 return error("Invalid record");
3481 unsigned Line = Record[0], Col = Record[1];
3482 unsigned ScopeID = Record[2], IAID = Record[3];
3484 MDNode *Scope = nullptr, *IA = nullptr;
3486 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
3488 return error("Invalid record");
3491 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
3493 return error("Invalid record");
3495 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3496 I->setDebugLoc(LastLoc);
3501 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3504 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3505 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3506 OpNum+1 > Record.size())
3507 return error("Invalid record");
3509 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3511 return error("Invalid record");
3512 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3513 InstructionList.push_back(I);
3514 if (OpNum < Record.size()) {
3515 if (Opc == Instruction::Add ||
3516 Opc == Instruction::Sub ||
3517 Opc == Instruction::Mul ||
3518 Opc == Instruction::Shl) {
3519 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3520 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3521 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3522 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3523 } else if (Opc == Instruction::SDiv ||
3524 Opc == Instruction::UDiv ||
3525 Opc == Instruction::LShr ||
3526 Opc == Instruction::AShr) {
3527 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3528 cast<BinaryOperator>(I)->setIsExact(true);
3529 } else if (isa<FPMathOperator>(I)) {
3530 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3532 I->setFastMathFlags(FMF);
3538 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3541 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3542 OpNum+2 != Record.size())
3543 return error("Invalid record");
3545 Type *ResTy = getTypeByID(Record[OpNum]);
3546 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3547 if (Opc == -1 || !ResTy)
3548 return error("Invalid record");
3549 Instruction *Temp = nullptr;
3550 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3552 InstructionList.push_back(Temp);
3553 CurBB->getInstList().push_back(Temp);
3556 auto CastOp = (Instruction::CastOps)Opc;
3557 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3558 return error("Invalid cast");
3559 I = CastInst::Create(CastOp, Op, ResTy);
3561 InstructionList.push_back(I);
3564 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3565 case bitc::FUNC_CODE_INST_GEP_OLD:
3566 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3572 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3573 InBounds = Record[OpNum++];
3574 Ty = getTypeByID(Record[OpNum++]);
3576 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3581 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3582 return error("Invalid record");
3585 Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3588 cast<PointerType>(BasePtr->getType()->getScalarType())
3591 "Explicit gep type does not match pointee type of pointer operand");
3593 SmallVector<Value*, 16> GEPIdx;
3594 while (OpNum != Record.size()) {
3596 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3597 return error("Invalid record");
3598 GEPIdx.push_back(Op);
3601 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3603 InstructionList.push_back(I);
3605 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3609 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3610 // EXTRACTVAL: [opty, opval, n x indices]
3613 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3614 return error("Invalid record");
3616 unsigned RecSize = Record.size();
3617 if (OpNum == RecSize)
3618 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3620 SmallVector<unsigned, 4> EXTRACTVALIdx;
3621 Type *CurTy = Agg->getType();
3622 for (; OpNum != RecSize; ++OpNum) {
3623 bool IsArray = CurTy->isArrayTy();
3624 bool IsStruct = CurTy->isStructTy();
3625 uint64_t Index = Record[OpNum];
3627 if (!IsStruct && !IsArray)
3628 return error("EXTRACTVAL: Invalid type");
3629 if ((unsigned)Index != Index)
3630 return error("Invalid value");
3631 if (IsStruct && Index >= CurTy->subtypes().size())
3632 return error("EXTRACTVAL: Invalid struct index");
3633 if (IsArray && Index >= CurTy->getArrayNumElements())
3634 return error("EXTRACTVAL: Invalid array index");
3635 EXTRACTVALIdx.push_back((unsigned)Index);
3638 CurTy = CurTy->subtypes()[Index];
3640 CurTy = CurTy->subtypes()[0];
3643 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3644 InstructionList.push_back(I);
3648 case bitc::FUNC_CODE_INST_INSERTVAL: {
3649 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3652 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3653 return error("Invalid record");
3655 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3656 return error("Invalid record");
3658 unsigned RecSize = Record.size();
3659 if (OpNum == RecSize)
3660 return error("INSERTVAL: Invalid instruction with 0 indices");
3662 SmallVector<unsigned, 4> INSERTVALIdx;
3663 Type *CurTy = Agg->getType();
3664 for (; OpNum != RecSize; ++OpNum) {
3665 bool IsArray = CurTy->isArrayTy();
3666 bool IsStruct = CurTy->isStructTy();
3667 uint64_t Index = Record[OpNum];
3669 if (!IsStruct && !IsArray)
3670 return error("INSERTVAL: Invalid type");
3671 if ((unsigned)Index != Index)
3672 return error("Invalid value");
3673 if (IsStruct && Index >= CurTy->subtypes().size())
3674 return error("INSERTVAL: Invalid struct index");
3675 if (IsArray && Index >= CurTy->getArrayNumElements())
3676 return error("INSERTVAL: Invalid array index");
3678 INSERTVALIdx.push_back((unsigned)Index);
3680 CurTy = CurTy->subtypes()[Index];
3682 CurTy = CurTy->subtypes()[0];
3685 if (CurTy != Val->getType())
3686 return error("Inserted value type doesn't match aggregate type");
3688 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3689 InstructionList.push_back(I);
3693 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3694 // obsolete form of select
3695 // handles select i1 ... in old bitcode
3697 Value *TrueVal, *FalseVal, *Cond;
3698 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3699 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3700 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3701 return error("Invalid record");
3703 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3704 InstructionList.push_back(I);
3708 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3709 // new form of select
3710 // handles select i1 or select [N x i1]
3712 Value *TrueVal, *FalseVal, *Cond;
3713 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3714 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3715 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3716 return error("Invalid record");
3718 // select condition can be either i1 or [N x i1]
3719 if (VectorType* vector_type =
3720 dyn_cast<VectorType>(Cond->getType())) {
3722 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3723 return error("Invalid type for value");
3726 if (Cond->getType() != Type::getInt1Ty(Context))
3727 return error("Invalid type for value");
3730 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3731 InstructionList.push_back(I);
3735 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3738 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3739 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3740 return error("Invalid record");
3741 if (!Vec->getType()->isVectorTy())
3742 return error("Invalid type for value");
3743 I = ExtractElementInst::Create(Vec, Idx);
3744 InstructionList.push_back(I);
3748 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3750 Value *Vec, *Elt, *Idx;
3751 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3752 return error("Invalid record");
3753 if (!Vec->getType()->isVectorTy())
3754 return error("Invalid type for value");
3755 if (popValue(Record, OpNum, NextValueNo,
3756 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3757 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3758 return error("Invalid record");
3759 I = InsertElementInst::Create(Vec, Elt, Idx);
3760 InstructionList.push_back(I);
3764 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3766 Value *Vec1, *Vec2, *Mask;
3767 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3768 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3769 return error("Invalid record");
3771 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3772 return error("Invalid record");
3773 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3774 return error("Invalid type for value");
3775 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3776 InstructionList.push_back(I);
3780 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3781 // Old form of ICmp/FCmp returning bool
3782 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3783 // both legal on vectors but had different behaviour.
3784 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3785 // FCmp/ICmp returning bool or vector of bool
3789 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3790 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3791 return error("Invalid record");
3793 unsigned PredVal = Record[OpNum];
3794 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3796 if (IsFP && Record.size() > OpNum+1)
3797 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3799 if (OpNum+1 != Record.size())
3800 return error("Invalid record");
3802 if (LHS->getType()->isFPOrFPVectorTy())
3803 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3805 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3808 I->setFastMathFlags(FMF);
3809 InstructionList.push_back(I);
3813 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3815 unsigned Size = Record.size();
3817 I = ReturnInst::Create(Context);
3818 InstructionList.push_back(I);
3823 Value *Op = nullptr;
3824 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3825 return error("Invalid record");
3826 if (OpNum != Record.size())
3827 return error("Invalid record");
3829 I = ReturnInst::Create(Context, Op);
3830 InstructionList.push_back(I);
3833 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3834 if (Record.size() != 1 && Record.size() != 3)
3835 return error("Invalid record");
3836 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3838 return error("Invalid record");
3840 if (Record.size() == 1) {
3841 I = BranchInst::Create(TrueDest);
3842 InstructionList.push_back(I);
3845 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3846 Value *Cond = getValue(Record, 2, NextValueNo,
3847 Type::getInt1Ty(Context));
3848 if (!FalseDest || !Cond)
3849 return error("Invalid record");
3850 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3851 InstructionList.push_back(I);
3855 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
3856 if (Record.size() != 1 && Record.size() != 2)
3857 return error("Invalid record");
3860 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3862 return error("Invalid record");
3863 BasicBlock *UnwindDest = nullptr;
3864 if (Record.size() == 2) {
3865 UnwindDest = getBasicBlock(Record[Idx++]);
3867 return error("Invalid record");
3870 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
3871 InstructionList.push_back(I);
3874 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3875 if (Record.size() != 2)
3876 return error("Invalid record");
3879 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3881 return error("Invalid record");
3882 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3884 return error("Invalid record");
3886 I = CatchReturnInst::Create(CatchPad, BB);
3887 InstructionList.push_back(I);
3890 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3891 // We must have, at minimum, the outer scope and the number of arguments.
3892 if (Record.size() < 2)
3893 return error("Invalid record");
3898 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3900 unsigned NumHandlers = Record[Idx++];
3902 SmallVector<BasicBlock *, 2> Handlers;
3903 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3904 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3906 return error("Invalid record");
3907 Handlers.push_back(BB);
3910 BasicBlock *UnwindDest = nullptr;
3911 if (Idx + 1 == Record.size()) {
3912 UnwindDest = getBasicBlock(Record[Idx++]);
3914 return error("Invalid record");
3917 if (Record.size() != Idx)
3918 return error("Invalid record");
3921 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3922 for (BasicBlock *Handler : Handlers)
3923 CatchSwitch->addHandler(Handler);
3925 InstructionList.push_back(I);
3928 case bitc::FUNC_CODE_INST_CATCHPAD:
3929 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3930 // We must have, at minimum, the outer scope and the number of arguments.
3931 if (Record.size() < 2)
3932 return error("Invalid record");
3937 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3939 unsigned NumArgOperands = Record[Idx++];
3941 SmallVector<Value *, 2> Args;
3942 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3944 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3945 return error("Invalid record");
3946 Args.push_back(Val);
3949 if (Record.size() != Idx)
3950 return error("Invalid record");
3952 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3953 I = CleanupPadInst::Create(ParentPad, Args);
3955 I = CatchPadInst::Create(ParentPad, Args);
3956 InstructionList.push_back(I);
3959 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3961 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3962 // "New" SwitchInst format with case ranges. The changes to write this
3963 // format were reverted but we still recognize bitcode that uses it.
3964 // Hopefully someday we will have support for case ranges and can use
3965 // this format again.
3967 Type *OpTy = getTypeByID(Record[1]);
3968 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3970 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3971 BasicBlock *Default = getBasicBlock(Record[3]);
3972 if (!OpTy || !Cond || !Default)
3973 return error("Invalid record");
3975 unsigned NumCases = Record[4];
3977 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3978 InstructionList.push_back(SI);
3980 unsigned CurIdx = 5;
3981 for (unsigned i = 0; i != NumCases; ++i) {
3982 SmallVector<ConstantInt*, 1> CaseVals;
3983 unsigned NumItems = Record[CurIdx++];
3984 for (unsigned ci = 0; ci != NumItems; ++ci) {
3985 bool isSingleNumber = Record[CurIdx++];
3988 unsigned ActiveWords = 1;
3989 if (ValueBitWidth > 64)
3990 ActiveWords = Record[CurIdx++];
3991 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3993 CurIdx += ActiveWords;
3995 if (!isSingleNumber) {
3997 if (ValueBitWidth > 64)
3998 ActiveWords = Record[CurIdx++];
3999 APInt High = readWideAPInt(
4000 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4001 CurIdx += ActiveWords;
4003 // FIXME: It is not clear whether values in the range should be
4004 // compared as signed or unsigned values. The partially
4005 // implemented changes that used this format in the past used
4006 // unsigned comparisons.
4007 for ( ; Low.ule(High); ++Low)
4008 CaseVals.push_back(ConstantInt::get(Context, Low));
4010 CaseVals.push_back(ConstantInt::get(Context, Low));
4012 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4013 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4014 cve = CaseVals.end(); cvi != cve; ++cvi)
4015 SI->addCase(*cvi, DestBB);
4021 // Old SwitchInst format without case ranges.
4023 if (Record.size() < 3 || (Record.size() & 1) == 0)
4024 return error("Invalid record");
4025 Type *OpTy = getTypeByID(Record[0]);
4026 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4027 BasicBlock *Default = getBasicBlock(Record[2]);
4028 if (!OpTy || !Cond || !Default)
4029 return error("Invalid record");
4030 unsigned NumCases = (Record.size()-3)/2;
4031 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4032 InstructionList.push_back(SI);
4033 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4034 ConstantInt *CaseVal =
4035 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4036 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4037 if (!CaseVal || !DestBB) {
4039 return error("Invalid record");
4041 SI->addCase(CaseVal, DestBB);
4046 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4047 if (Record.size() < 2)
4048 return error("Invalid record");
4049 Type *OpTy = getTypeByID(Record[0]);
4050 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4051 if (!OpTy || !Address)
4052 return error("Invalid record");
4053 unsigned NumDests = Record.size()-2;
4054 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4055 InstructionList.push_back(IBI);
4056 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4057 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4058 IBI->addDestination(DestBB);
4061 return error("Invalid record");
4068 case bitc::FUNC_CODE_INST_INVOKE: {
4069 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4070 if (Record.size() < 4)
4071 return error("Invalid record");
4073 AttributeList PAL = getAttributes(Record[OpNum++]);
4074 unsigned CCInfo = Record[OpNum++];
4075 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4076 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4078 FunctionType *FTy = nullptr;
4079 if (CCInfo >> 13 & 1 &&
4080 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4081 return error("Explicit invoke type is not a function type");
4084 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4085 return error("Invalid record");
4087 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4089 return error("Callee is not a pointer");
4091 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4093 return error("Callee is not of pointer to function type");
4094 } else if (CalleeTy->getElementType() != FTy)
4095 return error("Explicit invoke type does not match pointee type of "
4097 if (Record.size() < FTy->getNumParams() + OpNum)
4098 return error("Insufficient operands to call");
4100 SmallVector<Value*, 16> Ops;
4101 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4102 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4103 FTy->getParamType(i)));
4105 return error("Invalid record");
4108 if (!FTy->isVarArg()) {
4109 if (Record.size() != OpNum)
4110 return error("Invalid record");
4112 // Read type/value pairs for varargs params.
4113 while (OpNum != Record.size()) {
4115 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4116 return error("Invalid record");
4121 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4122 OperandBundles.clear();
4123 InstructionList.push_back(I);
4124 cast<InvokeInst>(I)->setCallingConv(
4125 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4126 cast<InvokeInst>(I)->setAttributes(PAL);
4129 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4131 Value *Val = nullptr;
4132 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4133 return error("Invalid record");
4134 I = ResumeInst::Create(Val);
4135 InstructionList.push_back(I);
4138 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4139 I = new UnreachableInst(Context);
4140 InstructionList.push_back(I);
4142 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4143 if (Record.size() < 1 || ((Record.size()-1)&1))
4144 return error("Invalid record");
4145 Type *Ty = getTypeByID(Record[0]);
4147 return error("Invalid record");
4149 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4150 InstructionList.push_back(PN);
4152 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4154 // With the new function encoding, it is possible that operands have
4155 // negative IDs (for forward references). Use a signed VBR
4156 // representation to keep the encoding small.
4158 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4160 V = getValue(Record, 1+i, NextValueNo, Ty);
4161 BasicBlock *BB = getBasicBlock(Record[2+i]);
4163 return error("Invalid record");
4164 PN->addIncoming(V, BB);
4170 case bitc::FUNC_CODE_INST_LANDINGPAD:
4171 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4172 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4174 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4175 if (Record.size() < 3)
4176 return error("Invalid record");
4178 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4179 if (Record.size() < 4)
4180 return error("Invalid record");
4182 Type *Ty = getTypeByID(Record[Idx++]);
4184 return error("Invalid record");
4185 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4186 Value *PersFn = nullptr;
4187 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4188 return error("Invalid record");
4190 if (!F->hasPersonalityFn())
4191 F->setPersonalityFn(cast<Constant>(PersFn));
4192 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4193 return error("Personality function mismatch");
4196 bool IsCleanup = !!Record[Idx++];
4197 unsigned NumClauses = Record[Idx++];
4198 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4199 LP->setCleanup(IsCleanup);
4200 for (unsigned J = 0; J != NumClauses; ++J) {
4201 LandingPadInst::ClauseType CT =
4202 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4205 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4207 return error("Invalid record");
4210 assert((CT != LandingPadInst::Catch ||
4211 !isa<ArrayType>(Val->getType())) &&
4212 "Catch clause has a invalid type!");
4213 assert((CT != LandingPadInst::Filter ||
4214 isa<ArrayType>(Val->getType())) &&
4215 "Filter clause has invalid type!");
4216 LP->addClause(cast<Constant>(Val));
4220 InstructionList.push_back(I);
4224 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4225 if (Record.size() != 4)
4226 return error("Invalid record");
4227 uint64_t AlignRecord = Record[3];
4228 const uint64_t InAllocaMask = uint64_t(1) << 5;
4229 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4230 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4231 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4233 bool InAlloca = AlignRecord & InAllocaMask;
4234 bool SwiftError = AlignRecord & SwiftErrorMask;
4235 Type *Ty = getTypeByID(Record[0]);
4236 if ((AlignRecord & ExplicitTypeMask) == 0) {
4237 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4239 return error("Old-style alloca with a non-pointer type");
4240 Ty = PTy->getElementType();
4242 Type *OpTy = getTypeByID(Record[1]);
4243 Value *Size = getFnValueByID(Record[2], OpTy);
4245 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4249 return error("Invalid record");
4251 // FIXME: Make this an optional field.
4252 const DataLayout &DL = TheModule->getDataLayout();
4253 unsigned AS = DL.getAllocaAddrSpace();
4255 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
4256 AI->setUsedWithInAlloca(InAlloca);
4257 AI->setSwiftError(SwiftError);
4259 InstructionList.push_back(I);
4262 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4265 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4266 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4267 return error("Invalid record");
4270 if (OpNum + 3 == Record.size())
4271 Ty = getTypeByID(Record[OpNum++]);
4272 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4275 Ty = cast<PointerType>(Op->getType())->getElementType();
4278 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4280 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4282 InstructionList.push_back(I);
4285 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4286 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
4289 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4290 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4291 return error("Invalid record");
4294 if (OpNum + 5 == Record.size())
4295 Ty = getTypeByID(Record[OpNum++]);
4296 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4299 Ty = cast<PointerType>(Op->getType())->getElementType();
4301 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4302 if (Ordering == AtomicOrdering::NotAtomic ||
4303 Ordering == AtomicOrdering::Release ||
4304 Ordering == AtomicOrdering::AcquireRelease)
4305 return error("Invalid record");
4306 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4307 return error("Invalid record");
4308 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4311 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4313 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID);
4315 InstructionList.push_back(I);
4318 case bitc::FUNC_CODE_INST_STORE:
4319 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4322 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4323 (BitCode == bitc::FUNC_CODE_INST_STORE
4324 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4325 : popValue(Record, OpNum, NextValueNo,
4326 cast<PointerType>(Ptr->getType())->getElementType(),
4328 OpNum + 2 != Record.size())
4329 return error("Invalid record");
4331 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4334 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4336 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4337 InstructionList.push_back(I);
4340 case bitc::FUNC_CODE_INST_STOREATOMIC:
4341 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4342 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
4345 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4346 !isa<PointerType>(Ptr->getType()) ||
4347 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4348 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4349 : popValue(Record, OpNum, NextValueNo,
4350 cast<PointerType>(Ptr->getType())->getElementType(),
4352 OpNum + 4 != Record.size())
4353 return error("Invalid record");
4355 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4357 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4358 if (Ordering == AtomicOrdering::NotAtomic ||
4359 Ordering == AtomicOrdering::Acquire ||
4360 Ordering == AtomicOrdering::AcquireRelease)
4361 return error("Invalid record");
4362 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4363 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4364 return error("Invalid record");
4367 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4369 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
4370 InstructionList.push_back(I);
4373 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4374 case bitc::FUNC_CODE_INST_CMPXCHG: {
4375 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
4376 // failureordering?, isweak?]
4378 Value *Ptr, *Cmp, *New;
4379 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4380 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4381 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4382 : popValue(Record, OpNum, NextValueNo,
4383 cast<PointerType>(Ptr->getType())->getElementType(),
4385 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4386 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4387 return error("Invalid record");
4388 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4389 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4390 SuccessOrdering == AtomicOrdering::Unordered)
4391 return error("Invalid record");
4392 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
4394 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4396 AtomicOrdering FailureOrdering;
4397 if (Record.size() < 7)
4399 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4401 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4403 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4405 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4407 if (Record.size() < 8) {
4408 // Before weak cmpxchgs existed, the instruction simply returned the
4409 // value loaded from memory, so bitcode files from that era will be
4410 // expecting the first component of a modern cmpxchg.
4411 CurBB->getInstList().push_back(I);
4412 I = ExtractValueInst::Create(I, 0);
4414 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4417 InstructionList.push_back(I);
4420 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4421 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
4424 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4425 !isa<PointerType>(Ptr->getType()) ||
4426 popValue(Record, OpNum, NextValueNo,
4427 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4428 OpNum+4 != Record.size())
4429 return error("Invalid record");
4430 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4431 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4432 Operation > AtomicRMWInst::LAST_BINOP)
4433 return error("Invalid record");
4434 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4435 if (Ordering == AtomicOrdering::NotAtomic ||
4436 Ordering == AtomicOrdering::Unordered)
4437 return error("Invalid record");
4438 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4439 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
4440 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4441 InstructionList.push_back(I);
4444 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
4445 if (2 != Record.size())
4446 return error("Invalid record");
4447 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4448 if (Ordering == AtomicOrdering::NotAtomic ||
4449 Ordering == AtomicOrdering::Unordered ||
4450 Ordering == AtomicOrdering::Monotonic)
4451 return error("Invalid record");
4452 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4453 I = new FenceInst(Context, Ordering, SSID);
4454 InstructionList.push_back(I);
4457 case bitc::FUNC_CODE_INST_CALL: {
4458 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4459 if (Record.size() < 3)
4460 return error("Invalid record");
4463 AttributeList PAL = getAttributes(Record[OpNum++]);
4464 unsigned CCInfo = Record[OpNum++];
4467 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4468 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4470 return error("Fast math flags indicator set for call with no FMF");
4473 FunctionType *FTy = nullptr;
4474 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4475 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4476 return error("Explicit call type is not a function type");
4479 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4480 return error("Invalid record");
4482 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4484 return error("Callee is not a pointer type");
4486 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4488 return error("Callee is not of pointer to function type");
4489 } else if (OpTy->getElementType() != FTy)
4490 return error("Explicit call type does not match pointee type of "
4492 if (Record.size() < FTy->getNumParams() + OpNum)
4493 return error("Insufficient operands to call");
4495 SmallVector<Value*, 16> Args;
4496 // Read the fixed params.
4497 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4498 if (FTy->getParamType(i)->isLabelTy())
4499 Args.push_back(getBasicBlock(Record[OpNum]));
4501 Args.push_back(getValue(Record, OpNum, NextValueNo,
4502 FTy->getParamType(i)));
4504 return error("Invalid record");
4507 // Read type/value pairs for varargs params.
4508 if (!FTy->isVarArg()) {
4509 if (OpNum != Record.size())
4510 return error("Invalid record");
4512 while (OpNum != Record.size()) {
4514 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4515 return error("Invalid record");
4520 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4521 OperandBundles.clear();
4522 InstructionList.push_back(I);
4523 cast<CallInst>(I)->setCallingConv(
4524 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4525 CallInst::TailCallKind TCK = CallInst::TCK_None;
4526 if (CCInfo & 1 << bitc::CALL_TAIL)
4527 TCK = CallInst::TCK_Tail;
4528 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
4529 TCK = CallInst::TCK_MustTail;
4530 if (CCInfo & (1 << bitc::CALL_NOTAIL))
4531 TCK = CallInst::TCK_NoTail;
4532 cast<CallInst>(I)->setTailCallKind(TCK);
4533 cast<CallInst>(I)->setAttributes(PAL);
4535 if (!isa<FPMathOperator>(I))
4536 return error("Fast-math-flags specified for call without "
4537 "floating-point scalar or vector return type");
4538 I->setFastMathFlags(FMF);
4542 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4543 if (Record.size() < 3)
4544 return error("Invalid record");
4545 Type *OpTy = getTypeByID(Record[0]);
4546 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4547 Type *ResTy = getTypeByID(Record[2]);
4548 if (!OpTy || !Op || !ResTy)
4549 return error("Invalid record");
4550 I = new VAArgInst(Op, ResTy);
4551 InstructionList.push_back(I);
4555 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4556 // A call or an invoke can be optionally prefixed with some variable
4557 // number of operand bundle blocks. These blocks are read into
4558 // OperandBundles and consumed at the next call or invoke instruction.
4560 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4561 return error("Invalid record");
4563 std::vector<Value *> Inputs;
4566 while (OpNum != Record.size()) {
4568 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4569 return error("Invalid record");
4570 Inputs.push_back(Op);
4573 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4578 // Add instruction to end of current BB. If there is no current BB, reject
4582 return error("Invalid instruction with no BB");
4584 if (!OperandBundles.empty()) {
4586 return error("Operand bundles found with no consumer");
4588 CurBB->getInstList().push_back(I);
4590 // If this was a terminator instruction, move to the next block.
4591 if (isa<TerminatorInst>(I)) {
4593 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4596 // Non-void values get registered in the value table for future use.
4597 if (I && !I->getType()->isVoidTy())
4598 ValueList.assignValue(I, NextValueNo++);
4603 if (!OperandBundles.empty())
4604 return error("Operand bundles found with no consumer");
4606 // Check the function list for unresolved values.
4607 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4608 if (!A->getParent()) {
4609 // We found at least one unresolved value. Nuke them all to avoid leaks.
4610 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4611 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4612 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4616 return error("Never resolved value found in function");
4620 // Unexpected unresolved metadata about to be dropped.
4621 if (MDLoader->hasFwdRefs())
4622 return error("Invalid function metadata: outgoing forward refs");
4624 // Trim the value list down to the size it was before we parsed this function.
4625 ValueList.shrinkTo(ModuleValueListSize);
4626 MDLoader->shrinkTo(ModuleMDLoaderSize);
4627 std::vector<BasicBlock*>().swap(FunctionBBs);
4628 return Error::success();
4631 /// Find the function body in the bitcode stream
4632 Error BitcodeReader::findFunctionInStream(
4634 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4635 while (DeferredFunctionInfoIterator->second == 0) {
4636 // This is the fallback handling for the old format bitcode that
4637 // didn't contain the function index in the VST, or when we have
4638 // an anonymous function which would not have a VST entry.
4639 // Assert that we have one of those two cases.
4640 assert(VSTOffset == 0 || !F->hasName());
4641 // Parse the next body in the stream and set its position in the
4642 // DeferredFunctionInfo map.
4643 if (Error Err = rememberAndSkipFunctionBodies())
4646 return Error::success();
4649 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
4650 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
4651 return SyncScope::ID(Val);
4652 if (Val >= SSIDs.size())
4653 return SyncScope::System; // Map unknown synchronization scopes to system.
4657 //===----------------------------------------------------------------------===//
4658 // GVMaterializer implementation
4659 //===----------------------------------------------------------------------===//
4661 Error BitcodeReader::materialize(GlobalValue *GV) {
4662 Function *F = dyn_cast<Function>(GV);
4663 // If it's not a function or is already material, ignore the request.
4664 if (!F || !F->isMaterializable())
4665 return Error::success();
4667 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4668 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4669 // If its position is recorded as 0, its body is somewhere in the stream
4670 // but we haven't seen it yet.
4671 if (DFII->second == 0)
4672 if (Error Err = findFunctionInStream(F, DFII))
4675 // Materialize metadata before parsing any function bodies.
4676 if (Error Err = materializeMetadata())
4679 // Move the bit stream to the saved position of the deferred function body.
4680 Stream.JumpToBit(DFII->second);
4682 if (Error Err = parseFunctionBody(F))
4684 F->setIsMaterializable(false);
4689 // Upgrade any old intrinsic calls in the function.
4690 for (auto &I : UpgradedIntrinsics) {
4691 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4695 if (CallInst *CI = dyn_cast<CallInst>(U))
4696 UpgradeIntrinsicCall(CI, I.second);
4700 // Update calls to the remangled intrinsics
4701 for (auto &I : RemangledIntrinsics)
4702 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4704 // Don't expect any other users than call sites
4705 CallSite(*UI++).setCalledFunction(I.second);
4707 // Finish fn->subprogram upgrade for materialized functions.
4708 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4709 F->setSubprogram(SP);
4711 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4712 if (!MDLoader->isStrippingTBAA()) {
4713 for (auto &I : instructions(F)) {
4714 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4715 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4717 MDLoader->setStripTBAA(true);
4718 stripTBAA(F->getParent());
4722 // Bring in any functions that this function forward-referenced via
4724 return materializeForwardReferencedFunctions();
4727 Error BitcodeReader::materializeModule() {
4728 if (Error Err = materializeMetadata())
4731 // Promise to materialize all forward references.
4732 WillMaterializeAllForwardRefs = true;
4734 // Iterate over the module, deserializing any functions that are still on
4736 for (Function &F : *TheModule) {
4737 if (Error Err = materialize(&F))
4740 // At this point, if there are any function bodies, parse the rest of
4741 // the bits in the module past the last function block we have recorded
4742 // through either lazy scanning or the VST.
4743 if (LastFunctionBlockBit || NextUnreadBit)
4744 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4745 ? LastFunctionBlockBit
4749 // Check that all block address forward references got resolved (as we
4751 if (!BasicBlockFwdRefs.empty())
4752 return error("Never resolved function from blockaddress");
4754 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4755 // delete the old functions to clean up. We can't do this unless the entire
4756 // module is materialized because there could always be another function body
4757 // with calls to the old function.
4758 for (auto &I : UpgradedIntrinsics) {
4759 for (auto *U : I.first->users()) {
4760 if (CallInst *CI = dyn_cast<CallInst>(U))
4761 UpgradeIntrinsicCall(CI, I.second);
4763 if (!I.first->use_empty())
4764 I.first->replaceAllUsesWith(I.second);
4765 I.first->eraseFromParent();
4767 UpgradedIntrinsics.clear();
4768 // Do the same for remangled intrinsics
4769 for (auto &I : RemangledIntrinsics) {
4770 I.first->replaceAllUsesWith(I.second);
4771 I.first->eraseFromParent();
4773 RemangledIntrinsics.clear();
4775 UpgradeDebugInfo(*TheModule);
4777 UpgradeModuleFlags(*TheModule);
4778 return Error::success();
4781 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4782 return IdentifiedStructTypes;
4785 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4786 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
4787 StringRef ModulePath, unsigned ModuleId)
4788 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4789 ModulePath(ModulePath), ModuleId(ModuleId) {}
4791 ModuleSummaryIndex::ModuleInfo *
4792 ModuleSummaryIndexBitcodeReader::addThisModule() {
4793 return TheIndex.addModule(ModulePath, ModuleId);
4796 std::pair<ValueInfo, GlobalValue::GUID>
4797 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
4798 auto VGI = ValueIdToValueInfoMap[ValueId];
4803 void ModuleSummaryIndexBitcodeReader::setValueGUID(
4804 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4805 StringRef SourceFileName) {
4806 std::string GlobalId =
4807 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4808 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4809 auto OriginalNameID = ValueGUID;
4810 if (GlobalValue::isLocalLinkage(Linkage))
4811 OriginalNameID = GlobalValue::getGUID(ValueName);
4812 if (PrintSummaryGUIDs)
4813 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4814 << ValueName << "\n";
4815 ValueIdToValueInfoMap[ValueID] =
4816 std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID);
4819 // Specialized value symbol table parser used when reading module index
4820 // blocks where we don't actually create global values. The parsed information
4821 // is saved in the bitcode reader for use when later parsing summaries.
4822 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
4824 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
4825 // With a strtab the VST is not required to parse the summary.
4827 return Error::success();
4829 assert(Offset > 0 && "Expected non-zero VST offset");
4830 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4832 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4833 return error("Invalid record");
4835 SmallVector<uint64_t, 64> Record;
4837 // Read all the records for this value table.
4838 SmallString<128> ValueName;
4841 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4843 switch (Entry.Kind) {
4844 case BitstreamEntry::SubBlock: // Handled for us already.
4845 case BitstreamEntry::Error:
4846 return error("Malformed block");
4847 case BitstreamEntry::EndBlock:
4848 // Done parsing VST, jump back to wherever we came from.
4849 Stream.JumpToBit(CurrentBit);
4850 return Error::success();
4851 case BitstreamEntry::Record:
4852 // The interesting case.
4858 switch (Stream.readRecord(Entry.ID, Record)) {
4859 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4861 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4862 if (convertToString(Record, 1, ValueName))
4863 return error("Invalid record");
4864 unsigned ValueID = Record[0];
4865 assert(!SourceFileName.empty());
4866 auto VLI = ValueIdToLinkageMap.find(ValueID);
4867 assert(VLI != ValueIdToLinkageMap.end() &&
4868 "No linkage found for VST entry?");
4869 auto Linkage = VLI->second;
4870 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4874 case bitc::VST_CODE_FNENTRY: {
4875 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
4876 if (convertToString(Record, 2, ValueName))
4877 return error("Invalid record");
4878 unsigned ValueID = Record[0];
4879 assert(!SourceFileName.empty());
4880 auto VLI = ValueIdToLinkageMap.find(ValueID);
4881 assert(VLI != ValueIdToLinkageMap.end() &&
4882 "No linkage found for VST entry?");
4883 auto Linkage = VLI->second;
4884 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4888 case bitc::VST_CODE_COMBINED_ENTRY: {
4889 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4890 unsigned ValueID = Record[0];
4891 GlobalValue::GUID RefGUID = Record[1];
4892 // The "original name", which is the second value of the pair will be
4893 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
4894 ValueIdToValueInfoMap[ValueID] =
4895 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
4902 // Parse just the blocks needed for building the index out of the module.
4903 // At the end of this routine the module Index is populated with a map
4904 // from global value id to GlobalValueSummary objects.
4905 Error ModuleSummaryIndexBitcodeReader::parseModule() {
4906 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4907 return error("Invalid record");
4909 SmallVector<uint64_t, 64> Record;
4910 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
4911 unsigned ValueId = 0;
4913 // Read the index for this module.
4915 BitstreamEntry Entry = Stream.advance();
4917 switch (Entry.Kind) {
4918 case BitstreamEntry::Error:
4919 return error("Malformed block");
4920 case BitstreamEntry::EndBlock:
4921 return Error::success();
4923 case BitstreamEntry::SubBlock:
4925 default: // Skip unknown content.
4926 if (Stream.SkipBlock())
4927 return error("Invalid record");
4929 case bitc::BLOCKINFO_BLOCK_ID:
4930 // Need to parse these to get abbrev ids (e.g. for VST)
4931 if (readBlockInfo())
4932 return error("Malformed block");
4934 case bitc::VALUE_SYMTAB_BLOCK_ID:
4935 // Should have been parsed earlier via VSTOffset, unless there
4936 // is no summary section.
4937 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4938 !SeenGlobalValSummary) &&
4939 "Expected early VST parse via VSTOffset record");
4940 if (Stream.SkipBlock())
4941 return error("Invalid record");
4943 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
4944 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
4945 assert(!SeenValueSymbolTable &&
4946 "Already read VST when parsing summary block?");
4947 // We might not have a VST if there were no values in the
4948 // summary. An empty summary block generated when we are
4949 // performing ThinLTO compiles so we don't later invoke
4950 // the regular LTO process on them.
4951 if (VSTOffset > 0) {
4952 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4954 SeenValueSymbolTable = true;
4956 SeenGlobalValSummary = true;
4957 if (Error Err = parseEntireSummary(Entry.ID))
4960 case bitc::MODULE_STRTAB_BLOCK_ID:
4961 if (Error Err = parseModuleStringTable())
4967 case BitstreamEntry::Record: {
4969 auto BitCode = Stream.readRecord(Entry.ID, Record);
4972 break; // Default behavior, ignore unknown content.
4973 case bitc::MODULE_CODE_VERSION: {
4974 if (Error Err = parseVersionRecord(Record).takeError())
4978 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4979 case bitc::MODULE_CODE_SOURCE_FILENAME: {
4980 SmallString<128> ValueName;
4981 if (convertToString(Record, 0, ValueName))
4982 return error("Invalid record");
4983 SourceFileName = ValueName.c_str();
4986 /// MODULE_CODE_HASH: [5*i32]
4987 case bitc::MODULE_CODE_HASH: {
4988 if (Record.size() != 5)
4989 return error("Invalid hash length " + Twine(Record.size()).str());
4990 auto &Hash = addThisModule()->second.second;
4992 for (auto &Val : Record) {
4993 assert(!(Val >> 32) && "Unexpected high bits set");
4998 /// MODULE_CODE_VSTOFFSET: [offset]
4999 case bitc::MODULE_CODE_VSTOFFSET:
5000 if (Record.size() < 1)
5001 return error("Invalid record");
5002 // Note that we subtract 1 here because the offset is relative to one
5003 // word before the start of the identification or module block, which
5004 // was historically always the start of the regular bitcode header.
5005 VSTOffset = Record[0] - 1;
5007 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
5008 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
5009 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
5010 // v2: [strtab offset, strtab size, v1]
5011 case bitc::MODULE_CODE_GLOBALVAR:
5012 case bitc::MODULE_CODE_FUNCTION:
5013 case bitc::MODULE_CODE_ALIAS: {
5015 ArrayRef<uint64_t> GVRecord;
5016 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5017 if (GVRecord.size() <= 3)
5018 return error("Invalid record");
5019 uint64_t RawLinkage = GVRecord[3];
5020 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5022 ValueIdToLinkageMap[ValueId++] = Linkage;
5026 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5036 std::vector<ValueInfo>
5037 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5038 std::vector<ValueInfo> Ret;
5039 Ret.reserve(Record.size());
5040 for (uint64_t RefValueId : Record)
5041 Ret.push_back(getValueInfoFromValueId(RefValueId).first);
5045 std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
5046 ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
5047 std::vector<FunctionSummary::EdgeTy> Ret;
5048 Ret.reserve(Record.size());
5049 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5050 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
5051 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
5052 if (IsOldProfileFormat) {
5053 I += 1; // Skip old callsitecount field
5055 I += 1; // Skip old profilecount field
5056 } else if (HasProfile)
5057 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
5058 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo{Hotness}});
5063 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
5064 // objects in the index.
5065 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5066 if (Stream.EnterSubBlock(ID))
5067 return error("Invalid record");
5068 SmallVector<uint64_t, 64> Record;
5072 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5073 if (Entry.Kind != BitstreamEntry::Record)
5074 return error("Invalid Summary Block: record for version expected");
5075 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
5076 return error("Invalid Summary Block: version expected");
5078 const uint64_t Version = Record[0];
5079 const bool IsOldProfileFormat = Version == 1;
5080 if (Version < 1 || Version > 4)
5081 return error("Invalid summary version " + Twine(Version) +
5082 ", 1, 2, 3 or 4 expected");
5085 // Keep around the last seen summary to be used when we see an optional
5086 // "OriginalName" attachement.
5087 GlobalValueSummary *LastSeenSummary = nullptr;
5088 GlobalValue::GUID LastSeenGUID = 0;
5090 // We can expect to see any number of type ID information records before
5091 // each function summary records; these variables store the information
5092 // collected so far so that it can be used to create the summary object.
5093 std::vector<GlobalValue::GUID> PendingTypeTests;
5094 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5095 PendingTypeCheckedLoadVCalls;
5096 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5097 PendingTypeCheckedLoadConstVCalls;
5100 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5102 switch (Entry.Kind) {
5103 case BitstreamEntry::SubBlock: // Handled for us already.
5104 case BitstreamEntry::Error:
5105 return error("Malformed block");
5106 case BitstreamEntry::EndBlock:
5107 return Error::success();
5108 case BitstreamEntry::Record:
5109 // The interesting case.
5113 // Read a record. The record format depends on whether this
5114 // is a per-module index or a combined index file. In the per-module
5115 // case the records contain the associated value's ID for correlation
5116 // with VST entries. In the combined index the correlation is done
5117 // via the bitcode offset of the summary records (which were saved
5118 // in the combined index VST entries). The records also contain
5119 // information used for ThinLTO renaming and importing.
5121 auto BitCode = Stream.readRecord(Entry.ID, Record);
5123 default: // Default behavior: ignore.
5125 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5126 uint64_t ValueID = Record[0];
5127 GlobalValue::GUID RefGUID = Record[1];
5128 ValueIdToValueInfoMap[ValueID] =
5129 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5132 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5133 // numrefs x valueid, n x (valueid)]
5134 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
5135 // numrefs x valueid,
5136 // n x (valueid, hotness)]
5137 case bitc::FS_PERMODULE:
5138 case bitc::FS_PERMODULE_PROFILE: {
5139 unsigned ValueID = Record[0];
5140 uint64_t RawFlags = Record[1];
5141 unsigned InstCount = Record[2];
5142 uint64_t RawFunFlags = 0;
5143 unsigned NumRefs = Record[3];
5144 int RefListStartIndex = 4;
5146 RawFunFlags = Record[3];
5147 NumRefs = Record[4];
5148 RefListStartIndex = 5;
5151 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5152 // The module path string ref set in the summary must be owned by the
5153 // index's module string table. Since we don't have a module path
5154 // string table section in the per-module index, we create a single
5155 // module path string table entry with an empty (0) ID to take
5157 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5158 assert(Record.size() >= RefListStartIndex + NumRefs &&
5159 "Record size inconsistent with number of references");
5160 std::vector<ValueInfo> Refs = makeRefList(
5161 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5162 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5163 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5164 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5165 IsOldProfileFormat, HasProfile);
5166 auto FS = llvm::make_unique<FunctionSummary>(
5167 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5168 std::move(Calls), std::move(PendingTypeTests),
5169 std::move(PendingTypeTestAssumeVCalls),
5170 std::move(PendingTypeCheckedLoadVCalls),
5171 std::move(PendingTypeTestAssumeConstVCalls),
5172 std::move(PendingTypeCheckedLoadConstVCalls));
5173 PendingTypeTests.clear();
5174 PendingTypeTestAssumeVCalls.clear();
5175 PendingTypeCheckedLoadVCalls.clear();
5176 PendingTypeTestAssumeConstVCalls.clear();
5177 PendingTypeCheckedLoadConstVCalls.clear();
5178 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
5179 FS->setModulePath(addThisModule()->first());
5180 FS->setOriginalName(VIAndOriginalGUID.second);
5181 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
5184 // FS_ALIAS: [valueid, flags, valueid]
5185 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5186 // they expect all aliasee summaries to be available.
5187 case bitc::FS_ALIAS: {
5188 unsigned ValueID = Record[0];
5189 uint64_t RawFlags = Record[1];
5190 unsigned AliaseeID = Record[2];
5191 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5192 auto AS = llvm::make_unique<AliasSummary>(Flags);
5193 // The module path string ref set in the summary must be owned by the
5194 // index's module string table. Since we don't have a module path
5195 // string table section in the per-module index, we create a single
5196 // module path string table entry with an empty (0) ID to take
5198 AS->setModulePath(addThisModule()->first());
5200 GlobalValue::GUID AliaseeGUID =
5201 getValueInfoFromValueId(AliaseeID).first.getGUID();
5202 auto AliaseeInModule =
5203 TheIndex.findSummaryInModule(AliaseeGUID, ModulePath);
5204 if (!AliaseeInModule)
5205 return error("Alias expects aliasee summary to be parsed");
5206 AS->setAliasee(AliaseeInModule);
5207 AS->setAliaseeGUID(AliaseeGUID);
5209 auto GUID = getValueInfoFromValueId(ValueID);
5210 AS->setOriginalName(GUID.second);
5211 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
5214 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
5215 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5216 unsigned ValueID = Record[0];
5217 uint64_t RawFlags = Record[1];
5218 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5219 std::vector<ValueInfo> Refs =
5220 makeRefList(ArrayRef<uint64_t>(Record).slice(2));
5221 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5222 FS->setModulePath(addThisModule()->first());
5223 auto GUID = getValueInfoFromValueId(ValueID);
5224 FS->setOriginalName(GUID.second);
5225 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
5228 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
5229 // numrefs x valueid, n x (valueid)]
5230 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
5231 // numrefs x valueid, n x (valueid, hotness)]
5232 case bitc::FS_COMBINED:
5233 case bitc::FS_COMBINED_PROFILE: {
5234 unsigned ValueID = Record[0];
5235 uint64_t ModuleId = Record[1];
5236 uint64_t RawFlags = Record[2];
5237 unsigned InstCount = Record[3];
5238 uint64_t RawFunFlags = 0;
5239 unsigned NumRefs = Record[4];
5240 int RefListStartIndex = 5;
5243 RawFunFlags = Record[4];
5244 NumRefs = Record[5];
5245 RefListStartIndex = 6;
5248 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5249 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5250 assert(Record.size() >= RefListStartIndex + NumRefs &&
5251 "Record size inconsistent with number of references");
5252 std::vector<ValueInfo> Refs = makeRefList(
5253 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5254 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5255 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5256 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5257 IsOldProfileFormat, HasProfile);
5258 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5259 auto FS = llvm::make_unique<FunctionSummary>(
5260 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5261 std::move(Edges), std::move(PendingTypeTests),
5262 std::move(PendingTypeTestAssumeVCalls),
5263 std::move(PendingTypeCheckedLoadVCalls),
5264 std::move(PendingTypeTestAssumeConstVCalls),
5265 std::move(PendingTypeCheckedLoadConstVCalls));
5266 PendingTypeTests.clear();
5267 PendingTypeTestAssumeVCalls.clear();
5268 PendingTypeCheckedLoadVCalls.clear();
5269 PendingTypeTestAssumeConstVCalls.clear();
5270 PendingTypeCheckedLoadConstVCalls.clear();
5271 LastSeenSummary = FS.get();
5272 LastSeenGUID = VI.getGUID();
5273 FS->setModulePath(ModuleIdMap[ModuleId]);
5274 TheIndex.addGlobalValueSummary(VI, std::move(FS));
5277 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
5278 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5279 // they expect all aliasee summaries to be available.
5280 case bitc::FS_COMBINED_ALIAS: {
5281 unsigned ValueID = Record[0];
5282 uint64_t ModuleId = Record[1];
5283 uint64_t RawFlags = Record[2];
5284 unsigned AliaseeValueId = Record[3];
5285 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5286 auto AS = llvm::make_unique<AliasSummary>(Flags);
5287 LastSeenSummary = AS.get();
5288 AS->setModulePath(ModuleIdMap[ModuleId]);
5291 getValueInfoFromValueId(AliaseeValueId).first.getGUID();
5292 auto AliaseeInModule =
5293 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
5294 AS->setAliasee(AliaseeInModule);
5295 AS->setAliaseeGUID(AliaseeGUID);
5297 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5298 LastSeenGUID = VI.getGUID();
5299 TheIndex.addGlobalValueSummary(VI, std::move(AS));
5302 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
5303 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5304 unsigned ValueID = Record[0];
5305 uint64_t ModuleId = Record[1];
5306 uint64_t RawFlags = Record[2];
5307 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5308 std::vector<ValueInfo> Refs =
5309 makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5310 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5311 LastSeenSummary = FS.get();
5312 FS->setModulePath(ModuleIdMap[ModuleId]);
5313 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5314 LastSeenGUID = VI.getGUID();
5315 TheIndex.addGlobalValueSummary(VI, std::move(FS));
5318 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5319 case bitc::FS_COMBINED_ORIGINAL_NAME: {
5320 uint64_t OriginalName = Record[0];
5321 if (!LastSeenSummary)
5322 return error("Name attachment that does not follow a combined record");
5323 LastSeenSummary->setOriginalName(OriginalName);
5324 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
5325 // Reset the LastSeenSummary
5326 LastSeenSummary = nullptr;
5330 case bitc::FS_TYPE_TESTS:
5331 assert(PendingTypeTests.empty());
5332 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5336 case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
5337 assert(PendingTypeTestAssumeVCalls.empty());
5338 for (unsigned I = 0; I != Record.size(); I += 2)
5339 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5342 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
5343 assert(PendingTypeCheckedLoadVCalls.empty());
5344 for (unsigned I = 0; I != Record.size(); I += 2)
5345 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5348 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
5349 PendingTypeTestAssumeConstVCalls.push_back(
5350 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5353 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
5354 PendingTypeCheckedLoadConstVCalls.push_back(
5355 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5358 case bitc::FS_CFI_FUNCTION_DEFS: {
5359 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
5360 for (unsigned I = 0; I != Record.size(); I += 2)
5361 CfiFunctionDefs.insert(
5362 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5365 case bitc::FS_CFI_FUNCTION_DECLS: {
5366 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
5367 for (unsigned I = 0; I != Record.size(); I += 2)
5368 CfiFunctionDecls.insert(
5369 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5374 llvm_unreachable("Exit infinite loop");
5377 // Parse the module string table block into the Index.
5378 // This populates the ModulePathStringTable map in the index.
5379 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5380 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5381 return error("Invalid record");
5383 SmallVector<uint64_t, 64> Record;
5385 SmallString<128> ModulePath;
5386 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
5389 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5391 switch (Entry.Kind) {
5392 case BitstreamEntry::SubBlock: // Handled for us already.
5393 case BitstreamEntry::Error:
5394 return error("Malformed block");
5395 case BitstreamEntry::EndBlock:
5396 return Error::success();
5397 case BitstreamEntry::Record:
5398 // The interesting case.
5403 switch (Stream.readRecord(Entry.ID, Record)) {
5404 default: // Default behavior: ignore.
5406 case bitc::MST_CODE_ENTRY: {
5407 // MST_ENTRY: [modid, namechar x N]
5408 uint64_t ModuleId = Record[0];
5410 if (convertToString(Record, 1, ModulePath))
5411 return error("Invalid record");
5413 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
5414 ModuleIdMap[ModuleId] = LastSeenModule->first();
5419 /// MST_CODE_HASH: [5*i32]
5420 case bitc::MST_CODE_HASH: {
5421 if (Record.size() != 5)
5422 return error("Invalid hash length " + Twine(Record.size()).str());
5423 if (!LastSeenModule)
5424 return error("Invalid hash that does not follow a module path");
5426 for (auto &Val : Record) {
5427 assert(!(Val >> 32) && "Unexpected high bits set");
5428 LastSeenModule->second.second[Pos++] = Val;
5430 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
5431 LastSeenModule = nullptr;
5436 llvm_unreachable("Exit infinite loop");
5441 // FIXME: This class is only here to support the transition to llvm::Error. It
5442 // will be removed once this transition is complete. Clients should prefer to
5443 // deal with the Error value directly, rather than converting to error_code.
5444 class BitcodeErrorCategoryType : public std::error_category {
5445 const char *name() const noexcept override {
5446 return "llvm.bitcode";
5449 std::string message(int IE) const override {
5450 BitcodeError E = static_cast<BitcodeError>(IE);
5452 case BitcodeError::CorruptedBitcode:
5453 return "Corrupted bitcode";
5455 llvm_unreachable("Unknown error type!");
5459 } // end anonymous namespace
5461 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5463 const std::error_category &llvm::BitcodeErrorCategory() {
5464 return *ErrorCategory;
5467 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
5468 unsigned Block, unsigned RecordID) {
5469 if (Stream.EnterSubBlock(Block))
5470 return error("Invalid record");
5474 BitstreamEntry Entry = Stream.advance();
5475 switch (Entry.Kind) {
5476 case BitstreamEntry::EndBlock:
5479 case BitstreamEntry::Error:
5480 return error("Malformed block");
5482 case BitstreamEntry::SubBlock:
5483 if (Stream.SkipBlock())
5484 return error("Malformed block");
5487 case BitstreamEntry::Record:
5489 SmallVector<uint64_t, 1> Record;
5490 if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
5497 //===----------------------------------------------------------------------===//
5498 // External interface
5499 //===----------------------------------------------------------------------===//
5501 Expected<std::vector<BitcodeModule>>
5502 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
5503 auto FOrErr = getBitcodeFileContents(Buffer);
5505 return FOrErr.takeError();
5506 return std::move(FOrErr->Mods);
5509 Expected<BitcodeFileContents>
5510 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
5511 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5513 return StreamOrErr.takeError();
5514 BitstreamCursor &Stream = *StreamOrErr;
5516 BitcodeFileContents F;
5518 uint64_t BCBegin = Stream.getCurrentByteNo();
5520 // We may be consuming bitcode from a client that leaves garbage at the end
5521 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5522 // the end that there cannot possibly be another module, stop looking.
5523 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
5526 BitstreamEntry Entry = Stream.advance();
5527 switch (Entry.Kind) {
5528 case BitstreamEntry::EndBlock:
5529 case BitstreamEntry::Error:
5530 return error("Malformed block");
5532 case BitstreamEntry::SubBlock: {
5533 uint64_t IdentificationBit = -1ull;
5534 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5535 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5536 if (Stream.SkipBlock())
5537 return error("Malformed block");
5539 Entry = Stream.advance();
5540 if (Entry.Kind != BitstreamEntry::SubBlock ||
5541 Entry.ID != bitc::MODULE_BLOCK_ID)
5542 return error("Malformed block");
5545 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5546 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5547 if (Stream.SkipBlock())
5548 return error("Malformed block");
5550 F.Mods.push_back({Stream.getBitcodeBytes().slice(
5551 BCBegin, Stream.getCurrentByteNo() - BCBegin),
5552 Buffer.getBufferIdentifier(), IdentificationBit,
5557 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
5558 Expected<StringRef> Strtab =
5559 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
5561 return Strtab.takeError();
5562 // This string table is used by every preceding bitcode module that does
5563 // not have its own string table. A bitcode file may have multiple
5564 // string tables if it was created by binary concatenation, for example
5565 // with "llvm-cat -b".
5566 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
5567 if (!I->Strtab.empty())
5569 I->Strtab = *Strtab;
5571 // Similarly, the string table is used by every preceding symbol table;
5572 // normally there will be just one unless the bitcode file was created
5573 // by binary concatenation.
5574 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
5575 F.StrtabForSymtab = *Strtab;
5579 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
5580 Expected<StringRef> SymtabOrErr =
5581 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
5583 return SymtabOrErr.takeError();
5585 // We can expect the bitcode file to have multiple symbol tables if it
5586 // was created by binary concatenation. In that case we silently
5587 // ignore any subsequent symbol tables, which is fine because this is a
5588 // low level function. The client is expected to notice that the number
5589 // of modules in the symbol table does not match the number of modules
5590 // in the input file and regenerate the symbol table.
5591 if (F.Symtab.empty())
5592 F.Symtab = *SymtabOrErr;
5596 if (Stream.SkipBlock())
5597 return error("Malformed block");
5600 case BitstreamEntry::Record:
5601 Stream.skipRecord(Entry.ID);
5607 /// \brief Get a lazy one-at-time loading module from bitcode.
5609 /// This isn't always used in a lazy context. In particular, it's also used by
5610 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
5611 /// in forward-referenced functions from block address references.
5613 /// \param[in] MaterializeAll Set to \c true if we should materialize
5615 Expected<std::unique_ptr<Module>>
5616 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
5617 bool ShouldLazyLoadMetadata, bool IsImporting) {
5618 BitstreamCursor Stream(Buffer);
5620 std::string ProducerIdentification;
5621 if (IdentificationBit != -1ull) {
5622 Stream.JumpToBit(IdentificationBit);
5623 Expected<std::string> ProducerIdentificationOrErr =
5624 readIdentificationBlock(Stream);
5625 if (!ProducerIdentificationOrErr)
5626 return ProducerIdentificationOrErr.takeError();
5628 ProducerIdentification = *ProducerIdentificationOrErr;
5631 Stream.JumpToBit(ModuleBit);
5632 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5635 std::unique_ptr<Module> M =
5636 llvm::make_unique<Module>(ModuleIdentifier, Context);
5637 M->setMaterializer(R);
5639 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5641 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5642 return std::move(Err);
5644 if (MaterializeAll) {
5645 // Read in the entire module, and destroy the BitcodeReader.
5646 if (Error Err = M->materializeAll())
5647 return std::move(Err);
5649 // Resolve forward references from blockaddresses.
5650 if (Error Err = R->materializeForwardReferencedFunctions())
5651 return std::move(Err);
5653 return std::move(M);
5656 Expected<std::unique_ptr<Module>>
5657 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5659 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
5662 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
5663 // We don't use ModuleIdentifier here because the client may need to control the
5664 // module path used in the combined summary (e.g. when reading summaries for
5665 // regular LTO modules).
5666 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
5667 StringRef ModulePath, uint64_t ModuleId) {
5668 BitstreamCursor Stream(Buffer);
5669 Stream.JumpToBit(ModuleBit);
5671 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
5672 ModulePath, ModuleId);
5673 return R.parseModule();
5676 // Parse the specified bitcode buffer, returning the function info index.
5677 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5678 BitstreamCursor Stream(Buffer);
5679 Stream.JumpToBit(ModuleBit);
5681 auto Index = llvm::make_unique<ModuleSummaryIndex>();
5682 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
5683 ModuleIdentifier, 0);
5685 if (Error Err = R.parseModule())
5686 return std::move(Err);
5688 return std::move(Index);
5691 // Check if the given bitcode buffer contains a global value summary block.
5692 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
5693 BitstreamCursor Stream(Buffer);
5694 Stream.JumpToBit(ModuleBit);
5696 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5697 return error("Invalid record");
5700 BitstreamEntry Entry = Stream.advance();
5702 switch (Entry.Kind) {
5703 case BitstreamEntry::Error:
5704 return error("Malformed block");
5705 case BitstreamEntry::EndBlock:
5706 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false};
5708 case BitstreamEntry::SubBlock:
5709 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
5710 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true};
5712 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID)
5713 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true};
5715 // Ignore other sub-blocks.
5716 if (Stream.SkipBlock())
5717 return error("Malformed block");
5720 case BitstreamEntry::Record:
5721 Stream.skipRecord(Entry.ID);
5727 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
5728 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5730 return MsOrErr.takeError();
5732 if (MsOrErr->size() != 1)
5733 return error("Expected a single module");
5735 return (*MsOrErr)[0];
5738 Expected<std::unique_ptr<Module>>
5739 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5740 bool ShouldLazyLoadMetadata, bool IsImporting) {
5741 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5743 return BM.takeError();
5745 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5748 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5749 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5750 bool ShouldLazyLoadMetadata, bool IsImporting) {
5751 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5754 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5758 Expected<std::unique_ptr<Module>>
5759 BitcodeModule::parseModule(LLVMContext &Context) {
5760 return getModuleImpl(Context, true, false, false);
5761 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5762 // written. We must defer until the Module has been fully materialized.
5765 Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5766 LLVMContext &Context) {
5767 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5769 return BM.takeError();
5771 return BM->parseModule(Context);
5774 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5775 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5777 return StreamOrErr.takeError();
5779 return readTriple(*StreamOrErr);
5782 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5783 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5785 return StreamOrErr.takeError();
5787 return hasObjCCategory(*StreamOrErr);
5790 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5791 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5793 return StreamOrErr.takeError();
5795 return readIdentificationCode(*StreamOrErr);
5798 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
5799 ModuleSummaryIndex &CombinedIndex,
5800 uint64_t ModuleId) {
5801 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5803 return BM.takeError();
5805 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
5808 Expected<std::unique_ptr<ModuleSummaryIndex>>
5809 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
5810 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5812 return BM.takeError();
5814 return BM->getSummary();
5817 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
5818 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5820 return BM.takeError();
5822 return BM->getLTOInfo();
5825 Expected<std::unique_ptr<ModuleSummaryIndex>>
5826 llvm::getModuleSummaryIndexForFile(StringRef Path,
5827 bool IgnoreEmptyThinLTOIndexFile) {
5828 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5829 MemoryBuffer::getFileOrSTDIN(Path);
5831 return errorCodeToError(FileOrErr.getError());
5832 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
5834 return getModuleSummaryIndex(**FileOrErr);