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"
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Bitcode/BitstreamReader.h"
26 #include "llvm/Bitcode/LLVMBitCodes.h"
27 #include "llvm/IR/Argument.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/AutoUpgrade.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/CallSite.h"
33 #include "llvm/IR/Comdat.h"
34 #include "llvm/IR/Constant.h"
35 #include "llvm/IR/Constants.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/DiagnosticInfo.h"
41 #include "llvm/IR/DiagnosticPrinter.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalIFunc.h"
45 #include "llvm/IR/GlobalIndirectSymbol.h"
46 #include "llvm/IR/GlobalObject.h"
47 #include "llvm/IR/GlobalValue.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/GVMaterializer.h"
50 #include "llvm/IR/InlineAsm.h"
51 #include "llvm/IR/InstIterator.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/Intrinsics.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/ModuleSummaryIndex.h"
59 #include "llvm/IR/OperandTraits.h"
60 #include "llvm/IR/Operator.h"
61 #include "llvm/IR/TrackingMDRef.h"
62 #include "llvm/IR/Type.h"
63 #include "llvm/IR/ValueHandle.h"
64 #include "llvm/IR/Verifier.h"
65 #include "llvm/Support/AtomicOrdering.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/Error.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/ManagedStatic.h"
73 #include "llvm/Support/MemoryBuffer.h"
74 #include "llvm/Support/raw_ostream.h"
84 #include <system_error>
91 static cl::opt<bool> PrintSummaryGUIDs(
92 "print-summary-global-ids", cl::init(false), cl::Hidden,
94 "Print the global id for each value when reading the module summary"));
99 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
102 Error error(const Twine &Message) {
103 return make_error<StringError>(
104 Message, make_error_code(BitcodeError::CorruptedBitcode));
107 /// Helper to read the header common to all bitcode files.
108 bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
109 // Sniff for the signature.
110 if (!Stream.canSkipToPos(4) ||
111 Stream.Read(8) != 'B' ||
112 Stream.Read(8) != 'C' ||
113 Stream.Read(4) != 0x0 ||
114 Stream.Read(4) != 0xC ||
115 Stream.Read(4) != 0xE ||
116 Stream.Read(4) != 0xD)
121 Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
122 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
123 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
125 if (Buffer.getBufferSize() & 3)
126 return error("Invalid bitcode signature");
128 // If we have a wrapper header, parse it and ignore the non-bc file contents.
129 // The magic number is 0x0B17C0DE stored in little endian.
130 if (isBitcodeWrapper(BufPtr, BufEnd))
131 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
132 return error("Invalid bitcode wrapper header");
134 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
135 if (!hasValidBitcodeHeader(Stream))
136 return error("Invalid bitcode signature");
138 return std::move(Stream);
141 /// Convert a string from a record into an std::string, return true on failure.
142 template <typename StrTy>
143 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
145 if (Idx > Record.size())
148 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
149 Result += (char)Record[i];
153 // Strip all the TBAA attachment for the module.
154 void stripTBAA(Module *M) {
156 if (F.isMaterializable())
158 for (auto &I : instructions(F))
159 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
163 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
164 /// "epoch" encoded in the bitcode, and return the producer name if any.
165 Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
166 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
167 return error("Invalid record");
169 // Read all the records.
170 SmallVector<uint64_t, 64> Record;
172 std::string ProducerIdentification;
175 BitstreamEntry Entry = Stream.advance();
177 switch (Entry.Kind) {
179 case BitstreamEntry::Error:
180 return error("Malformed block");
181 case BitstreamEntry::EndBlock:
182 return ProducerIdentification;
183 case BitstreamEntry::Record:
184 // The interesting case.
190 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
192 default: // Default behavior: reject
193 return error("Invalid value");
194 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
195 convertToString(Record, 0, ProducerIdentification);
197 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
198 unsigned epoch = (unsigned)Record[0];
199 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
201 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
202 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
209 Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
210 // We expect a number of well-defined blocks, though we don't necessarily
211 // need to understand them all.
213 if (Stream.AtEndOfStream())
216 BitstreamEntry Entry = Stream.advance();
217 switch (Entry.Kind) {
218 case BitstreamEntry::EndBlock:
219 case BitstreamEntry::Error:
220 return error("Malformed block");
222 case BitstreamEntry::SubBlock:
223 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
224 return readIdentificationBlock(Stream);
226 // Ignore other sub-blocks.
227 if (Stream.SkipBlock())
228 return error("Malformed block");
230 case BitstreamEntry::Record:
231 Stream.skipRecord(Entry.ID);
237 Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
238 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
239 return error("Invalid record");
241 SmallVector<uint64_t, 64> Record;
242 // Read all the records for this module.
245 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
247 switch (Entry.Kind) {
248 case BitstreamEntry::SubBlock: // Handled for us already.
249 case BitstreamEntry::Error:
250 return error("Malformed block");
251 case BitstreamEntry::EndBlock:
253 case BitstreamEntry::Record:
254 // The interesting case.
259 switch (Stream.readRecord(Entry.ID, Record)) {
261 break; // Default behavior, ignore unknown content.
262 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
264 if (convertToString(Record, 0, S))
265 return error("Invalid record");
266 // Check for the i386 and other (x86_64, ARM) conventions
267 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
268 S.find("__OBJC,__category") != std::string::npos)
275 llvm_unreachable("Exit infinite loop");
278 Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
279 // We expect a number of well-defined blocks, though we don't necessarily
280 // need to understand them all.
282 BitstreamEntry Entry = Stream.advance();
284 switch (Entry.Kind) {
285 case BitstreamEntry::Error:
286 return error("Malformed block");
287 case BitstreamEntry::EndBlock:
290 case BitstreamEntry::SubBlock:
291 if (Entry.ID == bitc::MODULE_BLOCK_ID)
292 return hasObjCCategoryInModule(Stream);
294 // Ignore other sub-blocks.
295 if (Stream.SkipBlock())
296 return error("Malformed block");
299 case BitstreamEntry::Record:
300 Stream.skipRecord(Entry.ID);
306 Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
307 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
308 return error("Invalid record");
310 SmallVector<uint64_t, 64> Record;
314 // Read all the records for this module.
316 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
318 switch (Entry.Kind) {
319 case BitstreamEntry::SubBlock: // Handled for us already.
320 case BitstreamEntry::Error:
321 return error("Malformed block");
322 case BitstreamEntry::EndBlock:
324 case BitstreamEntry::Record:
325 // The interesting case.
330 switch (Stream.readRecord(Entry.ID, Record)) {
331 default: break; // Default behavior, ignore unknown content.
332 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
334 if (convertToString(Record, 0, S))
335 return error("Invalid record");
342 llvm_unreachable("Exit infinite loop");
345 Expected<std::string> readTriple(BitstreamCursor &Stream) {
346 // We expect a number of well-defined blocks, though we don't necessarily
347 // need to understand them all.
349 BitstreamEntry Entry = Stream.advance();
351 switch (Entry.Kind) {
352 case BitstreamEntry::Error:
353 return error("Malformed block");
354 case BitstreamEntry::EndBlock:
357 case BitstreamEntry::SubBlock:
358 if (Entry.ID == bitc::MODULE_BLOCK_ID)
359 return readModuleTriple(Stream);
361 // Ignore other sub-blocks.
362 if (Stream.SkipBlock())
363 return error("Malformed block");
366 case BitstreamEntry::Record:
367 Stream.skipRecord(Entry.ID);
373 class BitcodeReaderBase {
375 BitcodeReaderBase(BitstreamCursor Stream) : Stream(std::move(Stream)) {
376 this->Stream.setBlockInfo(&BlockInfo);
379 BitstreamBlockInfo BlockInfo;
380 BitstreamCursor Stream;
382 bool readBlockInfo();
384 // Contains an arbitrary and optional string identifying the bitcode producer
385 std::string ProducerIdentification;
387 Error error(const Twine &Message);
390 Error BitcodeReaderBase::error(const Twine &Message) {
391 std::string FullMsg = Message.str();
392 if (!ProducerIdentification.empty())
393 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
394 LLVM_VERSION_STRING "')";
395 return ::error(FullMsg);
398 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
399 LLVMContext &Context;
400 Module *TheModule = nullptr;
401 // Next offset to start scanning for lazy parsing of function bodies.
402 uint64_t NextUnreadBit = 0;
403 // Last function offset found in the VST.
404 uint64_t LastFunctionBlockBit = 0;
405 bool SeenValueSymbolTable = false;
406 uint64_t VSTOffset = 0;
408 std::vector<Type*> TypeList;
409 BitcodeReaderValueList ValueList;
410 Optional<MetadataLoader> MDLoader;
411 std::vector<Comdat *> ComdatList;
412 SmallVector<Instruction *, 64> InstructionList;
414 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
415 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
416 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
417 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
418 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
420 /// The set of attributes by index. Index zero in the file is for null, and
421 /// is thus not represented here. As such all indices are off by one.
422 std::vector<AttributeSet> MAttributes;
424 /// The set of attribute groups.
425 std::map<unsigned, AttributeSet> MAttributeGroups;
427 /// While parsing a function body, this is a list of the basic blocks for the
429 std::vector<BasicBlock*> FunctionBBs;
431 // When reading the module header, this list is populated with functions that
432 // have bodies later in the file.
433 std::vector<Function*> FunctionsWithBodies;
435 // When intrinsic functions are encountered which require upgrading they are
436 // stored here with their replacement function.
437 typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
438 UpdatedIntrinsicMap UpgradedIntrinsics;
439 // Intrinsics which were remangled because of types rename
440 UpdatedIntrinsicMap RemangledIntrinsics;
442 // Several operations happen after the module header has been read, but
443 // before function bodies are processed. This keeps track of whether
444 // we've done this yet.
445 bool SeenFirstFunctionBody = false;
447 /// When function bodies are initially scanned, this map contains info about
448 /// where to find deferred function body in the stream.
449 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
451 /// When Metadata block is initially scanned when parsing the module, we may
452 /// choose to defer parsing of the metadata. This vector contains info about
453 /// which Metadata blocks are deferred.
454 std::vector<uint64_t> DeferredMetadataInfo;
456 /// These are basic blocks forward-referenced by block addresses. They are
457 /// inserted lazily into functions when they're loaded. The basic block ID is
458 /// its index into the vector.
459 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
460 std::deque<Function *> BasicBlockFwdRefQueue;
462 /// Indicates that we are using a new encoding for instruction operands where
463 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
464 /// instruction number, for a more compact encoding. Some instruction
465 /// operands are not relative to the instruction ID: basic block numbers, and
466 /// types. Once the old style function blocks have been phased out, we would
467 /// not need this flag.
468 bool UseRelativeIDs = false;
470 /// True if all functions will be materialized, negating the need to process
471 /// (e.g.) blockaddress forward references.
472 bool WillMaterializeAllForwardRefs = false;
474 bool StripDebugInfo = false;
475 TBAAVerifier TBAAVerifyHelper;
477 std::vector<std::string> BundleTags;
480 BitcodeReader(BitstreamCursor Stream, StringRef ProducerIdentification,
481 LLVMContext &Context);
483 Error materializeForwardReferencedFunctions();
485 Error materialize(GlobalValue *GV) override;
486 Error materializeModule() override;
487 std::vector<StructType *> getIdentifiedStructTypes() const override;
489 /// \brief Main interface to parsing a bitcode buffer.
490 /// \returns true if an error occurred.
491 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
492 bool IsImporting = false);
494 static uint64_t decodeSignRotatedValue(uint64_t V);
496 /// Materialize any deferred Metadata block.
497 Error materializeMetadata() override;
499 void setStripDebugInfo() override;
502 std::vector<StructType *> IdentifiedStructTypes;
503 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
504 StructType *createIdentifiedStructType(LLVMContext &Context);
506 Type *getTypeByID(unsigned ID);
508 Value *getFnValueByID(unsigned ID, Type *Ty) {
509 if (Ty && Ty->isMetadataTy())
510 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
511 return ValueList.getValueFwdRef(ID, Ty);
514 Metadata *getFnMetadataByID(unsigned ID) {
515 return MDLoader->getMetadataFwdRef(ID);
518 BasicBlock *getBasicBlock(unsigned ID) const {
519 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
520 return FunctionBBs[ID];
523 AttributeSet getAttributes(unsigned i) const {
524 if (i-1 < MAttributes.size())
525 return MAttributes[i-1];
526 return AttributeSet();
529 /// Read a value/type pair out of the specified record from slot 'Slot'.
530 /// Increment Slot past the number of slots used in the record. Return true on
532 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
533 unsigned InstNum, Value *&ResVal) {
534 if (Slot == Record.size()) return true;
535 unsigned ValNo = (unsigned)Record[Slot++];
536 // Adjust the ValNo, if it was encoded relative to the InstNum.
538 ValNo = InstNum - ValNo;
539 if (ValNo < InstNum) {
540 // If this is not a forward reference, just return the value we already
542 ResVal = getFnValueByID(ValNo, nullptr);
543 return ResVal == nullptr;
545 if (Slot == Record.size())
548 unsigned TypeNo = (unsigned)Record[Slot++];
549 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
550 return ResVal == nullptr;
553 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
554 /// past the number of slots used by the value in the record. Return true if
555 /// there is an error.
556 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
557 unsigned InstNum, Type *Ty, Value *&ResVal) {
558 if (getValue(Record, Slot, InstNum, Ty, ResVal))
560 // All values currently take a single record slot.
565 /// Like popValue, but does not increment the Slot number.
566 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
567 unsigned InstNum, Type *Ty, Value *&ResVal) {
568 ResVal = getValue(Record, Slot, InstNum, Ty);
569 return ResVal == nullptr;
572 /// Version of getValue that returns ResVal directly, or 0 if there is an
574 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
575 unsigned InstNum, Type *Ty) {
576 if (Slot == Record.size()) return nullptr;
577 unsigned ValNo = (unsigned)Record[Slot];
578 // Adjust the ValNo, if it was encoded relative to the InstNum.
580 ValNo = InstNum - ValNo;
581 return getFnValueByID(ValNo, Ty);
584 /// Like getValue, but decodes signed VBRs.
585 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
586 unsigned InstNum, Type *Ty) {
587 if (Slot == Record.size()) return nullptr;
588 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
589 // Adjust the ValNo, if it was encoded relative to the InstNum.
591 ValNo = InstNum - ValNo;
592 return getFnValueByID(ValNo, Ty);
595 /// Converts alignment exponent (i.e. power of two (or zero)) to the
596 /// corresponding alignment to use. If alignment is too large, returns
597 /// a corresponding error code.
598 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
599 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
600 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
601 Error parseAttributeBlock();
602 Error parseAttributeGroupBlock();
603 Error parseTypeTable();
604 Error parseTypeTableBody();
605 Error parseOperandBundleTags();
607 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
608 unsigned NameIndex, Triple &TT);
609 Error parseValueSymbolTable(uint64_t Offset = 0);
610 Error parseConstants();
611 Error rememberAndSkipFunctionBodies();
612 Error rememberAndSkipFunctionBody();
613 /// Save the positions of the Metadata blocks and skip parsing the blocks.
614 Error rememberAndSkipMetadata();
615 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
616 Error parseFunctionBody(Function *F);
617 Error globalCleanup();
618 Error resolveGlobalAndIndirectSymbolInits();
619 Error parseUseLists();
620 Error findFunctionInStream(
622 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
625 /// Class to manage reading and parsing function summary index bitcode
627 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
628 /// The module index built during parsing.
629 ModuleSummaryIndex &TheIndex;
631 /// Indicates whether we have encountered a global value summary section
632 /// yet during parsing.
633 bool SeenGlobalValSummary = false;
635 /// Indicates whether we have already parsed the VST, used for error checking.
636 bool SeenValueSymbolTable = false;
638 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
639 /// Used to enable on-demand parsing of the VST.
640 uint64_t VSTOffset = 0;
642 // Map to save ValueId to GUID association that was recorded in the
643 // ValueSymbolTable. It is used after the VST is parsed to convert
644 // call graph edges read from the function summary from referencing
645 // callees by their ValueId to using the GUID instead, which is how
646 // they are recorded in the summary index being built.
647 // We save a second GUID which is the same as the first one, but ignoring the
648 // linkage, i.e. for value other than local linkage they are identical.
649 DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
650 ValueIdToCallGraphGUIDMap;
652 /// Map populated during module path string table parsing, from the
653 /// module ID to a string reference owned by the index's module
654 /// path string table, used to correlate with combined index
656 DenseMap<uint64_t, StringRef> ModuleIdMap;
658 /// Original source file name recorded in a bitcode record.
659 std::string SourceFileName;
662 ModuleSummaryIndexBitcodeReader(
663 BitstreamCursor Stream, ModuleSummaryIndex &TheIndex);
665 Error parseModule(StringRef ModulePath);
668 Error parseValueSymbolTable(
670 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
671 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
672 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
673 bool IsOldProfileFormat,
675 Error parseEntireSummary(StringRef ModulePath);
676 Error parseModuleStringTable();
678 std::pair<GlobalValue::GUID, GlobalValue::GUID>
679 getGUIDFromValueId(unsigned ValueId);
682 } // end anonymous namespace
684 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
688 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
689 EC = EIB.convertToErrorCode();
690 Ctx.emitError(EIB.message());
694 return std::error_code();
697 BitcodeReader::BitcodeReader(BitstreamCursor Stream,
698 StringRef ProducerIdentification,
699 LLVMContext &Context)
700 : BitcodeReaderBase(std::move(Stream)), Context(Context),
702 this->ProducerIdentification = ProducerIdentification;
705 Error BitcodeReader::materializeForwardReferencedFunctions() {
706 if (WillMaterializeAllForwardRefs)
707 return Error::success();
709 // Prevent recursion.
710 WillMaterializeAllForwardRefs = true;
712 while (!BasicBlockFwdRefQueue.empty()) {
713 Function *F = BasicBlockFwdRefQueue.front();
714 BasicBlockFwdRefQueue.pop_front();
715 assert(F && "Expected valid function");
716 if (!BasicBlockFwdRefs.count(F))
717 // Already materialized.
720 // Check for a function that isn't materializable to prevent an infinite
721 // loop. When parsing a blockaddress stored in a global variable, there
722 // isn't a trivial way to check if a function will have a body without a
723 // linear search through FunctionsWithBodies, so just check it here.
724 if (!F->isMaterializable())
725 return error("Never resolved function from blockaddress");
727 // Try to materialize F.
728 if (Error Err = materialize(F))
731 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
734 WillMaterializeAllForwardRefs = false;
735 return Error::success();
738 //===----------------------------------------------------------------------===//
739 // Helper functions to implement forward reference resolution, etc.
740 //===----------------------------------------------------------------------===//
742 static bool hasImplicitComdat(size_t Val) {
746 case 1: // Old WeakAnyLinkage
747 case 4: // Old LinkOnceAnyLinkage
748 case 10: // Old WeakODRLinkage
749 case 11: // Old LinkOnceODRLinkage
754 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
756 default: // Map unknown/new linkages to external
758 return GlobalValue::ExternalLinkage;
760 return GlobalValue::AppendingLinkage;
762 return GlobalValue::InternalLinkage;
764 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
766 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
768 return GlobalValue::ExternalWeakLinkage;
770 return GlobalValue::CommonLinkage;
772 return GlobalValue::PrivateLinkage;
774 return GlobalValue::AvailableExternallyLinkage;
776 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
778 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
780 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
781 case 1: // Old value with implicit comdat.
783 return GlobalValue::WeakAnyLinkage;
784 case 10: // Old value with implicit comdat.
786 return GlobalValue::WeakODRLinkage;
787 case 4: // Old value with implicit comdat.
789 return GlobalValue::LinkOnceAnyLinkage;
790 case 11: // Old value with implicit comdat.
792 return GlobalValue::LinkOnceODRLinkage;
796 /// Decode the flags for GlobalValue in the summary.
797 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
799 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
800 // like getDecodedLinkage() above. Any future change to the linkage enum and
801 // to getDecodedLinkage() will need to be taken into account here as above.
802 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
803 RawFlags = RawFlags >> 4;
804 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
805 // The LiveRoot flag wasn't introduced until version 3. For dead stripping
806 // to work correctly on earlier versions, we must conservatively treat all
808 bool LiveRoot = (RawFlags & 0x2) || Version < 3;
809 return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, LiveRoot);
812 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
814 default: // Map unknown visibilities to default.
815 case 0: return GlobalValue::DefaultVisibility;
816 case 1: return GlobalValue::HiddenVisibility;
817 case 2: return GlobalValue::ProtectedVisibility;
821 static GlobalValue::DLLStorageClassTypes
822 getDecodedDLLStorageClass(unsigned Val) {
824 default: // Map unknown values to default.
825 case 0: return GlobalValue::DefaultStorageClass;
826 case 1: return GlobalValue::DLLImportStorageClass;
827 case 2: return GlobalValue::DLLExportStorageClass;
831 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
833 case 0: return GlobalVariable::NotThreadLocal;
834 default: // Map unknown non-zero value to general dynamic.
835 case 1: return GlobalVariable::GeneralDynamicTLSModel;
836 case 2: return GlobalVariable::LocalDynamicTLSModel;
837 case 3: return GlobalVariable::InitialExecTLSModel;
838 case 4: return GlobalVariable::LocalExecTLSModel;
842 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
844 default: // Map unknown to UnnamedAddr::None.
845 case 0: return GlobalVariable::UnnamedAddr::None;
846 case 1: return GlobalVariable::UnnamedAddr::Global;
847 case 2: return GlobalVariable::UnnamedAddr::Local;
851 static int getDecodedCastOpcode(unsigned Val) {
854 case bitc::CAST_TRUNC : return Instruction::Trunc;
855 case bitc::CAST_ZEXT : return Instruction::ZExt;
856 case bitc::CAST_SEXT : return Instruction::SExt;
857 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
858 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
859 case bitc::CAST_UITOFP : return Instruction::UIToFP;
860 case bitc::CAST_SITOFP : return Instruction::SIToFP;
861 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
862 case bitc::CAST_FPEXT : return Instruction::FPExt;
863 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
864 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
865 case bitc::CAST_BITCAST : return Instruction::BitCast;
866 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
870 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
871 bool IsFP = Ty->isFPOrFPVectorTy();
872 // BinOps are only valid for int/fp or vector of int/fp types
873 if (!IsFP && !Ty->isIntOrIntVectorTy())
879 case bitc::BINOP_ADD:
880 return IsFP ? Instruction::FAdd : Instruction::Add;
881 case bitc::BINOP_SUB:
882 return IsFP ? Instruction::FSub : Instruction::Sub;
883 case bitc::BINOP_MUL:
884 return IsFP ? Instruction::FMul : Instruction::Mul;
885 case bitc::BINOP_UDIV:
886 return IsFP ? -1 : Instruction::UDiv;
887 case bitc::BINOP_SDIV:
888 return IsFP ? Instruction::FDiv : Instruction::SDiv;
889 case bitc::BINOP_UREM:
890 return IsFP ? -1 : Instruction::URem;
891 case bitc::BINOP_SREM:
892 return IsFP ? Instruction::FRem : Instruction::SRem;
893 case bitc::BINOP_SHL:
894 return IsFP ? -1 : Instruction::Shl;
895 case bitc::BINOP_LSHR:
896 return IsFP ? -1 : Instruction::LShr;
897 case bitc::BINOP_ASHR:
898 return IsFP ? -1 : Instruction::AShr;
899 case bitc::BINOP_AND:
900 return IsFP ? -1 : Instruction::And;
902 return IsFP ? -1 : Instruction::Or;
903 case bitc::BINOP_XOR:
904 return IsFP ? -1 : Instruction::Xor;
908 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
910 default: return AtomicRMWInst::BAD_BINOP;
911 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
912 case bitc::RMW_ADD: return AtomicRMWInst::Add;
913 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
914 case bitc::RMW_AND: return AtomicRMWInst::And;
915 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
916 case bitc::RMW_OR: return AtomicRMWInst::Or;
917 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
918 case bitc::RMW_MAX: return AtomicRMWInst::Max;
919 case bitc::RMW_MIN: return AtomicRMWInst::Min;
920 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
921 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
925 static AtomicOrdering getDecodedOrdering(unsigned Val) {
927 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
928 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
929 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
930 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
931 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
932 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
933 default: // Map unknown orderings to sequentially-consistent.
934 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
938 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
940 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
941 default: // Map unknown scopes to cross-thread.
942 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
946 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
948 default: // Map unknown selection kinds to any.
949 case bitc::COMDAT_SELECTION_KIND_ANY:
951 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
952 return Comdat::ExactMatch;
953 case bitc::COMDAT_SELECTION_KIND_LARGEST:
954 return Comdat::Largest;
955 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
956 return Comdat::NoDuplicates;
957 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
958 return Comdat::SameSize;
962 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
964 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
965 FMF.setUnsafeAlgebra();
966 if (0 != (Val & FastMathFlags::NoNaNs))
968 if (0 != (Val & FastMathFlags::NoInfs))
970 if (0 != (Val & FastMathFlags::NoSignedZeros))
971 FMF.setNoSignedZeros();
972 if (0 != (Val & FastMathFlags::AllowReciprocal))
973 FMF.setAllowReciprocal();
977 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
979 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
980 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
985 Type *BitcodeReader::getTypeByID(unsigned ID) {
986 // The type table size is always specified correctly.
987 if (ID >= TypeList.size())
990 if (Type *Ty = TypeList[ID])
993 // If we have a forward reference, the only possible case is when it is to a
994 // named struct. Just create a placeholder for now.
995 return TypeList[ID] = createIdentifiedStructType(Context);
998 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1000 auto *Ret = StructType::create(Context, Name);
1001 IdentifiedStructTypes.push_back(Ret);
1005 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1006 auto *Ret = StructType::create(Context);
1007 IdentifiedStructTypes.push_back(Ret);
1011 //===----------------------------------------------------------------------===//
1012 // Functions for parsing blocks from the bitcode file
1013 //===----------------------------------------------------------------------===//
1015 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1017 case Attribute::EndAttrKinds:
1018 llvm_unreachable("Synthetic enumerators which should never get here");
1020 case Attribute::None: return 0;
1021 case Attribute::ZExt: return 1 << 0;
1022 case Attribute::SExt: return 1 << 1;
1023 case Attribute::NoReturn: return 1 << 2;
1024 case Attribute::InReg: return 1 << 3;
1025 case Attribute::StructRet: return 1 << 4;
1026 case Attribute::NoUnwind: return 1 << 5;
1027 case Attribute::NoAlias: return 1 << 6;
1028 case Attribute::ByVal: return 1 << 7;
1029 case Attribute::Nest: return 1 << 8;
1030 case Attribute::ReadNone: return 1 << 9;
1031 case Attribute::ReadOnly: return 1 << 10;
1032 case Attribute::NoInline: return 1 << 11;
1033 case Attribute::AlwaysInline: return 1 << 12;
1034 case Attribute::OptimizeForSize: return 1 << 13;
1035 case Attribute::StackProtect: return 1 << 14;
1036 case Attribute::StackProtectReq: return 1 << 15;
1037 case Attribute::Alignment: return 31 << 16;
1038 case Attribute::NoCapture: return 1 << 21;
1039 case Attribute::NoRedZone: return 1 << 22;
1040 case Attribute::NoImplicitFloat: return 1 << 23;
1041 case Attribute::Naked: return 1 << 24;
1042 case Attribute::InlineHint: return 1 << 25;
1043 case Attribute::StackAlignment: return 7 << 26;
1044 case Attribute::ReturnsTwice: return 1 << 29;
1045 case Attribute::UWTable: return 1 << 30;
1046 case Attribute::NonLazyBind: return 1U << 31;
1047 case Attribute::SanitizeAddress: return 1ULL << 32;
1048 case Attribute::MinSize: return 1ULL << 33;
1049 case Attribute::NoDuplicate: return 1ULL << 34;
1050 case Attribute::StackProtectStrong: return 1ULL << 35;
1051 case Attribute::SanitizeThread: return 1ULL << 36;
1052 case Attribute::SanitizeMemory: return 1ULL << 37;
1053 case Attribute::NoBuiltin: return 1ULL << 38;
1054 case Attribute::Returned: return 1ULL << 39;
1055 case Attribute::Cold: return 1ULL << 40;
1056 case Attribute::Builtin: return 1ULL << 41;
1057 case Attribute::OptimizeNone: return 1ULL << 42;
1058 case Attribute::InAlloca: return 1ULL << 43;
1059 case Attribute::NonNull: return 1ULL << 44;
1060 case Attribute::JumpTable: return 1ULL << 45;
1061 case Attribute::Convergent: return 1ULL << 46;
1062 case Attribute::SafeStack: return 1ULL << 47;
1063 case Attribute::NoRecurse: return 1ULL << 48;
1064 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1065 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1066 case Attribute::SwiftSelf: return 1ULL << 51;
1067 case Attribute::SwiftError: return 1ULL << 52;
1068 case Attribute::WriteOnly: return 1ULL << 53;
1069 case Attribute::Dereferenceable:
1070 llvm_unreachable("dereferenceable attribute not supported in raw format");
1072 case Attribute::DereferenceableOrNull:
1073 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1076 case Attribute::ArgMemOnly:
1077 llvm_unreachable("argmemonly attribute not supported in raw format");
1079 case Attribute::AllocSize:
1080 llvm_unreachable("allocsize not supported in raw format");
1083 llvm_unreachable("Unsupported attribute type");
1086 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1089 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1090 I = Attribute::AttrKind(I + 1)) {
1091 if (I == Attribute::Dereferenceable ||
1092 I == Attribute::DereferenceableOrNull ||
1093 I == Attribute::ArgMemOnly ||
1094 I == Attribute::AllocSize)
1096 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1097 if (I == Attribute::Alignment)
1098 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1099 else if (I == Attribute::StackAlignment)
1100 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1107 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1108 /// been decoded from the given integer. This function must stay in sync with
1109 /// 'encodeLLVMAttributesForBitcode'.
1110 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1111 uint64_t EncodedAttrs) {
1112 // FIXME: Remove in 4.0.
1114 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1115 // the bits above 31 down by 11 bits.
1116 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1117 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1118 "Alignment must be a power of two.");
1121 B.addAlignmentAttr(Alignment);
1122 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1123 (EncodedAttrs & 0xffff));
1126 Error BitcodeReader::parseAttributeBlock() {
1127 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1128 return error("Invalid record");
1130 if (!MAttributes.empty())
1131 return error("Invalid multiple blocks");
1133 SmallVector<uint64_t, 64> Record;
1135 SmallVector<AttributeSet, 8> Attrs;
1137 // Read all the records.
1139 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1141 switch (Entry.Kind) {
1142 case BitstreamEntry::SubBlock: // Handled for us already.
1143 case BitstreamEntry::Error:
1144 return error("Malformed block");
1145 case BitstreamEntry::EndBlock:
1146 return Error::success();
1147 case BitstreamEntry::Record:
1148 // The interesting case.
1154 switch (Stream.readRecord(Entry.ID, Record)) {
1155 default: // Default behavior: ignore.
1157 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1158 // FIXME: Remove in 4.0.
1159 if (Record.size() & 1)
1160 return error("Invalid record");
1162 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1164 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1165 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1168 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1172 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1173 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1174 Attrs.push_back(MAttributeGroups[Record[i]]);
1176 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1184 // Returns Attribute::None on unrecognized codes.
1185 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1188 return Attribute::None;
1189 case bitc::ATTR_KIND_ALIGNMENT:
1190 return Attribute::Alignment;
1191 case bitc::ATTR_KIND_ALWAYS_INLINE:
1192 return Attribute::AlwaysInline;
1193 case bitc::ATTR_KIND_ARGMEMONLY:
1194 return Attribute::ArgMemOnly;
1195 case bitc::ATTR_KIND_BUILTIN:
1196 return Attribute::Builtin;
1197 case bitc::ATTR_KIND_BY_VAL:
1198 return Attribute::ByVal;
1199 case bitc::ATTR_KIND_IN_ALLOCA:
1200 return Attribute::InAlloca;
1201 case bitc::ATTR_KIND_COLD:
1202 return Attribute::Cold;
1203 case bitc::ATTR_KIND_CONVERGENT:
1204 return Attribute::Convergent;
1205 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1206 return Attribute::InaccessibleMemOnly;
1207 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1208 return Attribute::InaccessibleMemOrArgMemOnly;
1209 case bitc::ATTR_KIND_INLINE_HINT:
1210 return Attribute::InlineHint;
1211 case bitc::ATTR_KIND_IN_REG:
1212 return Attribute::InReg;
1213 case bitc::ATTR_KIND_JUMP_TABLE:
1214 return Attribute::JumpTable;
1215 case bitc::ATTR_KIND_MIN_SIZE:
1216 return Attribute::MinSize;
1217 case bitc::ATTR_KIND_NAKED:
1218 return Attribute::Naked;
1219 case bitc::ATTR_KIND_NEST:
1220 return Attribute::Nest;
1221 case bitc::ATTR_KIND_NO_ALIAS:
1222 return Attribute::NoAlias;
1223 case bitc::ATTR_KIND_NO_BUILTIN:
1224 return Attribute::NoBuiltin;
1225 case bitc::ATTR_KIND_NO_CAPTURE:
1226 return Attribute::NoCapture;
1227 case bitc::ATTR_KIND_NO_DUPLICATE:
1228 return Attribute::NoDuplicate;
1229 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1230 return Attribute::NoImplicitFloat;
1231 case bitc::ATTR_KIND_NO_INLINE:
1232 return Attribute::NoInline;
1233 case bitc::ATTR_KIND_NO_RECURSE:
1234 return Attribute::NoRecurse;
1235 case bitc::ATTR_KIND_NON_LAZY_BIND:
1236 return Attribute::NonLazyBind;
1237 case bitc::ATTR_KIND_NON_NULL:
1238 return Attribute::NonNull;
1239 case bitc::ATTR_KIND_DEREFERENCEABLE:
1240 return Attribute::Dereferenceable;
1241 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1242 return Attribute::DereferenceableOrNull;
1243 case bitc::ATTR_KIND_ALLOC_SIZE:
1244 return Attribute::AllocSize;
1245 case bitc::ATTR_KIND_NO_RED_ZONE:
1246 return Attribute::NoRedZone;
1247 case bitc::ATTR_KIND_NO_RETURN:
1248 return Attribute::NoReturn;
1249 case bitc::ATTR_KIND_NO_UNWIND:
1250 return Attribute::NoUnwind;
1251 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1252 return Attribute::OptimizeForSize;
1253 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1254 return Attribute::OptimizeNone;
1255 case bitc::ATTR_KIND_READ_NONE:
1256 return Attribute::ReadNone;
1257 case bitc::ATTR_KIND_READ_ONLY:
1258 return Attribute::ReadOnly;
1259 case bitc::ATTR_KIND_RETURNED:
1260 return Attribute::Returned;
1261 case bitc::ATTR_KIND_RETURNS_TWICE:
1262 return Attribute::ReturnsTwice;
1263 case bitc::ATTR_KIND_S_EXT:
1264 return Attribute::SExt;
1265 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1266 return Attribute::StackAlignment;
1267 case bitc::ATTR_KIND_STACK_PROTECT:
1268 return Attribute::StackProtect;
1269 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1270 return Attribute::StackProtectReq;
1271 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1272 return Attribute::StackProtectStrong;
1273 case bitc::ATTR_KIND_SAFESTACK:
1274 return Attribute::SafeStack;
1275 case bitc::ATTR_KIND_STRUCT_RET:
1276 return Attribute::StructRet;
1277 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1278 return Attribute::SanitizeAddress;
1279 case bitc::ATTR_KIND_SANITIZE_THREAD:
1280 return Attribute::SanitizeThread;
1281 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1282 return Attribute::SanitizeMemory;
1283 case bitc::ATTR_KIND_SWIFT_ERROR:
1284 return Attribute::SwiftError;
1285 case bitc::ATTR_KIND_SWIFT_SELF:
1286 return Attribute::SwiftSelf;
1287 case bitc::ATTR_KIND_UW_TABLE:
1288 return Attribute::UWTable;
1289 case bitc::ATTR_KIND_WRITEONLY:
1290 return Attribute::WriteOnly;
1291 case bitc::ATTR_KIND_Z_EXT:
1292 return Attribute::ZExt;
1296 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1297 unsigned &Alignment) {
1298 // Note: Alignment in bitcode files is incremented by 1, so that zero
1299 // can be used for default alignment.
1300 if (Exponent > Value::MaxAlignmentExponent + 1)
1301 return error("Invalid alignment value");
1302 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1303 return Error::success();
1306 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1307 *Kind = getAttrFromCode(Code);
1308 if (*Kind == Attribute::None)
1309 return error("Unknown attribute kind (" + Twine(Code) + ")");
1310 return Error::success();
1313 Error BitcodeReader::parseAttributeGroupBlock() {
1314 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1315 return error("Invalid record");
1317 if (!MAttributeGroups.empty())
1318 return error("Invalid multiple blocks");
1320 SmallVector<uint64_t, 64> Record;
1322 // Read all the records.
1324 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1326 switch (Entry.Kind) {
1327 case BitstreamEntry::SubBlock: // Handled for us already.
1328 case BitstreamEntry::Error:
1329 return error("Malformed block");
1330 case BitstreamEntry::EndBlock:
1331 return Error::success();
1332 case BitstreamEntry::Record:
1333 // The interesting case.
1339 switch (Stream.readRecord(Entry.ID, Record)) {
1340 default: // Default behavior: ignore.
1342 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1343 if (Record.size() < 3)
1344 return error("Invalid record");
1346 uint64_t GrpID = Record[0];
1347 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1350 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1351 if (Record[i] == 0) { // Enum attribute
1352 Attribute::AttrKind Kind;
1353 if (Error Err = parseAttrKind(Record[++i], &Kind))
1356 B.addAttribute(Kind);
1357 } else if (Record[i] == 1) { // Integer attribute
1358 Attribute::AttrKind Kind;
1359 if (Error Err = parseAttrKind(Record[++i], &Kind))
1361 if (Kind == Attribute::Alignment)
1362 B.addAlignmentAttr(Record[++i]);
1363 else if (Kind == Attribute::StackAlignment)
1364 B.addStackAlignmentAttr(Record[++i]);
1365 else if (Kind == Attribute::Dereferenceable)
1366 B.addDereferenceableAttr(Record[++i]);
1367 else if (Kind == Attribute::DereferenceableOrNull)
1368 B.addDereferenceableOrNullAttr(Record[++i]);
1369 else if (Kind == Attribute::AllocSize)
1370 B.addAllocSizeAttrFromRawRepr(Record[++i]);
1371 } else { // String attribute
1372 assert((Record[i] == 3 || Record[i] == 4) &&
1373 "Invalid attribute group entry");
1374 bool HasValue = (Record[i++] == 4);
1375 SmallString<64> KindStr;
1376 SmallString<64> ValStr;
1378 while (Record[i] != 0 && i != e)
1379 KindStr += Record[i++];
1380 assert(Record[i] == 0 && "Kind string not null terminated");
1383 // Has a value associated with it.
1384 ++i; // Skip the '0' that terminates the "kind" string.
1385 while (Record[i] != 0 && i != e)
1386 ValStr += Record[i++];
1387 assert(Record[i] == 0 && "Value string not null terminated");
1390 B.addAttribute(KindStr.str(), ValStr.str());
1394 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1401 Error BitcodeReader::parseTypeTable() {
1402 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1403 return error("Invalid record");
1405 return parseTypeTableBody();
1408 Error BitcodeReader::parseTypeTableBody() {
1409 if (!TypeList.empty())
1410 return error("Invalid multiple blocks");
1412 SmallVector<uint64_t, 64> Record;
1413 unsigned NumRecords = 0;
1415 SmallString<64> TypeName;
1417 // Read all the records for this type table.
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 if (NumRecords != TypeList.size())
1427 return error("Malformed block");
1428 return Error::success();
1429 case BitstreamEntry::Record:
1430 // The interesting case.
1436 Type *ResultTy = nullptr;
1437 switch (Stream.readRecord(Entry.ID, Record)) {
1439 return error("Invalid value");
1440 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1441 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1442 // type list. This allows us to reserve space.
1443 if (Record.size() < 1)
1444 return error("Invalid record");
1445 TypeList.resize(Record[0]);
1447 case bitc::TYPE_CODE_VOID: // VOID
1448 ResultTy = Type::getVoidTy(Context);
1450 case bitc::TYPE_CODE_HALF: // HALF
1451 ResultTy = Type::getHalfTy(Context);
1453 case bitc::TYPE_CODE_FLOAT: // FLOAT
1454 ResultTy = Type::getFloatTy(Context);
1456 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1457 ResultTy = Type::getDoubleTy(Context);
1459 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1460 ResultTy = Type::getX86_FP80Ty(Context);
1462 case bitc::TYPE_CODE_FP128: // FP128
1463 ResultTy = Type::getFP128Ty(Context);
1465 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1466 ResultTy = Type::getPPC_FP128Ty(Context);
1468 case bitc::TYPE_CODE_LABEL: // LABEL
1469 ResultTy = Type::getLabelTy(Context);
1471 case bitc::TYPE_CODE_METADATA: // METADATA
1472 ResultTy = Type::getMetadataTy(Context);
1474 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1475 ResultTy = Type::getX86_MMXTy(Context);
1477 case bitc::TYPE_CODE_TOKEN: // TOKEN
1478 ResultTy = Type::getTokenTy(Context);
1480 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1481 if (Record.size() < 1)
1482 return error("Invalid record");
1484 uint64_t NumBits = Record[0];
1485 if (NumBits < IntegerType::MIN_INT_BITS ||
1486 NumBits > IntegerType::MAX_INT_BITS)
1487 return error("Bitwidth for integer type out of range");
1488 ResultTy = IntegerType::get(Context, NumBits);
1491 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1492 // [pointee type, address space]
1493 if (Record.size() < 1)
1494 return error("Invalid record");
1495 unsigned AddressSpace = 0;
1496 if (Record.size() == 2)
1497 AddressSpace = Record[1];
1498 ResultTy = getTypeByID(Record[0]);
1500 !PointerType::isValidElementType(ResultTy))
1501 return error("Invalid type");
1502 ResultTy = PointerType::get(ResultTy, AddressSpace);
1505 case bitc::TYPE_CODE_FUNCTION_OLD: {
1506 // FIXME: attrid is dead, remove it in LLVM 4.0
1507 // FUNCTION: [vararg, attrid, retty, paramty x N]
1508 if (Record.size() < 3)
1509 return error("Invalid record");
1510 SmallVector<Type*, 8> ArgTys;
1511 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1512 if (Type *T = getTypeByID(Record[i]))
1513 ArgTys.push_back(T);
1518 ResultTy = getTypeByID(Record[2]);
1519 if (!ResultTy || ArgTys.size() < Record.size()-3)
1520 return error("Invalid type");
1522 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1525 case bitc::TYPE_CODE_FUNCTION: {
1526 // FUNCTION: [vararg, retty, paramty x N]
1527 if (Record.size() < 2)
1528 return error("Invalid record");
1529 SmallVector<Type*, 8> ArgTys;
1530 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1531 if (Type *T = getTypeByID(Record[i])) {
1532 if (!FunctionType::isValidArgumentType(T))
1533 return error("Invalid function argument type");
1534 ArgTys.push_back(T);
1540 ResultTy = getTypeByID(Record[1]);
1541 if (!ResultTy || ArgTys.size() < Record.size()-2)
1542 return error("Invalid type");
1544 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1547 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1548 if (Record.size() < 1)
1549 return error("Invalid record");
1550 SmallVector<Type*, 8> EltTys;
1551 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1552 if (Type *T = getTypeByID(Record[i]))
1553 EltTys.push_back(T);
1557 if (EltTys.size() != Record.size()-1)
1558 return error("Invalid type");
1559 ResultTy = StructType::get(Context, EltTys, Record[0]);
1562 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1563 if (convertToString(Record, 0, TypeName))
1564 return error("Invalid record");
1567 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1568 if (Record.size() < 1)
1569 return error("Invalid record");
1571 if (NumRecords >= TypeList.size())
1572 return error("Invalid TYPE table");
1574 // Check to see if this was forward referenced, if so fill in the temp.
1575 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1577 Res->setName(TypeName);
1578 TypeList[NumRecords] = nullptr;
1579 } else // Otherwise, create a new struct.
1580 Res = createIdentifiedStructType(Context, TypeName);
1583 SmallVector<Type*, 8> EltTys;
1584 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1585 if (Type *T = getTypeByID(Record[i]))
1586 EltTys.push_back(T);
1590 if (EltTys.size() != Record.size()-1)
1591 return error("Invalid record");
1592 Res->setBody(EltTys, Record[0]);
1596 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1597 if (Record.size() != 1)
1598 return error("Invalid record");
1600 if (NumRecords >= TypeList.size())
1601 return error("Invalid TYPE table");
1603 // Check to see if this was forward referenced, if so fill in the temp.
1604 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1606 Res->setName(TypeName);
1607 TypeList[NumRecords] = nullptr;
1608 } else // Otherwise, create a new struct with no body.
1609 Res = createIdentifiedStructType(Context, TypeName);
1614 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1615 if (Record.size() < 2)
1616 return error("Invalid record");
1617 ResultTy = getTypeByID(Record[1]);
1618 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1619 return error("Invalid type");
1620 ResultTy = ArrayType::get(ResultTy, Record[0]);
1622 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1623 if (Record.size() < 2)
1624 return error("Invalid record");
1626 return error("Invalid vector length");
1627 ResultTy = getTypeByID(Record[1]);
1628 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1629 return error("Invalid type");
1630 ResultTy = VectorType::get(ResultTy, Record[0]);
1634 if (NumRecords >= TypeList.size())
1635 return error("Invalid TYPE table");
1636 if (TypeList[NumRecords])
1638 "Invalid TYPE table: Only named structs can be forward referenced");
1639 assert(ResultTy && "Didn't read a type?");
1640 TypeList[NumRecords++] = ResultTy;
1644 Error BitcodeReader::parseOperandBundleTags() {
1645 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1646 return error("Invalid record");
1648 if (!BundleTags.empty())
1649 return error("Invalid multiple blocks");
1651 SmallVector<uint64_t, 64> Record;
1654 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1656 switch (Entry.Kind) {
1657 case BitstreamEntry::SubBlock: // Handled for us already.
1658 case BitstreamEntry::Error:
1659 return error("Malformed block");
1660 case BitstreamEntry::EndBlock:
1661 return Error::success();
1662 case BitstreamEntry::Record:
1663 // The interesting case.
1667 // Tags are implicitly mapped to integers by their order.
1669 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1670 return error("Invalid record");
1672 // OPERAND_BUNDLE_TAG: [strchr x N]
1673 BundleTags.emplace_back();
1674 if (convertToString(Record, 0, BundleTags.back()))
1675 return error("Invalid record");
1680 /// Associate a value with its name from the given index in the provided record.
1681 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1682 unsigned NameIndex, Triple &TT) {
1683 SmallString<128> ValueName;
1684 if (convertToString(Record, NameIndex, ValueName))
1685 return error("Invalid record");
1686 unsigned ValueID = Record[0];
1687 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1688 return error("Invalid record");
1689 Value *V = ValueList[ValueID];
1691 StringRef NameStr(ValueName.data(), ValueName.size());
1692 if (NameStr.find_first_of(0) != StringRef::npos)
1693 return error("Invalid value name");
1694 V->setName(NameStr);
1695 auto *GO = dyn_cast<GlobalObject>(V);
1697 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1698 if (TT.isOSBinFormatMachO())
1699 GO->setComdat(nullptr);
1701 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1707 /// Helper to note and return the current location, and jump to the given
1709 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1710 BitstreamCursor &Stream) {
1711 // Save the current parsing location so we can jump back at the end
1713 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1714 Stream.JumpToBit(Offset * 32);
1716 // Do some checking if we are in debug mode.
1717 BitstreamEntry Entry = Stream.advance();
1718 assert(Entry.Kind == BitstreamEntry::SubBlock);
1719 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1721 // In NDEBUG mode ignore the output so we don't get an unused variable
1728 /// Parse the value symbol table at either the current parsing location or
1729 /// at the given bit offset if provided.
1730 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1731 uint64_t CurrentBit;
1732 // Pass in the Offset to distinguish between calling for the module-level
1733 // VST (where we want to jump to the VST offset) and the function-level
1734 // VST (where we don't).
1736 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
1738 // Compute the delta between the bitcode indices in the VST (the word offset
1739 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1740 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1741 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1742 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1743 // just before entering the VST subblock because: 1) the EnterSubBlock
1744 // changes the AbbrevID width; 2) the VST block is nested within the same
1745 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1746 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1747 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1748 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1749 unsigned FuncBitcodeOffsetDelta =
1750 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1752 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1753 return error("Invalid record");
1755 SmallVector<uint64_t, 64> Record;
1757 Triple TT(TheModule->getTargetTriple());
1759 // Read all the records for this value table.
1760 SmallString<128> ValueName;
1763 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1765 switch (Entry.Kind) {
1766 case BitstreamEntry::SubBlock: // Handled for us already.
1767 case BitstreamEntry::Error:
1768 return error("Malformed block");
1769 case BitstreamEntry::EndBlock:
1771 Stream.JumpToBit(CurrentBit);
1772 return Error::success();
1773 case BitstreamEntry::Record:
1774 // The interesting case.
1780 switch (Stream.readRecord(Entry.ID, Record)) {
1781 default: // Default behavior: unknown type.
1783 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
1784 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1785 if (Error Err = ValOrErr.takeError())
1790 case bitc::VST_CODE_FNENTRY: {
1791 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
1792 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1793 if (Error Err = ValOrErr.takeError())
1795 Value *V = ValOrErr.get();
1797 auto *GO = dyn_cast<GlobalObject>(V);
1799 // If this is an alias, need to get the actual Function object
1800 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1801 auto *GA = dyn_cast<GlobalAlias>(V);
1803 GO = GA->getBaseObject();
1807 // Note that we subtract 1 here because the offset is relative to one word
1808 // before the start of the identification or module block, which was
1809 // historically always the start of the regular bitcode header.
1810 uint64_t FuncWordOffset = Record[1] - 1;
1811 Function *F = dyn_cast<Function>(GO);
1813 uint64_t FuncBitOffset = FuncWordOffset * 32;
1814 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1815 // Set the LastFunctionBlockBit to point to the last function block.
1816 // Later when parsing is resumed after function materialization,
1817 // we can simply skip that last function block.
1818 if (FuncBitOffset > LastFunctionBlockBit)
1819 LastFunctionBlockBit = FuncBitOffset;
1822 case bitc::VST_CODE_BBENTRY: {
1823 if (convertToString(Record, 1, ValueName))
1824 return error("Invalid record");
1825 BasicBlock *BB = getBasicBlock(Record[0]);
1827 return error("Invalid record");
1829 BB->setName(StringRef(ValueName.data(), ValueName.size()));
1837 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
1839 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1844 // There is no such thing as -0 with integers. "-0" really means MININT.
1848 /// Resolve all of the initializers for global values and aliases that we can.
1849 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
1850 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1851 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
1852 IndirectSymbolInitWorklist;
1853 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1854 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1855 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
1857 GlobalInitWorklist.swap(GlobalInits);
1858 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
1859 FunctionPrefixWorklist.swap(FunctionPrefixes);
1860 FunctionPrologueWorklist.swap(FunctionPrologues);
1861 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
1863 while (!GlobalInitWorklist.empty()) {
1864 unsigned ValID = GlobalInitWorklist.back().second;
1865 if (ValID >= ValueList.size()) {
1866 // Not ready to resolve this yet, it requires something later in the file.
1867 GlobalInits.push_back(GlobalInitWorklist.back());
1869 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1870 GlobalInitWorklist.back().first->setInitializer(C);
1872 return error("Expected a constant");
1874 GlobalInitWorklist.pop_back();
1877 while (!IndirectSymbolInitWorklist.empty()) {
1878 unsigned ValID = IndirectSymbolInitWorklist.back().second;
1879 if (ValID >= ValueList.size()) {
1880 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
1882 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
1884 return error("Expected a constant");
1885 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
1886 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
1887 return error("Alias and aliasee types don't match");
1888 GIS->setIndirectSymbol(C);
1890 IndirectSymbolInitWorklist.pop_back();
1893 while (!FunctionPrefixWorklist.empty()) {
1894 unsigned ValID = FunctionPrefixWorklist.back().second;
1895 if (ValID >= ValueList.size()) {
1896 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1898 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1899 FunctionPrefixWorklist.back().first->setPrefixData(C);
1901 return error("Expected a constant");
1903 FunctionPrefixWorklist.pop_back();
1906 while (!FunctionPrologueWorklist.empty()) {
1907 unsigned ValID = FunctionPrologueWorklist.back().second;
1908 if (ValID >= ValueList.size()) {
1909 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1911 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1912 FunctionPrologueWorklist.back().first->setPrologueData(C);
1914 return error("Expected a constant");
1916 FunctionPrologueWorklist.pop_back();
1919 while (!FunctionPersonalityFnWorklist.empty()) {
1920 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
1921 if (ValID >= ValueList.size()) {
1922 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
1924 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1925 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
1927 return error("Expected a constant");
1929 FunctionPersonalityFnWorklist.pop_back();
1932 return Error::success();
1935 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1936 SmallVector<uint64_t, 8> Words(Vals.size());
1937 transform(Vals, Words.begin(),
1938 BitcodeReader::decodeSignRotatedValue);
1940 return APInt(TypeBits, Words);
1943 Error BitcodeReader::parseConstants() {
1944 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1945 return error("Invalid record");
1947 SmallVector<uint64_t, 64> Record;
1949 // Read all the records for this value table.
1950 Type *CurTy = Type::getInt32Ty(Context);
1951 unsigned NextCstNo = ValueList.size();
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:
1961 if (NextCstNo != ValueList.size())
1962 return error("Invalid constant reference");
1964 // Once all the constants have been read, go through and resolve forward
1966 ValueList.resolveConstantForwardRefs();
1967 return Error::success();
1968 case BitstreamEntry::Record:
1969 // The interesting case.
1975 Type *VoidType = Type::getVoidTy(Context);
1977 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1979 default: // Default behavior: unknown constant
1980 case bitc::CST_CODE_UNDEF: // UNDEF
1981 V = UndefValue::get(CurTy);
1983 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1985 return error("Invalid record");
1986 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1987 return error("Invalid record");
1988 if (TypeList[Record[0]] == VoidType)
1989 return error("Invalid constant type");
1990 CurTy = TypeList[Record[0]];
1991 continue; // Skip the ValueList manipulation.
1992 case bitc::CST_CODE_NULL: // NULL
1993 V = Constant::getNullValue(CurTy);
1995 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1996 if (!CurTy->isIntegerTy() || Record.empty())
1997 return error("Invalid record");
1998 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2000 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2001 if (!CurTy->isIntegerTy() || Record.empty())
2002 return error("Invalid record");
2005 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2006 V = ConstantInt::get(Context, VInt);
2010 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2012 return error("Invalid record");
2013 if (CurTy->isHalfTy())
2014 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2015 APInt(16, (uint16_t)Record[0])));
2016 else if (CurTy->isFloatTy())
2017 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2018 APInt(32, (uint32_t)Record[0])));
2019 else if (CurTy->isDoubleTy())
2020 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2021 APInt(64, Record[0])));
2022 else if (CurTy->isX86_FP80Ty()) {
2023 // Bits are not stored the same way as a normal i80 APInt, compensate.
2024 uint64_t Rearrange[2];
2025 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2026 Rearrange[1] = Record[0] >> 48;
2027 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2028 APInt(80, Rearrange)));
2029 } else if (CurTy->isFP128Ty())
2030 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2031 APInt(128, Record)));
2032 else if (CurTy->isPPC_FP128Ty())
2033 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2034 APInt(128, Record)));
2036 V = UndefValue::get(CurTy);
2040 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2042 return error("Invalid record");
2044 unsigned Size = Record.size();
2045 SmallVector<Constant*, 16> Elts;
2047 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2048 for (unsigned i = 0; i != Size; ++i)
2049 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2050 STy->getElementType(i)));
2051 V = ConstantStruct::get(STy, Elts);
2052 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2053 Type *EltTy = ATy->getElementType();
2054 for (unsigned i = 0; i != Size; ++i)
2055 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2056 V = ConstantArray::get(ATy, Elts);
2057 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2058 Type *EltTy = VTy->getElementType();
2059 for (unsigned i = 0; i != Size; ++i)
2060 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2061 V = ConstantVector::get(Elts);
2063 V = UndefValue::get(CurTy);
2067 case bitc::CST_CODE_STRING: // STRING: [values]
2068 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2070 return error("Invalid record");
2072 SmallString<16> Elts(Record.begin(), Record.end());
2073 V = ConstantDataArray::getString(Context, Elts,
2074 BitCode == bitc::CST_CODE_CSTRING);
2077 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2079 return error("Invalid record");
2081 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2082 if (EltTy->isIntegerTy(8)) {
2083 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2084 if (isa<VectorType>(CurTy))
2085 V = ConstantDataVector::get(Context, Elts);
2087 V = ConstantDataArray::get(Context, Elts);
2088 } else if (EltTy->isIntegerTy(16)) {
2089 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2090 if (isa<VectorType>(CurTy))
2091 V = ConstantDataVector::get(Context, Elts);
2093 V = ConstantDataArray::get(Context, Elts);
2094 } else if (EltTy->isIntegerTy(32)) {
2095 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2096 if (isa<VectorType>(CurTy))
2097 V = ConstantDataVector::get(Context, Elts);
2099 V = ConstantDataArray::get(Context, Elts);
2100 } else if (EltTy->isIntegerTy(64)) {
2101 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2102 if (isa<VectorType>(CurTy))
2103 V = ConstantDataVector::get(Context, Elts);
2105 V = ConstantDataArray::get(Context, Elts);
2106 } else if (EltTy->isHalfTy()) {
2107 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2108 if (isa<VectorType>(CurTy))
2109 V = ConstantDataVector::getFP(Context, Elts);
2111 V = ConstantDataArray::getFP(Context, Elts);
2112 } else if (EltTy->isFloatTy()) {
2113 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2114 if (isa<VectorType>(CurTy))
2115 V = ConstantDataVector::getFP(Context, Elts);
2117 V = ConstantDataArray::getFP(Context, Elts);
2118 } else if (EltTy->isDoubleTy()) {
2119 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2120 if (isa<VectorType>(CurTy))
2121 V = ConstantDataVector::getFP(Context, Elts);
2123 V = ConstantDataArray::getFP(Context, Elts);
2125 return error("Invalid type for value");
2129 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2130 if (Record.size() < 3)
2131 return error("Invalid record");
2132 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2134 V = UndefValue::get(CurTy); // Unknown binop.
2136 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2137 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2139 if (Record.size() >= 4) {
2140 if (Opc == Instruction::Add ||
2141 Opc == Instruction::Sub ||
2142 Opc == Instruction::Mul ||
2143 Opc == Instruction::Shl) {
2144 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2145 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2146 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2147 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2148 } else if (Opc == Instruction::SDiv ||
2149 Opc == Instruction::UDiv ||
2150 Opc == Instruction::LShr ||
2151 Opc == Instruction::AShr) {
2152 if (Record[3] & (1 << bitc::PEO_EXACT))
2153 Flags |= SDivOperator::IsExact;
2156 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2160 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2161 if (Record.size() < 3)
2162 return error("Invalid record");
2163 int Opc = getDecodedCastOpcode(Record[0]);
2165 V = UndefValue::get(CurTy); // Unknown cast.
2167 Type *OpTy = getTypeByID(Record[1]);
2169 return error("Invalid record");
2170 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2171 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2172 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2176 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2177 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2178 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2181 Type *PointeeType = nullptr;
2182 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2184 PointeeType = getTypeByID(Record[OpNum++]);
2186 bool InBounds = false;
2187 Optional<unsigned> InRangeIndex;
2188 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2189 uint64_t Op = Record[OpNum++];
2191 InRangeIndex = Op >> 1;
2192 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2195 SmallVector<Constant*, 16> Elts;
2196 while (OpNum != Record.size()) {
2197 Type *ElTy = getTypeByID(Record[OpNum++]);
2199 return error("Invalid record");
2200 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2205 cast<PointerType>(Elts[0]->getType()->getScalarType())
2207 return error("Explicit gep operator type does not match pointee type "
2208 "of pointer operand");
2210 if (Elts.size() < 1)
2211 return error("Invalid gep with no operands");
2213 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2214 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2215 InBounds, InRangeIndex);
2218 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2219 if (Record.size() < 3)
2220 return error("Invalid record");
2222 Type *SelectorTy = Type::getInt1Ty(Context);
2224 // The selector might be an i1 or an <n x i1>
2225 // Get the type from the ValueList before getting a forward ref.
2226 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2227 if (Value *V = ValueList[Record[0]])
2228 if (SelectorTy != V->getType())
2229 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2231 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2233 ValueList.getConstantFwdRef(Record[1],CurTy),
2234 ValueList.getConstantFwdRef(Record[2],CurTy));
2237 case bitc::CST_CODE_CE_EXTRACTELT
2238 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2239 if (Record.size() < 3)
2240 return error("Invalid record");
2242 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2244 return error("Invalid record");
2245 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2246 Constant *Op1 = nullptr;
2247 if (Record.size() == 4) {
2248 Type *IdxTy = getTypeByID(Record[2]);
2250 return error("Invalid record");
2251 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2252 } else // TODO: Remove with llvm 4.0
2253 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2255 return error("Invalid record");
2256 V = ConstantExpr::getExtractElement(Op0, Op1);
2259 case bitc::CST_CODE_CE_INSERTELT
2260 : { // CE_INSERTELT: [opval, opval, opty, opval]
2261 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2262 if (Record.size() < 3 || !OpTy)
2263 return error("Invalid record");
2264 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2265 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2266 OpTy->getElementType());
2267 Constant *Op2 = nullptr;
2268 if (Record.size() == 4) {
2269 Type *IdxTy = getTypeByID(Record[2]);
2271 return error("Invalid record");
2272 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2273 } else // TODO: Remove with llvm 4.0
2274 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2276 return error("Invalid record");
2277 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2280 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2281 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2282 if (Record.size() < 3 || !OpTy)
2283 return error("Invalid record");
2284 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2285 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2286 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2287 OpTy->getNumElements());
2288 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2289 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2292 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2293 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2295 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2296 if (Record.size() < 4 || !RTy || !OpTy)
2297 return error("Invalid record");
2298 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2299 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2300 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2301 RTy->getNumElements());
2302 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2303 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2306 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2307 if (Record.size() < 4)
2308 return error("Invalid record");
2309 Type *OpTy = getTypeByID(Record[0]);
2311 return error("Invalid record");
2312 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2313 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2315 if (OpTy->isFPOrFPVectorTy())
2316 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2318 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2321 // This maintains backward compatibility, pre-asm dialect keywords.
2322 // FIXME: Remove with the 4.0 release.
2323 case bitc::CST_CODE_INLINEASM_OLD: {
2324 if (Record.size() < 2)
2325 return error("Invalid record");
2326 std::string AsmStr, ConstrStr;
2327 bool HasSideEffects = Record[0] & 1;
2328 bool IsAlignStack = Record[0] >> 1;
2329 unsigned AsmStrSize = Record[1];
2330 if (2+AsmStrSize >= Record.size())
2331 return error("Invalid record");
2332 unsigned ConstStrSize = Record[2+AsmStrSize];
2333 if (3+AsmStrSize+ConstStrSize > Record.size())
2334 return error("Invalid record");
2336 for (unsigned i = 0; i != AsmStrSize; ++i)
2337 AsmStr += (char)Record[2+i];
2338 for (unsigned i = 0; i != ConstStrSize; ++i)
2339 ConstrStr += (char)Record[3+AsmStrSize+i];
2340 PointerType *PTy = cast<PointerType>(CurTy);
2341 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2342 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2345 // This version adds support for the asm dialect keywords (e.g.,
2347 case bitc::CST_CODE_INLINEASM: {
2348 if (Record.size() < 2)
2349 return error("Invalid record");
2350 std::string AsmStr, ConstrStr;
2351 bool HasSideEffects = Record[0] & 1;
2352 bool IsAlignStack = (Record[0] >> 1) & 1;
2353 unsigned AsmDialect = Record[0] >> 2;
2354 unsigned AsmStrSize = Record[1];
2355 if (2+AsmStrSize >= Record.size())
2356 return error("Invalid record");
2357 unsigned ConstStrSize = Record[2+AsmStrSize];
2358 if (3+AsmStrSize+ConstStrSize > Record.size())
2359 return error("Invalid record");
2361 for (unsigned i = 0; i != AsmStrSize; ++i)
2362 AsmStr += (char)Record[2+i];
2363 for (unsigned i = 0; i != ConstStrSize; ++i)
2364 ConstrStr += (char)Record[3+AsmStrSize+i];
2365 PointerType *PTy = cast<PointerType>(CurTy);
2366 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2367 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2368 InlineAsm::AsmDialect(AsmDialect));
2371 case bitc::CST_CODE_BLOCKADDRESS:{
2372 if (Record.size() < 3)
2373 return error("Invalid record");
2374 Type *FnTy = getTypeByID(Record[0]);
2376 return error("Invalid record");
2378 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2380 return error("Invalid record");
2382 // If the function is already parsed we can insert the block address right
2385 unsigned BBID = Record[2];
2387 // Invalid reference to entry block.
2388 return error("Invalid ID");
2390 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2391 for (size_t I = 0, E = BBID; I != E; ++I) {
2393 return error("Invalid ID");
2398 // Otherwise insert a placeholder and remember it so it can be inserted
2399 // when the function is parsed.
2400 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2402 BasicBlockFwdRefQueue.push_back(Fn);
2403 if (FwdBBs.size() < BBID + 1)
2404 FwdBBs.resize(BBID + 1);
2406 FwdBBs[BBID] = BasicBlock::Create(Context);
2409 V = BlockAddress::get(Fn, BB);
2414 ValueList.assignValue(V, NextCstNo);
2419 Error BitcodeReader::parseUseLists() {
2420 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2421 return error("Invalid record");
2423 // Read all the records.
2424 SmallVector<uint64_t, 64> Record;
2427 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2429 switch (Entry.Kind) {
2430 case BitstreamEntry::SubBlock: // Handled for us already.
2431 case BitstreamEntry::Error:
2432 return error("Malformed block");
2433 case BitstreamEntry::EndBlock:
2434 return Error::success();
2435 case BitstreamEntry::Record:
2436 // The interesting case.
2440 // Read a use list record.
2443 switch (Stream.readRecord(Entry.ID, Record)) {
2444 default: // Default behavior: unknown type.
2446 case bitc::USELIST_CODE_BB:
2449 case bitc::USELIST_CODE_DEFAULT: {
2450 unsigned RecordLength = Record.size();
2451 if (RecordLength < 3)
2452 // Records should have at least an ID and two indexes.
2453 return error("Invalid record");
2454 unsigned ID = Record.back();
2459 assert(ID < FunctionBBs.size() && "Basic block not found");
2460 V = FunctionBBs[ID];
2463 unsigned NumUses = 0;
2464 SmallDenseMap<const Use *, unsigned, 16> Order;
2465 for (const Use &U : V->materialized_uses()) {
2466 if (++NumUses > Record.size())
2468 Order[&U] = Record[NumUses - 1];
2470 if (Order.size() != Record.size() || NumUses > Record.size())
2471 // Mismatches can happen if the functions are being materialized lazily
2472 // (out-of-order), or a value has been upgraded.
2475 V->sortUseList([&](const Use &L, const Use &R) {
2476 return Order.lookup(&L) < Order.lookup(&R);
2484 /// When we see the block for metadata, remember where it is and then skip it.
2485 /// This lets us lazily deserialize the metadata.
2486 Error BitcodeReader::rememberAndSkipMetadata() {
2487 // Save the current stream state.
2488 uint64_t CurBit = Stream.GetCurrentBitNo();
2489 DeferredMetadataInfo.push_back(CurBit);
2491 // Skip over the block for now.
2492 if (Stream.SkipBlock())
2493 return error("Invalid record");
2494 return Error::success();
2497 Error BitcodeReader::materializeMetadata() {
2498 for (uint64_t BitPos : DeferredMetadataInfo) {
2499 // Move the bit stream to the saved position.
2500 Stream.JumpToBit(BitPos);
2501 if (Error Err = MDLoader->parseModuleMetadata())
2504 DeferredMetadataInfo.clear();
2505 return Error::success();
2508 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2510 /// When we see the block for a function body, remember where it is and then
2511 /// skip it. This lets us lazily deserialize the functions.
2512 Error BitcodeReader::rememberAndSkipFunctionBody() {
2513 // Get the function we are talking about.
2514 if (FunctionsWithBodies.empty())
2515 return error("Insufficient function protos");
2517 Function *Fn = FunctionsWithBodies.back();
2518 FunctionsWithBodies.pop_back();
2520 // Save the current stream state.
2521 uint64_t CurBit = Stream.GetCurrentBitNo();
2523 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2524 "Mismatch between VST and scanned function offsets");
2525 DeferredFunctionInfo[Fn] = CurBit;
2527 // Skip over the function block for now.
2528 if (Stream.SkipBlock())
2529 return error("Invalid record");
2530 return Error::success();
2533 Error BitcodeReader::globalCleanup() {
2534 // Patch the initializers for globals and aliases up.
2535 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2537 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2538 return error("Malformed global initializer set");
2540 // Look for intrinsic functions which need to be upgraded at some point
2541 for (Function &F : *TheModule) {
2543 if (UpgradeIntrinsicFunction(&F, NewFn))
2544 UpgradedIntrinsics[&F] = NewFn;
2545 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2546 // Some types could be renamed during loading if several modules are
2547 // loaded in the same LLVMContext (LTO scenario). In this case we should
2548 // remangle intrinsics names as well.
2549 RemangledIntrinsics[&F] = Remangled.getValue();
2552 // Look for global variables which need to be renamed.
2553 for (GlobalVariable &GV : TheModule->globals())
2554 UpgradeGlobalVariable(&GV);
2556 // Force deallocation of memory for these vectors to favor the client that
2557 // want lazy deserialization.
2558 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2559 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
2560 IndirectSymbolInits);
2561 return Error::success();
2564 /// Support for lazy parsing of function bodies. This is required if we
2565 /// either have an old bitcode file without a VST forward declaration record,
2566 /// or if we have an anonymous function being materialized, since anonymous
2567 /// functions do not have a name and are therefore not in the VST.
2568 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2569 Stream.JumpToBit(NextUnreadBit);
2571 if (Stream.AtEndOfStream())
2572 return error("Could not find function in stream");
2574 if (!SeenFirstFunctionBody)
2575 return error("Trying to materialize functions before seeing function blocks");
2577 // An old bitcode file with the symbol table at the end would have
2578 // finished the parse greedily.
2579 assert(SeenValueSymbolTable);
2581 SmallVector<uint64_t, 64> Record;
2584 BitstreamEntry Entry = Stream.advance();
2585 switch (Entry.Kind) {
2587 return error("Expect SubBlock");
2588 case BitstreamEntry::SubBlock:
2591 return error("Expect function block");
2592 case bitc::FUNCTION_BLOCK_ID:
2593 if (Error Err = rememberAndSkipFunctionBody())
2595 NextUnreadBit = Stream.GetCurrentBitNo();
2596 return Error::success();
2602 bool BitcodeReaderBase::readBlockInfo() {
2603 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2606 BlockInfo = std::move(*NewBlockInfo);
2610 Error BitcodeReader::parseModule(uint64_t ResumeBit,
2611 bool ShouldLazyLoadMetadata) {
2613 Stream.JumpToBit(ResumeBit);
2614 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2615 return error("Invalid record");
2617 SmallVector<uint64_t, 64> Record;
2618 std::vector<std::string> SectionTable;
2619 std::vector<std::string> GCTable;
2621 // Read all the records for this module.
2623 BitstreamEntry Entry = Stream.advance();
2625 switch (Entry.Kind) {
2626 case BitstreamEntry::Error:
2627 return error("Malformed block");
2628 case BitstreamEntry::EndBlock:
2629 return globalCleanup();
2631 case BitstreamEntry::SubBlock:
2633 default: // Skip unknown content.
2634 if (Stream.SkipBlock())
2635 return error("Invalid record");
2637 case bitc::BLOCKINFO_BLOCK_ID:
2638 if (readBlockInfo())
2639 return error("Malformed block");
2641 case bitc::PARAMATTR_BLOCK_ID:
2642 if (Error Err = parseAttributeBlock())
2645 case bitc::PARAMATTR_GROUP_BLOCK_ID:
2646 if (Error Err = parseAttributeGroupBlock())
2649 case bitc::TYPE_BLOCK_ID_NEW:
2650 if (Error Err = parseTypeTable())
2653 case bitc::VALUE_SYMTAB_BLOCK_ID:
2654 if (!SeenValueSymbolTable) {
2655 // Either this is an old form VST without function index and an
2656 // associated VST forward declaration record (which would have caused
2657 // the VST to be jumped to and parsed before it was encountered
2658 // normally in the stream), or there were no function blocks to
2659 // trigger an earlier parsing of the VST.
2660 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
2661 if (Error Err = parseValueSymbolTable())
2663 SeenValueSymbolTable = true;
2665 // We must have had a VST forward declaration record, which caused
2666 // the parser to jump to and parse the VST earlier.
2667 assert(VSTOffset > 0);
2668 if (Stream.SkipBlock())
2669 return error("Invalid record");
2672 case bitc::CONSTANTS_BLOCK_ID:
2673 if (Error Err = parseConstants())
2675 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2678 case bitc::METADATA_BLOCK_ID:
2679 if (ShouldLazyLoadMetadata) {
2680 if (Error Err = rememberAndSkipMetadata())
2684 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2685 if (Error Err = MDLoader->parseModuleMetadata())
2688 case bitc::METADATA_KIND_BLOCK_ID:
2689 if (Error Err = MDLoader->parseMetadataKinds())
2692 case bitc::FUNCTION_BLOCK_ID:
2693 // If this is the first function body we've seen, reverse the
2694 // FunctionsWithBodies list.
2695 if (!SeenFirstFunctionBody) {
2696 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2697 if (Error Err = globalCleanup())
2699 SeenFirstFunctionBody = true;
2702 if (VSTOffset > 0) {
2703 // If we have a VST forward declaration record, make sure we
2704 // parse the VST now if we haven't already. It is needed to
2705 // set up the DeferredFunctionInfo vector for lazy reading.
2706 if (!SeenValueSymbolTable) {
2707 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
2709 SeenValueSymbolTable = true;
2710 // Fall through so that we record the NextUnreadBit below.
2711 // This is necessary in case we have an anonymous function that
2712 // is later materialized. Since it will not have a VST entry we
2713 // need to fall back to the lazy parse to find its offset.
2715 // If we have a VST forward declaration record, but have already
2716 // parsed the VST (just above, when the first function body was
2717 // encountered here), then we are resuming the parse after
2718 // materializing functions. The ResumeBit points to the
2719 // start of the last function block recorded in the
2720 // DeferredFunctionInfo map. Skip it.
2721 if (Stream.SkipBlock())
2722 return error("Invalid record");
2727 // Support older bitcode files that did not have the function
2728 // index in the VST, nor a VST forward declaration record, as
2729 // well as anonymous functions that do not have VST entries.
2730 // Build the DeferredFunctionInfo vector on the fly.
2731 if (Error Err = rememberAndSkipFunctionBody())
2734 // Suspend parsing when we reach the function bodies. Subsequent
2735 // materialization calls will resume it when necessary. If the bitcode
2736 // file is old, the symbol table will be at the end instead and will not
2737 // have been seen yet. In this case, just finish the parse now.
2738 if (SeenValueSymbolTable) {
2739 NextUnreadBit = Stream.GetCurrentBitNo();
2740 // After the VST has been parsed, we need to make sure intrinsic name
2741 // are auto-upgraded.
2742 return globalCleanup();
2745 case bitc::USELIST_BLOCK_ID:
2746 if (Error Err = parseUseLists())
2749 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
2750 if (Error Err = parseOperandBundleTags())
2756 case BitstreamEntry::Record:
2757 // The interesting case.
2762 auto BitCode = Stream.readRecord(Entry.ID, Record);
2764 default: break; // Default behavior, ignore unknown content.
2765 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2766 if (Record.size() < 1)
2767 return error("Invalid record");
2768 // Only version #0 and #1 are supported so far.
2769 unsigned module_version = Record[0];
2770 switch (module_version) {
2772 return error("Invalid value");
2774 UseRelativeIDs = false;
2777 UseRelativeIDs = true;
2782 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2784 if (convertToString(Record, 0, S))
2785 return error("Invalid record");
2786 TheModule->setTargetTriple(S);
2789 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2791 if (convertToString(Record, 0, S))
2792 return error("Invalid record");
2793 TheModule->setDataLayout(S);
2796 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2798 if (convertToString(Record, 0, S))
2799 return error("Invalid record");
2800 TheModule->setModuleInlineAsm(S);
2803 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2804 // FIXME: Remove in 4.0.
2806 if (convertToString(Record, 0, S))
2807 return error("Invalid record");
2811 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2813 if (convertToString(Record, 0, S))
2814 return error("Invalid record");
2815 SectionTable.push_back(S);
2818 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2820 if (convertToString(Record, 0, S))
2821 return error("Invalid record");
2822 GCTable.push_back(S);
2825 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2826 if (Record.size() < 2)
2827 return error("Invalid record");
2828 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2829 unsigned ComdatNameSize = Record[1];
2830 std::string ComdatName;
2831 ComdatName.reserve(ComdatNameSize);
2832 for (unsigned i = 0; i != ComdatNameSize; ++i)
2833 ComdatName += (char)Record[2 + i];
2834 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2835 C->setSelectionKind(SK);
2836 ComdatList.push_back(C);
2839 // GLOBALVAR: [pointer type, isconst, initid,
2840 // linkage, alignment, section, visibility, threadlocal,
2841 // unnamed_addr, externally_initialized, dllstorageclass,
2843 case bitc::MODULE_CODE_GLOBALVAR: {
2844 if (Record.size() < 6)
2845 return error("Invalid record");
2846 Type *Ty = getTypeByID(Record[0]);
2848 return error("Invalid record");
2849 bool isConstant = Record[1] & 1;
2850 bool explicitType = Record[1] & 2;
2851 unsigned AddressSpace;
2853 AddressSpace = Record[1] >> 2;
2855 if (!Ty->isPointerTy())
2856 return error("Invalid type for value");
2857 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2858 Ty = cast<PointerType>(Ty)->getElementType();
2861 uint64_t RawLinkage = Record[3];
2862 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2864 if (Error Err = parseAlignmentValue(Record[4], Alignment))
2866 std::string Section;
2868 if (Record[5]-1 >= SectionTable.size())
2869 return error("Invalid ID");
2870 Section = SectionTable[Record[5]-1];
2872 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2873 // Local linkage must have default visibility.
2874 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2875 // FIXME: Change to an error if non-default in 4.0.
2876 Visibility = getDecodedVisibility(Record[6]);
2878 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2879 if (Record.size() > 7)
2880 TLM = getDecodedThreadLocalMode(Record[7]);
2882 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2883 if (Record.size() > 8)
2884 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2886 bool ExternallyInitialized = false;
2887 if (Record.size() > 9)
2888 ExternallyInitialized = Record[9];
2890 GlobalVariable *NewGV =
2891 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2892 TLM, AddressSpace, ExternallyInitialized);
2893 NewGV->setAlignment(Alignment);
2894 if (!Section.empty())
2895 NewGV->setSection(Section);
2896 NewGV->setVisibility(Visibility);
2897 NewGV->setUnnamedAddr(UnnamedAddr);
2899 if (Record.size() > 10)
2900 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2902 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2904 ValueList.push_back(NewGV);
2906 // Remember which value to use for the global initializer.
2907 if (unsigned InitID = Record[2])
2908 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2910 if (Record.size() > 11) {
2911 if (unsigned ComdatID = Record[11]) {
2912 if (ComdatID > ComdatList.size())
2913 return error("Invalid global variable comdat ID");
2914 NewGV->setComdat(ComdatList[ComdatID - 1]);
2916 } else if (hasImplicitComdat(RawLinkage)) {
2917 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2922 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2923 // alignment, section, visibility, gc, unnamed_addr,
2924 // prologuedata, dllstorageclass, comdat, prefixdata]
2925 case bitc::MODULE_CODE_FUNCTION: {
2926 if (Record.size() < 8)
2927 return error("Invalid record");
2928 Type *Ty = getTypeByID(Record[0]);
2930 return error("Invalid record");
2931 if (auto *PTy = dyn_cast<PointerType>(Ty))
2932 Ty = PTy->getElementType();
2933 auto *FTy = dyn_cast<FunctionType>(Ty);
2935 return error("Invalid type for value");
2936 auto CC = static_cast<CallingConv::ID>(Record[1]);
2937 if (CC & ~CallingConv::MaxID)
2938 return error("Invalid calling convention ID");
2940 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2943 Func->setCallingConv(CC);
2944 bool isProto = Record[2];
2945 uint64_t RawLinkage = Record[3];
2946 Func->setLinkage(getDecodedLinkage(RawLinkage));
2947 Func->setAttributes(getAttributes(Record[4]));
2950 if (Error Err = parseAlignmentValue(Record[5], Alignment))
2952 Func->setAlignment(Alignment);
2954 if (Record[6]-1 >= SectionTable.size())
2955 return error("Invalid ID");
2956 Func->setSection(SectionTable[Record[6]-1]);
2958 // Local linkage must have default visibility.
2959 if (!Func->hasLocalLinkage())
2960 // FIXME: Change to an error if non-default in 4.0.
2961 Func->setVisibility(getDecodedVisibility(Record[7]));
2962 if (Record.size() > 8 && Record[8]) {
2963 if (Record[8]-1 >= GCTable.size())
2964 return error("Invalid ID");
2965 Func->setGC(GCTable[Record[8] - 1]);
2967 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2968 if (Record.size() > 9)
2969 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2970 Func->setUnnamedAddr(UnnamedAddr);
2971 if (Record.size() > 10 && Record[10] != 0)
2972 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2974 if (Record.size() > 11)
2975 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2977 upgradeDLLImportExportLinkage(Func, RawLinkage);
2979 if (Record.size() > 12) {
2980 if (unsigned ComdatID = Record[12]) {
2981 if (ComdatID > ComdatList.size())
2982 return error("Invalid function comdat ID");
2983 Func->setComdat(ComdatList[ComdatID - 1]);
2985 } else if (hasImplicitComdat(RawLinkage)) {
2986 Func->setComdat(reinterpret_cast<Comdat *>(1));
2989 if (Record.size() > 13 && Record[13] != 0)
2990 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2992 if (Record.size() > 14 && Record[14] != 0)
2993 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
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;
3006 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3007 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3008 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3009 case bitc::MODULE_CODE_IFUNC:
3010 case bitc::MODULE_CODE_ALIAS:
3011 case bitc::MODULE_CODE_ALIAS_OLD: {
3012 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3013 if (Record.size() < (3 + (unsigned)NewRecord))
3014 return error("Invalid record");
3016 Type *Ty = getTypeByID(Record[OpNum++]);
3018 return error("Invalid record");
3022 auto *PTy = dyn_cast<PointerType>(Ty);
3024 return error("Invalid type for value");
3025 Ty = PTy->getElementType();
3026 AddrSpace = PTy->getAddressSpace();
3028 AddrSpace = Record[OpNum++];
3031 auto Val = Record[OpNum++];
3032 auto Linkage = Record[OpNum++];
3033 GlobalIndirectSymbol *NewGA;
3034 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3035 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3036 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3039 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3040 "", nullptr, TheModule);
3041 // Old bitcode files didn't have visibility field.
3042 // Local linkage must have default visibility.
3043 if (OpNum != Record.size()) {
3044 auto VisInd = OpNum++;
3045 if (!NewGA->hasLocalLinkage())
3046 // FIXME: Change to an error if non-default in 4.0.
3047 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3049 if (OpNum != Record.size())
3050 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3052 upgradeDLLImportExportLinkage(NewGA, Linkage);
3053 if (OpNum != Record.size())
3054 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3055 if (OpNum != Record.size())
3056 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3057 ValueList.push_back(NewGA);
3058 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3061 /// MODULE_CODE_PURGEVALS: [numvals]
3062 case bitc::MODULE_CODE_PURGEVALS:
3063 // Trim down the value list to the specified size.
3064 if (Record.size() < 1 || Record[0] > ValueList.size())
3065 return error("Invalid record");
3066 ValueList.shrinkTo(Record[0]);
3068 /// MODULE_CODE_VSTOFFSET: [offset]
3069 case bitc::MODULE_CODE_VSTOFFSET:
3070 if (Record.size() < 1)
3071 return error("Invalid record");
3072 // Note that we subtract 1 here because the offset is relative to one word
3073 // before the start of the identification or module block, which was
3074 // historically always the start of the regular bitcode header.
3075 VSTOffset = Record[0] - 1;
3077 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3078 case bitc::MODULE_CODE_SOURCE_FILENAME:
3079 SmallString<128> ValueName;
3080 if (convertToString(Record, 0, ValueName))
3081 return error("Invalid record");
3082 TheModule->setSourceFileName(ValueName);
3089 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3092 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3093 [&](unsigned ID) { return getTypeByID(ID); });
3094 return parseModule(0, ShouldLazyLoadMetadata);
3098 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3099 if (!isa<PointerType>(PtrType))
3100 return error("Load/Store operand is not a pointer type");
3101 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3103 if (ValType && ValType != ElemType)
3104 return error("Explicit load/store type does not match pointee "
3105 "type of pointer operand");
3106 if (!PointerType::isLoadableOrStorableType(ElemType))
3107 return error("Cannot load/store from pointer");
3108 return Error::success();
3111 /// Lazily parse the specified function body block.
3112 Error BitcodeReader::parseFunctionBody(Function *F) {
3113 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3114 return error("Invalid record");
3116 // Unexpected unresolved metadata when parsing function.
3117 if (MDLoader->hasFwdRefs())
3118 return error("Invalid function metadata: incoming forward references");
3120 InstructionList.clear();
3121 unsigned ModuleValueListSize = ValueList.size();
3122 unsigned ModuleMDLoaderSize = MDLoader->size();
3124 // Add all the function arguments to the value table.
3125 for (Argument &I : F->args())
3126 ValueList.push_back(&I);
3128 unsigned NextValueNo = ValueList.size();
3129 BasicBlock *CurBB = nullptr;
3130 unsigned CurBBNo = 0;
3133 auto getLastInstruction = [&]() -> Instruction * {
3134 if (CurBB && !CurBB->empty())
3135 return &CurBB->back();
3136 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3137 !FunctionBBs[CurBBNo - 1]->empty())
3138 return &FunctionBBs[CurBBNo - 1]->back();
3142 std::vector<OperandBundleDef> OperandBundles;
3144 // Read all the records.
3145 SmallVector<uint64_t, 64> Record;
3148 BitstreamEntry Entry = Stream.advance();
3150 switch (Entry.Kind) {
3151 case BitstreamEntry::Error:
3152 return error("Malformed block");
3153 case BitstreamEntry::EndBlock:
3154 goto OutOfRecordLoop;
3156 case BitstreamEntry::SubBlock:
3158 default: // Skip unknown content.
3159 if (Stream.SkipBlock())
3160 return error("Invalid record");
3162 case bitc::CONSTANTS_BLOCK_ID:
3163 if (Error Err = parseConstants())
3165 NextValueNo = ValueList.size();
3167 case bitc::VALUE_SYMTAB_BLOCK_ID:
3168 if (Error Err = parseValueSymbolTable())
3171 case bitc::METADATA_ATTACHMENT_ID:
3172 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3175 case bitc::METADATA_BLOCK_ID:
3176 assert(DeferredMetadataInfo.empty() &&
3177 "Must read all module-level metadata before function-level");
3178 if (Error Err = MDLoader->parseFunctionMetadata())
3181 case bitc::USELIST_BLOCK_ID:
3182 if (Error Err = parseUseLists())
3188 case BitstreamEntry::Record:
3189 // The interesting case.
3195 Instruction *I = nullptr;
3196 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3198 default: // Default behavior: reject
3199 return error("Invalid value");
3200 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3201 if (Record.size() < 1 || Record[0] == 0)
3202 return error("Invalid record");
3203 // Create all the basic blocks for the function.
3204 FunctionBBs.resize(Record[0]);
3206 // See if anything took the address of blocks in this function.
3207 auto BBFRI = BasicBlockFwdRefs.find(F);
3208 if (BBFRI == BasicBlockFwdRefs.end()) {
3209 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3210 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3212 auto &BBRefs = BBFRI->second;
3213 // Check for invalid basic block references.
3214 if (BBRefs.size() > FunctionBBs.size())
3215 return error("Invalid ID");
3216 assert(!BBRefs.empty() && "Unexpected empty array");
3217 assert(!BBRefs.front() && "Invalid reference to entry block");
3218 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3220 if (I < RE && BBRefs[I]) {
3221 BBRefs[I]->insertInto(F);
3222 FunctionBBs[I] = BBRefs[I];
3224 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3227 // Erase from the table.
3228 BasicBlockFwdRefs.erase(BBFRI);
3231 CurBB = FunctionBBs[0];
3235 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3236 // This record indicates that the last instruction is at the same
3237 // location as the previous instruction with a location.
3238 I = getLastInstruction();
3241 return error("Invalid record");
3242 I->setDebugLoc(LastLoc);
3246 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3247 I = getLastInstruction();
3248 if (!I || Record.size() < 4)
3249 return error("Invalid record");
3251 unsigned Line = Record[0], Col = Record[1];
3252 unsigned ScopeID = Record[2], IAID = Record[3];
3254 MDNode *Scope = nullptr, *IA = nullptr;
3256 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
3258 return error("Invalid record");
3261 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
3263 return error("Invalid record");
3265 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3266 I->setDebugLoc(LastLoc);
3271 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3274 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3275 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3276 OpNum+1 > Record.size())
3277 return error("Invalid record");
3279 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3281 return error("Invalid record");
3282 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3283 InstructionList.push_back(I);
3284 if (OpNum < Record.size()) {
3285 if (Opc == Instruction::Add ||
3286 Opc == Instruction::Sub ||
3287 Opc == Instruction::Mul ||
3288 Opc == Instruction::Shl) {
3289 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3290 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3291 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3292 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3293 } else if (Opc == Instruction::SDiv ||
3294 Opc == Instruction::UDiv ||
3295 Opc == Instruction::LShr ||
3296 Opc == Instruction::AShr) {
3297 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3298 cast<BinaryOperator>(I)->setIsExact(true);
3299 } else if (isa<FPMathOperator>(I)) {
3300 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3302 I->setFastMathFlags(FMF);
3308 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3311 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3312 OpNum+2 != Record.size())
3313 return error("Invalid record");
3315 Type *ResTy = getTypeByID(Record[OpNum]);
3316 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3317 if (Opc == -1 || !ResTy)
3318 return error("Invalid record");
3319 Instruction *Temp = nullptr;
3320 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3322 InstructionList.push_back(Temp);
3323 CurBB->getInstList().push_back(Temp);
3326 auto CastOp = (Instruction::CastOps)Opc;
3327 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3328 return error("Invalid cast");
3329 I = CastInst::Create(CastOp, Op, ResTy);
3331 InstructionList.push_back(I);
3334 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3335 case bitc::FUNC_CODE_INST_GEP_OLD:
3336 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3342 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3343 InBounds = Record[OpNum++];
3344 Ty = getTypeByID(Record[OpNum++]);
3346 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3351 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3352 return error("Invalid record");
3355 Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3358 cast<PointerType>(BasePtr->getType()->getScalarType())
3361 "Explicit gep type does not match pointee type of pointer operand");
3363 SmallVector<Value*, 16> GEPIdx;
3364 while (OpNum != Record.size()) {
3366 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3367 return error("Invalid record");
3368 GEPIdx.push_back(Op);
3371 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3373 InstructionList.push_back(I);
3375 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3379 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3380 // EXTRACTVAL: [opty, opval, n x indices]
3383 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3384 return error("Invalid record");
3386 unsigned RecSize = Record.size();
3387 if (OpNum == RecSize)
3388 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3390 SmallVector<unsigned, 4> EXTRACTVALIdx;
3391 Type *CurTy = Agg->getType();
3392 for (; OpNum != RecSize; ++OpNum) {
3393 bool IsArray = CurTy->isArrayTy();
3394 bool IsStruct = CurTy->isStructTy();
3395 uint64_t Index = Record[OpNum];
3397 if (!IsStruct && !IsArray)
3398 return error("EXTRACTVAL: Invalid type");
3399 if ((unsigned)Index != Index)
3400 return error("Invalid value");
3401 if (IsStruct && Index >= CurTy->subtypes().size())
3402 return error("EXTRACTVAL: Invalid struct index");
3403 if (IsArray && Index >= CurTy->getArrayNumElements())
3404 return error("EXTRACTVAL: Invalid array index");
3405 EXTRACTVALIdx.push_back((unsigned)Index);
3408 CurTy = CurTy->subtypes()[Index];
3410 CurTy = CurTy->subtypes()[0];
3413 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3414 InstructionList.push_back(I);
3418 case bitc::FUNC_CODE_INST_INSERTVAL: {
3419 // INSERTVAL: [opty, opval, opty, opval, n x indices]
3422 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3423 return error("Invalid record");
3425 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3426 return error("Invalid record");
3428 unsigned RecSize = Record.size();
3429 if (OpNum == RecSize)
3430 return error("INSERTVAL: Invalid instruction with 0 indices");
3432 SmallVector<unsigned, 4> INSERTVALIdx;
3433 Type *CurTy = Agg->getType();
3434 for (; OpNum != RecSize; ++OpNum) {
3435 bool IsArray = CurTy->isArrayTy();
3436 bool IsStruct = CurTy->isStructTy();
3437 uint64_t Index = Record[OpNum];
3439 if (!IsStruct && !IsArray)
3440 return error("INSERTVAL: Invalid type");
3441 if ((unsigned)Index != Index)
3442 return error("Invalid value");
3443 if (IsStruct && Index >= CurTy->subtypes().size())
3444 return error("INSERTVAL: Invalid struct index");
3445 if (IsArray && Index >= CurTy->getArrayNumElements())
3446 return error("INSERTVAL: Invalid array index");
3448 INSERTVALIdx.push_back((unsigned)Index);
3450 CurTy = CurTy->subtypes()[Index];
3452 CurTy = CurTy->subtypes()[0];
3455 if (CurTy != Val->getType())
3456 return error("Inserted value type doesn't match aggregate type");
3458 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3459 InstructionList.push_back(I);
3463 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3464 // obsolete form of select
3465 // handles select i1 ... in old bitcode
3467 Value *TrueVal, *FalseVal, *Cond;
3468 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3469 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3470 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3471 return error("Invalid record");
3473 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3474 InstructionList.push_back(I);
3478 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3479 // new form of select
3480 // handles select i1 or select [N x i1]
3482 Value *TrueVal, *FalseVal, *Cond;
3483 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3484 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3485 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3486 return error("Invalid record");
3488 // select condition can be either i1 or [N x i1]
3489 if (VectorType* vector_type =
3490 dyn_cast<VectorType>(Cond->getType())) {
3492 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3493 return error("Invalid type for value");
3496 if (Cond->getType() != Type::getInt1Ty(Context))
3497 return error("Invalid type for value");
3500 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3501 InstructionList.push_back(I);
3505 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3508 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3509 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3510 return error("Invalid record");
3511 if (!Vec->getType()->isVectorTy())
3512 return error("Invalid type for value");
3513 I = ExtractElementInst::Create(Vec, Idx);
3514 InstructionList.push_back(I);
3518 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3520 Value *Vec, *Elt, *Idx;
3521 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3522 return error("Invalid record");
3523 if (!Vec->getType()->isVectorTy())
3524 return error("Invalid type for value");
3525 if (popValue(Record, OpNum, NextValueNo,
3526 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3527 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3528 return error("Invalid record");
3529 I = InsertElementInst::Create(Vec, Elt, Idx);
3530 InstructionList.push_back(I);
3534 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3536 Value *Vec1, *Vec2, *Mask;
3537 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3538 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3539 return error("Invalid record");
3541 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3542 return error("Invalid record");
3543 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3544 return error("Invalid type for value");
3545 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3546 InstructionList.push_back(I);
3550 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3551 // Old form of ICmp/FCmp returning bool
3552 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3553 // both legal on vectors but had different behaviour.
3554 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3555 // FCmp/ICmp returning bool or vector of bool
3559 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3560 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3561 return error("Invalid record");
3563 unsigned PredVal = Record[OpNum];
3564 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3566 if (IsFP && Record.size() > OpNum+1)
3567 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3569 if (OpNum+1 != Record.size())
3570 return error("Invalid record");
3572 if (LHS->getType()->isFPOrFPVectorTy())
3573 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3575 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3578 I->setFastMathFlags(FMF);
3579 InstructionList.push_back(I);
3583 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3585 unsigned Size = Record.size();
3587 I = ReturnInst::Create(Context);
3588 InstructionList.push_back(I);
3593 Value *Op = nullptr;
3594 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3595 return error("Invalid record");
3596 if (OpNum != Record.size())
3597 return error("Invalid record");
3599 I = ReturnInst::Create(Context, Op);
3600 InstructionList.push_back(I);
3603 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3604 if (Record.size() != 1 && Record.size() != 3)
3605 return error("Invalid record");
3606 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3608 return error("Invalid record");
3610 if (Record.size() == 1) {
3611 I = BranchInst::Create(TrueDest);
3612 InstructionList.push_back(I);
3615 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3616 Value *Cond = getValue(Record, 2, NextValueNo,
3617 Type::getInt1Ty(Context));
3618 if (!FalseDest || !Cond)
3619 return error("Invalid record");
3620 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3621 InstructionList.push_back(I);
3625 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
3626 if (Record.size() != 1 && Record.size() != 2)
3627 return error("Invalid record");
3630 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3632 return error("Invalid record");
3633 BasicBlock *UnwindDest = nullptr;
3634 if (Record.size() == 2) {
3635 UnwindDest = getBasicBlock(Record[Idx++]);
3637 return error("Invalid record");
3640 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
3641 InstructionList.push_back(I);
3644 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3645 if (Record.size() != 2)
3646 return error("Invalid record");
3649 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3651 return error("Invalid record");
3652 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3654 return error("Invalid record");
3656 I = CatchReturnInst::Create(CatchPad, BB);
3657 InstructionList.push_back(I);
3660 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3661 // We must have, at minimum, the outer scope and the number of arguments.
3662 if (Record.size() < 2)
3663 return error("Invalid record");
3668 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3670 unsigned NumHandlers = Record[Idx++];
3672 SmallVector<BasicBlock *, 2> Handlers;
3673 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3674 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3676 return error("Invalid record");
3677 Handlers.push_back(BB);
3680 BasicBlock *UnwindDest = nullptr;
3681 if (Idx + 1 == Record.size()) {
3682 UnwindDest = getBasicBlock(Record[Idx++]);
3684 return error("Invalid record");
3687 if (Record.size() != Idx)
3688 return error("Invalid record");
3691 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3692 for (BasicBlock *Handler : Handlers)
3693 CatchSwitch->addHandler(Handler);
3695 InstructionList.push_back(I);
3698 case bitc::FUNC_CODE_INST_CATCHPAD:
3699 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3700 // We must have, at minimum, the outer scope and the number of arguments.
3701 if (Record.size() < 2)
3702 return error("Invalid record");
3707 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3709 unsigned NumArgOperands = Record[Idx++];
3711 SmallVector<Value *, 2> Args;
3712 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3714 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3715 return error("Invalid record");
3716 Args.push_back(Val);
3719 if (Record.size() != Idx)
3720 return error("Invalid record");
3722 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3723 I = CleanupPadInst::Create(ParentPad, Args);
3725 I = CatchPadInst::Create(ParentPad, Args);
3726 InstructionList.push_back(I);
3729 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3731 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3732 // "New" SwitchInst format with case ranges. The changes to write this
3733 // format were reverted but we still recognize bitcode that uses it.
3734 // Hopefully someday we will have support for case ranges and can use
3735 // this format again.
3737 Type *OpTy = getTypeByID(Record[1]);
3738 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3740 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3741 BasicBlock *Default = getBasicBlock(Record[3]);
3742 if (!OpTy || !Cond || !Default)
3743 return error("Invalid record");
3745 unsigned NumCases = Record[4];
3747 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3748 InstructionList.push_back(SI);
3750 unsigned CurIdx = 5;
3751 for (unsigned i = 0; i != NumCases; ++i) {
3752 SmallVector<ConstantInt*, 1> CaseVals;
3753 unsigned NumItems = Record[CurIdx++];
3754 for (unsigned ci = 0; ci != NumItems; ++ci) {
3755 bool isSingleNumber = Record[CurIdx++];
3758 unsigned ActiveWords = 1;
3759 if (ValueBitWidth > 64)
3760 ActiveWords = Record[CurIdx++];
3761 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3763 CurIdx += ActiveWords;
3765 if (!isSingleNumber) {
3767 if (ValueBitWidth > 64)
3768 ActiveWords = Record[CurIdx++];
3769 APInt High = readWideAPInt(
3770 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3771 CurIdx += ActiveWords;
3773 // FIXME: It is not clear whether values in the range should be
3774 // compared as signed or unsigned values. The partially
3775 // implemented changes that used this format in the past used
3776 // unsigned comparisons.
3777 for ( ; Low.ule(High); ++Low)
3778 CaseVals.push_back(ConstantInt::get(Context, Low));
3780 CaseVals.push_back(ConstantInt::get(Context, Low));
3782 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3783 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3784 cve = CaseVals.end(); cvi != cve; ++cvi)
3785 SI->addCase(*cvi, DestBB);
3791 // Old SwitchInst format without case ranges.
3793 if (Record.size() < 3 || (Record.size() & 1) == 0)
3794 return error("Invalid record");
3795 Type *OpTy = getTypeByID(Record[0]);
3796 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3797 BasicBlock *Default = getBasicBlock(Record[2]);
3798 if (!OpTy || !Cond || !Default)
3799 return error("Invalid record");
3800 unsigned NumCases = (Record.size()-3)/2;
3801 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3802 InstructionList.push_back(SI);
3803 for (unsigned i = 0, e = NumCases; i != e; ++i) {
3804 ConstantInt *CaseVal =
3805 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3806 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3807 if (!CaseVal || !DestBB) {
3809 return error("Invalid record");
3811 SI->addCase(CaseVal, DestBB);
3816 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3817 if (Record.size() < 2)
3818 return error("Invalid record");
3819 Type *OpTy = getTypeByID(Record[0]);
3820 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3821 if (!OpTy || !Address)
3822 return error("Invalid record");
3823 unsigned NumDests = Record.size()-2;
3824 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3825 InstructionList.push_back(IBI);
3826 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3827 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3828 IBI->addDestination(DestBB);
3831 return error("Invalid record");
3838 case bitc::FUNC_CODE_INST_INVOKE: {
3839 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3840 if (Record.size() < 4)
3841 return error("Invalid record");
3843 AttributeSet PAL = getAttributes(Record[OpNum++]);
3844 unsigned CCInfo = Record[OpNum++];
3845 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3846 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3848 FunctionType *FTy = nullptr;
3849 if (CCInfo >> 13 & 1 &&
3850 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3851 return error("Explicit invoke type is not a function type");
3854 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3855 return error("Invalid record");
3857 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3859 return error("Callee is not a pointer");
3861 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3863 return error("Callee is not of pointer to function type");
3864 } else if (CalleeTy->getElementType() != FTy)
3865 return error("Explicit invoke type does not match pointee type of "
3867 if (Record.size() < FTy->getNumParams() + OpNum)
3868 return error("Insufficient operands to call");
3870 SmallVector<Value*, 16> Ops;
3871 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3872 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3873 FTy->getParamType(i)));
3875 return error("Invalid record");
3878 if (!FTy->isVarArg()) {
3879 if (Record.size() != OpNum)
3880 return error("Invalid record");
3882 // Read type/value pairs for varargs params.
3883 while (OpNum != Record.size()) {
3885 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3886 return error("Invalid record");
3891 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
3892 OperandBundles.clear();
3893 InstructionList.push_back(I);
3894 cast<InvokeInst>(I)->setCallingConv(
3895 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
3896 cast<InvokeInst>(I)->setAttributes(PAL);
3899 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3901 Value *Val = nullptr;
3902 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3903 return error("Invalid record");
3904 I = ResumeInst::Create(Val);
3905 InstructionList.push_back(I);
3908 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3909 I = new UnreachableInst(Context);
3910 InstructionList.push_back(I);
3912 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3913 if (Record.size() < 1 || ((Record.size()-1)&1))
3914 return error("Invalid record");
3915 Type *Ty = getTypeByID(Record[0]);
3917 return error("Invalid record");
3919 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3920 InstructionList.push_back(PN);
3922 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3924 // With the new function encoding, it is possible that operands have
3925 // negative IDs (for forward references). Use a signed VBR
3926 // representation to keep the encoding small.
3928 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3930 V = getValue(Record, 1+i, NextValueNo, Ty);
3931 BasicBlock *BB = getBasicBlock(Record[2+i]);
3933 return error("Invalid record");
3934 PN->addIncoming(V, BB);
3940 case bitc::FUNC_CODE_INST_LANDINGPAD:
3941 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
3942 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3944 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
3945 if (Record.size() < 3)
3946 return error("Invalid record");
3948 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
3949 if (Record.size() < 4)
3950 return error("Invalid record");
3952 Type *Ty = getTypeByID(Record[Idx++]);
3954 return error("Invalid record");
3955 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
3956 Value *PersFn = nullptr;
3957 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3958 return error("Invalid record");
3960 if (!F->hasPersonalityFn())
3961 F->setPersonalityFn(cast<Constant>(PersFn));
3962 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
3963 return error("Personality function mismatch");
3966 bool IsCleanup = !!Record[Idx++];
3967 unsigned NumClauses = Record[Idx++];
3968 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
3969 LP->setCleanup(IsCleanup);
3970 for (unsigned J = 0; J != NumClauses; ++J) {
3971 LandingPadInst::ClauseType CT =
3972 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3975 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3977 return error("Invalid record");
3980 assert((CT != LandingPadInst::Catch ||
3981 !isa<ArrayType>(Val->getType())) &&
3982 "Catch clause has a invalid type!");
3983 assert((CT != LandingPadInst::Filter ||
3984 isa<ArrayType>(Val->getType())) &&
3985 "Filter clause has invalid type!");
3986 LP->addClause(cast<Constant>(Val));
3990 InstructionList.push_back(I);
3994 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3995 if (Record.size() != 4)
3996 return error("Invalid record");
3997 uint64_t AlignRecord = Record[3];
3998 const uint64_t InAllocaMask = uint64_t(1) << 5;
3999 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4000 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4001 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4003 bool InAlloca = AlignRecord & InAllocaMask;
4004 bool SwiftError = AlignRecord & SwiftErrorMask;
4005 Type *Ty = getTypeByID(Record[0]);
4006 if ((AlignRecord & ExplicitTypeMask) == 0) {
4007 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4009 return error("Old-style alloca with a non-pointer type");
4010 Ty = PTy->getElementType();
4012 Type *OpTy = getTypeByID(Record[1]);
4013 Value *Size = getFnValueByID(Record[2], OpTy);
4015 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4019 return error("Invalid record");
4020 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4021 AI->setUsedWithInAlloca(InAlloca);
4022 AI->setSwiftError(SwiftError);
4024 InstructionList.push_back(I);
4027 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4030 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4031 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4032 return error("Invalid record");
4035 if (OpNum + 3 == Record.size())
4036 Ty = getTypeByID(Record[OpNum++]);
4037 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4040 Ty = cast<PointerType>(Op->getType())->getElementType();
4043 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4045 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4047 InstructionList.push_back(I);
4050 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4051 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4054 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4055 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4056 return error("Invalid record");
4059 if (OpNum + 5 == Record.size())
4060 Ty = getTypeByID(Record[OpNum++]);
4061 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4064 Ty = cast<PointerType>(Op->getType())->getElementType();
4066 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4067 if (Ordering == AtomicOrdering::NotAtomic ||
4068 Ordering == AtomicOrdering::Release ||
4069 Ordering == AtomicOrdering::AcquireRelease)
4070 return error("Invalid record");
4071 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4072 return error("Invalid record");
4073 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4076 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4078 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4080 InstructionList.push_back(I);
4083 case bitc::FUNC_CODE_INST_STORE:
4084 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4087 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4088 (BitCode == bitc::FUNC_CODE_INST_STORE
4089 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4090 : popValue(Record, OpNum, NextValueNo,
4091 cast<PointerType>(Ptr->getType())->getElementType(),
4093 OpNum + 2 != Record.size())
4094 return error("Invalid record");
4096 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4099 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4101 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4102 InstructionList.push_back(I);
4105 case bitc::FUNC_CODE_INST_STOREATOMIC:
4106 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4107 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4110 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4111 !isa<PointerType>(Ptr->getType()) ||
4112 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4113 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4114 : popValue(Record, OpNum, NextValueNo,
4115 cast<PointerType>(Ptr->getType())->getElementType(),
4117 OpNum + 4 != Record.size())
4118 return error("Invalid record");
4120 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4122 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4123 if (Ordering == AtomicOrdering::NotAtomic ||
4124 Ordering == AtomicOrdering::Acquire ||
4125 Ordering == AtomicOrdering::AcquireRelease)
4126 return error("Invalid record");
4127 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4128 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4129 return error("Invalid record");
4132 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4134 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4135 InstructionList.push_back(I);
4138 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4139 case bitc::FUNC_CODE_INST_CMPXCHG: {
4140 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4141 // failureordering?, isweak?]
4143 Value *Ptr, *Cmp, *New;
4144 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4145 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4146 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4147 : popValue(Record, OpNum, NextValueNo,
4148 cast<PointerType>(Ptr->getType())->getElementType(),
4150 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4151 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4152 return error("Invalid record");
4153 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4154 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4155 SuccessOrdering == AtomicOrdering::Unordered)
4156 return error("Invalid record");
4157 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4159 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4161 AtomicOrdering FailureOrdering;
4162 if (Record.size() < 7)
4164 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4166 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4168 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4170 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4172 if (Record.size() < 8) {
4173 // Before weak cmpxchgs existed, the instruction simply returned the
4174 // value loaded from memory, so bitcode files from that era will be
4175 // expecting the first component of a modern cmpxchg.
4176 CurBB->getInstList().push_back(I);
4177 I = ExtractValueInst::Create(I, 0);
4179 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4182 InstructionList.push_back(I);
4185 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4186 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4189 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4190 !isa<PointerType>(Ptr->getType()) ||
4191 popValue(Record, OpNum, NextValueNo,
4192 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4193 OpNum+4 != Record.size())
4194 return error("Invalid record");
4195 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4196 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4197 Operation > AtomicRMWInst::LAST_BINOP)
4198 return error("Invalid record");
4199 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4200 if (Ordering == AtomicOrdering::NotAtomic ||
4201 Ordering == AtomicOrdering::Unordered)
4202 return error("Invalid record");
4203 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4204 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4205 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4206 InstructionList.push_back(I);
4209 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4210 if (2 != Record.size())
4211 return error("Invalid record");
4212 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4213 if (Ordering == AtomicOrdering::NotAtomic ||
4214 Ordering == AtomicOrdering::Unordered ||
4215 Ordering == AtomicOrdering::Monotonic)
4216 return error("Invalid record");
4217 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4218 I = new FenceInst(Context, Ordering, SynchScope);
4219 InstructionList.push_back(I);
4222 case bitc::FUNC_CODE_INST_CALL: {
4223 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4224 if (Record.size() < 3)
4225 return error("Invalid record");
4228 AttributeSet PAL = getAttributes(Record[OpNum++]);
4229 unsigned CCInfo = Record[OpNum++];
4232 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4233 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4235 return error("Fast math flags indicator set for call with no FMF");
4238 FunctionType *FTy = nullptr;
4239 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4240 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4241 return error("Explicit call type is not a function type");
4244 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4245 return error("Invalid record");
4247 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4249 return error("Callee is not a pointer type");
4251 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4253 return error("Callee is not of pointer to function type");
4254 } else if (OpTy->getElementType() != FTy)
4255 return error("Explicit call type does not match pointee type of "
4257 if (Record.size() < FTy->getNumParams() + OpNum)
4258 return error("Insufficient operands to call");
4260 SmallVector<Value*, 16> Args;
4261 // Read the fixed params.
4262 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4263 if (FTy->getParamType(i)->isLabelTy())
4264 Args.push_back(getBasicBlock(Record[OpNum]));
4266 Args.push_back(getValue(Record, OpNum, NextValueNo,
4267 FTy->getParamType(i)));
4269 return error("Invalid record");
4272 // Read type/value pairs for varargs params.
4273 if (!FTy->isVarArg()) {
4274 if (OpNum != Record.size())
4275 return error("Invalid record");
4277 while (OpNum != Record.size()) {
4279 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4280 return error("Invalid record");
4285 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4286 OperandBundles.clear();
4287 InstructionList.push_back(I);
4288 cast<CallInst>(I)->setCallingConv(
4289 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4290 CallInst::TailCallKind TCK = CallInst::TCK_None;
4291 if (CCInfo & 1 << bitc::CALL_TAIL)
4292 TCK = CallInst::TCK_Tail;
4293 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
4294 TCK = CallInst::TCK_MustTail;
4295 if (CCInfo & (1 << bitc::CALL_NOTAIL))
4296 TCK = CallInst::TCK_NoTail;
4297 cast<CallInst>(I)->setTailCallKind(TCK);
4298 cast<CallInst>(I)->setAttributes(PAL);
4300 if (!isa<FPMathOperator>(I))
4301 return error("Fast-math-flags specified for call without "
4302 "floating-point scalar or vector return type");
4303 I->setFastMathFlags(FMF);
4307 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4308 if (Record.size() < 3)
4309 return error("Invalid record");
4310 Type *OpTy = getTypeByID(Record[0]);
4311 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4312 Type *ResTy = getTypeByID(Record[2]);
4313 if (!OpTy || !Op || !ResTy)
4314 return error("Invalid record");
4315 I = new VAArgInst(Op, ResTy);
4316 InstructionList.push_back(I);
4320 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4321 // A call or an invoke can be optionally prefixed with some variable
4322 // number of operand bundle blocks. These blocks are read into
4323 // OperandBundles and consumed at the next call or invoke instruction.
4325 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4326 return error("Invalid record");
4328 std::vector<Value *> Inputs;
4331 while (OpNum != Record.size()) {
4333 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4334 return error("Invalid record");
4335 Inputs.push_back(Op);
4338 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4343 // Add instruction to end of current BB. If there is no current BB, reject
4347 return error("Invalid instruction with no BB");
4349 if (!OperandBundles.empty()) {
4351 return error("Operand bundles found with no consumer");
4353 CurBB->getInstList().push_back(I);
4355 // If this was a terminator instruction, move to the next block.
4356 if (isa<TerminatorInst>(I)) {
4358 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4361 // Non-void values get registered in the value table for future use.
4362 if (I && !I->getType()->isVoidTy())
4363 ValueList.assignValue(I, NextValueNo++);
4368 if (!OperandBundles.empty())
4369 return error("Operand bundles found with no consumer");
4371 // Check the function list for unresolved values.
4372 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4373 if (!A->getParent()) {
4374 // We found at least one unresolved value. Nuke them all to avoid leaks.
4375 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4376 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4377 A->replaceAllUsesWith(UndefValue::get(A->getType()));
4381 return error("Never resolved value found in function");
4385 // Unexpected unresolved metadata about to be dropped.
4386 if (MDLoader->hasFwdRefs())
4387 return error("Invalid function metadata: outgoing forward refs");
4389 // Trim the value list down to the size it was before we parsed this function.
4390 ValueList.shrinkTo(ModuleValueListSize);
4391 MDLoader->shrinkTo(ModuleMDLoaderSize);
4392 std::vector<BasicBlock*>().swap(FunctionBBs);
4393 return Error::success();
4396 /// Find the function body in the bitcode stream
4397 Error BitcodeReader::findFunctionInStream(
4399 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4400 while (DeferredFunctionInfoIterator->second == 0) {
4401 // This is the fallback handling for the old format bitcode that
4402 // didn't contain the function index in the VST, or when we have
4403 // an anonymous function which would not have a VST entry.
4404 // Assert that we have one of those two cases.
4405 assert(VSTOffset == 0 || !F->hasName());
4406 // Parse the next body in the stream and set its position in the
4407 // DeferredFunctionInfo map.
4408 if (Error Err = rememberAndSkipFunctionBodies())
4411 return Error::success();
4414 //===----------------------------------------------------------------------===//
4415 // GVMaterializer implementation
4416 //===----------------------------------------------------------------------===//
4418 Error BitcodeReader::materialize(GlobalValue *GV) {
4419 Function *F = dyn_cast<Function>(GV);
4420 // If it's not a function or is already material, ignore the request.
4421 if (!F || !F->isMaterializable())
4422 return Error::success();
4424 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4425 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4426 // If its position is recorded as 0, its body is somewhere in the stream
4427 // but we haven't seen it yet.
4428 if (DFII->second == 0)
4429 if (Error Err = findFunctionInStream(F, DFII))
4432 // Materialize metadata before parsing any function bodies.
4433 if (Error Err = materializeMetadata())
4436 // Move the bit stream to the saved position of the deferred function body.
4437 Stream.JumpToBit(DFII->second);
4439 if (Error Err = parseFunctionBody(F))
4441 F->setIsMaterializable(false);
4446 // Upgrade any old intrinsic calls in the function.
4447 for (auto &I : UpgradedIntrinsics) {
4448 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4452 if (CallInst *CI = dyn_cast<CallInst>(U))
4453 UpgradeIntrinsicCall(CI, I.second);
4457 // Update calls to the remangled intrinsics
4458 for (auto &I : RemangledIntrinsics)
4459 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4461 // Don't expect any other users than call sites
4462 CallSite(*UI++).setCalledFunction(I.second);
4464 // Finish fn->subprogram upgrade for materialized functions.
4465 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4466 F->setSubprogram(SP);
4468 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4469 if (!MDLoader->isStrippingTBAA()) {
4470 for (auto &I : instructions(F)) {
4471 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4472 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4474 MDLoader->setStripTBAA(true);
4475 stripTBAA(F->getParent());
4479 // Bring in any functions that this function forward-referenced via
4481 return materializeForwardReferencedFunctions();
4484 Error BitcodeReader::materializeModule() {
4485 if (Error Err = materializeMetadata())
4488 // Promise to materialize all forward references.
4489 WillMaterializeAllForwardRefs = true;
4491 // Iterate over the module, deserializing any functions that are still on
4493 for (Function &F : *TheModule) {
4494 if (Error Err = materialize(&F))
4497 // At this point, if there are any function bodies, parse the rest of
4498 // the bits in the module past the last function block we have recorded
4499 // through either lazy scanning or the VST.
4500 if (LastFunctionBlockBit || NextUnreadBit)
4501 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4502 ? LastFunctionBlockBit
4506 // Check that all block address forward references got resolved (as we
4508 if (!BasicBlockFwdRefs.empty())
4509 return error("Never resolved function from blockaddress");
4511 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4512 // delete the old functions to clean up. We can't do this unless the entire
4513 // module is materialized because there could always be another function body
4514 // with calls to the old function.
4515 for (auto &I : UpgradedIntrinsics) {
4516 for (auto *U : I.first->users()) {
4517 if (CallInst *CI = dyn_cast<CallInst>(U))
4518 UpgradeIntrinsicCall(CI, I.second);
4520 if (!I.first->use_empty())
4521 I.first->replaceAllUsesWith(I.second);
4522 I.first->eraseFromParent();
4524 UpgradedIntrinsics.clear();
4525 // Do the same for remangled intrinsics
4526 for (auto &I : RemangledIntrinsics) {
4527 I.first->replaceAllUsesWith(I.second);
4528 I.first->eraseFromParent();
4530 RemangledIntrinsics.clear();
4532 UpgradeDebugInfo(*TheModule);
4534 UpgradeModuleFlags(*TheModule);
4535 return Error::success();
4538 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4539 return IdentifiedStructTypes;
4542 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4543 BitstreamCursor Cursor, ModuleSummaryIndex &TheIndex)
4544 : BitcodeReaderBase(std::move(Cursor)), TheIndex(TheIndex) {}
4546 std::pair<GlobalValue::GUID, GlobalValue::GUID>
4547 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
4548 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
4549 assert(VGI != ValueIdToCallGraphGUIDMap.end());
4553 // Specialized value symbol table parser used when reading module index
4554 // blocks where we don't actually create global values. The parsed information
4555 // is saved in the bitcode reader for use when later parsing summaries.
4556 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
4558 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
4559 assert(Offset > 0 && "Expected non-zero VST offset");
4560 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4562 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4563 return error("Invalid record");
4565 SmallVector<uint64_t, 64> Record;
4567 // Read all the records for this value table.
4568 SmallString<128> ValueName;
4571 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4573 switch (Entry.Kind) {
4574 case BitstreamEntry::SubBlock: // Handled for us already.
4575 case BitstreamEntry::Error:
4576 return error("Malformed block");
4577 case BitstreamEntry::EndBlock:
4578 // Done parsing VST, jump back to wherever we came from.
4579 Stream.JumpToBit(CurrentBit);
4580 return Error::success();
4581 case BitstreamEntry::Record:
4582 // The interesting case.
4588 switch (Stream.readRecord(Entry.ID, Record)) {
4589 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4591 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4592 if (convertToString(Record, 1, ValueName))
4593 return error("Invalid record");
4594 unsigned ValueID = Record[0];
4595 assert(!SourceFileName.empty());
4596 auto VLI = ValueIdToLinkageMap.find(ValueID);
4597 assert(VLI != ValueIdToLinkageMap.end() &&
4598 "No linkage found for VST entry?");
4599 auto Linkage = VLI->second;
4600 std::string GlobalId =
4601 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4602 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4603 auto OriginalNameID = ValueGUID;
4604 if (GlobalValue::isLocalLinkage(Linkage))
4605 OriginalNameID = GlobalValue::getGUID(ValueName);
4606 if (PrintSummaryGUIDs)
4607 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4608 << ValueName << "\n";
4609 ValueIdToCallGraphGUIDMap[ValueID] =
4610 std::make_pair(ValueGUID, OriginalNameID);
4614 case bitc::VST_CODE_FNENTRY: {
4615 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
4616 if (convertToString(Record, 2, ValueName))
4617 return error("Invalid record");
4618 unsigned ValueID = Record[0];
4619 assert(!SourceFileName.empty());
4620 auto VLI = ValueIdToLinkageMap.find(ValueID);
4621 assert(VLI != ValueIdToLinkageMap.end() &&
4622 "No linkage found for VST entry?");
4623 auto Linkage = VLI->second;
4624 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
4625 ValueName, VLI->second, SourceFileName);
4626 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
4627 auto OriginalNameID = FunctionGUID;
4628 if (GlobalValue::isLocalLinkage(Linkage))
4629 OriginalNameID = GlobalValue::getGUID(ValueName);
4630 if (PrintSummaryGUIDs)
4631 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
4632 << ValueName << "\n";
4633 ValueIdToCallGraphGUIDMap[ValueID] =
4634 std::make_pair(FunctionGUID, OriginalNameID);
4639 case bitc::VST_CODE_COMBINED_ENTRY: {
4640 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4641 unsigned ValueID = Record[0];
4642 GlobalValue::GUID RefGUID = Record[1];
4643 // The "original name", which is the second value of the pair will be
4644 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
4645 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
4652 // Parse just the blocks needed for building the index out of the module.
4653 // At the end of this routine the module Index is populated with a map
4654 // from global value id to GlobalValueSummary objects.
4655 Error ModuleSummaryIndexBitcodeReader::parseModule(StringRef ModulePath) {
4656 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4657 return error("Invalid record");
4659 SmallVector<uint64_t, 64> Record;
4660 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
4661 unsigned ValueId = 0;
4663 // Read the index for this module.
4665 BitstreamEntry Entry = Stream.advance();
4667 switch (Entry.Kind) {
4668 case BitstreamEntry::Error:
4669 return error("Malformed block");
4670 case BitstreamEntry::EndBlock:
4671 return Error::success();
4673 case BitstreamEntry::SubBlock:
4675 default: // Skip unknown content.
4676 if (Stream.SkipBlock())
4677 return error("Invalid record");
4679 case bitc::BLOCKINFO_BLOCK_ID:
4680 // Need to parse these to get abbrev ids (e.g. for VST)
4681 if (readBlockInfo())
4682 return error("Malformed block");
4684 case bitc::VALUE_SYMTAB_BLOCK_ID:
4685 // Should have been parsed earlier via VSTOffset, unless there
4686 // is no summary section.
4687 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4688 !SeenGlobalValSummary) &&
4689 "Expected early VST parse via VSTOffset record");
4690 if (Stream.SkipBlock())
4691 return error("Invalid record");
4693 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
4694 assert(!SeenValueSymbolTable &&
4695 "Already read VST when parsing summary block?");
4696 // We might not have a VST if there were no values in the
4697 // summary. An empty summary block generated when we are
4698 // performing ThinLTO compiles so we don't later invoke
4699 // the regular LTO process on them.
4700 if (VSTOffset > 0) {
4701 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4703 SeenValueSymbolTable = true;
4705 SeenGlobalValSummary = true;
4706 if (Error Err = parseEntireSummary(ModulePath))
4709 case bitc::MODULE_STRTAB_BLOCK_ID:
4710 if (Error Err = parseModuleStringTable())
4716 case BitstreamEntry::Record: {
4718 auto BitCode = Stream.readRecord(Entry.ID, Record);
4721 break; // Default behavior, ignore unknown content.
4722 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4723 case bitc::MODULE_CODE_SOURCE_FILENAME: {
4724 SmallString<128> ValueName;
4725 if (convertToString(Record, 0, ValueName))
4726 return error("Invalid record");
4727 SourceFileName = ValueName.c_str();
4730 /// MODULE_CODE_HASH: [5*i32]
4731 case bitc::MODULE_CODE_HASH: {
4732 if (Record.size() != 5)
4733 return error("Invalid hash length " + Twine(Record.size()).str());
4734 if (TheIndex.modulePaths().empty())
4735 // We always seed the index with the module.
4736 TheIndex.addModulePath(ModulePath, 0);
4737 if (TheIndex.modulePaths().size() != 1)
4738 return error("Don't expect multiple modules defined?");
4739 auto &Hash = TheIndex.modulePaths().begin()->second.second;
4741 for (auto &Val : Record) {
4742 assert(!(Val >> 32) && "Unexpected high bits set");
4747 /// MODULE_CODE_VSTOFFSET: [offset]
4748 case bitc::MODULE_CODE_VSTOFFSET:
4749 if (Record.size() < 1)
4750 return error("Invalid record");
4751 // Note that we subtract 1 here because the offset is relative to one
4752 // word before the start of the identification or module block, which
4753 // was historically always the start of the regular bitcode header.
4754 VSTOffset = Record[0] - 1;
4756 // GLOBALVAR: [pointer type, isconst, initid,
4757 // linkage, alignment, section, visibility, threadlocal,
4758 // unnamed_addr, externally_initialized, dllstorageclass,
4760 case bitc::MODULE_CODE_GLOBALVAR: {
4761 if (Record.size() < 6)
4762 return error("Invalid record");
4763 uint64_t RawLinkage = Record[3];
4764 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
4765 ValueIdToLinkageMap[ValueId++] = Linkage;
4768 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
4769 // alignment, section, visibility, gc, unnamed_addr,
4770 // prologuedata, dllstorageclass, comdat, prefixdata]
4771 case bitc::MODULE_CODE_FUNCTION: {
4772 if (Record.size() < 8)
4773 return error("Invalid record");
4774 uint64_t RawLinkage = Record[3];
4775 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
4776 ValueIdToLinkageMap[ValueId++] = Linkage;
4779 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4781 case bitc::MODULE_CODE_ALIAS: {
4782 if (Record.size() < 6)
4783 return error("Invalid record");
4784 uint64_t RawLinkage = Record[3];
4785 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
4786 ValueIdToLinkageMap[ValueId++] = Linkage;
4796 std::vector<ValueInfo>
4797 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
4798 std::vector<ValueInfo> Ret;
4799 Ret.reserve(Record.size());
4800 for (uint64_t RefValueId : Record)
4801 Ret.push_back(getGUIDFromValueId(RefValueId).first);
4805 std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
4806 ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
4807 std::vector<FunctionSummary::EdgeTy> Ret;
4808 Ret.reserve(Record.size());
4809 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
4810 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
4811 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(Record[I]).first;
4812 if (IsOldProfileFormat) {
4813 I += 1; // Skip old callsitecount field
4815 I += 1; // Skip old profilecount field
4816 } else if (HasProfile)
4817 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
4818 Ret.push_back(FunctionSummary::EdgeTy{CalleeGUID, CalleeInfo{Hotness}});
4823 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
4824 // objects in the index.
4825 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
4826 StringRef ModulePath) {
4827 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
4828 return error("Invalid record");
4829 SmallVector<uint64_t, 64> Record;
4833 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4834 if (Entry.Kind != BitstreamEntry::Record)
4835 return error("Invalid Summary Block: record for version expected");
4836 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
4837 return error("Invalid Summary Block: version expected");
4839 const uint64_t Version = Record[0];
4840 const bool IsOldProfileFormat = Version == 1;
4841 if (Version < 1 || Version > 3)
4842 return error("Invalid summary version " + Twine(Version) +
4843 ", 1, 2 or 3 expected");
4846 // Keep around the last seen summary to be used when we see an optional
4847 // "OriginalName" attachement.
4848 GlobalValueSummary *LastSeenSummary = nullptr;
4849 bool Combined = false;
4850 std::vector<GlobalValue::GUID> PendingTypeTests;
4853 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4855 switch (Entry.Kind) {
4856 case BitstreamEntry::SubBlock: // Handled for us already.
4857 case BitstreamEntry::Error:
4858 return error("Malformed block");
4859 case BitstreamEntry::EndBlock:
4860 // For a per-module index, remove any entries that still have empty
4861 // summaries. The VST parsing creates entries eagerly for all symbols,
4862 // but not all have associated summaries (e.g. it doesn't know how to
4863 // distinguish between VST_CODE_ENTRY for function declarations vs global
4864 // variables with initializers that end up with a summary). Remove those
4865 // entries now so that we don't need to rely on the combined index merger
4866 // to clean them up (especially since that may not run for the first
4867 // module's index if we merge into that).
4869 TheIndex.removeEmptySummaryEntries();
4870 return Error::success();
4871 case BitstreamEntry::Record:
4872 // The interesting case.
4876 // Read a record. The record format depends on whether this
4877 // is a per-module index or a combined index file. In the per-module
4878 // case the records contain the associated value's ID for correlation
4879 // with VST entries. In the combined index the correlation is done
4880 // via the bitcode offset of the summary records (which were saved
4881 // in the combined index VST entries). The records also contain
4882 // information used for ThinLTO renaming and importing.
4884 auto BitCode = Stream.readRecord(Entry.ID, Record);
4886 default: // Default behavior: ignore.
4888 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
4890 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
4891 // numrefs x valueid,
4892 // n x (valueid, hotness)]
4893 case bitc::FS_PERMODULE:
4894 case bitc::FS_PERMODULE_PROFILE: {
4895 unsigned ValueID = Record[0];
4896 uint64_t RawFlags = Record[1];
4897 unsigned InstCount = Record[2];
4898 unsigned NumRefs = Record[3];
4899 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4900 // The module path string ref set in the summary must be owned by the
4901 // index's module string table. Since we don't have a module path
4902 // string table section in the per-module index, we create a single
4903 // module path string table entry with an empty (0) ID to take
4905 static int RefListStartIndex = 4;
4906 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
4907 assert(Record.size() >= RefListStartIndex + NumRefs &&
4908 "Record size inconsistent with number of references");
4909 std::vector<ValueInfo> Refs = makeRefList(
4910 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
4911 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
4912 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
4913 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
4914 IsOldProfileFormat, HasProfile);
4915 auto FS = llvm::make_unique<FunctionSummary>(
4916 Flags, InstCount, std::move(Refs), std::move(Calls),
4917 std::move(PendingTypeTests));
4918 PendingTypeTests.clear();
4919 auto GUID = getGUIDFromValueId(ValueID);
4920 FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
4921 FS->setOriginalName(GUID.second);
4922 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
4925 // FS_ALIAS: [valueid, flags, valueid]
4926 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
4927 // they expect all aliasee summaries to be available.
4928 case bitc::FS_ALIAS: {
4929 unsigned ValueID = Record[0];
4930 uint64_t RawFlags = Record[1];
4931 unsigned AliaseeID = Record[2];
4932 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4934 llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
4935 // The module path string ref set in the summary must be owned by the
4936 // index's module string table. Since we don't have a module path
4937 // string table section in the per-module index, we create a single
4938 // module path string table entry with an empty (0) ID to take
4940 AS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
4942 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
4943 auto *AliaseeSummary = TheIndex.getGlobalValueSummary(AliaseeGUID);
4944 if (!AliaseeSummary)
4945 return error("Alias expects aliasee summary to be parsed");
4946 AS->setAliasee(AliaseeSummary);
4948 auto GUID = getGUIDFromValueId(ValueID);
4949 AS->setOriginalName(GUID.second);
4950 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
4953 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
4954 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
4955 unsigned ValueID = Record[0];
4956 uint64_t RawFlags = Record[1];
4957 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4958 std::vector<ValueInfo> Refs =
4959 makeRefList(ArrayRef<uint64_t>(Record).slice(2));
4960 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
4961 FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
4962 auto GUID = getGUIDFromValueId(ValueID);
4963 FS->setOriginalName(GUID.second);
4964 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
4967 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
4968 // numrefs x valueid, n x (valueid)]
4969 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
4970 // numrefs x valueid, n x (valueid, hotness)]
4971 case bitc::FS_COMBINED:
4972 case bitc::FS_COMBINED_PROFILE: {
4973 unsigned ValueID = Record[0];
4974 uint64_t ModuleId = Record[1];
4975 uint64_t RawFlags = Record[2];
4976 unsigned InstCount = Record[3];
4977 unsigned NumRefs = Record[4];
4978 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4979 static int RefListStartIndex = 5;
4980 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
4981 assert(Record.size() >= RefListStartIndex + NumRefs &&
4982 "Record size inconsistent with number of references");
4983 std::vector<ValueInfo> Refs = makeRefList(
4984 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
4985 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
4986 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
4987 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
4988 IsOldProfileFormat, HasProfile);
4989 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
4990 auto FS = llvm::make_unique<FunctionSummary>(
4991 Flags, InstCount, std::move(Refs), std::move(Edges),
4992 std::move(PendingTypeTests));
4993 PendingTypeTests.clear();
4994 LastSeenSummary = FS.get();
4995 FS->setModulePath(ModuleIdMap[ModuleId]);
4996 TheIndex.addGlobalValueSummary(GUID, std::move(FS));
5000 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
5001 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5002 // they expect all aliasee summaries to be available.
5003 case bitc::FS_COMBINED_ALIAS: {
5004 unsigned ValueID = Record[0];
5005 uint64_t ModuleId = Record[1];
5006 uint64_t RawFlags = Record[2];
5007 unsigned AliaseeValueId = Record[3];
5008 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5009 auto AS = llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
5010 LastSeenSummary = AS.get();
5011 AS->setModulePath(ModuleIdMap[ModuleId]);
5013 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
5014 auto AliaseeInModule =
5015 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
5016 if (!AliaseeInModule)
5017 return error("Alias expects aliasee summary to be parsed");
5018 AS->setAliasee(AliaseeInModule);
5020 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
5021 TheIndex.addGlobalValueSummary(GUID, std::move(AS));
5025 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
5026 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5027 unsigned ValueID = Record[0];
5028 uint64_t ModuleId = Record[1];
5029 uint64_t RawFlags = Record[2];
5030 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5031 std::vector<ValueInfo> Refs =
5032 makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5033 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5034 LastSeenSummary = FS.get();
5035 FS->setModulePath(ModuleIdMap[ModuleId]);
5036 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
5037 TheIndex.addGlobalValueSummary(GUID, std::move(FS));
5041 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5042 case bitc::FS_COMBINED_ORIGINAL_NAME: {
5043 uint64_t OriginalName = Record[0];
5044 if (!LastSeenSummary)
5045 return error("Name attachment that does not follow a combined record");
5046 LastSeenSummary->setOriginalName(OriginalName);
5047 // Reset the LastSeenSummary
5048 LastSeenSummary = nullptr;
5051 case bitc::FS_TYPE_TESTS: {
5052 assert(PendingTypeTests.empty());
5053 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5059 llvm_unreachable("Exit infinite loop");
5062 // Parse the module string table block into the Index.
5063 // This populates the ModulePathStringTable map in the index.
5064 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5065 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5066 return error("Invalid record");
5068 SmallVector<uint64_t, 64> Record;
5070 SmallString<128> ModulePath;
5071 ModulePathStringTableTy::iterator LastSeenModulePath;
5074 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5076 switch (Entry.Kind) {
5077 case BitstreamEntry::SubBlock: // Handled for us already.
5078 case BitstreamEntry::Error:
5079 return error("Malformed block");
5080 case BitstreamEntry::EndBlock:
5081 return Error::success();
5082 case BitstreamEntry::Record:
5083 // The interesting case.
5088 switch (Stream.readRecord(Entry.ID, Record)) {
5089 default: // Default behavior: ignore.
5091 case bitc::MST_CODE_ENTRY: {
5092 // MST_ENTRY: [modid, namechar x N]
5093 uint64_t ModuleId = Record[0];
5095 if (convertToString(Record, 1, ModulePath))
5096 return error("Invalid record");
5098 LastSeenModulePath = TheIndex.addModulePath(ModulePath, ModuleId);
5099 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
5104 /// MST_CODE_HASH: [5*i32]
5105 case bitc::MST_CODE_HASH: {
5106 if (Record.size() != 5)
5107 return error("Invalid hash length " + Twine(Record.size()).str());
5108 if (LastSeenModulePath == TheIndex.modulePaths().end())
5109 return error("Invalid hash that does not follow a module path");
5111 for (auto &Val : Record) {
5112 assert(!(Val >> 32) && "Unexpected high bits set");
5113 LastSeenModulePath->second.second[Pos++] = Val;
5115 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
5116 LastSeenModulePath = TheIndex.modulePaths().end();
5121 llvm_unreachable("Exit infinite loop");
5126 // FIXME: This class is only here to support the transition to llvm::Error. It
5127 // will be removed once this transition is complete. Clients should prefer to
5128 // deal with the Error value directly, rather than converting to error_code.
5129 class BitcodeErrorCategoryType : public std::error_category {
5130 const char *name() const noexcept override {
5131 return "llvm.bitcode";
5133 std::string message(int IE) const override {
5134 BitcodeError E = static_cast<BitcodeError>(IE);
5136 case BitcodeError::CorruptedBitcode:
5137 return "Corrupted bitcode";
5139 llvm_unreachable("Unknown error type!");
5143 } // end anonymous namespace
5145 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5147 const std::error_category &llvm::BitcodeErrorCategory() {
5148 return *ErrorCategory;
5151 //===----------------------------------------------------------------------===//
5152 // External interface
5153 //===----------------------------------------------------------------------===//
5155 Expected<std::vector<BitcodeModule>>
5156 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
5157 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5159 return StreamOrErr.takeError();
5160 BitstreamCursor &Stream = *StreamOrErr;
5162 std::vector<BitcodeModule> Modules;
5164 uint64_t BCBegin = Stream.getCurrentByteNo();
5166 // We may be consuming bitcode from a client that leaves garbage at the end
5167 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5168 // the end that there cannot possibly be another module, stop looking.
5169 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
5172 BitstreamEntry Entry = Stream.advance();
5173 switch (Entry.Kind) {
5174 case BitstreamEntry::EndBlock:
5175 case BitstreamEntry::Error:
5176 return error("Malformed block");
5178 case BitstreamEntry::SubBlock: {
5179 uint64_t IdentificationBit = -1ull;
5180 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5181 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5182 if (Stream.SkipBlock())
5183 return error("Malformed block");
5185 Entry = Stream.advance();
5186 if (Entry.Kind != BitstreamEntry::SubBlock ||
5187 Entry.ID != bitc::MODULE_BLOCK_ID)
5188 return error("Malformed block");
5191 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5192 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5193 if (Stream.SkipBlock())
5194 return error("Malformed block");
5196 Modules.push_back({Stream.getBitcodeBytes().slice(
5197 BCBegin, Stream.getCurrentByteNo() - BCBegin),
5198 Buffer.getBufferIdentifier(), IdentificationBit,
5203 if (Stream.SkipBlock())
5204 return error("Malformed block");
5207 case BitstreamEntry::Record:
5208 Stream.skipRecord(Entry.ID);
5214 /// \brief Get a lazy one-at-time loading module from bitcode.
5216 /// This isn't always used in a lazy context. In particular, it's also used by
5217 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
5218 /// in forward-referenced functions from block address references.
5220 /// \param[in] MaterializeAll Set to \c true if we should materialize
5222 Expected<std::unique_ptr<Module>>
5223 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
5224 bool ShouldLazyLoadMetadata, bool IsImporting) {
5225 BitstreamCursor Stream(Buffer);
5227 std::string ProducerIdentification;
5228 if (IdentificationBit != -1ull) {
5229 Stream.JumpToBit(IdentificationBit);
5230 Expected<std::string> ProducerIdentificationOrErr =
5231 readIdentificationBlock(Stream);
5232 if (!ProducerIdentificationOrErr)
5233 return ProducerIdentificationOrErr.takeError();
5235 ProducerIdentification = *ProducerIdentificationOrErr;
5238 Stream.JumpToBit(ModuleBit);
5240 new BitcodeReader(std::move(Stream), ProducerIdentification, Context);
5242 std::unique_ptr<Module> M =
5243 llvm::make_unique<Module>(ModuleIdentifier, Context);
5244 M->setMaterializer(R);
5246 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5248 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5249 return std::move(Err);
5251 if (MaterializeAll) {
5252 // Read in the entire module, and destroy the BitcodeReader.
5253 if (Error Err = M->materializeAll())
5254 return std::move(Err);
5256 // Resolve forward references from blockaddresses.
5257 if (Error Err = R->materializeForwardReferencedFunctions())
5258 return std::move(Err);
5260 return std::move(M);
5263 Expected<std::unique_ptr<Module>>
5264 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5266 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
5269 // Parse the specified bitcode buffer, returning the function info index.
5270 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5271 BitstreamCursor Stream(Buffer);
5272 Stream.JumpToBit(ModuleBit);
5274 auto Index = llvm::make_unique<ModuleSummaryIndex>();
5275 ModuleSummaryIndexBitcodeReader R(std::move(Stream), *Index);
5277 if (Error Err = R.parseModule(ModuleIdentifier))
5278 return std::move(Err);
5280 return std::move(Index);
5283 // Check if the given bitcode buffer contains a global value summary block.
5284 Expected<bool> BitcodeModule::hasSummary() {
5285 BitstreamCursor Stream(Buffer);
5286 Stream.JumpToBit(ModuleBit);
5288 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5289 return error("Invalid record");
5292 BitstreamEntry Entry = Stream.advance();
5294 switch (Entry.Kind) {
5295 case BitstreamEntry::Error:
5296 return error("Malformed block");
5297 case BitstreamEntry::EndBlock:
5300 case BitstreamEntry::SubBlock:
5301 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
5304 // Ignore other sub-blocks.
5305 if (Stream.SkipBlock())
5306 return error("Malformed block");
5309 case BitstreamEntry::Record:
5310 Stream.skipRecord(Entry.ID);
5316 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
5317 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5319 return MsOrErr.takeError();
5321 if (MsOrErr->size() != 1)
5322 return error("Expected a single module");
5324 return (*MsOrErr)[0];
5327 Expected<std::unique_ptr<Module>>
5328 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5329 bool ShouldLazyLoadMetadata, bool IsImporting) {
5330 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5332 return BM.takeError();
5334 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5337 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5338 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5339 bool ShouldLazyLoadMetadata, bool IsImporting) {
5340 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5343 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5347 Expected<std::unique_ptr<Module>>
5348 BitcodeModule::parseModule(LLVMContext &Context) {
5349 return getModuleImpl(Context, true, false, false);
5350 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5351 // written. We must defer until the Module has been fully materialized.
5354 Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5355 LLVMContext &Context) {
5356 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5358 return BM.takeError();
5360 return BM->parseModule(Context);
5363 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5364 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5366 return StreamOrErr.takeError();
5368 return readTriple(*StreamOrErr);
5371 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5372 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5374 return StreamOrErr.takeError();
5376 return hasObjCCategory(*StreamOrErr);
5379 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5380 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5382 return StreamOrErr.takeError();
5384 return readIdentificationCode(*StreamOrErr);
5387 Expected<std::unique_ptr<ModuleSummaryIndex>>
5388 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
5389 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5391 return BM.takeError();
5393 return BM->getSummary();
5396 Expected<bool> llvm::hasGlobalValueSummary(MemoryBufferRef Buffer) {
5397 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5399 return BM.takeError();
5401 return BM->hasSummary();