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 & FastMathFlags::AllowReassoc))
1050 FMF.setAllowReassoc();
1051 if (0 != (Val & FastMathFlags::NoNaNs))
1053 if (0 != (Val & FastMathFlags::NoInfs))
1055 if (0 != (Val & FastMathFlags::NoSignedZeros))
1056 FMF.setNoSignedZeros();
1057 if (0 != (Val & FastMathFlags::AllowReciprocal))
1058 FMF.setAllowReciprocal();
1059 if (0 != (Val & FastMathFlags::AllowContract))
1060 FMF.setAllowContract(true);
1061 if (0 != (Val & FastMathFlags::ApproxFunc))
1062 FMF.setApproxFunc();
1066 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1068 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1069 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1073 Type *BitcodeReader::getTypeByID(unsigned ID) {
1074 // The type table size is always specified correctly.
1075 if (ID >= TypeList.size())
1078 if (Type *Ty = TypeList[ID])
1081 // If we have a forward reference, the only possible case is when it is to a
1082 // named struct. Just create a placeholder for now.
1083 return TypeList[ID] = createIdentifiedStructType(Context);
1086 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1088 auto *Ret = StructType::create(Context, Name);
1089 IdentifiedStructTypes.push_back(Ret);
1093 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1094 auto *Ret = StructType::create(Context);
1095 IdentifiedStructTypes.push_back(Ret);
1099 //===----------------------------------------------------------------------===//
1100 // Functions for parsing blocks from the bitcode file
1101 //===----------------------------------------------------------------------===//
1103 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1105 case Attribute::EndAttrKinds:
1106 llvm_unreachable("Synthetic enumerators which should never get here");
1108 case Attribute::None: return 0;
1109 case Attribute::ZExt: return 1 << 0;
1110 case Attribute::SExt: return 1 << 1;
1111 case Attribute::NoReturn: return 1 << 2;
1112 case Attribute::InReg: return 1 << 3;
1113 case Attribute::StructRet: return 1 << 4;
1114 case Attribute::NoUnwind: return 1 << 5;
1115 case Attribute::NoAlias: return 1 << 6;
1116 case Attribute::ByVal: return 1 << 7;
1117 case Attribute::Nest: return 1 << 8;
1118 case Attribute::ReadNone: return 1 << 9;
1119 case Attribute::ReadOnly: return 1 << 10;
1120 case Attribute::NoInline: return 1 << 11;
1121 case Attribute::AlwaysInline: return 1 << 12;
1122 case Attribute::OptimizeForSize: return 1 << 13;
1123 case Attribute::StackProtect: return 1 << 14;
1124 case Attribute::StackProtectReq: return 1 << 15;
1125 case Attribute::Alignment: return 31 << 16;
1126 case Attribute::NoCapture: return 1 << 21;
1127 case Attribute::NoRedZone: return 1 << 22;
1128 case Attribute::NoImplicitFloat: return 1 << 23;
1129 case Attribute::Naked: return 1 << 24;
1130 case Attribute::InlineHint: return 1 << 25;
1131 case Attribute::StackAlignment: return 7 << 26;
1132 case Attribute::ReturnsTwice: return 1 << 29;
1133 case Attribute::UWTable: return 1 << 30;
1134 case Attribute::NonLazyBind: return 1U << 31;
1135 case Attribute::SanitizeAddress: return 1ULL << 32;
1136 case Attribute::MinSize: return 1ULL << 33;
1137 case Attribute::NoDuplicate: return 1ULL << 34;
1138 case Attribute::StackProtectStrong: return 1ULL << 35;
1139 case Attribute::SanitizeThread: return 1ULL << 36;
1140 case Attribute::SanitizeMemory: return 1ULL << 37;
1141 case Attribute::NoBuiltin: return 1ULL << 38;
1142 case Attribute::Returned: return 1ULL << 39;
1143 case Attribute::Cold: return 1ULL << 40;
1144 case Attribute::Builtin: return 1ULL << 41;
1145 case Attribute::OptimizeNone: return 1ULL << 42;
1146 case Attribute::InAlloca: return 1ULL << 43;
1147 case Attribute::NonNull: return 1ULL << 44;
1148 case Attribute::JumpTable: return 1ULL << 45;
1149 case Attribute::Convergent: return 1ULL << 46;
1150 case Attribute::SafeStack: return 1ULL << 47;
1151 case Attribute::NoRecurse: return 1ULL << 48;
1152 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1153 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1154 case Attribute::SwiftSelf: return 1ULL << 51;
1155 case Attribute::SwiftError: return 1ULL << 52;
1156 case Attribute::WriteOnly: return 1ULL << 53;
1157 case Attribute::Speculatable: return 1ULL << 54;
1158 case Attribute::StrictFP: return 1ULL << 55;
1159 case Attribute::SanitizeHWAddress: return 1ULL << 56;
1160 case Attribute::Dereferenceable:
1161 llvm_unreachable("dereferenceable attribute not supported in raw format");
1163 case Attribute::DereferenceableOrNull:
1164 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1167 case Attribute::ArgMemOnly:
1168 llvm_unreachable("argmemonly attribute not supported in raw format");
1170 case Attribute::AllocSize:
1171 llvm_unreachable("allocsize not supported in raw format");
1174 llvm_unreachable("Unsupported attribute type");
1177 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1180 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1181 I = Attribute::AttrKind(I + 1)) {
1182 if (I == Attribute::Dereferenceable ||
1183 I == Attribute::DereferenceableOrNull ||
1184 I == Attribute::ArgMemOnly ||
1185 I == Attribute::AllocSize)
1187 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1188 if (I == Attribute::Alignment)
1189 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1190 else if (I == Attribute::StackAlignment)
1191 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1198 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1199 /// been decoded from the given integer. This function must stay in sync with
1200 /// 'encodeLLVMAttributesForBitcode'.
1201 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1202 uint64_t EncodedAttrs) {
1203 // FIXME: Remove in 4.0.
1205 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1206 // the bits above 31 down by 11 bits.
1207 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1208 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1209 "Alignment must be a power of two.");
1212 B.addAlignmentAttr(Alignment);
1213 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1214 (EncodedAttrs & 0xffff));
1217 Error BitcodeReader::parseAttributeBlock() {
1218 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1219 return error("Invalid record");
1221 if (!MAttributes.empty())
1222 return error("Invalid multiple blocks");
1224 SmallVector<uint64_t, 64> Record;
1226 SmallVector<AttributeList, 8> Attrs;
1228 // Read all the records.
1230 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1232 switch (Entry.Kind) {
1233 case BitstreamEntry::SubBlock: // Handled for us already.
1234 case BitstreamEntry::Error:
1235 return error("Malformed block");
1236 case BitstreamEntry::EndBlock:
1237 return Error::success();
1238 case BitstreamEntry::Record:
1239 // The interesting case.
1245 switch (Stream.readRecord(Entry.ID, Record)) {
1246 default: // Default behavior: ignore.
1248 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1249 // FIXME: Remove in 4.0.
1250 if (Record.size() & 1)
1251 return error("Invalid record");
1253 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1255 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1256 Attrs.push_back(AttributeList::get(Context, Record[i], B));
1259 MAttributes.push_back(AttributeList::get(Context, Attrs));
1262 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1263 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1264 Attrs.push_back(MAttributeGroups[Record[i]]);
1266 MAttributes.push_back(AttributeList::get(Context, Attrs));
1273 // Returns Attribute::None on unrecognized codes.
1274 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1277 return Attribute::None;
1278 case bitc::ATTR_KIND_ALIGNMENT:
1279 return Attribute::Alignment;
1280 case bitc::ATTR_KIND_ALWAYS_INLINE:
1281 return Attribute::AlwaysInline;
1282 case bitc::ATTR_KIND_ARGMEMONLY:
1283 return Attribute::ArgMemOnly;
1284 case bitc::ATTR_KIND_BUILTIN:
1285 return Attribute::Builtin;
1286 case bitc::ATTR_KIND_BY_VAL:
1287 return Attribute::ByVal;
1288 case bitc::ATTR_KIND_IN_ALLOCA:
1289 return Attribute::InAlloca;
1290 case bitc::ATTR_KIND_COLD:
1291 return Attribute::Cold;
1292 case bitc::ATTR_KIND_CONVERGENT:
1293 return Attribute::Convergent;
1294 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1295 return Attribute::InaccessibleMemOnly;
1296 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1297 return Attribute::InaccessibleMemOrArgMemOnly;
1298 case bitc::ATTR_KIND_INLINE_HINT:
1299 return Attribute::InlineHint;
1300 case bitc::ATTR_KIND_IN_REG:
1301 return Attribute::InReg;
1302 case bitc::ATTR_KIND_JUMP_TABLE:
1303 return Attribute::JumpTable;
1304 case bitc::ATTR_KIND_MIN_SIZE:
1305 return Attribute::MinSize;
1306 case bitc::ATTR_KIND_NAKED:
1307 return Attribute::Naked;
1308 case bitc::ATTR_KIND_NEST:
1309 return Attribute::Nest;
1310 case bitc::ATTR_KIND_NO_ALIAS:
1311 return Attribute::NoAlias;
1312 case bitc::ATTR_KIND_NO_BUILTIN:
1313 return Attribute::NoBuiltin;
1314 case bitc::ATTR_KIND_NO_CAPTURE:
1315 return Attribute::NoCapture;
1316 case bitc::ATTR_KIND_NO_DUPLICATE:
1317 return Attribute::NoDuplicate;
1318 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1319 return Attribute::NoImplicitFloat;
1320 case bitc::ATTR_KIND_NO_INLINE:
1321 return Attribute::NoInline;
1322 case bitc::ATTR_KIND_NO_RECURSE:
1323 return Attribute::NoRecurse;
1324 case bitc::ATTR_KIND_NON_LAZY_BIND:
1325 return Attribute::NonLazyBind;
1326 case bitc::ATTR_KIND_NON_NULL:
1327 return Attribute::NonNull;
1328 case bitc::ATTR_KIND_DEREFERENCEABLE:
1329 return Attribute::Dereferenceable;
1330 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1331 return Attribute::DereferenceableOrNull;
1332 case bitc::ATTR_KIND_ALLOC_SIZE:
1333 return Attribute::AllocSize;
1334 case bitc::ATTR_KIND_NO_RED_ZONE:
1335 return Attribute::NoRedZone;
1336 case bitc::ATTR_KIND_NO_RETURN:
1337 return Attribute::NoReturn;
1338 case bitc::ATTR_KIND_NO_UNWIND:
1339 return Attribute::NoUnwind;
1340 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1341 return Attribute::OptimizeForSize;
1342 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1343 return Attribute::OptimizeNone;
1344 case bitc::ATTR_KIND_READ_NONE:
1345 return Attribute::ReadNone;
1346 case bitc::ATTR_KIND_READ_ONLY:
1347 return Attribute::ReadOnly;
1348 case bitc::ATTR_KIND_RETURNED:
1349 return Attribute::Returned;
1350 case bitc::ATTR_KIND_RETURNS_TWICE:
1351 return Attribute::ReturnsTwice;
1352 case bitc::ATTR_KIND_S_EXT:
1353 return Attribute::SExt;
1354 case bitc::ATTR_KIND_SPECULATABLE:
1355 return Attribute::Speculatable;
1356 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1357 return Attribute::StackAlignment;
1358 case bitc::ATTR_KIND_STACK_PROTECT:
1359 return Attribute::StackProtect;
1360 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1361 return Attribute::StackProtectReq;
1362 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1363 return Attribute::StackProtectStrong;
1364 case bitc::ATTR_KIND_SAFESTACK:
1365 return Attribute::SafeStack;
1366 case bitc::ATTR_KIND_STRICT_FP:
1367 return Attribute::StrictFP;
1368 case bitc::ATTR_KIND_STRUCT_RET:
1369 return Attribute::StructRet;
1370 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1371 return Attribute::SanitizeAddress;
1372 case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1373 return Attribute::SanitizeHWAddress;
1374 case bitc::ATTR_KIND_SANITIZE_THREAD:
1375 return Attribute::SanitizeThread;
1376 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1377 return Attribute::SanitizeMemory;
1378 case bitc::ATTR_KIND_SWIFT_ERROR:
1379 return Attribute::SwiftError;
1380 case bitc::ATTR_KIND_SWIFT_SELF:
1381 return Attribute::SwiftSelf;
1382 case bitc::ATTR_KIND_UW_TABLE:
1383 return Attribute::UWTable;
1384 case bitc::ATTR_KIND_WRITEONLY:
1385 return Attribute::WriteOnly;
1386 case bitc::ATTR_KIND_Z_EXT:
1387 return Attribute::ZExt;
1391 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1392 unsigned &Alignment) {
1393 // Note: Alignment in bitcode files is incremented by 1, so that zero
1394 // can be used for default alignment.
1395 if (Exponent > Value::MaxAlignmentExponent + 1)
1396 return error("Invalid alignment value");
1397 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1398 return Error::success();
1401 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1402 *Kind = getAttrFromCode(Code);
1403 if (*Kind == Attribute::None)
1404 return error("Unknown attribute kind (" + Twine(Code) + ")");
1405 return Error::success();
1408 Error BitcodeReader::parseAttributeGroupBlock() {
1409 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1410 return error("Invalid record");
1412 if (!MAttributeGroups.empty())
1413 return error("Invalid multiple blocks");
1415 SmallVector<uint64_t, 64> Record;
1417 // Read all the records.
1419 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1421 switch (Entry.Kind) {
1422 case BitstreamEntry::SubBlock: // Handled for us already.
1423 case BitstreamEntry::Error:
1424 return error("Malformed block");
1425 case BitstreamEntry::EndBlock:
1426 return Error::success();
1427 case BitstreamEntry::Record:
1428 // The interesting case.
1434 switch (Stream.readRecord(Entry.ID, Record)) {
1435 default: // Default behavior: ignore.
1437 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1438 if (Record.size() < 3)
1439 return error("Invalid record");
1441 uint64_t GrpID = Record[0];
1442 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1445 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1446 if (Record[i] == 0) { // Enum attribute
1447 Attribute::AttrKind Kind;
1448 if (Error Err = parseAttrKind(Record[++i], &Kind))
1451 B.addAttribute(Kind);
1452 } else if (Record[i] == 1) { // Integer attribute
1453 Attribute::AttrKind Kind;
1454 if (Error Err = parseAttrKind(Record[++i], &Kind))
1456 if (Kind == Attribute::Alignment)
1457 B.addAlignmentAttr(Record[++i]);
1458 else if (Kind == Attribute::StackAlignment)
1459 B.addStackAlignmentAttr(Record[++i]);
1460 else if (Kind == Attribute::Dereferenceable)
1461 B.addDereferenceableAttr(Record[++i]);
1462 else if (Kind == Attribute::DereferenceableOrNull)
1463 B.addDereferenceableOrNullAttr(Record[++i]);
1464 else if (Kind == Attribute::AllocSize)
1465 B.addAllocSizeAttrFromRawRepr(Record[++i]);
1466 } else { // String attribute
1467 assert((Record[i] == 3 || Record[i] == 4) &&
1468 "Invalid attribute group entry");
1469 bool HasValue = (Record[i++] == 4);
1470 SmallString<64> KindStr;
1471 SmallString<64> ValStr;
1473 while (Record[i] != 0 && i != e)
1474 KindStr += Record[i++];
1475 assert(Record[i] == 0 && "Kind string not null terminated");
1478 // Has a value associated with it.
1479 ++i; // Skip the '0' that terminates the "kind" string.
1480 while (Record[i] != 0 && i != e)
1481 ValStr += Record[i++];
1482 assert(Record[i] == 0 && "Value string not null terminated");
1485 B.addAttribute(KindStr.str(), ValStr.str());
1489 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1496 Error BitcodeReader::parseTypeTable() {
1497 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1498 return error("Invalid record");
1500 return parseTypeTableBody();
1503 Error BitcodeReader::parseTypeTableBody() {
1504 if (!TypeList.empty())
1505 return error("Invalid multiple blocks");
1507 SmallVector<uint64_t, 64> Record;
1508 unsigned NumRecords = 0;
1510 SmallString<64> TypeName;
1512 // Read all the records for this type table.
1514 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1516 switch (Entry.Kind) {
1517 case BitstreamEntry::SubBlock: // Handled for us already.
1518 case BitstreamEntry::Error:
1519 return error("Malformed block");
1520 case BitstreamEntry::EndBlock:
1521 if (NumRecords != TypeList.size())
1522 return error("Malformed block");
1523 return Error::success();
1524 case BitstreamEntry::Record:
1525 // The interesting case.
1531 Type *ResultTy = nullptr;
1532 switch (Stream.readRecord(Entry.ID, Record)) {
1534 return error("Invalid value");
1535 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1536 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1537 // type list. This allows us to reserve space.
1538 if (Record.size() < 1)
1539 return error("Invalid record");
1540 TypeList.resize(Record[0]);
1542 case bitc::TYPE_CODE_VOID: // VOID
1543 ResultTy = Type::getVoidTy(Context);
1545 case bitc::TYPE_CODE_HALF: // HALF
1546 ResultTy = Type::getHalfTy(Context);
1548 case bitc::TYPE_CODE_FLOAT: // FLOAT
1549 ResultTy = Type::getFloatTy(Context);
1551 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1552 ResultTy = Type::getDoubleTy(Context);
1554 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1555 ResultTy = Type::getX86_FP80Ty(Context);
1557 case bitc::TYPE_CODE_FP128: // FP128
1558 ResultTy = Type::getFP128Ty(Context);
1560 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1561 ResultTy = Type::getPPC_FP128Ty(Context);
1563 case bitc::TYPE_CODE_LABEL: // LABEL
1564 ResultTy = Type::getLabelTy(Context);
1566 case bitc::TYPE_CODE_METADATA: // METADATA
1567 ResultTy = Type::getMetadataTy(Context);
1569 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1570 ResultTy = Type::getX86_MMXTy(Context);
1572 case bitc::TYPE_CODE_TOKEN: // TOKEN
1573 ResultTy = Type::getTokenTy(Context);
1575 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1576 if (Record.size() < 1)
1577 return error("Invalid record");
1579 uint64_t NumBits = Record[0];
1580 if (NumBits < IntegerType::MIN_INT_BITS ||
1581 NumBits > IntegerType::MAX_INT_BITS)
1582 return error("Bitwidth for integer type out of range");
1583 ResultTy = IntegerType::get(Context, NumBits);
1586 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1587 // [pointee type, address space]
1588 if (Record.size() < 1)
1589 return error("Invalid record");
1590 unsigned AddressSpace = 0;
1591 if (Record.size() == 2)
1592 AddressSpace = Record[1];
1593 ResultTy = getTypeByID(Record[0]);
1595 !PointerType::isValidElementType(ResultTy))
1596 return error("Invalid type");
1597 ResultTy = PointerType::get(ResultTy, AddressSpace);
1600 case bitc::TYPE_CODE_FUNCTION_OLD: {
1601 // FIXME: attrid is dead, remove it in LLVM 4.0
1602 // FUNCTION: [vararg, attrid, retty, paramty x N]
1603 if (Record.size() < 3)
1604 return error("Invalid record");
1605 SmallVector<Type*, 8> ArgTys;
1606 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1607 if (Type *T = getTypeByID(Record[i]))
1608 ArgTys.push_back(T);
1613 ResultTy = getTypeByID(Record[2]);
1614 if (!ResultTy || ArgTys.size() < Record.size()-3)
1615 return error("Invalid type");
1617 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1620 case bitc::TYPE_CODE_FUNCTION: {
1621 // FUNCTION: [vararg, retty, paramty x N]
1622 if (Record.size() < 2)
1623 return error("Invalid record");
1624 SmallVector<Type*, 8> ArgTys;
1625 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1626 if (Type *T = getTypeByID(Record[i])) {
1627 if (!FunctionType::isValidArgumentType(T))
1628 return error("Invalid function argument type");
1629 ArgTys.push_back(T);
1635 ResultTy = getTypeByID(Record[1]);
1636 if (!ResultTy || ArgTys.size() < Record.size()-2)
1637 return error("Invalid type");
1639 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1642 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1643 if (Record.size() < 1)
1644 return error("Invalid record");
1645 SmallVector<Type*, 8> EltTys;
1646 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1647 if (Type *T = getTypeByID(Record[i]))
1648 EltTys.push_back(T);
1652 if (EltTys.size() != Record.size()-1)
1653 return error("Invalid type");
1654 ResultTy = StructType::get(Context, EltTys, Record[0]);
1657 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1658 if (convertToString(Record, 0, TypeName))
1659 return error("Invalid record");
1662 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1663 if (Record.size() < 1)
1664 return error("Invalid record");
1666 if (NumRecords >= TypeList.size())
1667 return error("Invalid TYPE table");
1669 // Check to see if this was forward referenced, if so fill in the temp.
1670 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1672 Res->setName(TypeName);
1673 TypeList[NumRecords] = nullptr;
1674 } else // Otherwise, create a new struct.
1675 Res = createIdentifiedStructType(Context, TypeName);
1678 SmallVector<Type*, 8> EltTys;
1679 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1680 if (Type *T = getTypeByID(Record[i]))
1681 EltTys.push_back(T);
1685 if (EltTys.size() != Record.size()-1)
1686 return error("Invalid record");
1687 Res->setBody(EltTys, Record[0]);
1691 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1692 if (Record.size() != 1)
1693 return error("Invalid record");
1695 if (NumRecords >= TypeList.size())
1696 return error("Invalid TYPE table");
1698 // Check to see if this was forward referenced, if so fill in the temp.
1699 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1701 Res->setName(TypeName);
1702 TypeList[NumRecords] = nullptr;
1703 } else // Otherwise, create a new struct with no body.
1704 Res = createIdentifiedStructType(Context, TypeName);
1709 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1710 if (Record.size() < 2)
1711 return error("Invalid record");
1712 ResultTy = getTypeByID(Record[1]);
1713 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1714 return error("Invalid type");
1715 ResultTy = ArrayType::get(ResultTy, Record[0]);
1717 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1718 if (Record.size() < 2)
1719 return error("Invalid record");
1721 return error("Invalid vector length");
1722 ResultTy = getTypeByID(Record[1]);
1723 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1724 return error("Invalid type");
1725 ResultTy = VectorType::get(ResultTy, Record[0]);
1729 if (NumRecords >= TypeList.size())
1730 return error("Invalid TYPE table");
1731 if (TypeList[NumRecords])
1733 "Invalid TYPE table: Only named structs can be forward referenced");
1734 assert(ResultTy && "Didn't read a type?");
1735 TypeList[NumRecords++] = ResultTy;
1739 Error BitcodeReader::parseOperandBundleTags() {
1740 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1741 return error("Invalid record");
1743 if (!BundleTags.empty())
1744 return error("Invalid multiple blocks");
1746 SmallVector<uint64_t, 64> Record;
1749 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1751 switch (Entry.Kind) {
1752 case BitstreamEntry::SubBlock: // Handled for us already.
1753 case BitstreamEntry::Error:
1754 return error("Malformed block");
1755 case BitstreamEntry::EndBlock:
1756 return Error::success();
1757 case BitstreamEntry::Record:
1758 // The interesting case.
1762 // Tags are implicitly mapped to integers by their order.
1764 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1765 return error("Invalid record");
1767 // OPERAND_BUNDLE_TAG: [strchr x N]
1768 BundleTags.emplace_back();
1769 if (convertToString(Record, 0, BundleTags.back()))
1770 return error("Invalid record");
1775 Error BitcodeReader::parseSyncScopeNames() {
1776 if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1777 return error("Invalid record");
1780 return error("Invalid multiple synchronization scope names blocks");
1782 SmallVector<uint64_t, 64> Record;
1784 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1785 switch (Entry.Kind) {
1786 case BitstreamEntry::SubBlock: // Handled for us already.
1787 case BitstreamEntry::Error:
1788 return error("Malformed block");
1789 case BitstreamEntry::EndBlock:
1791 return error("Invalid empty synchronization scope names block");
1792 return Error::success();
1793 case BitstreamEntry::Record:
1794 // The interesting case.
1798 // Synchronization scope names are implicitly mapped to synchronization
1799 // scope IDs by their order.
1801 if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1802 return error("Invalid record");
1804 SmallString<16> SSN;
1805 if (convertToString(Record, 0, SSN))
1806 return error("Invalid record");
1808 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1813 /// Associate a value with its name from the given index in the provided record.
1814 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1815 unsigned NameIndex, Triple &TT) {
1816 SmallString<128> ValueName;
1817 if (convertToString(Record, NameIndex, ValueName))
1818 return error("Invalid record");
1819 unsigned ValueID = Record[0];
1820 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1821 return error("Invalid record");
1822 Value *V = ValueList[ValueID];
1824 StringRef NameStr(ValueName.data(), ValueName.size());
1825 if (NameStr.find_first_of(0) != StringRef::npos)
1826 return error("Invalid value name");
1827 V->setName(NameStr);
1828 auto *GO = dyn_cast<GlobalObject>(V);
1830 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1831 if (TT.supportsCOMDAT())
1832 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1834 GO->setComdat(nullptr);
1840 /// Helper to note and return the current location, and jump to the given
1842 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1843 BitstreamCursor &Stream) {
1844 // Save the current parsing location so we can jump back at the end
1846 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1847 Stream.JumpToBit(Offset * 32);
1849 // Do some checking if we are in debug mode.
1850 BitstreamEntry Entry = Stream.advance();
1851 assert(Entry.Kind == BitstreamEntry::SubBlock);
1852 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1854 // In NDEBUG mode ignore the output so we don't get an unused variable
1861 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1863 ArrayRef<uint64_t> Record) {
1864 // Note that we subtract 1 here because the offset is relative to one word
1865 // before the start of the identification or module block, which was
1866 // historically always the start of the regular bitcode header.
1867 uint64_t FuncWordOffset = Record[1] - 1;
1868 uint64_t FuncBitOffset = FuncWordOffset * 32;
1869 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1870 // Set the LastFunctionBlockBit to point to the last function block.
1871 // Later when parsing is resumed after function materialization,
1872 // we can simply skip that last function block.
1873 if (FuncBitOffset > LastFunctionBlockBit)
1874 LastFunctionBlockBit = FuncBitOffset;
1877 /// Read a new-style GlobalValue symbol table.
1878 Error BitcodeReader::parseGlobalValueSymbolTable() {
1879 unsigned FuncBitcodeOffsetDelta =
1880 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1882 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1883 return error("Invalid record");
1885 SmallVector<uint64_t, 64> Record;
1887 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1889 switch (Entry.Kind) {
1890 case BitstreamEntry::SubBlock:
1891 case BitstreamEntry::Error:
1892 return error("Malformed block");
1893 case BitstreamEntry::EndBlock:
1894 return Error::success();
1895 case BitstreamEntry::Record:
1900 switch (Stream.readRecord(Entry.ID, Record)) {
1901 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1902 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1903 cast<Function>(ValueList[Record[0]]), Record);
1909 /// Parse the value symbol table at either the current parsing location or
1910 /// at the given bit offset if provided.
1911 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1912 uint64_t CurrentBit;
1913 // Pass in the Offset to distinguish between calling for the module-level
1914 // VST (where we want to jump to the VST offset) and the function-level
1915 // VST (where we don't).
1917 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
1918 // If this module uses a string table, read this as a module-level VST.
1920 if (Error Err = parseGlobalValueSymbolTable())
1922 Stream.JumpToBit(CurrentBit);
1923 return Error::success();
1925 // Otherwise, the VST will be in a similar format to a function-level VST,
1926 // and will contain symbol names.
1929 // Compute the delta between the bitcode indices in the VST (the word offset
1930 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1931 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1932 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1933 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1934 // just before entering the VST subblock because: 1) the EnterSubBlock
1935 // changes the AbbrevID width; 2) the VST block is nested within the same
1936 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1937 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1938 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1939 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1940 unsigned FuncBitcodeOffsetDelta =
1941 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1943 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1944 return error("Invalid record");
1946 SmallVector<uint64_t, 64> Record;
1948 Triple TT(TheModule->getTargetTriple());
1950 // Read all the records for this value table.
1951 SmallString<128> ValueName;
1954 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1956 switch (Entry.Kind) {
1957 case BitstreamEntry::SubBlock: // Handled for us already.
1958 case BitstreamEntry::Error:
1959 return error("Malformed block");
1960 case BitstreamEntry::EndBlock:
1962 Stream.JumpToBit(CurrentBit);
1963 return Error::success();
1964 case BitstreamEntry::Record:
1965 // The interesting case.
1971 switch (Stream.readRecord(Entry.ID, Record)) {
1972 default: // Default behavior: unknown type.
1974 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
1975 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1976 if (Error Err = ValOrErr.takeError())
1981 case bitc::VST_CODE_FNENTRY: {
1982 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
1983 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1984 if (Error Err = ValOrErr.takeError())
1986 Value *V = ValOrErr.get();
1988 // Ignore function offsets emitted for aliases of functions in older
1989 // versions of LLVM.
1990 if (auto *F = dyn_cast<Function>(V))
1991 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
1994 case bitc::VST_CODE_BBENTRY: {
1995 if (convertToString(Record, 1, ValueName))
1996 return error("Invalid record");
1997 BasicBlock *BB = getBasicBlock(Record[0]);
1999 return error("Invalid record");
2001 BB->setName(StringRef(ValueName.data(), ValueName.size()));
2009 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2011 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2016 // There is no such thing as -0 with integers. "-0" really means MININT.
2020 /// Resolve all of the initializers for global values and aliases that we can.
2021 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2022 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2023 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2024 IndirectSymbolInitWorklist;
2025 std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2026 std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2027 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2029 GlobalInitWorklist.swap(GlobalInits);
2030 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2031 FunctionPrefixWorklist.swap(FunctionPrefixes);
2032 FunctionPrologueWorklist.swap(FunctionPrologues);
2033 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2035 while (!GlobalInitWorklist.empty()) {
2036 unsigned ValID = GlobalInitWorklist.back().second;
2037 if (ValID >= ValueList.size()) {
2038 // Not ready to resolve this yet, it requires something later in the file.
2039 GlobalInits.push_back(GlobalInitWorklist.back());
2041 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2042 GlobalInitWorklist.back().first->setInitializer(C);
2044 return error("Expected a constant");
2046 GlobalInitWorklist.pop_back();
2049 while (!IndirectSymbolInitWorklist.empty()) {
2050 unsigned ValID = IndirectSymbolInitWorklist.back().second;
2051 if (ValID >= ValueList.size()) {
2052 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2054 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2056 return error("Expected a constant");
2057 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2058 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2059 return error("Alias and aliasee types don't match");
2060 GIS->setIndirectSymbol(C);
2062 IndirectSymbolInitWorklist.pop_back();
2065 while (!FunctionPrefixWorklist.empty()) {
2066 unsigned ValID = FunctionPrefixWorklist.back().second;
2067 if (ValID >= ValueList.size()) {
2068 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2070 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2071 FunctionPrefixWorklist.back().first->setPrefixData(C);
2073 return error("Expected a constant");
2075 FunctionPrefixWorklist.pop_back();
2078 while (!FunctionPrologueWorklist.empty()) {
2079 unsigned ValID = FunctionPrologueWorklist.back().second;
2080 if (ValID >= ValueList.size()) {
2081 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2083 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2084 FunctionPrologueWorklist.back().first->setPrologueData(C);
2086 return error("Expected a constant");
2088 FunctionPrologueWorklist.pop_back();
2091 while (!FunctionPersonalityFnWorklist.empty()) {
2092 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2093 if (ValID >= ValueList.size()) {
2094 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2096 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2097 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2099 return error("Expected a constant");
2101 FunctionPersonalityFnWorklist.pop_back();
2104 return Error::success();
2107 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2108 SmallVector<uint64_t, 8> Words(Vals.size());
2109 transform(Vals, Words.begin(),
2110 BitcodeReader::decodeSignRotatedValue);
2112 return APInt(TypeBits, Words);
2115 Error BitcodeReader::parseConstants() {
2116 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2117 return error("Invalid record");
2119 SmallVector<uint64_t, 64> Record;
2121 // Read all the records for this value table.
2122 Type *CurTy = Type::getInt32Ty(Context);
2123 unsigned NextCstNo = ValueList.size();
2126 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2128 switch (Entry.Kind) {
2129 case BitstreamEntry::SubBlock: // Handled for us already.
2130 case BitstreamEntry::Error:
2131 return error("Malformed block");
2132 case BitstreamEntry::EndBlock:
2133 if (NextCstNo != ValueList.size())
2134 return error("Invalid constant reference");
2136 // Once all the constants have been read, go through and resolve forward
2138 ValueList.resolveConstantForwardRefs();
2139 return Error::success();
2140 case BitstreamEntry::Record:
2141 // The interesting case.
2147 Type *VoidType = Type::getVoidTy(Context);
2149 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2151 default: // Default behavior: unknown constant
2152 case bitc::CST_CODE_UNDEF: // UNDEF
2153 V = UndefValue::get(CurTy);
2155 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2157 return error("Invalid record");
2158 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2159 return error("Invalid record");
2160 if (TypeList[Record[0]] == VoidType)
2161 return error("Invalid constant type");
2162 CurTy = TypeList[Record[0]];
2163 continue; // Skip the ValueList manipulation.
2164 case bitc::CST_CODE_NULL: // NULL
2165 V = Constant::getNullValue(CurTy);
2167 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2168 if (!CurTy->isIntegerTy() || Record.empty())
2169 return error("Invalid record");
2170 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2172 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2173 if (!CurTy->isIntegerTy() || Record.empty())
2174 return error("Invalid record");
2177 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2178 V = ConstantInt::get(Context, VInt);
2182 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2184 return error("Invalid record");
2185 if (CurTy->isHalfTy())
2186 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2187 APInt(16, (uint16_t)Record[0])));
2188 else if (CurTy->isFloatTy())
2189 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2190 APInt(32, (uint32_t)Record[0])));
2191 else if (CurTy->isDoubleTy())
2192 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2193 APInt(64, Record[0])));
2194 else if (CurTy->isX86_FP80Ty()) {
2195 // Bits are not stored the same way as a normal i80 APInt, compensate.
2196 uint64_t Rearrange[2];
2197 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2198 Rearrange[1] = Record[0] >> 48;
2199 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2200 APInt(80, Rearrange)));
2201 } else if (CurTy->isFP128Ty())
2202 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2203 APInt(128, Record)));
2204 else if (CurTy->isPPC_FP128Ty())
2205 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2206 APInt(128, Record)));
2208 V = UndefValue::get(CurTy);
2212 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2214 return error("Invalid record");
2216 unsigned Size = Record.size();
2217 SmallVector<Constant*, 16> Elts;
2219 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2220 for (unsigned i = 0; i != Size; ++i)
2221 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2222 STy->getElementType(i)));
2223 V = ConstantStruct::get(STy, Elts);
2224 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2225 Type *EltTy = ATy->getElementType();
2226 for (unsigned i = 0; i != Size; ++i)
2227 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2228 V = ConstantArray::get(ATy, Elts);
2229 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2230 Type *EltTy = VTy->getElementType();
2231 for (unsigned i = 0; i != Size; ++i)
2232 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2233 V = ConstantVector::get(Elts);
2235 V = UndefValue::get(CurTy);
2239 case bitc::CST_CODE_STRING: // STRING: [values]
2240 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2242 return error("Invalid record");
2244 SmallString<16> Elts(Record.begin(), Record.end());
2245 V = ConstantDataArray::getString(Context, Elts,
2246 BitCode == bitc::CST_CODE_CSTRING);
2249 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2251 return error("Invalid record");
2253 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2254 if (EltTy->isIntegerTy(8)) {
2255 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2256 if (isa<VectorType>(CurTy))
2257 V = ConstantDataVector::get(Context, Elts);
2259 V = ConstantDataArray::get(Context, Elts);
2260 } else if (EltTy->isIntegerTy(16)) {
2261 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2262 if (isa<VectorType>(CurTy))
2263 V = ConstantDataVector::get(Context, Elts);
2265 V = ConstantDataArray::get(Context, Elts);
2266 } else if (EltTy->isIntegerTy(32)) {
2267 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2268 if (isa<VectorType>(CurTy))
2269 V = ConstantDataVector::get(Context, Elts);
2271 V = ConstantDataArray::get(Context, Elts);
2272 } else if (EltTy->isIntegerTy(64)) {
2273 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2274 if (isa<VectorType>(CurTy))
2275 V = ConstantDataVector::get(Context, Elts);
2277 V = ConstantDataArray::get(Context, Elts);
2278 } else if (EltTy->isHalfTy()) {
2279 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2280 if (isa<VectorType>(CurTy))
2281 V = ConstantDataVector::getFP(Context, Elts);
2283 V = ConstantDataArray::getFP(Context, Elts);
2284 } else if (EltTy->isFloatTy()) {
2285 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2286 if (isa<VectorType>(CurTy))
2287 V = ConstantDataVector::getFP(Context, Elts);
2289 V = ConstantDataArray::getFP(Context, Elts);
2290 } else if (EltTy->isDoubleTy()) {
2291 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2292 if (isa<VectorType>(CurTy))
2293 V = ConstantDataVector::getFP(Context, Elts);
2295 V = ConstantDataArray::getFP(Context, Elts);
2297 return error("Invalid type for value");
2301 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2302 if (Record.size() < 3)
2303 return error("Invalid record");
2304 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2306 V = UndefValue::get(CurTy); // Unknown binop.
2308 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2309 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2311 if (Record.size() >= 4) {
2312 if (Opc == Instruction::Add ||
2313 Opc == Instruction::Sub ||
2314 Opc == Instruction::Mul ||
2315 Opc == Instruction::Shl) {
2316 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2317 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2318 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2319 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2320 } else if (Opc == Instruction::SDiv ||
2321 Opc == Instruction::UDiv ||
2322 Opc == Instruction::LShr ||
2323 Opc == Instruction::AShr) {
2324 if (Record[3] & (1 << bitc::PEO_EXACT))
2325 Flags |= SDivOperator::IsExact;
2328 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2332 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2333 if (Record.size() < 3)
2334 return error("Invalid record");
2335 int Opc = getDecodedCastOpcode(Record[0]);
2337 V = UndefValue::get(CurTy); // Unknown cast.
2339 Type *OpTy = getTypeByID(Record[1]);
2341 return error("Invalid record");
2342 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2343 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2344 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2348 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2349 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2350 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2353 Type *PointeeType = nullptr;
2354 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2356 PointeeType = getTypeByID(Record[OpNum++]);
2358 bool InBounds = false;
2359 Optional<unsigned> InRangeIndex;
2360 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2361 uint64_t Op = Record[OpNum++];
2363 InRangeIndex = Op >> 1;
2364 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2367 SmallVector<Constant*, 16> Elts;
2368 while (OpNum != Record.size()) {
2369 Type *ElTy = getTypeByID(Record[OpNum++]);
2371 return error("Invalid record");
2372 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2377 cast<PointerType>(Elts[0]->getType()->getScalarType())
2379 return error("Explicit gep operator type does not match pointee type "
2380 "of pointer operand");
2382 if (Elts.size() < 1)
2383 return error("Invalid gep with no operands");
2385 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2386 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2387 InBounds, InRangeIndex);
2390 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2391 if (Record.size() < 3)
2392 return error("Invalid record");
2394 Type *SelectorTy = Type::getInt1Ty(Context);
2396 // The selector might be an i1 or an <n x i1>
2397 // Get the type from the ValueList before getting a forward ref.
2398 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2399 if (Value *V = ValueList[Record[0]])
2400 if (SelectorTy != V->getType())
2401 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2403 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2405 ValueList.getConstantFwdRef(Record[1],CurTy),
2406 ValueList.getConstantFwdRef(Record[2],CurTy));
2409 case bitc::CST_CODE_CE_EXTRACTELT
2410 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2411 if (Record.size() < 3)
2412 return error("Invalid record");
2414 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2416 return error("Invalid record");
2417 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2418 Constant *Op1 = nullptr;
2419 if (Record.size() == 4) {
2420 Type *IdxTy = getTypeByID(Record[2]);
2422 return error("Invalid record");
2423 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2424 } else // TODO: Remove with llvm 4.0
2425 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2427 return error("Invalid record");
2428 V = ConstantExpr::getExtractElement(Op0, Op1);
2431 case bitc::CST_CODE_CE_INSERTELT
2432 : { // CE_INSERTELT: [opval, opval, opty, opval]
2433 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2434 if (Record.size() < 3 || !OpTy)
2435 return error("Invalid record");
2436 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2437 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2438 OpTy->getElementType());
2439 Constant *Op2 = nullptr;
2440 if (Record.size() == 4) {
2441 Type *IdxTy = getTypeByID(Record[2]);
2443 return error("Invalid record");
2444 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2445 } else // TODO: Remove with llvm 4.0
2446 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2448 return error("Invalid record");
2449 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2452 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2453 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2454 if (Record.size() < 3 || !OpTy)
2455 return error("Invalid record");
2456 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2457 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2458 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2459 OpTy->getNumElements());
2460 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2461 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2464 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2465 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2467 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2468 if (Record.size() < 4 || !RTy || !OpTy)
2469 return error("Invalid record");
2470 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2471 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2472 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2473 RTy->getNumElements());
2474 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2475 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2478 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2479 if (Record.size() < 4)
2480 return error("Invalid record");
2481 Type *OpTy = getTypeByID(Record[0]);
2483 return error("Invalid record");
2484 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2485 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2487 if (OpTy->isFPOrFPVectorTy())
2488 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2490 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2493 // This maintains backward compatibility, pre-asm dialect keywords.
2494 // FIXME: Remove with the 4.0 release.
2495 case bitc::CST_CODE_INLINEASM_OLD: {
2496 if (Record.size() < 2)
2497 return error("Invalid record");
2498 std::string AsmStr, ConstrStr;
2499 bool HasSideEffects = Record[0] & 1;
2500 bool IsAlignStack = Record[0] >> 1;
2501 unsigned AsmStrSize = Record[1];
2502 if (2+AsmStrSize >= Record.size())
2503 return error("Invalid record");
2504 unsigned ConstStrSize = Record[2+AsmStrSize];
2505 if (3+AsmStrSize+ConstStrSize > Record.size())
2506 return error("Invalid record");
2508 for (unsigned i = 0; i != AsmStrSize; ++i)
2509 AsmStr += (char)Record[2+i];
2510 for (unsigned i = 0; i != ConstStrSize; ++i)
2511 ConstrStr += (char)Record[3+AsmStrSize+i];
2512 PointerType *PTy = cast<PointerType>(CurTy);
2513 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2514 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2517 // This version adds support for the asm dialect keywords (e.g.,
2519 case bitc::CST_CODE_INLINEASM: {
2520 if (Record.size() < 2)
2521 return error("Invalid record");
2522 std::string AsmStr, ConstrStr;
2523 bool HasSideEffects = Record[0] & 1;
2524 bool IsAlignStack = (Record[0] >> 1) & 1;
2525 unsigned AsmDialect = Record[0] >> 2;
2526 unsigned AsmStrSize = Record[1];
2527 if (2+AsmStrSize >= Record.size())
2528 return error("Invalid record");
2529 unsigned ConstStrSize = Record[2+AsmStrSize];
2530 if (3+AsmStrSize+ConstStrSize > Record.size())
2531 return error("Invalid record");
2533 for (unsigned i = 0; i != AsmStrSize; ++i)
2534 AsmStr += (char)Record[2+i];
2535 for (unsigned i = 0; i != ConstStrSize; ++i)
2536 ConstrStr += (char)Record[3+AsmStrSize+i];
2537 PointerType *PTy = cast<PointerType>(CurTy);
2538 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2539 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2540 InlineAsm::AsmDialect(AsmDialect));
2543 case bitc::CST_CODE_BLOCKADDRESS:{
2544 if (Record.size() < 3)
2545 return error("Invalid record");
2546 Type *FnTy = getTypeByID(Record[0]);
2548 return error("Invalid record");
2550 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2552 return error("Invalid record");
2554 // If the function is already parsed we can insert the block address right
2557 unsigned BBID = Record[2];
2559 // Invalid reference to entry block.
2560 return error("Invalid ID");
2562 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2563 for (size_t I = 0, E = BBID; I != E; ++I) {
2565 return error("Invalid ID");
2570 // Otherwise insert a placeholder and remember it so it can be inserted
2571 // when the function is parsed.
2572 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2574 BasicBlockFwdRefQueue.push_back(Fn);
2575 if (FwdBBs.size() < BBID + 1)
2576 FwdBBs.resize(BBID + 1);
2578 FwdBBs[BBID] = BasicBlock::Create(Context);
2581 V = BlockAddress::get(Fn, BB);
2586 ValueList.assignValue(V, NextCstNo);
2591 Error BitcodeReader::parseUseLists() {
2592 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2593 return error("Invalid record");
2595 // Read all the records.
2596 SmallVector<uint64_t, 64> Record;
2599 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2601 switch (Entry.Kind) {
2602 case BitstreamEntry::SubBlock: // Handled for us already.
2603 case BitstreamEntry::Error:
2604 return error("Malformed block");
2605 case BitstreamEntry::EndBlock:
2606 return Error::success();
2607 case BitstreamEntry::Record:
2608 // The interesting case.
2612 // Read a use list record.
2615 switch (Stream.readRecord(Entry.ID, Record)) {
2616 default: // Default behavior: unknown type.
2618 case bitc::USELIST_CODE_BB:
2621 case bitc::USELIST_CODE_DEFAULT: {
2622 unsigned RecordLength = Record.size();
2623 if (RecordLength < 3)
2624 // Records should have at least an ID and two indexes.
2625 return error("Invalid record");
2626 unsigned ID = Record.back();
2631 assert(ID < FunctionBBs.size() && "Basic block not found");
2632 V = FunctionBBs[ID];
2635 unsigned NumUses = 0;
2636 SmallDenseMap<const Use *, unsigned, 16> Order;
2637 for (const Use &U : V->materialized_uses()) {
2638 if (++NumUses > Record.size())
2640 Order[&U] = Record[NumUses - 1];
2642 if (Order.size() != Record.size() || NumUses > Record.size())
2643 // Mismatches can happen if the functions are being materialized lazily
2644 // (out-of-order), or a value has been upgraded.
2647 V->sortUseList([&](const Use &L, const Use &R) {
2648 return Order.lookup(&L) < Order.lookup(&R);
2656 /// When we see the block for metadata, remember where it is and then skip it.
2657 /// This lets us lazily deserialize the metadata.
2658 Error BitcodeReader::rememberAndSkipMetadata() {
2659 // Save the current stream state.
2660 uint64_t CurBit = Stream.GetCurrentBitNo();
2661 DeferredMetadataInfo.push_back(CurBit);
2663 // Skip over the block for now.
2664 if (Stream.SkipBlock())
2665 return error("Invalid record");
2666 return Error::success();
2669 Error BitcodeReader::materializeMetadata() {
2670 for (uint64_t BitPos : DeferredMetadataInfo) {
2671 // Move the bit stream to the saved position.
2672 Stream.JumpToBit(BitPos);
2673 if (Error Err = MDLoader->parseModuleMetadata())
2677 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2679 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2680 NamedMDNode *LinkerOpts =
2681 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2682 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2683 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2686 DeferredMetadataInfo.clear();
2687 return Error::success();
2690 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2692 /// When we see the block for a function body, remember where it is and then
2693 /// skip it. This lets us lazily deserialize the functions.
2694 Error BitcodeReader::rememberAndSkipFunctionBody() {
2695 // Get the function we are talking about.
2696 if (FunctionsWithBodies.empty())
2697 return error("Insufficient function protos");
2699 Function *Fn = FunctionsWithBodies.back();
2700 FunctionsWithBodies.pop_back();
2702 // Save the current stream state.
2703 uint64_t CurBit = Stream.GetCurrentBitNo();
2705 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2706 "Mismatch between VST and scanned function offsets");
2707 DeferredFunctionInfo[Fn] = CurBit;
2709 // Skip over the function block for now.
2710 if (Stream.SkipBlock())
2711 return error("Invalid record");
2712 return Error::success();
2715 Error BitcodeReader::globalCleanup() {
2716 // Patch the initializers for globals and aliases up.
2717 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2719 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2720 return error("Malformed global initializer set");
2722 // Look for intrinsic functions which need to be upgraded at some point
2723 for (Function &F : *TheModule) {
2724 MDLoader->upgradeDebugIntrinsics(F);
2726 if (UpgradeIntrinsicFunction(&F, NewFn))
2727 UpgradedIntrinsics[&F] = NewFn;
2728 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2729 // Some types could be renamed during loading if several modules are
2730 // loaded in the same LLVMContext (LTO scenario). In this case we should
2731 // remangle intrinsics names as well.
2732 RemangledIntrinsics[&F] = Remangled.getValue();
2735 // Look for global variables which need to be renamed.
2736 for (GlobalVariable &GV : TheModule->globals())
2737 UpgradeGlobalVariable(&GV);
2739 // Force deallocation of memory for these vectors to favor the client that
2740 // want lazy deserialization.
2741 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
2742 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
2743 IndirectSymbolInits);
2744 return Error::success();
2747 /// Support for lazy parsing of function bodies. This is required if we
2748 /// either have an old bitcode file without a VST forward declaration record,
2749 /// or if we have an anonymous function being materialized, since anonymous
2750 /// functions do not have a name and are therefore not in the VST.
2751 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2752 Stream.JumpToBit(NextUnreadBit);
2754 if (Stream.AtEndOfStream())
2755 return error("Could not find function in stream");
2757 if (!SeenFirstFunctionBody)
2758 return error("Trying to materialize functions before seeing function blocks");
2760 // An old bitcode file with the symbol table at the end would have
2761 // finished the parse greedily.
2762 assert(SeenValueSymbolTable);
2764 SmallVector<uint64_t, 64> Record;
2767 BitstreamEntry Entry = Stream.advance();
2768 switch (Entry.Kind) {
2770 return error("Expect SubBlock");
2771 case BitstreamEntry::SubBlock:
2774 return error("Expect function block");
2775 case bitc::FUNCTION_BLOCK_ID:
2776 if (Error Err = rememberAndSkipFunctionBody())
2778 NextUnreadBit = Stream.GetCurrentBitNo();
2779 return Error::success();
2785 bool BitcodeReaderBase::readBlockInfo() {
2786 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2789 BlockInfo = std::move(*NewBlockInfo);
2793 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
2794 // v1: [selection_kind, name]
2795 // v2: [strtab_offset, strtab_size, selection_kind]
2797 std::tie(Name, Record) = readNameFromStrtab(Record);
2800 return error("Invalid record");
2801 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2802 std::string OldFormatName;
2804 if (Record.size() < 2)
2805 return error("Invalid record");
2806 unsigned ComdatNameSize = Record[1];
2807 OldFormatName.reserve(ComdatNameSize);
2808 for (unsigned i = 0; i != ComdatNameSize; ++i)
2809 OldFormatName += (char)Record[2 + i];
2810 Name = OldFormatName;
2812 Comdat *C = TheModule->getOrInsertComdat(Name);
2813 C->setSelectionKind(SK);
2814 ComdatList.push_back(C);
2815 return Error::success();
2818 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
2819 // v1: [pointer type, isconst, initid, linkage, alignment, section,
2820 // visibility, threadlocal, unnamed_addr, externally_initialized,
2821 // dllstorageclass, comdat, attributes, preemption specifier] (name in VST)
2822 // v2: [strtab_offset, strtab_size, v1]
2824 std::tie(Name, Record) = readNameFromStrtab(Record);
2826 if (Record.size() < 6)
2827 return error("Invalid record");
2828 Type *Ty = getTypeByID(Record[0]);
2830 return error("Invalid record");
2831 bool isConstant = Record[1] & 1;
2832 bool explicitType = Record[1] & 2;
2833 unsigned AddressSpace;
2835 AddressSpace = Record[1] >> 2;
2837 if (!Ty->isPointerTy())
2838 return error("Invalid type for value");
2839 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2840 Ty = cast<PointerType>(Ty)->getElementType();
2843 uint64_t RawLinkage = Record[3];
2844 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2846 if (Error Err = parseAlignmentValue(Record[4], Alignment))
2848 std::string Section;
2850 if (Record[5] - 1 >= SectionTable.size())
2851 return error("Invalid ID");
2852 Section = SectionTable[Record[5] - 1];
2854 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2855 // Local linkage must have default visibility.
2856 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2857 // FIXME: Change to an error if non-default in 4.0.
2858 Visibility = getDecodedVisibility(Record[6]);
2860 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2861 if (Record.size() > 7)
2862 TLM = getDecodedThreadLocalMode(Record[7]);
2864 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2865 if (Record.size() > 8)
2866 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2868 bool ExternallyInitialized = false;
2869 if (Record.size() > 9)
2870 ExternallyInitialized = Record[9];
2872 GlobalVariable *NewGV =
2873 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
2874 nullptr, TLM, AddressSpace, ExternallyInitialized);
2875 NewGV->setAlignment(Alignment);
2876 if (!Section.empty())
2877 NewGV->setSection(Section);
2878 NewGV->setVisibility(Visibility);
2879 NewGV->setUnnamedAddr(UnnamedAddr);
2881 if (Record.size() > 10)
2882 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2884 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2886 ValueList.push_back(NewGV);
2888 // Remember which value to use for the global initializer.
2889 if (unsigned InitID = Record[2])
2890 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2892 if (Record.size() > 11) {
2893 if (unsigned ComdatID = Record[11]) {
2894 if (ComdatID > ComdatList.size())
2895 return error("Invalid global variable comdat ID");
2896 NewGV->setComdat(ComdatList[ComdatID - 1]);
2898 } else if (hasImplicitComdat(RawLinkage)) {
2899 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2902 if (Record.size() > 12) {
2903 auto AS = getAttributes(Record[12]).getFnAttributes();
2904 NewGV->setAttributes(AS);
2907 if (Record.size() > 13) {
2908 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
2911 return Error::success();
2914 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
2915 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
2916 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
2917 // prefixdata, personalityfn, preemption specifier] (name in VST)
2918 // v2: [strtab_offset, strtab_size, v1]
2920 std::tie(Name, Record) = readNameFromStrtab(Record);
2922 if (Record.size() < 8)
2923 return error("Invalid record");
2924 Type *Ty = getTypeByID(Record[0]);
2926 return error("Invalid record");
2927 if (auto *PTy = dyn_cast<PointerType>(Ty))
2928 Ty = PTy->getElementType();
2929 auto *FTy = dyn_cast<FunctionType>(Ty);
2931 return error("Invalid type for value");
2932 auto CC = static_cast<CallingConv::ID>(Record[1]);
2933 if (CC & ~CallingConv::MaxID)
2934 return error("Invalid calling convention ID");
2937 Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule);
2939 Func->setCallingConv(CC);
2940 bool isProto = Record[2];
2941 uint64_t RawLinkage = Record[3];
2942 Func->setLinkage(getDecodedLinkage(RawLinkage));
2943 Func->setAttributes(getAttributes(Record[4]));
2946 if (Error Err = parseAlignmentValue(Record[5], Alignment))
2948 Func->setAlignment(Alignment);
2950 if (Record[6] - 1 >= SectionTable.size())
2951 return error("Invalid ID");
2952 Func->setSection(SectionTable[Record[6] - 1]);
2954 // Local linkage must have default visibility.
2955 if (!Func->hasLocalLinkage())
2956 // FIXME: Change to an error if non-default in 4.0.
2957 Func->setVisibility(getDecodedVisibility(Record[7]));
2958 if (Record.size() > 8 && Record[8]) {
2959 if (Record[8] - 1 >= GCTable.size())
2960 return error("Invalid ID");
2961 Func->setGC(GCTable[Record[8] - 1]);
2963 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2964 if (Record.size() > 9)
2965 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2966 Func->setUnnamedAddr(UnnamedAddr);
2967 if (Record.size() > 10 && Record[10] != 0)
2968 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2970 if (Record.size() > 11)
2971 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2973 upgradeDLLImportExportLinkage(Func, RawLinkage);
2975 if (Record.size() > 12) {
2976 if (unsigned ComdatID = Record[12]) {
2977 if (ComdatID > ComdatList.size())
2978 return error("Invalid function comdat ID");
2979 Func->setComdat(ComdatList[ComdatID - 1]);
2981 } else if (hasImplicitComdat(RawLinkage)) {
2982 Func->setComdat(reinterpret_cast<Comdat *>(1));
2985 if (Record.size() > 13 && Record[13] != 0)
2986 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
2988 if (Record.size() > 14 && Record[14] != 0)
2989 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2991 if (Record.size() > 15) {
2992 Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
2995 ValueList.push_back(Func);
2997 // If this is a function with a body, remember the prototype we are
2998 // creating now, so that we can match up the body with them later.
3000 Func->setIsMaterializable(true);
3001 FunctionsWithBodies.push_back(Func);
3002 DeferredFunctionInfo[Func] = 0;
3004 return Error::success();
3007 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3008 unsigned BitCode, ArrayRef<uint64_t> Record) {
3009 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3010 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3011 // dllstorageclass, threadlocal, unnamed_addr,
3012 // preemption specifier] (name in VST)
3013 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3014 // visibility, dllstorageclass, threadlocal, unnamed_addr,
3015 // preemption specifier] (name in VST)
3016 // v2: [strtab_offset, strtab_size, v1]
3018 std::tie(Name, Record) = readNameFromStrtab(Record);
3020 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3021 if (Record.size() < (3 + (unsigned)NewRecord))
3022 return error("Invalid record");
3024 Type *Ty = getTypeByID(Record[OpNum++]);
3026 return error("Invalid record");
3030 auto *PTy = dyn_cast<PointerType>(Ty);
3032 return error("Invalid type for value");
3033 Ty = PTy->getElementType();
3034 AddrSpace = PTy->getAddressSpace();
3036 AddrSpace = Record[OpNum++];
3039 auto Val = Record[OpNum++];
3040 auto Linkage = Record[OpNum++];
3041 GlobalIndirectSymbol *NewGA;
3042 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3043 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3044 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3047 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3048 nullptr, TheModule);
3049 // Old bitcode files didn't have visibility field.
3050 // Local linkage must have default visibility.
3051 if (OpNum != Record.size()) {
3052 auto VisInd = OpNum++;
3053 if (!NewGA->hasLocalLinkage())
3054 // FIXME: Change to an error if non-default in 4.0.
3055 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3057 if (OpNum != Record.size())
3058 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3060 upgradeDLLImportExportLinkage(NewGA, Linkage);
3061 if (OpNum != Record.size())
3062 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3063 if (OpNum != Record.size())
3064 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3065 if (OpNum != Record.size())
3066 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3067 ValueList.push_back(NewGA);
3068 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3069 return Error::success();
3072 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3073 bool ShouldLazyLoadMetadata) {
3075 Stream.JumpToBit(ResumeBit);
3076 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3077 return error("Invalid record");
3079 SmallVector<uint64_t, 64> Record;
3081 // Read all the records for this module.
3083 BitstreamEntry Entry = Stream.advance();
3085 switch (Entry.Kind) {
3086 case BitstreamEntry::Error:
3087 return error("Malformed block");
3088 case BitstreamEntry::EndBlock:
3089 return globalCleanup();
3091 case BitstreamEntry::SubBlock:
3093 default: // Skip unknown content.
3094 if (Stream.SkipBlock())
3095 return error("Invalid record");
3097 case bitc::BLOCKINFO_BLOCK_ID:
3098 if (readBlockInfo())
3099 return error("Malformed block");
3101 case bitc::PARAMATTR_BLOCK_ID:
3102 if (Error Err = parseAttributeBlock())
3105 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3106 if (Error Err = parseAttributeGroupBlock())
3109 case bitc::TYPE_BLOCK_ID_NEW:
3110 if (Error Err = parseTypeTable())
3113 case bitc::VALUE_SYMTAB_BLOCK_ID:
3114 if (!SeenValueSymbolTable) {
3115 // Either this is an old form VST without function index and an
3116 // associated VST forward declaration record (which would have caused
3117 // the VST to be jumped to and parsed before it was encountered
3118 // normally in the stream), or there were no function blocks to
3119 // trigger an earlier parsing of the VST.
3120 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3121 if (Error Err = parseValueSymbolTable())
3123 SeenValueSymbolTable = true;
3125 // We must have had a VST forward declaration record, which caused
3126 // the parser to jump to and parse the VST earlier.
3127 assert(VSTOffset > 0);
3128 if (Stream.SkipBlock())
3129 return error("Invalid record");
3132 case bitc::CONSTANTS_BLOCK_ID:
3133 if (Error Err = parseConstants())
3135 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3138 case bitc::METADATA_BLOCK_ID:
3139 if (ShouldLazyLoadMetadata) {
3140 if (Error Err = rememberAndSkipMetadata())
3144 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3145 if (Error Err = MDLoader->parseModuleMetadata())
3148 case bitc::METADATA_KIND_BLOCK_ID:
3149 if (Error Err = MDLoader->parseMetadataKinds())
3152 case bitc::FUNCTION_BLOCK_ID:
3153 // If this is the first function body we've seen, reverse the
3154 // FunctionsWithBodies list.
3155 if (!SeenFirstFunctionBody) {
3156 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3157 if (Error Err = globalCleanup())
3159 SeenFirstFunctionBody = true;
3162 if (VSTOffset > 0) {
3163 // If we have a VST forward declaration record, make sure we
3164 // parse the VST now if we haven't already. It is needed to
3165 // set up the DeferredFunctionInfo vector for lazy reading.
3166 if (!SeenValueSymbolTable) {
3167 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3169 SeenValueSymbolTable = true;
3170 // Fall through so that we record the NextUnreadBit below.
3171 // This is necessary in case we have an anonymous function that
3172 // is later materialized. Since it will not have a VST entry we
3173 // need to fall back to the lazy parse to find its offset.
3175 // If we have a VST forward declaration record, but have already
3176 // parsed the VST (just above, when the first function body was
3177 // encountered here), then we are resuming the parse after
3178 // materializing functions. The ResumeBit points to the
3179 // start of the last function block recorded in the
3180 // DeferredFunctionInfo map. Skip it.
3181 if (Stream.SkipBlock())
3182 return error("Invalid record");
3187 // Support older bitcode files that did not have the function
3188 // index in the VST, nor a VST forward declaration record, as
3189 // well as anonymous functions that do not have VST entries.
3190 // Build the DeferredFunctionInfo vector on the fly.
3191 if (Error Err = rememberAndSkipFunctionBody())
3194 // Suspend parsing when we reach the function bodies. Subsequent
3195 // materialization calls will resume it when necessary. If the bitcode
3196 // file is old, the symbol table will be at the end instead and will not
3197 // have been seen yet. In this case, just finish the parse now.
3198 if (SeenValueSymbolTable) {
3199 NextUnreadBit = Stream.GetCurrentBitNo();
3200 // After the VST has been parsed, we need to make sure intrinsic name
3201 // are auto-upgraded.
3202 return globalCleanup();
3205 case bitc::USELIST_BLOCK_ID:
3206 if (Error Err = parseUseLists())
3209 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3210 if (Error Err = parseOperandBundleTags())
3213 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3214 if (Error Err = parseSyncScopeNames())
3220 case BitstreamEntry::Record:
3221 // The interesting case.
3226 auto BitCode = Stream.readRecord(Entry.ID, Record);
3228 default: break; // Default behavior, ignore unknown content.
3229 case bitc::MODULE_CODE_VERSION: {
3230 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3232 return VersionOrErr.takeError();
3233 UseRelativeIDs = *VersionOrErr >= 1;
3236 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3238 if (convertToString(Record, 0, S))
3239 return error("Invalid record");
3240 TheModule->setTargetTriple(S);
3243 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3245 if (convertToString(Record, 0, S))
3246 return error("Invalid record");
3247 TheModule->setDataLayout(S);
3250 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3252 if (convertToString(Record, 0, S))
3253 return error("Invalid record");
3254 TheModule->setModuleInlineAsm(S);
3257 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3258 // FIXME: Remove in 4.0.
3260 if (convertToString(Record, 0, S))
3261 return error("Invalid record");
3265 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3267 if (convertToString(Record, 0, S))
3268 return error("Invalid record");
3269 SectionTable.push_back(S);
3272 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3274 if (convertToString(Record, 0, S))
3275 return error("Invalid record");
3276 GCTable.push_back(S);
3279 case bitc::MODULE_CODE_COMDAT:
3280 if (Error Err = parseComdatRecord(Record))
3283 case bitc::MODULE_CODE_GLOBALVAR:
3284 if (Error Err = parseGlobalVarRecord(Record))
3287 case bitc::MODULE_CODE_FUNCTION:
3288 if (Error Err = parseFunctionRecord(Record))
3291 case bitc::MODULE_CODE_IFUNC:
3292 case bitc::MODULE_CODE_ALIAS:
3293 case bitc::MODULE_CODE_ALIAS_OLD:
3294 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3297 /// MODULE_CODE_VSTOFFSET: [offset]
3298 case bitc::MODULE_CODE_VSTOFFSET:
3299 if (Record.size() < 1)
3300 return error("Invalid record");
3301 // Note that we subtract 1 here because the offset is relative to one word
3302 // before the start of the identification or module block, which was
3303 // historically always the start of the regular bitcode header.
3304 VSTOffset = Record[0] - 1;
3306 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3307 case bitc::MODULE_CODE_SOURCE_FILENAME:
3308 SmallString<128> ValueName;
3309 if (convertToString(Record, 0, ValueName))
3310 return error("Invalid record");
3311 TheModule->setSourceFileName(ValueName);
3318 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3321 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3322 [&](unsigned ID) { return getTypeByID(ID); });
3323 return parseModule(0, ShouldLazyLoadMetadata);
3326 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3327 if (!isa<PointerType>(PtrType))
3328 return error("Load/Store operand is not a pointer type");
3329 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3331 if (ValType && ValType != ElemType)
3332 return error("Explicit load/store type does not match pointee "
3333 "type of pointer operand");
3334 if (!PointerType::isLoadableOrStorableType(ElemType))
3335 return error("Cannot load/store from pointer");
3336 return Error::success();
3339 /// Lazily parse the specified function body block.
3340 Error BitcodeReader::parseFunctionBody(Function *F) {
3341 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3342 return error("Invalid record");
3344 // Unexpected unresolved metadata when parsing function.
3345 if (MDLoader->hasFwdRefs())
3346 return error("Invalid function metadata: incoming forward references");
3348 InstructionList.clear();
3349 unsigned ModuleValueListSize = ValueList.size();
3350 unsigned ModuleMDLoaderSize = MDLoader->size();
3352 // Add all the function arguments to the value table.
3353 for (Argument &I : F->args())
3354 ValueList.push_back(&I);
3356 unsigned NextValueNo = ValueList.size();
3357 BasicBlock *CurBB = nullptr;
3358 unsigned CurBBNo = 0;
3361 auto getLastInstruction = [&]() -> Instruction * {
3362 if (CurBB && !CurBB->empty())
3363 return &CurBB->back();
3364 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3365 !FunctionBBs[CurBBNo - 1]->empty())
3366 return &FunctionBBs[CurBBNo - 1]->back();
3370 std::vector<OperandBundleDef> OperandBundles;
3372 // Read all the records.
3373 SmallVector<uint64_t, 64> Record;
3376 BitstreamEntry Entry = Stream.advance();
3378 switch (Entry.Kind) {
3379 case BitstreamEntry::Error:
3380 return error("Malformed block");
3381 case BitstreamEntry::EndBlock:
3382 goto OutOfRecordLoop;
3384 case BitstreamEntry::SubBlock:
3386 default: // Skip unknown content.
3387 if (Stream.SkipBlock())
3388 return error("Invalid record");
3390 case bitc::CONSTANTS_BLOCK_ID:
3391 if (Error Err = parseConstants())
3393 NextValueNo = ValueList.size();
3395 case bitc::VALUE_SYMTAB_BLOCK_ID:
3396 if (Error Err = parseValueSymbolTable())
3399 case bitc::METADATA_ATTACHMENT_ID:
3400 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3403 case bitc::METADATA_BLOCK_ID:
3404 assert(DeferredMetadataInfo.empty() &&
3405 "Must read all module-level metadata before function-level");
3406 if (Error Err = MDLoader->parseFunctionMetadata())
3409 case bitc::USELIST_BLOCK_ID:
3410 if (Error Err = parseUseLists())
3416 case BitstreamEntry::Record:
3417 // The interesting case.
3423 Instruction *I = nullptr;
3424 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3426 default: // Default behavior: reject
3427 return error("Invalid value");
3428 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3429 if (Record.size() < 1 || Record[0] == 0)
3430 return error("Invalid record");
3431 // Create all the basic blocks for the function.
3432 FunctionBBs.resize(Record[0]);
3434 // See if anything took the address of blocks in this function.
3435 auto BBFRI = BasicBlockFwdRefs.find(F);
3436 if (BBFRI == BasicBlockFwdRefs.end()) {
3437 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3438 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3440 auto &BBRefs = BBFRI->second;
3441 // Check for invalid basic block references.
3442 if (BBRefs.size() > FunctionBBs.size())
3443 return error("Invalid ID");
3444 assert(!BBRefs.empty() && "Unexpected empty array");
3445 assert(!BBRefs.front() && "Invalid reference to entry block");
3446 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3448 if (I < RE && BBRefs[I]) {
3449 BBRefs[I]->insertInto(F);
3450 FunctionBBs[I] = BBRefs[I];
3452 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3455 // Erase from the table.
3456 BasicBlockFwdRefs.erase(BBFRI);
3459 CurBB = FunctionBBs[0];
3463 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3464 // This record indicates that the last instruction is at the same
3465 // location as the previous instruction with a location.
3466 I = getLastInstruction();
3469 return error("Invalid record");
3470 I->setDebugLoc(LastLoc);
3474 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3475 I = getLastInstruction();
3476 if (!I || Record.size() < 4)
3477 return error("Invalid record");
3479 unsigned Line = Record[0], Col = Record[1];
3480 unsigned ScopeID = Record[2], IAID = Record[3];
3482 MDNode *Scope = nullptr, *IA = nullptr;
3484 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
3486 return error("Invalid record");
3489 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
3491 return error("Invalid record");
3493 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3494 I->setDebugLoc(LastLoc);
3499 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3502 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3503 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3504 OpNum+1 > Record.size())
3505 return error("Invalid record");
3507 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3509 return error("Invalid record");
3510 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3511 InstructionList.push_back(I);
3512 if (OpNum < Record.size()) {
3513 if (Opc == Instruction::Add ||
3514 Opc == Instruction::Sub ||
3515 Opc == Instruction::Mul ||
3516 Opc == Instruction::Shl) {
3517 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3518 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3519 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3520 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3521 } else if (Opc == Instruction::SDiv ||
3522 Opc == Instruction::UDiv ||
3523 Opc == Instruction::LShr ||
3524 Opc == Instruction::AShr) {
3525 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3526 cast<BinaryOperator>(I)->setIsExact(true);
3527 } else if (isa<FPMathOperator>(I)) {
3528 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3530 I->setFastMathFlags(FMF);
3536 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3539 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3540 OpNum+2 != Record.size())
3541 return error("Invalid record");
3543 Type *ResTy = getTypeByID(Record[OpNum]);
3544 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3545 if (Opc == -1 || !ResTy)
3546 return error("Invalid record");
3547 Instruction *Temp = nullptr;
3548 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3550 InstructionList.push_back(Temp);
3551 CurBB->getInstList().push_back(Temp);
3554 auto CastOp = (Instruction::CastOps)Opc;
3555 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3556 return error("Invalid cast");
3557 I = CastInst::Create(CastOp, Op, ResTy);
3559 InstructionList.push_back(I);
3562 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3563 case bitc::FUNC_CODE_INST_GEP_OLD:
3564 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3570 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3571 InBounds = Record[OpNum++];
3572 Ty = getTypeByID(Record[OpNum++]);
3574 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3579 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3580 return error("Invalid record");
3583 Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3586 cast<PointerType>(BasePtr->getType()->getScalarType())
3589 "Explicit gep type does not match pointee type of pointer operand");
3591 SmallVector<Value*, 16> GEPIdx;
3592 while (OpNum != Record.size()) {
3594 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3595 return error("Invalid record");
3596 GEPIdx.push_back(Op);
3599 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3601 InstructionList.push_back(I);
3603 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3607 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3608 // EXTRACTVAL: [opty, opval, n x indices]
3611 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3612 return error("Invalid record");
3614 unsigned RecSize = Record.size();
3615 if (OpNum == RecSize)
3616 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3618 SmallVector<unsigned, 4> EXTRACTVALIdx;
3619 Type *CurTy = Agg->getType();
3620 for (; OpNum != RecSize; ++OpNum) {
3621 bool IsArray = CurTy->isArrayTy();
3622 bool IsStruct = CurTy->isStructTy();
3623 uint64_t Index = Record[OpNum];
3625 if (!IsStruct && !IsArray)
3626 return error("EXTRACTVAL: Invalid type");
3627 if ((unsigned)Index != Index)
3628 return error("Invalid value");
3629 if (IsStruct && Index >= CurTy->subtypes().size())
3630 return error("EXTRACTVAL: Invalid struct index");
3631 if (IsArray && Index >= CurTy->getArrayNumElements())
3632 return error("EXTRACTVAL: Invalid array index");
3633 EXTRACTVALIdx.push_back((unsigned)Index);
3636 CurTy = CurTy->subtypes()[Index];
3638 CurTy = CurTy->subtypes()[0];
3641 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3642 InstructionList.push_back(I);
3646 case bitc::FUNC_CODE_INST_INSERTVAL: {
3647 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3650 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3651 return error("Invalid record");
3653 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3654 return error("Invalid record");
3656 unsigned RecSize = Record.size();
3657 if (OpNum == RecSize)
3658 return error("INSERTVAL: Invalid instruction with 0 indices");
3660 SmallVector<unsigned, 4> INSERTVALIdx;
3661 Type *CurTy = Agg->getType();
3662 for (; OpNum != RecSize; ++OpNum) {
3663 bool IsArray = CurTy->isArrayTy();
3664 bool IsStruct = CurTy->isStructTy();
3665 uint64_t Index = Record[OpNum];
3667 if (!IsStruct && !IsArray)
3668 return error("INSERTVAL: Invalid type");
3669 if ((unsigned)Index != Index)
3670 return error("Invalid value");
3671 if (IsStruct && Index >= CurTy->subtypes().size())
3672 return error("INSERTVAL: Invalid struct index");
3673 if (IsArray && Index >= CurTy->getArrayNumElements())
3674 return error("INSERTVAL: Invalid array index");
3676 INSERTVALIdx.push_back((unsigned)Index);
3678 CurTy = CurTy->subtypes()[Index];
3680 CurTy = CurTy->subtypes()[0];
3683 if (CurTy != Val->getType())
3684 return error("Inserted value type doesn't match aggregate type");
3686 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3687 InstructionList.push_back(I);
3691 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3692 // obsolete form of select
3693 // handles select i1 ... in old bitcode
3695 Value *TrueVal, *FalseVal, *Cond;
3696 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3697 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3698 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3699 return error("Invalid record");
3701 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3702 InstructionList.push_back(I);
3706 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3707 // new form of select
3708 // handles select i1 or select [N x i1]
3710 Value *TrueVal, *FalseVal, *Cond;
3711 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3712 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3713 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3714 return error("Invalid record");
3716 // select condition can be either i1 or [N x i1]
3717 if (VectorType* vector_type =
3718 dyn_cast<VectorType>(Cond->getType())) {
3720 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3721 return error("Invalid type for value");
3724 if (Cond->getType() != Type::getInt1Ty(Context))
3725 return error("Invalid type for value");
3728 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3729 InstructionList.push_back(I);
3733 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3736 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3737 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3738 return error("Invalid record");
3739 if (!Vec->getType()->isVectorTy())
3740 return error("Invalid type for value");
3741 I = ExtractElementInst::Create(Vec, Idx);
3742 InstructionList.push_back(I);
3746 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3748 Value *Vec, *Elt, *Idx;
3749 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3750 return error("Invalid record");
3751 if (!Vec->getType()->isVectorTy())
3752 return error("Invalid type for value");
3753 if (popValue(Record, OpNum, NextValueNo,
3754 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3755 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3756 return error("Invalid record");
3757 I = InsertElementInst::Create(Vec, Elt, Idx);
3758 InstructionList.push_back(I);
3762 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3764 Value *Vec1, *Vec2, *Mask;
3765 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3766 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3767 return error("Invalid record");
3769 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3770 return error("Invalid record");
3771 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3772 return error("Invalid type for value");
3773 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3774 InstructionList.push_back(I);
3778 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3779 // Old form of ICmp/FCmp returning bool
3780 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3781 // both legal on vectors but had different behaviour.
3782 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3783 // FCmp/ICmp returning bool or vector of bool
3787 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3788 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3789 return error("Invalid record");
3791 unsigned PredVal = Record[OpNum];
3792 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3794 if (IsFP && Record.size() > OpNum+1)
3795 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3797 if (OpNum+1 != Record.size())
3798 return error("Invalid record");
3800 if (LHS->getType()->isFPOrFPVectorTy())
3801 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3803 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3806 I->setFastMathFlags(FMF);
3807 InstructionList.push_back(I);
3811 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3813 unsigned Size = Record.size();
3815 I = ReturnInst::Create(Context);
3816 InstructionList.push_back(I);
3821 Value *Op = nullptr;
3822 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3823 return error("Invalid record");
3824 if (OpNum != Record.size())
3825 return error("Invalid record");
3827 I = ReturnInst::Create(Context, Op);
3828 InstructionList.push_back(I);
3831 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3832 if (Record.size() != 1 && Record.size() != 3)
3833 return error("Invalid record");
3834 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3836 return error("Invalid record");
3838 if (Record.size() == 1) {
3839 I = BranchInst::Create(TrueDest);
3840 InstructionList.push_back(I);
3843 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3844 Value *Cond = getValue(Record, 2, NextValueNo,
3845 Type::getInt1Ty(Context));
3846 if (!FalseDest || !Cond)
3847 return error("Invalid record");
3848 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3849 InstructionList.push_back(I);
3853 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
3854 if (Record.size() != 1 && Record.size() != 2)
3855 return error("Invalid record");
3858 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3860 return error("Invalid record");
3861 BasicBlock *UnwindDest = nullptr;
3862 if (Record.size() == 2) {
3863 UnwindDest = getBasicBlock(Record[Idx++]);
3865 return error("Invalid record");
3868 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
3869 InstructionList.push_back(I);
3872 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3873 if (Record.size() != 2)
3874 return error("Invalid record");
3877 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3879 return error("Invalid record");
3880 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3882 return error("Invalid record");
3884 I = CatchReturnInst::Create(CatchPad, BB);
3885 InstructionList.push_back(I);
3888 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3889 // We must have, at minimum, the outer scope and the number of arguments.
3890 if (Record.size() < 2)
3891 return error("Invalid record");
3896 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3898 unsigned NumHandlers = Record[Idx++];
3900 SmallVector<BasicBlock *, 2> Handlers;
3901 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3902 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3904 return error("Invalid record");
3905 Handlers.push_back(BB);
3908 BasicBlock *UnwindDest = nullptr;
3909 if (Idx + 1 == Record.size()) {
3910 UnwindDest = getBasicBlock(Record[Idx++]);
3912 return error("Invalid record");
3915 if (Record.size() != Idx)
3916 return error("Invalid record");
3919 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3920 for (BasicBlock *Handler : Handlers)
3921 CatchSwitch->addHandler(Handler);
3923 InstructionList.push_back(I);
3926 case bitc::FUNC_CODE_INST_CATCHPAD:
3927 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3928 // We must have, at minimum, the outer scope and the number of arguments.
3929 if (Record.size() < 2)
3930 return error("Invalid record");
3935 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3937 unsigned NumArgOperands = Record[Idx++];
3939 SmallVector<Value *, 2> Args;
3940 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3942 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3943 return error("Invalid record");
3944 Args.push_back(Val);
3947 if (Record.size() != Idx)
3948 return error("Invalid record");
3950 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3951 I = CleanupPadInst::Create(ParentPad, Args);
3953 I = CatchPadInst::Create(ParentPad, Args);
3954 InstructionList.push_back(I);
3957 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3959 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3960 // "New" SwitchInst format with case ranges. The changes to write this
3961 // format were reverted but we still recognize bitcode that uses it.
3962 // Hopefully someday we will have support for case ranges and can use
3963 // this format again.
3965 Type *OpTy = getTypeByID(Record[1]);
3966 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3968 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3969 BasicBlock *Default = getBasicBlock(Record[3]);
3970 if (!OpTy || !Cond || !Default)
3971 return error("Invalid record");
3973 unsigned NumCases = Record[4];
3975 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3976 InstructionList.push_back(SI);
3978 unsigned CurIdx = 5;
3979 for (unsigned i = 0; i != NumCases; ++i) {
3980 SmallVector<ConstantInt*, 1> CaseVals;
3981 unsigned NumItems = Record[CurIdx++];
3982 for (unsigned ci = 0; ci != NumItems; ++ci) {
3983 bool isSingleNumber = Record[CurIdx++];
3986 unsigned ActiveWords = 1;
3987 if (ValueBitWidth > 64)
3988 ActiveWords = Record[CurIdx++];
3989 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3991 CurIdx += ActiveWords;
3993 if (!isSingleNumber) {
3995 if (ValueBitWidth > 64)
3996 ActiveWords = Record[CurIdx++];
3997 APInt High = readWideAPInt(
3998 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3999 CurIdx += ActiveWords;
4001 // FIXME: It is not clear whether values in the range should be
4002 // compared as signed or unsigned values. The partially
4003 // implemented changes that used this format in the past used
4004 // unsigned comparisons.
4005 for ( ; Low.ule(High); ++Low)
4006 CaseVals.push_back(ConstantInt::get(Context, Low));
4008 CaseVals.push_back(ConstantInt::get(Context, Low));
4010 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4011 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4012 cve = CaseVals.end(); cvi != cve; ++cvi)
4013 SI->addCase(*cvi, DestBB);
4019 // Old SwitchInst format without case ranges.
4021 if (Record.size() < 3 || (Record.size() & 1) == 0)
4022 return error("Invalid record");
4023 Type *OpTy = getTypeByID(Record[0]);
4024 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4025 BasicBlock *Default = getBasicBlock(Record[2]);
4026 if (!OpTy || !Cond || !Default)
4027 return error("Invalid record");
4028 unsigned NumCases = (Record.size()-3)/2;
4029 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4030 InstructionList.push_back(SI);
4031 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4032 ConstantInt *CaseVal =
4033 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4034 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4035 if (!CaseVal || !DestBB) {
4037 return error("Invalid record");
4039 SI->addCase(CaseVal, DestBB);
4044 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4045 if (Record.size() < 2)
4046 return error("Invalid record");
4047 Type *OpTy = getTypeByID(Record[0]);
4048 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4049 if (!OpTy || !Address)
4050 return error("Invalid record");
4051 unsigned NumDests = Record.size()-2;
4052 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4053 InstructionList.push_back(IBI);
4054 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4055 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4056 IBI->addDestination(DestBB);
4059 return error("Invalid record");
4066 case bitc::FUNC_CODE_INST_INVOKE: {
4067 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4068 if (Record.size() < 4)
4069 return error("Invalid record");
4071 AttributeList PAL = getAttributes(Record[OpNum++]);
4072 unsigned CCInfo = Record[OpNum++];
4073 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4074 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4076 FunctionType *FTy = nullptr;
4077 if (CCInfo >> 13 & 1 &&
4078 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4079 return error("Explicit invoke type is not a function type");
4082 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4083 return error("Invalid record");
4085 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4087 return error("Callee is not a pointer");
4089 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4091 return error("Callee is not of pointer to function type");
4092 } else if (CalleeTy->getElementType() != FTy)
4093 return error("Explicit invoke type does not match pointee type of "
4095 if (Record.size() < FTy->getNumParams() + OpNum)
4096 return error("Insufficient operands to call");
4098 SmallVector<Value*, 16> Ops;
4099 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4100 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4101 FTy->getParamType(i)));
4103 return error("Invalid record");
4106 if (!FTy->isVarArg()) {
4107 if (Record.size() != OpNum)
4108 return error("Invalid record");
4110 // Read type/value pairs for varargs params.
4111 while (OpNum != Record.size()) {
4113 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4114 return error("Invalid record");
4119 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4120 OperandBundles.clear();
4121 InstructionList.push_back(I);
4122 cast<InvokeInst>(I)->setCallingConv(
4123 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4124 cast<InvokeInst>(I)->setAttributes(PAL);
4127 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4129 Value *Val = nullptr;
4130 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4131 return error("Invalid record");
4132 I = ResumeInst::Create(Val);
4133 InstructionList.push_back(I);
4136 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4137 I = new UnreachableInst(Context);
4138 InstructionList.push_back(I);
4140 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4141 if (Record.size() < 1 || ((Record.size()-1)&1))
4142 return error("Invalid record");
4143 Type *Ty = getTypeByID(Record[0]);
4145 return error("Invalid record");
4147 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4148 InstructionList.push_back(PN);
4150 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4152 // With the new function encoding, it is possible that operands have
4153 // negative IDs (for forward references). Use a signed VBR
4154 // representation to keep the encoding small.
4156 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4158 V = getValue(Record, 1+i, NextValueNo, Ty);
4159 BasicBlock *BB = getBasicBlock(Record[2+i]);
4161 return error("Invalid record");
4162 PN->addIncoming(V, BB);
4168 case bitc::FUNC_CODE_INST_LANDINGPAD:
4169 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4170 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4172 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4173 if (Record.size() < 3)
4174 return error("Invalid record");
4176 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4177 if (Record.size() < 4)
4178 return error("Invalid record");
4180 Type *Ty = getTypeByID(Record[Idx++]);
4182 return error("Invalid record");
4183 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4184 Value *PersFn = nullptr;
4185 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4186 return error("Invalid record");
4188 if (!F->hasPersonalityFn())
4189 F->setPersonalityFn(cast<Constant>(PersFn));
4190 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4191 return error("Personality function mismatch");
4194 bool IsCleanup = !!Record[Idx++];
4195 unsigned NumClauses = Record[Idx++];
4196 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4197 LP->setCleanup(IsCleanup);
4198 for (unsigned J = 0; J != NumClauses; ++J) {
4199 LandingPadInst::ClauseType CT =
4200 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4203 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4205 return error("Invalid record");
4208 assert((CT != LandingPadInst::Catch ||
4209 !isa<ArrayType>(Val->getType())) &&
4210 "Catch clause has a invalid type!");
4211 assert((CT != LandingPadInst::Filter ||
4212 isa<ArrayType>(Val->getType())) &&
4213 "Filter clause has invalid type!");
4214 LP->addClause(cast<Constant>(Val));
4218 InstructionList.push_back(I);
4222 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4223 if (Record.size() != 4)
4224 return error("Invalid record");
4225 uint64_t AlignRecord = Record[3];
4226 const uint64_t InAllocaMask = uint64_t(1) << 5;
4227 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4228 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4229 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4231 bool InAlloca = AlignRecord & InAllocaMask;
4232 bool SwiftError = AlignRecord & SwiftErrorMask;
4233 Type *Ty = getTypeByID(Record[0]);
4234 if ((AlignRecord & ExplicitTypeMask) == 0) {
4235 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4237 return error("Old-style alloca with a non-pointer type");
4238 Ty = PTy->getElementType();
4240 Type *OpTy = getTypeByID(Record[1]);
4241 Value *Size = getFnValueByID(Record[2], OpTy);
4243 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4247 return error("Invalid record");
4249 // FIXME: Make this an optional field.
4250 const DataLayout &DL = TheModule->getDataLayout();
4251 unsigned AS = DL.getAllocaAddrSpace();
4253 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
4254 AI->setUsedWithInAlloca(InAlloca);
4255 AI->setSwiftError(SwiftError);
4257 InstructionList.push_back(I);
4260 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4263 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4264 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4265 return error("Invalid record");
4268 if (OpNum + 3 == Record.size())
4269 Ty = getTypeByID(Record[OpNum++]);
4270 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4273 Ty = cast<PointerType>(Op->getType())->getElementType();
4276 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4278 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4280 InstructionList.push_back(I);
4283 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4284 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
4287 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4288 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4289 return error("Invalid record");
4292 if (OpNum + 5 == Record.size())
4293 Ty = getTypeByID(Record[OpNum++]);
4294 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4297 Ty = cast<PointerType>(Op->getType())->getElementType();
4299 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4300 if (Ordering == AtomicOrdering::NotAtomic ||
4301 Ordering == AtomicOrdering::Release ||
4302 Ordering == AtomicOrdering::AcquireRelease)
4303 return error("Invalid record");
4304 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4305 return error("Invalid record");
4306 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4309 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4311 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID);
4313 InstructionList.push_back(I);
4316 case bitc::FUNC_CODE_INST_STORE:
4317 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4320 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4321 (BitCode == bitc::FUNC_CODE_INST_STORE
4322 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4323 : popValue(Record, OpNum, NextValueNo,
4324 cast<PointerType>(Ptr->getType())->getElementType(),
4326 OpNum + 2 != Record.size())
4327 return error("Invalid record");
4329 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4332 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4334 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4335 InstructionList.push_back(I);
4338 case bitc::FUNC_CODE_INST_STOREATOMIC:
4339 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4340 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
4343 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4344 !isa<PointerType>(Ptr->getType()) ||
4345 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4346 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4347 : popValue(Record, OpNum, NextValueNo,
4348 cast<PointerType>(Ptr->getType())->getElementType(),
4350 OpNum + 4 != Record.size())
4351 return error("Invalid record");
4353 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4355 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4356 if (Ordering == AtomicOrdering::NotAtomic ||
4357 Ordering == AtomicOrdering::Acquire ||
4358 Ordering == AtomicOrdering::AcquireRelease)
4359 return error("Invalid record");
4360 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4361 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4362 return error("Invalid record");
4365 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4367 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
4368 InstructionList.push_back(I);
4371 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4372 case bitc::FUNC_CODE_INST_CMPXCHG: {
4373 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
4374 // failureordering?, isweak?]
4376 Value *Ptr, *Cmp, *New;
4377 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4378 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4379 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4380 : popValue(Record, OpNum, NextValueNo,
4381 cast<PointerType>(Ptr->getType())->getElementType(),
4383 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4384 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4385 return error("Invalid record");
4386 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4387 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4388 SuccessOrdering == AtomicOrdering::Unordered)
4389 return error("Invalid record");
4390 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
4392 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4394 AtomicOrdering FailureOrdering;
4395 if (Record.size() < 7)
4397 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4399 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4401 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4403 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4405 if (Record.size() < 8) {
4406 // Before weak cmpxchgs existed, the instruction simply returned the
4407 // value loaded from memory, so bitcode files from that era will be
4408 // expecting the first component of a modern cmpxchg.
4409 CurBB->getInstList().push_back(I);
4410 I = ExtractValueInst::Create(I, 0);
4412 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4415 InstructionList.push_back(I);
4418 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4419 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
4422 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4423 !isa<PointerType>(Ptr->getType()) ||
4424 popValue(Record, OpNum, NextValueNo,
4425 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4426 OpNum+4 != Record.size())
4427 return error("Invalid record");
4428 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4429 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4430 Operation > AtomicRMWInst::LAST_BINOP)
4431 return error("Invalid record");
4432 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4433 if (Ordering == AtomicOrdering::NotAtomic ||
4434 Ordering == AtomicOrdering::Unordered)
4435 return error("Invalid record");
4436 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4437 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
4438 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4439 InstructionList.push_back(I);
4442 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
4443 if (2 != Record.size())
4444 return error("Invalid record");
4445 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4446 if (Ordering == AtomicOrdering::NotAtomic ||
4447 Ordering == AtomicOrdering::Unordered ||
4448 Ordering == AtomicOrdering::Monotonic)
4449 return error("Invalid record");
4450 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4451 I = new FenceInst(Context, Ordering, SSID);
4452 InstructionList.push_back(I);
4455 case bitc::FUNC_CODE_INST_CALL: {
4456 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4457 if (Record.size() < 3)
4458 return error("Invalid record");
4461 AttributeList PAL = getAttributes(Record[OpNum++]);
4462 unsigned CCInfo = Record[OpNum++];
4465 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4466 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4468 return error("Fast math flags indicator set for call with no FMF");
4471 FunctionType *FTy = nullptr;
4472 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4473 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4474 return error("Explicit call type is not a function type");
4477 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4478 return error("Invalid record");
4480 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4482 return error("Callee is not a pointer type");
4484 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4486 return error("Callee is not of pointer to function type");
4487 } else if (OpTy->getElementType() != FTy)
4488 return error("Explicit call type does not match pointee type of "
4490 if (Record.size() < FTy->getNumParams() + OpNum)
4491 return error("Insufficient operands to call");
4493 SmallVector<Value*, 16> Args;
4494 // Read the fixed params.
4495 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4496 if (FTy->getParamType(i)->isLabelTy())
4497 Args.push_back(getBasicBlock(Record[OpNum]));
4499 Args.push_back(getValue(Record, OpNum, NextValueNo,
4500 FTy->getParamType(i)));
4502 return error("Invalid record");
4505 // Read type/value pairs for varargs params.
4506 if (!FTy->isVarArg()) {
4507 if (OpNum != Record.size())
4508 return error("Invalid record");
4510 while (OpNum != Record.size()) {
4512 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4513 return error("Invalid record");
4518 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4519 OperandBundles.clear();
4520 InstructionList.push_back(I);
4521 cast<CallInst>(I)->setCallingConv(
4522 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4523 CallInst::TailCallKind TCK = CallInst::TCK_None;
4524 if (CCInfo & 1 << bitc::CALL_TAIL)
4525 TCK = CallInst::TCK_Tail;
4526 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
4527 TCK = CallInst::TCK_MustTail;
4528 if (CCInfo & (1 << bitc::CALL_NOTAIL))
4529 TCK = CallInst::TCK_NoTail;
4530 cast<CallInst>(I)->setTailCallKind(TCK);
4531 cast<CallInst>(I)->setAttributes(PAL);
4533 if (!isa<FPMathOperator>(I))
4534 return error("Fast-math-flags specified for call without "
4535 "floating-point scalar or vector return type");
4536 I->setFastMathFlags(FMF);
4540 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4541 if (Record.size() < 3)
4542 return error("Invalid record");
4543 Type *OpTy = getTypeByID(Record[0]);
4544 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4545 Type *ResTy = getTypeByID(Record[2]);
4546 if (!OpTy || !Op || !ResTy)
4547 return error("Invalid record");
4548 I = new VAArgInst(Op, ResTy);
4549 InstructionList.push_back(I);
4553 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4554 // A call or an invoke can be optionally prefixed with some variable
4555 // number of operand bundle blocks. These blocks are read into
4556 // OperandBundles and consumed at the next call or invoke instruction.
4558 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4559 return error("Invalid record");
4561 std::vector<Value *> Inputs;
4564 while (OpNum != Record.size()) {
4566 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4567 return error("Invalid record");
4568 Inputs.push_back(Op);
4571 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4576 // Add instruction to end of current BB. If there is no current BB, reject
4580 return error("Invalid instruction with no BB");
4582 if (!OperandBundles.empty()) {
4584 return error("Operand bundles found with no consumer");
4586 CurBB->getInstList().push_back(I);
4588 // If this was a terminator instruction, move to the next block.
4589 if (isa<TerminatorInst>(I)) {
4591 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4594 // Non-void values get registered in the value table for future use.
4595 if (I && !I->getType()->isVoidTy())
4596 ValueList.assignValue(I, NextValueNo++);
4601 if (!OperandBundles.empty())
4602 return error("Operand bundles found with no consumer");
4604 // Check the function list for unresolved values.
4605 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4606 if (!A->getParent()) {
4607 // We found at least one unresolved value. Nuke them all to avoid leaks.
4608 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4609 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4610 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4614 return error("Never resolved value found in function");
4618 // Unexpected unresolved metadata about to be dropped.
4619 if (MDLoader->hasFwdRefs())
4620 return error("Invalid function metadata: outgoing forward refs");
4622 // Trim the value list down to the size it was before we parsed this function.
4623 ValueList.shrinkTo(ModuleValueListSize);
4624 MDLoader->shrinkTo(ModuleMDLoaderSize);
4625 std::vector<BasicBlock*>().swap(FunctionBBs);
4626 return Error::success();
4629 /// Find the function body in the bitcode stream
4630 Error BitcodeReader::findFunctionInStream(
4632 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4633 while (DeferredFunctionInfoIterator->second == 0) {
4634 // This is the fallback handling for the old format bitcode that
4635 // didn't contain the function index in the VST, or when we have
4636 // an anonymous function which would not have a VST entry.
4637 // Assert that we have one of those two cases.
4638 assert(VSTOffset == 0 || !F->hasName());
4639 // Parse the next body in the stream and set its position in the
4640 // DeferredFunctionInfo map.
4641 if (Error Err = rememberAndSkipFunctionBodies())
4644 return Error::success();
4647 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
4648 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
4649 return SyncScope::ID(Val);
4650 if (Val >= SSIDs.size())
4651 return SyncScope::System; // Map unknown synchronization scopes to system.
4655 //===----------------------------------------------------------------------===//
4656 // GVMaterializer implementation
4657 //===----------------------------------------------------------------------===//
4659 Error BitcodeReader::materialize(GlobalValue *GV) {
4660 Function *F = dyn_cast<Function>(GV);
4661 // If it's not a function or is already material, ignore the request.
4662 if (!F || !F->isMaterializable())
4663 return Error::success();
4665 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4666 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4667 // If its position is recorded as 0, its body is somewhere in the stream
4668 // but we haven't seen it yet.
4669 if (DFII->second == 0)
4670 if (Error Err = findFunctionInStream(F, DFII))
4673 // Materialize metadata before parsing any function bodies.
4674 if (Error Err = materializeMetadata())
4677 // Move the bit stream to the saved position of the deferred function body.
4678 Stream.JumpToBit(DFII->second);
4680 if (Error Err = parseFunctionBody(F))
4682 F->setIsMaterializable(false);
4687 // Upgrade any old intrinsic calls in the function.
4688 for (auto &I : UpgradedIntrinsics) {
4689 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4693 if (CallInst *CI = dyn_cast<CallInst>(U))
4694 UpgradeIntrinsicCall(CI, I.second);
4698 // Update calls to the remangled intrinsics
4699 for (auto &I : RemangledIntrinsics)
4700 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4702 // Don't expect any other users than call sites
4703 CallSite(*UI++).setCalledFunction(I.second);
4705 // Finish fn->subprogram upgrade for materialized functions.
4706 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4707 F->setSubprogram(SP);
4709 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4710 if (!MDLoader->isStrippingTBAA()) {
4711 for (auto &I : instructions(F)) {
4712 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4713 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4715 MDLoader->setStripTBAA(true);
4716 stripTBAA(F->getParent());
4720 // Bring in any functions that this function forward-referenced via
4722 return materializeForwardReferencedFunctions();
4725 Error BitcodeReader::materializeModule() {
4726 if (Error Err = materializeMetadata())
4729 // Promise to materialize all forward references.
4730 WillMaterializeAllForwardRefs = true;
4732 // Iterate over the module, deserializing any functions that are still on
4734 for (Function &F : *TheModule) {
4735 if (Error Err = materialize(&F))
4738 // At this point, if there are any function bodies, parse the rest of
4739 // the bits in the module past the last function block we have recorded
4740 // through either lazy scanning or the VST.
4741 if (LastFunctionBlockBit || NextUnreadBit)
4742 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4743 ? LastFunctionBlockBit
4747 // Check that all block address forward references got resolved (as we
4749 if (!BasicBlockFwdRefs.empty())
4750 return error("Never resolved function from blockaddress");
4752 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4753 // delete the old functions to clean up. We can't do this unless the entire
4754 // module is materialized because there could always be another function body
4755 // with calls to the old function.
4756 for (auto &I : UpgradedIntrinsics) {
4757 for (auto *U : I.first->users()) {
4758 if (CallInst *CI = dyn_cast<CallInst>(U))
4759 UpgradeIntrinsicCall(CI, I.second);
4761 if (!I.first->use_empty())
4762 I.first->replaceAllUsesWith(I.second);
4763 I.first->eraseFromParent();
4765 UpgradedIntrinsics.clear();
4766 // Do the same for remangled intrinsics
4767 for (auto &I : RemangledIntrinsics) {
4768 I.first->replaceAllUsesWith(I.second);
4769 I.first->eraseFromParent();
4771 RemangledIntrinsics.clear();
4773 UpgradeDebugInfo(*TheModule);
4775 UpgradeModuleFlags(*TheModule);
4776 return Error::success();
4779 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4780 return IdentifiedStructTypes;
4783 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4784 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
4785 StringRef ModulePath, unsigned ModuleId)
4786 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4787 ModulePath(ModulePath), ModuleId(ModuleId) {}
4789 ModuleSummaryIndex::ModuleInfo *
4790 ModuleSummaryIndexBitcodeReader::addThisModule() {
4791 return TheIndex.addModule(ModulePath, ModuleId);
4794 std::pair<ValueInfo, GlobalValue::GUID>
4795 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
4796 auto VGI = ValueIdToValueInfoMap[ValueId];
4801 void ModuleSummaryIndexBitcodeReader::setValueGUID(
4802 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4803 StringRef SourceFileName) {
4804 std::string GlobalId =
4805 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4806 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4807 auto OriginalNameID = ValueGUID;
4808 if (GlobalValue::isLocalLinkage(Linkage))
4809 OriginalNameID = GlobalValue::getGUID(ValueName);
4810 if (PrintSummaryGUIDs)
4811 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4812 << ValueName << "\n";
4813 ValueIdToValueInfoMap[ValueID] =
4814 std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID);
4817 // Specialized value symbol table parser used when reading module index
4818 // blocks where we don't actually create global values. The parsed information
4819 // is saved in the bitcode reader for use when later parsing summaries.
4820 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
4822 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
4823 // With a strtab the VST is not required to parse the summary.
4825 return Error::success();
4827 assert(Offset > 0 && "Expected non-zero VST offset");
4828 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4830 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4831 return error("Invalid record");
4833 SmallVector<uint64_t, 64> Record;
4835 // Read all the records for this value table.
4836 SmallString<128> ValueName;
4839 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4841 switch (Entry.Kind) {
4842 case BitstreamEntry::SubBlock: // Handled for us already.
4843 case BitstreamEntry::Error:
4844 return error("Malformed block");
4845 case BitstreamEntry::EndBlock:
4846 // Done parsing VST, jump back to wherever we came from.
4847 Stream.JumpToBit(CurrentBit);
4848 return Error::success();
4849 case BitstreamEntry::Record:
4850 // The interesting case.
4856 switch (Stream.readRecord(Entry.ID, Record)) {
4857 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4859 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4860 if (convertToString(Record, 1, ValueName))
4861 return error("Invalid record");
4862 unsigned ValueID = Record[0];
4863 assert(!SourceFileName.empty());
4864 auto VLI = ValueIdToLinkageMap.find(ValueID);
4865 assert(VLI != ValueIdToLinkageMap.end() &&
4866 "No linkage found for VST entry?");
4867 auto Linkage = VLI->second;
4868 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4872 case bitc::VST_CODE_FNENTRY: {
4873 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
4874 if (convertToString(Record, 2, ValueName))
4875 return error("Invalid record");
4876 unsigned ValueID = Record[0];
4877 assert(!SourceFileName.empty());
4878 auto VLI = ValueIdToLinkageMap.find(ValueID);
4879 assert(VLI != ValueIdToLinkageMap.end() &&
4880 "No linkage found for VST entry?");
4881 auto Linkage = VLI->second;
4882 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4886 case bitc::VST_CODE_COMBINED_ENTRY: {
4887 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4888 unsigned ValueID = Record[0];
4889 GlobalValue::GUID RefGUID = Record[1];
4890 // The "original name", which is the second value of the pair will be
4891 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
4892 ValueIdToValueInfoMap[ValueID] =
4893 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
4900 // Parse just the blocks needed for building the index out of the module.
4901 // At the end of this routine the module Index is populated with a map
4902 // from global value id to GlobalValueSummary objects.
4903 Error ModuleSummaryIndexBitcodeReader::parseModule() {
4904 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4905 return error("Invalid record");
4907 SmallVector<uint64_t, 64> Record;
4908 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
4909 unsigned ValueId = 0;
4911 // Read the index for this module.
4913 BitstreamEntry Entry = Stream.advance();
4915 switch (Entry.Kind) {
4916 case BitstreamEntry::Error:
4917 return error("Malformed block");
4918 case BitstreamEntry::EndBlock:
4919 return Error::success();
4921 case BitstreamEntry::SubBlock:
4923 default: // Skip unknown content.
4924 if (Stream.SkipBlock())
4925 return error("Invalid record");
4927 case bitc::BLOCKINFO_BLOCK_ID:
4928 // Need to parse these to get abbrev ids (e.g. for VST)
4929 if (readBlockInfo())
4930 return error("Malformed block");
4932 case bitc::VALUE_SYMTAB_BLOCK_ID:
4933 // Should have been parsed earlier via VSTOffset, unless there
4934 // is no summary section.
4935 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4936 !SeenGlobalValSummary) &&
4937 "Expected early VST parse via VSTOffset record");
4938 if (Stream.SkipBlock())
4939 return error("Invalid record");
4941 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
4942 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
4943 assert(!SeenValueSymbolTable &&
4944 "Already read VST when parsing summary block?");
4945 // We might not have a VST if there were no values in the
4946 // summary. An empty summary block generated when we are
4947 // performing ThinLTO compiles so we don't later invoke
4948 // the regular LTO process on them.
4949 if (VSTOffset > 0) {
4950 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4952 SeenValueSymbolTable = true;
4954 SeenGlobalValSummary = true;
4955 if (Error Err = parseEntireSummary(Entry.ID))
4958 case bitc::MODULE_STRTAB_BLOCK_ID:
4959 if (Error Err = parseModuleStringTable())
4965 case BitstreamEntry::Record: {
4967 auto BitCode = Stream.readRecord(Entry.ID, Record);
4970 break; // Default behavior, ignore unknown content.
4971 case bitc::MODULE_CODE_VERSION: {
4972 if (Error Err = parseVersionRecord(Record).takeError())
4976 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4977 case bitc::MODULE_CODE_SOURCE_FILENAME: {
4978 SmallString<128> ValueName;
4979 if (convertToString(Record, 0, ValueName))
4980 return error("Invalid record");
4981 SourceFileName = ValueName.c_str();
4984 /// MODULE_CODE_HASH: [5*i32]
4985 case bitc::MODULE_CODE_HASH: {
4986 if (Record.size() != 5)
4987 return error("Invalid hash length " + Twine(Record.size()).str());
4988 auto &Hash = addThisModule()->second.second;
4990 for (auto &Val : Record) {
4991 assert(!(Val >> 32) && "Unexpected high bits set");
4996 /// MODULE_CODE_VSTOFFSET: [offset]
4997 case bitc::MODULE_CODE_VSTOFFSET:
4998 if (Record.size() < 1)
4999 return error("Invalid record");
5000 // Note that we subtract 1 here because the offset is relative to one
5001 // word before the start of the identification or module block, which
5002 // was historically always the start of the regular bitcode header.
5003 VSTOffset = Record[0] - 1;
5005 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
5006 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
5007 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
5008 // v2: [strtab offset, strtab size, v1]
5009 case bitc::MODULE_CODE_GLOBALVAR:
5010 case bitc::MODULE_CODE_FUNCTION:
5011 case bitc::MODULE_CODE_ALIAS: {
5013 ArrayRef<uint64_t> GVRecord;
5014 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5015 if (GVRecord.size() <= 3)
5016 return error("Invalid record");
5017 uint64_t RawLinkage = GVRecord[3];
5018 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5020 ValueIdToLinkageMap[ValueId++] = Linkage;
5024 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5034 std::vector<ValueInfo>
5035 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5036 std::vector<ValueInfo> Ret;
5037 Ret.reserve(Record.size());
5038 for (uint64_t RefValueId : Record)
5039 Ret.push_back(getValueInfoFromValueId(RefValueId).first);
5043 std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
5044 ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
5045 std::vector<FunctionSummary::EdgeTy> Ret;
5046 Ret.reserve(Record.size());
5047 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5048 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
5049 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
5050 if (IsOldProfileFormat) {
5051 I += 1; // Skip old callsitecount field
5053 I += 1; // Skip old profilecount field
5054 } else if (HasProfile)
5055 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
5056 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo{Hotness}});
5061 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
5062 // objects in the index.
5063 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5064 if (Stream.EnterSubBlock(ID))
5065 return error("Invalid record");
5066 SmallVector<uint64_t, 64> Record;
5070 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5071 if (Entry.Kind != BitstreamEntry::Record)
5072 return error("Invalid Summary Block: record for version expected");
5073 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
5074 return error("Invalid Summary Block: version expected");
5076 const uint64_t Version = Record[0];
5077 const bool IsOldProfileFormat = Version == 1;
5078 if (Version < 1 || Version > 4)
5079 return error("Invalid summary version " + Twine(Version) +
5080 ", 1, 2, 3 or 4 expected");
5083 // Keep around the last seen summary to be used when we see an optional
5084 // "OriginalName" attachement.
5085 GlobalValueSummary *LastSeenSummary = nullptr;
5086 GlobalValue::GUID LastSeenGUID = 0;
5088 // We can expect to see any number of type ID information records before
5089 // each function summary records; these variables store the information
5090 // collected so far so that it can be used to create the summary object.
5091 std::vector<GlobalValue::GUID> PendingTypeTests;
5092 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5093 PendingTypeCheckedLoadVCalls;
5094 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5095 PendingTypeCheckedLoadConstVCalls;
5098 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5100 switch (Entry.Kind) {
5101 case BitstreamEntry::SubBlock: // Handled for us already.
5102 case BitstreamEntry::Error:
5103 return error("Malformed block");
5104 case BitstreamEntry::EndBlock:
5105 return Error::success();
5106 case BitstreamEntry::Record:
5107 // The interesting case.
5111 // Read a record. The record format depends on whether this
5112 // is a per-module index or a combined index file. In the per-module
5113 // case the records contain the associated value's ID for correlation
5114 // with VST entries. In the combined index the correlation is done
5115 // via the bitcode offset of the summary records (which were saved
5116 // in the combined index VST entries). The records also contain
5117 // information used for ThinLTO renaming and importing.
5119 auto BitCode = Stream.readRecord(Entry.ID, Record);
5121 default: // Default behavior: ignore.
5123 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5124 uint64_t ValueID = Record[0];
5125 GlobalValue::GUID RefGUID = Record[1];
5126 ValueIdToValueInfoMap[ValueID] =
5127 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5130 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5131 // numrefs x valueid, n x (valueid)]
5132 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
5133 // numrefs x valueid,
5134 // n x (valueid, hotness)]
5135 case bitc::FS_PERMODULE:
5136 case bitc::FS_PERMODULE_PROFILE: {
5137 unsigned ValueID = Record[0];
5138 uint64_t RawFlags = Record[1];
5139 unsigned InstCount = Record[2];
5140 uint64_t RawFunFlags = 0;
5141 unsigned NumRefs = Record[3];
5142 int RefListStartIndex = 4;
5144 RawFunFlags = Record[3];
5145 NumRefs = Record[4];
5146 RefListStartIndex = 5;
5149 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5150 // The module path string ref set in the summary must be owned by the
5151 // index's module string table. Since we don't have a module path
5152 // string table section in the per-module index, we create a single
5153 // module path string table entry with an empty (0) ID to take
5155 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5156 assert(Record.size() >= RefListStartIndex + NumRefs &&
5157 "Record size inconsistent with number of references");
5158 std::vector<ValueInfo> Refs = makeRefList(
5159 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5160 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5161 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5162 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5163 IsOldProfileFormat, HasProfile);
5164 auto FS = llvm::make_unique<FunctionSummary>(
5165 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5166 std::move(Calls), std::move(PendingTypeTests),
5167 std::move(PendingTypeTestAssumeVCalls),
5168 std::move(PendingTypeCheckedLoadVCalls),
5169 std::move(PendingTypeTestAssumeConstVCalls),
5170 std::move(PendingTypeCheckedLoadConstVCalls));
5171 PendingTypeTests.clear();
5172 PendingTypeTestAssumeVCalls.clear();
5173 PendingTypeCheckedLoadVCalls.clear();
5174 PendingTypeTestAssumeConstVCalls.clear();
5175 PendingTypeCheckedLoadConstVCalls.clear();
5176 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
5177 FS->setModulePath(addThisModule()->first());
5178 FS->setOriginalName(VIAndOriginalGUID.second);
5179 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
5182 // FS_ALIAS: [valueid, flags, valueid]
5183 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5184 // they expect all aliasee summaries to be available.
5185 case bitc::FS_ALIAS: {
5186 unsigned ValueID = Record[0];
5187 uint64_t RawFlags = Record[1];
5188 unsigned AliaseeID = Record[2];
5189 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5190 auto AS = llvm::make_unique<AliasSummary>(Flags);
5191 // The module path string ref set in the summary must be owned by the
5192 // index's module string table. Since we don't have a module path
5193 // string table section in the per-module index, we create a single
5194 // module path string table entry with an empty (0) ID to take
5196 AS->setModulePath(addThisModule()->first());
5198 GlobalValue::GUID AliaseeGUID =
5199 getValueInfoFromValueId(AliaseeID).first.getGUID();
5200 auto AliaseeInModule =
5201 TheIndex.findSummaryInModule(AliaseeGUID, ModulePath);
5202 if (!AliaseeInModule)
5203 return error("Alias expects aliasee summary to be parsed");
5204 AS->setAliasee(AliaseeInModule);
5205 AS->setAliaseeGUID(AliaseeGUID);
5207 auto GUID = getValueInfoFromValueId(ValueID);
5208 AS->setOriginalName(GUID.second);
5209 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
5212 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
5213 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5214 unsigned ValueID = Record[0];
5215 uint64_t RawFlags = Record[1];
5216 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5217 std::vector<ValueInfo> Refs =
5218 makeRefList(ArrayRef<uint64_t>(Record).slice(2));
5219 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5220 FS->setModulePath(addThisModule()->first());
5221 auto GUID = getValueInfoFromValueId(ValueID);
5222 FS->setOriginalName(GUID.second);
5223 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
5226 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
5227 // numrefs x valueid, n x (valueid)]
5228 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
5229 // numrefs x valueid, n x (valueid, hotness)]
5230 case bitc::FS_COMBINED:
5231 case bitc::FS_COMBINED_PROFILE: {
5232 unsigned ValueID = Record[0];
5233 uint64_t ModuleId = Record[1];
5234 uint64_t RawFlags = Record[2];
5235 unsigned InstCount = Record[3];
5236 uint64_t RawFunFlags = 0;
5237 unsigned NumRefs = Record[4];
5238 int RefListStartIndex = 5;
5241 RawFunFlags = Record[4];
5242 NumRefs = Record[5];
5243 RefListStartIndex = 6;
5246 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5247 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5248 assert(Record.size() >= RefListStartIndex + NumRefs &&
5249 "Record size inconsistent with number of references");
5250 std::vector<ValueInfo> Refs = makeRefList(
5251 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5252 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5253 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5254 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5255 IsOldProfileFormat, HasProfile);
5256 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5257 auto FS = llvm::make_unique<FunctionSummary>(
5258 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5259 std::move(Edges), std::move(PendingTypeTests),
5260 std::move(PendingTypeTestAssumeVCalls),
5261 std::move(PendingTypeCheckedLoadVCalls),
5262 std::move(PendingTypeTestAssumeConstVCalls),
5263 std::move(PendingTypeCheckedLoadConstVCalls));
5264 PendingTypeTests.clear();
5265 PendingTypeTestAssumeVCalls.clear();
5266 PendingTypeCheckedLoadVCalls.clear();
5267 PendingTypeTestAssumeConstVCalls.clear();
5268 PendingTypeCheckedLoadConstVCalls.clear();
5269 LastSeenSummary = FS.get();
5270 LastSeenGUID = VI.getGUID();
5271 FS->setModulePath(ModuleIdMap[ModuleId]);
5272 TheIndex.addGlobalValueSummary(VI, std::move(FS));
5275 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
5276 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5277 // they expect all aliasee summaries to be available.
5278 case bitc::FS_COMBINED_ALIAS: {
5279 unsigned ValueID = Record[0];
5280 uint64_t ModuleId = Record[1];
5281 uint64_t RawFlags = Record[2];
5282 unsigned AliaseeValueId = Record[3];
5283 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5284 auto AS = llvm::make_unique<AliasSummary>(Flags);
5285 LastSeenSummary = AS.get();
5286 AS->setModulePath(ModuleIdMap[ModuleId]);
5289 getValueInfoFromValueId(AliaseeValueId).first.getGUID();
5290 auto AliaseeInModule =
5291 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
5292 AS->setAliasee(AliaseeInModule);
5293 AS->setAliaseeGUID(AliaseeGUID);
5295 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5296 LastSeenGUID = VI.getGUID();
5297 TheIndex.addGlobalValueSummary(VI, std::move(AS));
5300 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
5301 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5302 unsigned ValueID = Record[0];
5303 uint64_t ModuleId = Record[1];
5304 uint64_t RawFlags = Record[2];
5305 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5306 std::vector<ValueInfo> Refs =
5307 makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5308 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5309 LastSeenSummary = FS.get();
5310 FS->setModulePath(ModuleIdMap[ModuleId]);
5311 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5312 LastSeenGUID = VI.getGUID();
5313 TheIndex.addGlobalValueSummary(VI, std::move(FS));
5316 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5317 case bitc::FS_COMBINED_ORIGINAL_NAME: {
5318 uint64_t OriginalName = Record[0];
5319 if (!LastSeenSummary)
5320 return error("Name attachment that does not follow a combined record");
5321 LastSeenSummary->setOriginalName(OriginalName);
5322 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
5323 // Reset the LastSeenSummary
5324 LastSeenSummary = nullptr;
5328 case bitc::FS_TYPE_TESTS:
5329 assert(PendingTypeTests.empty());
5330 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5334 case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
5335 assert(PendingTypeTestAssumeVCalls.empty());
5336 for (unsigned I = 0; I != Record.size(); I += 2)
5337 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5340 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
5341 assert(PendingTypeCheckedLoadVCalls.empty());
5342 for (unsigned I = 0; I != Record.size(); I += 2)
5343 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5346 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
5347 PendingTypeTestAssumeConstVCalls.push_back(
5348 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5351 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
5352 PendingTypeCheckedLoadConstVCalls.push_back(
5353 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5356 case bitc::FS_CFI_FUNCTION_DEFS: {
5357 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
5358 for (unsigned I = 0; I != Record.size(); I += 2)
5359 CfiFunctionDefs.insert(
5360 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5363 case bitc::FS_CFI_FUNCTION_DECLS: {
5364 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
5365 for (unsigned I = 0; I != Record.size(); I += 2)
5366 CfiFunctionDecls.insert(
5367 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5372 llvm_unreachable("Exit infinite loop");
5375 // Parse the module string table block into the Index.
5376 // This populates the ModulePathStringTable map in the index.
5377 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5378 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5379 return error("Invalid record");
5381 SmallVector<uint64_t, 64> Record;
5383 SmallString<128> ModulePath;
5384 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
5387 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5389 switch (Entry.Kind) {
5390 case BitstreamEntry::SubBlock: // Handled for us already.
5391 case BitstreamEntry::Error:
5392 return error("Malformed block");
5393 case BitstreamEntry::EndBlock:
5394 return Error::success();
5395 case BitstreamEntry::Record:
5396 // The interesting case.
5401 switch (Stream.readRecord(Entry.ID, Record)) {
5402 default: // Default behavior: ignore.
5404 case bitc::MST_CODE_ENTRY: {
5405 // MST_ENTRY: [modid, namechar x N]
5406 uint64_t ModuleId = Record[0];
5408 if (convertToString(Record, 1, ModulePath))
5409 return error("Invalid record");
5411 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
5412 ModuleIdMap[ModuleId] = LastSeenModule->first();
5417 /// MST_CODE_HASH: [5*i32]
5418 case bitc::MST_CODE_HASH: {
5419 if (Record.size() != 5)
5420 return error("Invalid hash length " + Twine(Record.size()).str());
5421 if (!LastSeenModule)
5422 return error("Invalid hash that does not follow a module path");
5424 for (auto &Val : Record) {
5425 assert(!(Val >> 32) && "Unexpected high bits set");
5426 LastSeenModule->second.second[Pos++] = Val;
5428 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
5429 LastSeenModule = nullptr;
5434 llvm_unreachable("Exit infinite loop");
5439 // FIXME: This class is only here to support the transition to llvm::Error. It
5440 // will be removed once this transition is complete. Clients should prefer to
5441 // deal with the Error value directly, rather than converting to error_code.
5442 class BitcodeErrorCategoryType : public std::error_category {
5443 const char *name() const noexcept override {
5444 return "llvm.bitcode";
5447 std::string message(int IE) const override {
5448 BitcodeError E = static_cast<BitcodeError>(IE);
5450 case BitcodeError::CorruptedBitcode:
5451 return "Corrupted bitcode";
5453 llvm_unreachable("Unknown error type!");
5457 } // end anonymous namespace
5459 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5461 const std::error_category &llvm::BitcodeErrorCategory() {
5462 return *ErrorCategory;
5465 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
5466 unsigned Block, unsigned RecordID) {
5467 if (Stream.EnterSubBlock(Block))
5468 return error("Invalid record");
5472 BitstreamEntry Entry = Stream.advance();
5473 switch (Entry.Kind) {
5474 case BitstreamEntry::EndBlock:
5477 case BitstreamEntry::Error:
5478 return error("Malformed block");
5480 case BitstreamEntry::SubBlock:
5481 if (Stream.SkipBlock())
5482 return error("Malformed block");
5485 case BitstreamEntry::Record:
5487 SmallVector<uint64_t, 1> Record;
5488 if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
5495 //===----------------------------------------------------------------------===//
5496 // External interface
5497 //===----------------------------------------------------------------------===//
5499 Expected<std::vector<BitcodeModule>>
5500 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
5501 auto FOrErr = getBitcodeFileContents(Buffer);
5503 return FOrErr.takeError();
5504 return std::move(FOrErr->Mods);
5507 Expected<BitcodeFileContents>
5508 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
5509 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5511 return StreamOrErr.takeError();
5512 BitstreamCursor &Stream = *StreamOrErr;
5514 BitcodeFileContents F;
5516 uint64_t BCBegin = Stream.getCurrentByteNo();
5518 // We may be consuming bitcode from a client that leaves garbage at the end
5519 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5520 // the end that there cannot possibly be another module, stop looking.
5521 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
5524 BitstreamEntry Entry = Stream.advance();
5525 switch (Entry.Kind) {
5526 case BitstreamEntry::EndBlock:
5527 case BitstreamEntry::Error:
5528 return error("Malformed block");
5530 case BitstreamEntry::SubBlock: {
5531 uint64_t IdentificationBit = -1ull;
5532 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5533 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5534 if (Stream.SkipBlock())
5535 return error("Malformed block");
5537 Entry = Stream.advance();
5538 if (Entry.Kind != BitstreamEntry::SubBlock ||
5539 Entry.ID != bitc::MODULE_BLOCK_ID)
5540 return error("Malformed block");
5543 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5544 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5545 if (Stream.SkipBlock())
5546 return error("Malformed block");
5548 F.Mods.push_back({Stream.getBitcodeBytes().slice(
5549 BCBegin, Stream.getCurrentByteNo() - BCBegin),
5550 Buffer.getBufferIdentifier(), IdentificationBit,
5555 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
5556 Expected<StringRef> Strtab =
5557 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
5559 return Strtab.takeError();
5560 // This string table is used by every preceding bitcode module that does
5561 // not have its own string table. A bitcode file may have multiple
5562 // string tables if it was created by binary concatenation, for example
5563 // with "llvm-cat -b".
5564 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
5565 if (!I->Strtab.empty())
5567 I->Strtab = *Strtab;
5569 // Similarly, the string table is used by every preceding symbol table;
5570 // normally there will be just one unless the bitcode file was created
5571 // by binary concatenation.
5572 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
5573 F.StrtabForSymtab = *Strtab;
5577 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
5578 Expected<StringRef> SymtabOrErr =
5579 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
5581 return SymtabOrErr.takeError();
5583 // We can expect the bitcode file to have multiple symbol tables if it
5584 // was created by binary concatenation. In that case we silently
5585 // ignore any subsequent symbol tables, which is fine because this is a
5586 // low level function. The client is expected to notice that the number
5587 // of modules in the symbol table does not match the number of modules
5588 // in the input file and regenerate the symbol table.
5589 if (F.Symtab.empty())
5590 F.Symtab = *SymtabOrErr;
5594 if (Stream.SkipBlock())
5595 return error("Malformed block");
5598 case BitstreamEntry::Record:
5599 Stream.skipRecord(Entry.ID);
5605 /// \brief Get a lazy one-at-time loading module from bitcode.
5607 /// This isn't always used in a lazy context. In particular, it's also used by
5608 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
5609 /// in forward-referenced functions from block address references.
5611 /// \param[in] MaterializeAll Set to \c true if we should materialize
5613 Expected<std::unique_ptr<Module>>
5614 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
5615 bool ShouldLazyLoadMetadata, bool IsImporting) {
5616 BitstreamCursor Stream(Buffer);
5618 std::string ProducerIdentification;
5619 if (IdentificationBit != -1ull) {
5620 Stream.JumpToBit(IdentificationBit);
5621 Expected<std::string> ProducerIdentificationOrErr =
5622 readIdentificationBlock(Stream);
5623 if (!ProducerIdentificationOrErr)
5624 return ProducerIdentificationOrErr.takeError();
5626 ProducerIdentification = *ProducerIdentificationOrErr;
5629 Stream.JumpToBit(ModuleBit);
5630 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5633 std::unique_ptr<Module> M =
5634 llvm::make_unique<Module>(ModuleIdentifier, Context);
5635 M->setMaterializer(R);
5637 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5639 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5640 return std::move(Err);
5642 if (MaterializeAll) {
5643 // Read in the entire module, and destroy the BitcodeReader.
5644 if (Error Err = M->materializeAll())
5645 return std::move(Err);
5647 // Resolve forward references from blockaddresses.
5648 if (Error Err = R->materializeForwardReferencedFunctions())
5649 return std::move(Err);
5651 return std::move(M);
5654 Expected<std::unique_ptr<Module>>
5655 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5657 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
5660 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
5661 // We don't use ModuleIdentifier here because the client may need to control the
5662 // module path used in the combined summary (e.g. when reading summaries for
5663 // regular LTO modules).
5664 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
5665 StringRef ModulePath, uint64_t ModuleId) {
5666 BitstreamCursor Stream(Buffer);
5667 Stream.JumpToBit(ModuleBit);
5669 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
5670 ModulePath, ModuleId);
5671 return R.parseModule();
5674 // Parse the specified bitcode buffer, returning the function info index.
5675 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5676 BitstreamCursor Stream(Buffer);
5677 Stream.JumpToBit(ModuleBit);
5679 auto Index = llvm::make_unique<ModuleSummaryIndex>();
5680 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
5681 ModuleIdentifier, 0);
5683 if (Error Err = R.parseModule())
5684 return std::move(Err);
5686 return std::move(Index);
5689 // Check if the given bitcode buffer contains a global value summary block.
5690 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
5691 BitstreamCursor Stream(Buffer);
5692 Stream.JumpToBit(ModuleBit);
5694 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5695 return error("Invalid record");
5698 BitstreamEntry Entry = Stream.advance();
5700 switch (Entry.Kind) {
5701 case BitstreamEntry::Error:
5702 return error("Malformed block");
5703 case BitstreamEntry::EndBlock:
5704 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false};
5706 case BitstreamEntry::SubBlock:
5707 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
5708 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true};
5710 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID)
5711 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true};
5713 // Ignore other sub-blocks.
5714 if (Stream.SkipBlock())
5715 return error("Malformed block");
5718 case BitstreamEntry::Record:
5719 Stream.skipRecord(Entry.ID);
5725 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
5726 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5728 return MsOrErr.takeError();
5730 if (MsOrErr->size() != 1)
5731 return error("Expected a single module");
5733 return (*MsOrErr)[0];
5736 Expected<std::unique_ptr<Module>>
5737 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5738 bool ShouldLazyLoadMetadata, bool IsImporting) {
5739 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5741 return BM.takeError();
5743 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5746 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5747 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5748 bool ShouldLazyLoadMetadata, bool IsImporting) {
5749 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5752 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5756 Expected<std::unique_ptr<Module>>
5757 BitcodeModule::parseModule(LLVMContext &Context) {
5758 return getModuleImpl(Context, true, false, false);
5759 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5760 // written. We must defer until the Module has been fully materialized.
5763 Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5764 LLVMContext &Context) {
5765 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5767 return BM.takeError();
5769 return BM->parseModule(Context);
5772 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5773 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5775 return StreamOrErr.takeError();
5777 return readTriple(*StreamOrErr);
5780 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5781 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5783 return StreamOrErr.takeError();
5785 return hasObjCCategory(*StreamOrErr);
5788 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5789 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5791 return StreamOrErr.takeError();
5793 return readIdentificationCode(*StreamOrErr);
5796 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
5797 ModuleSummaryIndex &CombinedIndex,
5798 uint64_t ModuleId) {
5799 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5801 return BM.takeError();
5803 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
5806 Expected<std::unique_ptr<ModuleSummaryIndex>>
5807 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
5808 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5810 return BM.takeError();
5812 return BM->getSummary();
5815 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
5816 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5818 return BM.takeError();
5820 return BM->getLTOInfo();
5823 Expected<std::unique_ptr<ModuleSummaryIndex>>
5824 llvm::getModuleSummaryIndexForFile(StringRef Path,
5825 bool IgnoreEmptyThinLTOIndexFile) {
5826 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5827 MemoryBuffer::getFileOrSTDIN(Path);
5829 return errorCodeToError(FileOrErr.getError());
5830 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
5832 return getModuleSummaryIndex(**FileOrErr);