1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Bitcode/BitcodeReader.h"
10 #include "MetadataLoader.h"
11 #include "ValueList.h"
12 #include "llvm/ADT/APFloat.h"
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Bitstream/BitstreamReader.h"
24 #include "llvm/Bitcode/LLVMBitCodes.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/IR/Argument.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/AutoUpgrade.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Comdat.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DebugInfo.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GVMaterializer.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalIFunc.h"
44 #include "llvm/IR/GlobalIndirectSymbol.h"
45 #include "llvm/IR/GlobalObject.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/InlineAsm.h"
49 #include "llvm/IR/InstIterator.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/IR/ModuleSummaryIndex.h"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/IR/Type.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/IR/Verifier.h"
62 #include "llvm/Support/AtomicOrdering.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Compiler.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/Error.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/ErrorOr.h"
70 #include "llvm/Support/ManagedStatic.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/MemoryBuffer.h"
73 #include "llvm/Support/raw_ostream.h"
83 #include <system_error>
90 static cl::opt
<bool> PrintSummaryGUIDs(
91 "print-summary-global-ids", cl::init(false), cl::Hidden
,
93 "Print the global id for each value when reading the module summary"));
98 SWITCH_INST_MAGIC
= 0x4B5 // May 2012 => 1205 => Hex
101 } // end anonymous namespace
103 static Error
error(const Twine
&Message
) {
104 return make_error
<StringError
>(
105 Message
, make_error_code(BitcodeError::CorruptedBitcode
));
108 static Error
hasInvalidBitcodeHeader(BitstreamCursor
&Stream
) {
109 if (!Stream
.canSkipToPos(4))
110 return createStringError(std::errc::illegal_byte_sequence
,
111 "file too small to contain bitcode header");
112 for (unsigned C
: {'B', 'C'})
113 if (Expected
<SimpleBitstreamCursor::word_t
> Res
= Stream
.Read(8)) {
115 return createStringError(std::errc::illegal_byte_sequence
,
116 "file doesn't start with bitcode header");
118 return Res
.takeError();
119 for (unsigned C
: {0x0, 0xC, 0xE, 0xD})
120 if (Expected
<SimpleBitstreamCursor::word_t
> Res
= Stream
.Read(4)) {
122 return createStringError(std::errc::illegal_byte_sequence
,
123 "file doesn't start with bitcode header");
125 return Res
.takeError();
126 return Error::success();
129 static Expected
<BitstreamCursor
> initStream(MemoryBufferRef Buffer
) {
130 const unsigned char *BufPtr
= (const unsigned char *)Buffer
.getBufferStart();
131 const unsigned char *BufEnd
= BufPtr
+ Buffer
.getBufferSize();
133 if (Buffer
.getBufferSize() & 3)
134 return error("Invalid bitcode signature");
136 // If we have a wrapper header, parse it and ignore the non-bc file contents.
137 // The magic number is 0x0B17C0DE stored in little endian.
138 if (isBitcodeWrapper(BufPtr
, BufEnd
))
139 if (SkipBitcodeWrapperHeader(BufPtr
, BufEnd
, true))
140 return error("Invalid bitcode wrapper header");
142 BitstreamCursor
Stream(ArrayRef
<uint8_t>(BufPtr
, BufEnd
));
143 if (Error Err
= hasInvalidBitcodeHeader(Stream
))
144 return std::move(Err
);
146 return std::move(Stream
);
149 /// Convert a string from a record into an std::string, return true on failure.
150 template <typename StrTy
>
151 static bool convertToString(ArrayRef
<uint64_t> Record
, unsigned Idx
,
153 if (Idx
> Record
.size())
156 for (unsigned i
= Idx
, e
= Record
.size(); i
!= e
; ++i
)
157 Result
+= (char)Record
[i
];
161 // Strip all the TBAA attachment for the module.
162 static void stripTBAA(Module
*M
) {
164 if (F
.isMaterializable())
166 for (auto &I
: instructions(F
))
167 I
.setMetadata(LLVMContext::MD_tbaa
, nullptr);
171 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
172 /// "epoch" encoded in the bitcode, and return the producer name if any.
173 static Expected
<std::string
> readIdentificationBlock(BitstreamCursor
&Stream
) {
174 if (Error Err
= Stream
.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID
))
175 return std::move(Err
);
177 // Read all the records.
178 SmallVector
<uint64_t, 64> Record
;
180 std::string ProducerIdentification
;
183 BitstreamEntry Entry
;
184 if (Expected
<BitstreamEntry
> Res
= Stream
.advance())
187 return Res
.takeError();
189 switch (Entry
.Kind
) {
191 case BitstreamEntry::Error
:
192 return error("Malformed block");
193 case BitstreamEntry::EndBlock
:
194 return ProducerIdentification
;
195 case BitstreamEntry::Record
:
196 // The interesting case.
202 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
204 return MaybeBitCode
.takeError();
205 switch (MaybeBitCode
.get()) {
206 default: // Default behavior: reject
207 return error("Invalid value");
208 case bitc::IDENTIFICATION_CODE_STRING
: // IDENTIFICATION: [strchr x N]
209 convertToString(Record
, 0, ProducerIdentification
);
211 case bitc::IDENTIFICATION_CODE_EPOCH
: { // EPOCH: [epoch#]
212 unsigned epoch
= (unsigned)Record
[0];
213 if (epoch
!= bitc::BITCODE_CURRENT_EPOCH
) {
215 Twine("Incompatible epoch: Bitcode '") + Twine(epoch
) +
216 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH
) + "'");
223 static Expected
<std::string
> readIdentificationCode(BitstreamCursor
&Stream
) {
224 // We expect a number of well-defined blocks, though we don't necessarily
225 // need to understand them all.
227 if (Stream
.AtEndOfStream())
230 BitstreamEntry Entry
;
231 if (Expected
<BitstreamEntry
> Res
= Stream
.advance())
232 Entry
= std::move(Res
.get());
234 return Res
.takeError();
236 switch (Entry
.Kind
) {
237 case BitstreamEntry::EndBlock
:
238 case BitstreamEntry::Error
:
239 return error("Malformed block");
241 case BitstreamEntry::SubBlock
:
242 if (Entry
.ID
== bitc::IDENTIFICATION_BLOCK_ID
)
243 return readIdentificationBlock(Stream
);
245 // Ignore other sub-blocks.
246 if (Error Err
= Stream
.SkipBlock())
247 return std::move(Err
);
249 case BitstreamEntry::Record
:
250 if (Expected
<unsigned> Skipped
= Stream
.skipRecord(Entry
.ID
))
253 return Skipped
.takeError();
258 static Expected
<bool> hasObjCCategoryInModule(BitstreamCursor
&Stream
) {
259 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
260 return std::move(Err
);
262 SmallVector
<uint64_t, 64> Record
;
263 // Read all the records for this module.
266 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
268 return MaybeEntry
.takeError();
269 BitstreamEntry Entry
= MaybeEntry
.get();
271 switch (Entry
.Kind
) {
272 case BitstreamEntry::SubBlock
: // Handled for us already.
273 case BitstreamEntry::Error
:
274 return error("Malformed block");
275 case BitstreamEntry::EndBlock
:
277 case BitstreamEntry::Record
:
278 // The interesting case.
283 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
285 return MaybeRecord
.takeError();
286 switch (MaybeRecord
.get()) {
288 break; // Default behavior, ignore unknown content.
289 case bitc::MODULE_CODE_SECTIONNAME
: { // SECTIONNAME: [strchr x N]
291 if (convertToString(Record
, 0, S
))
292 return error("Invalid record");
293 // Check for the i386 and other (x86_64, ARM) conventions
294 if (S
.find("__DATA,__objc_catlist") != std::string::npos
||
295 S
.find("__OBJC,__category") != std::string::npos
)
302 llvm_unreachable("Exit infinite loop");
305 static Expected
<bool> hasObjCCategory(BitstreamCursor
&Stream
) {
306 // We expect a number of well-defined blocks, though we don't necessarily
307 // need to understand them all.
309 BitstreamEntry Entry
;
310 if (Expected
<BitstreamEntry
> Res
= Stream
.advance())
311 Entry
= std::move(Res
.get());
313 return Res
.takeError();
315 switch (Entry
.Kind
) {
316 case BitstreamEntry::Error
:
317 return error("Malformed block");
318 case BitstreamEntry::EndBlock
:
321 case BitstreamEntry::SubBlock
:
322 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
)
323 return hasObjCCategoryInModule(Stream
);
325 // Ignore other sub-blocks.
326 if (Error Err
= Stream
.SkipBlock())
327 return std::move(Err
);
330 case BitstreamEntry::Record
:
331 if (Expected
<unsigned> Skipped
= Stream
.skipRecord(Entry
.ID
))
334 return Skipped
.takeError();
339 static Expected
<std::string
> readModuleTriple(BitstreamCursor
&Stream
) {
340 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
341 return std::move(Err
);
343 SmallVector
<uint64_t, 64> Record
;
347 // Read all the records for this module.
349 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
351 return MaybeEntry
.takeError();
352 BitstreamEntry Entry
= MaybeEntry
.get();
354 switch (Entry
.Kind
) {
355 case BitstreamEntry::SubBlock
: // Handled for us already.
356 case BitstreamEntry::Error
:
357 return error("Malformed block");
358 case BitstreamEntry::EndBlock
:
360 case BitstreamEntry::Record
:
361 // The interesting case.
366 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
368 return MaybeRecord
.takeError();
369 switch (MaybeRecord
.get()) {
370 default: break; // Default behavior, ignore unknown content.
371 case bitc::MODULE_CODE_TRIPLE
: { // TRIPLE: [strchr x N]
373 if (convertToString(Record
, 0, S
))
374 return error("Invalid record");
381 llvm_unreachable("Exit infinite loop");
384 static Expected
<std::string
> readTriple(BitstreamCursor
&Stream
) {
385 // We expect a number of well-defined blocks, though we don't necessarily
386 // need to understand them all.
388 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advance();
390 return MaybeEntry
.takeError();
391 BitstreamEntry Entry
= MaybeEntry
.get();
393 switch (Entry
.Kind
) {
394 case BitstreamEntry::Error
:
395 return error("Malformed block");
396 case BitstreamEntry::EndBlock
:
399 case BitstreamEntry::SubBlock
:
400 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
)
401 return readModuleTriple(Stream
);
403 // Ignore other sub-blocks.
404 if (Error Err
= Stream
.SkipBlock())
405 return std::move(Err
);
408 case BitstreamEntry::Record
:
409 if (llvm::Expected
<unsigned> Skipped
= Stream
.skipRecord(Entry
.ID
))
412 return Skipped
.takeError();
419 class BitcodeReaderBase
{
421 BitcodeReaderBase(BitstreamCursor Stream
, StringRef Strtab
)
422 : Stream(std::move(Stream
)), Strtab(Strtab
) {
423 this->Stream
.setBlockInfo(&BlockInfo
);
426 BitstreamBlockInfo BlockInfo
;
427 BitstreamCursor Stream
;
430 /// In version 2 of the bitcode we store names of global values and comdats in
431 /// a string table rather than in the VST.
432 bool UseStrtab
= false;
434 Expected
<unsigned> parseVersionRecord(ArrayRef
<uint64_t> Record
);
436 /// If this module uses a string table, pop the reference to the string table
437 /// and return the referenced string and the rest of the record. Otherwise
438 /// just return the record itself.
439 std::pair
<StringRef
, ArrayRef
<uint64_t>>
440 readNameFromStrtab(ArrayRef
<uint64_t> Record
);
442 bool readBlockInfo();
444 // Contains an arbitrary and optional string identifying the bitcode producer
445 std::string ProducerIdentification
;
447 Error
error(const Twine
&Message
);
450 } // end anonymous namespace
452 Error
BitcodeReaderBase::error(const Twine
&Message
) {
453 std::string FullMsg
= Message
.str();
454 if (!ProducerIdentification
.empty())
455 FullMsg
+= " (Producer: '" + ProducerIdentification
+ "' Reader: 'LLVM " +
456 LLVM_VERSION_STRING
"')";
457 return ::error(FullMsg
);
461 BitcodeReaderBase::parseVersionRecord(ArrayRef
<uint64_t> Record
) {
463 return error("Invalid record");
464 unsigned ModuleVersion
= Record
[0];
465 if (ModuleVersion
> 2)
466 return error("Invalid value");
467 UseStrtab
= ModuleVersion
>= 2;
468 return ModuleVersion
;
471 std::pair
<StringRef
, ArrayRef
<uint64_t>>
472 BitcodeReaderBase::readNameFromStrtab(ArrayRef
<uint64_t> Record
) {
475 // Invalid reference. Let the caller complain about the record being empty.
476 if (Record
[0] + Record
[1] > Strtab
.size())
478 return {StringRef(Strtab
.data() + Record
[0], Record
[1]), Record
.slice(2)};
483 class BitcodeReader
: public BitcodeReaderBase
, public GVMaterializer
{
484 LLVMContext
&Context
;
485 Module
*TheModule
= nullptr;
486 // Next offset to start scanning for lazy parsing of function bodies.
487 uint64_t NextUnreadBit
= 0;
488 // Last function offset found in the VST.
489 uint64_t LastFunctionBlockBit
= 0;
490 bool SeenValueSymbolTable
= false;
491 uint64_t VSTOffset
= 0;
493 std::vector
<std::string
> SectionTable
;
494 std::vector
<std::string
> GCTable
;
496 std::vector
<Type
*> TypeList
;
497 DenseMap
<Function
*, FunctionType
*> FunctionTypes
;
498 BitcodeReaderValueList ValueList
;
499 Optional
<MetadataLoader
> MDLoader
;
500 std::vector
<Comdat
*> ComdatList
;
501 SmallVector
<Instruction
*, 64> InstructionList
;
503 std::vector
<std::pair
<GlobalVariable
*, unsigned>> GlobalInits
;
504 std::vector
<std::pair
<GlobalIndirectSymbol
*, unsigned>> IndirectSymbolInits
;
505 std::vector
<std::pair
<Function
*, unsigned>> FunctionPrefixes
;
506 std::vector
<std::pair
<Function
*, unsigned>> FunctionPrologues
;
507 std::vector
<std::pair
<Function
*, unsigned>> FunctionPersonalityFns
;
509 /// The set of attributes by index. Index zero in the file is for null, and
510 /// is thus not represented here. As such all indices are off by one.
511 std::vector
<AttributeList
> MAttributes
;
513 /// The set of attribute groups.
514 std::map
<unsigned, AttributeList
> MAttributeGroups
;
516 /// While parsing a function body, this is a list of the basic blocks for the
518 std::vector
<BasicBlock
*> FunctionBBs
;
520 // When reading the module header, this list is populated with functions that
521 // have bodies later in the file.
522 std::vector
<Function
*> FunctionsWithBodies
;
524 // When intrinsic functions are encountered which require upgrading they are
525 // stored here with their replacement function.
526 using UpdatedIntrinsicMap
= DenseMap
<Function
*, Function
*>;
527 UpdatedIntrinsicMap UpgradedIntrinsics
;
528 // Intrinsics which were remangled because of types rename
529 UpdatedIntrinsicMap RemangledIntrinsics
;
531 // Several operations happen after the module header has been read, but
532 // before function bodies are processed. This keeps track of whether
533 // we've done this yet.
534 bool SeenFirstFunctionBody
= false;
536 /// When function bodies are initially scanned, this map contains info about
537 /// where to find deferred function body in the stream.
538 DenseMap
<Function
*, uint64_t> DeferredFunctionInfo
;
540 /// When Metadata block is initially scanned when parsing the module, we may
541 /// choose to defer parsing of the metadata. This vector contains info about
542 /// which Metadata blocks are deferred.
543 std::vector
<uint64_t> DeferredMetadataInfo
;
545 /// These are basic blocks forward-referenced by block addresses. They are
546 /// inserted lazily into functions when they're loaded. The basic block ID is
547 /// its index into the vector.
548 DenseMap
<Function
*, std::vector
<BasicBlock
*>> BasicBlockFwdRefs
;
549 std::deque
<Function
*> BasicBlockFwdRefQueue
;
551 /// Indicates that we are using a new encoding for instruction operands where
552 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
553 /// instruction number, for a more compact encoding. Some instruction
554 /// operands are not relative to the instruction ID: basic block numbers, and
555 /// types. Once the old style function blocks have been phased out, we would
556 /// not need this flag.
557 bool UseRelativeIDs
= false;
559 /// True if all functions will be materialized, negating the need to process
560 /// (e.g.) blockaddress forward references.
561 bool WillMaterializeAllForwardRefs
= false;
563 bool StripDebugInfo
= false;
564 TBAAVerifier TBAAVerifyHelper
;
566 std::vector
<std::string
> BundleTags
;
567 SmallVector
<SyncScope::ID
, 8> SSIDs
;
570 BitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
571 StringRef ProducerIdentification
, LLVMContext
&Context
);
573 Error
materializeForwardReferencedFunctions();
575 Error
materialize(GlobalValue
*GV
) override
;
576 Error
materializeModule() override
;
577 std::vector
<StructType
*> getIdentifiedStructTypes() const override
;
579 /// Main interface to parsing a bitcode buffer.
580 /// \returns true if an error occurred.
581 Error
parseBitcodeInto(Module
*M
, bool ShouldLazyLoadMetadata
= false,
582 bool IsImporting
= false);
584 static uint64_t decodeSignRotatedValue(uint64_t V
);
586 /// Materialize any deferred Metadata block.
587 Error
materializeMetadata() override
;
589 void setStripDebugInfo() override
;
592 std::vector
<StructType
*> IdentifiedStructTypes
;
593 StructType
*createIdentifiedStructType(LLVMContext
&Context
, StringRef Name
);
594 StructType
*createIdentifiedStructType(LLVMContext
&Context
);
596 /// Map all pointer types within \param Ty to the opaque pointer
597 /// type in the same address space if opaque pointers are being
598 /// used, otherwise nop. This converts a bitcode-reader internal
599 /// type into one suitable for use in a Value.
600 Type
*flattenPointerTypes(Type
*Ty
) {
604 /// Given a fully structured pointer type (i.e. not opaque), return
605 /// the flattened form of its element, suitable for use in a Value.
606 Type
*getPointerElementFlatType(Type
*Ty
) {
607 return flattenPointerTypes(cast
<PointerType
>(Ty
)->getElementType());
610 /// Given a fully structured pointer type, get its element type in
611 /// both fully structured form, and flattened form suitable for use
613 std::pair
<Type
*, Type
*> getPointerElementTypes(Type
*FullTy
) {
614 Type
*ElTy
= cast
<PointerType
>(FullTy
)->getElementType();
615 return std::make_pair(ElTy
, flattenPointerTypes(ElTy
));
618 /// Return the flattened type (suitable for use in a Value)
619 /// specified by the given \param ID .
620 Type
*getTypeByID(unsigned ID
) {
621 return flattenPointerTypes(getFullyStructuredTypeByID(ID
));
624 /// Return the fully structured (bitcode-reader internal) type
625 /// corresponding to the given \param ID .
626 Type
*getFullyStructuredTypeByID(unsigned ID
);
628 Value
*getFnValueByID(unsigned ID
, Type
*Ty
, Type
**FullTy
= nullptr) {
629 if (Ty
&& Ty
->isMetadataTy())
630 return MetadataAsValue::get(Ty
->getContext(), getFnMetadataByID(ID
));
631 return ValueList
.getValueFwdRef(ID
, Ty
, FullTy
);
634 Metadata
*getFnMetadataByID(unsigned ID
) {
635 return MDLoader
->getMetadataFwdRefOrLoad(ID
);
638 BasicBlock
*getBasicBlock(unsigned ID
) const {
639 if (ID
>= FunctionBBs
.size()) return nullptr; // Invalid ID
640 return FunctionBBs
[ID
];
643 AttributeList
getAttributes(unsigned i
) const {
644 if (i
-1 < MAttributes
.size())
645 return MAttributes
[i
-1];
646 return AttributeList();
649 /// Read a value/type pair out of the specified record from slot 'Slot'.
650 /// Increment Slot past the number of slots used in the record. Return true on
652 bool getValueTypePair(SmallVectorImpl
<uint64_t> &Record
, unsigned &Slot
,
653 unsigned InstNum
, Value
*&ResVal
,
654 Type
**FullTy
= nullptr) {
655 if (Slot
== Record
.size()) return true;
656 unsigned ValNo
= (unsigned)Record
[Slot
++];
657 // Adjust the ValNo, if it was encoded relative to the InstNum.
659 ValNo
= InstNum
- ValNo
;
660 if (ValNo
< InstNum
) {
661 // If this is not a forward reference, just return the value we already
663 ResVal
= getFnValueByID(ValNo
, nullptr, FullTy
);
664 return ResVal
== nullptr;
666 if (Slot
== Record
.size())
669 unsigned TypeNo
= (unsigned)Record
[Slot
++];
670 ResVal
= getFnValueByID(ValNo
, getTypeByID(TypeNo
));
672 *FullTy
= getFullyStructuredTypeByID(TypeNo
);
673 return ResVal
== nullptr;
676 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
677 /// past the number of slots used by the value in the record. Return true if
678 /// there is an error.
679 bool popValue(SmallVectorImpl
<uint64_t> &Record
, unsigned &Slot
,
680 unsigned InstNum
, Type
*Ty
, Value
*&ResVal
) {
681 if (getValue(Record
, Slot
, InstNum
, Ty
, ResVal
))
683 // All values currently take a single record slot.
688 /// Like popValue, but does not increment the Slot number.
689 bool getValue(SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
690 unsigned InstNum
, Type
*Ty
, Value
*&ResVal
) {
691 ResVal
= getValue(Record
, Slot
, InstNum
, Ty
);
692 return ResVal
== nullptr;
695 /// Version of getValue that returns ResVal directly, or 0 if there is an
697 Value
*getValue(SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
698 unsigned InstNum
, Type
*Ty
) {
699 if (Slot
== Record
.size()) return nullptr;
700 unsigned ValNo
= (unsigned)Record
[Slot
];
701 // Adjust the ValNo, if it was encoded relative to the InstNum.
703 ValNo
= InstNum
- ValNo
;
704 return getFnValueByID(ValNo
, Ty
);
707 /// Like getValue, but decodes signed VBRs.
708 Value
*getValueSigned(SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
709 unsigned InstNum
, Type
*Ty
) {
710 if (Slot
== Record
.size()) return nullptr;
711 unsigned ValNo
= (unsigned)decodeSignRotatedValue(Record
[Slot
]);
712 // Adjust the ValNo, if it was encoded relative to the InstNum.
714 ValNo
= InstNum
- ValNo
;
715 return getFnValueByID(ValNo
, Ty
);
718 /// Upgrades old-style typeless byval attributes by adding the corresponding
719 /// argument's pointee type.
720 void propagateByValTypes(CallBase
*CB
, ArrayRef
<Type
*> ArgsFullTys
);
722 /// Converts alignment exponent (i.e. power of two (or zero)) to the
723 /// corresponding alignment to use. If alignment is too large, returns
724 /// a corresponding error code.
725 Error
parseAlignmentValue(uint64_t Exponent
, unsigned &Alignment
);
726 Error
parseAttrKind(uint64_t Code
, Attribute::AttrKind
*Kind
);
727 Error
parseModule(uint64_t ResumeBit
, bool ShouldLazyLoadMetadata
= false);
729 Error
parseComdatRecord(ArrayRef
<uint64_t> Record
);
730 Error
parseGlobalVarRecord(ArrayRef
<uint64_t> Record
);
731 Error
parseFunctionRecord(ArrayRef
<uint64_t> Record
);
732 Error
parseGlobalIndirectSymbolRecord(unsigned BitCode
,
733 ArrayRef
<uint64_t> Record
);
735 Error
parseAttributeBlock();
736 Error
parseAttributeGroupBlock();
737 Error
parseTypeTable();
738 Error
parseTypeTableBody();
739 Error
parseOperandBundleTags();
740 Error
parseSyncScopeNames();
742 Expected
<Value
*> recordValue(SmallVectorImpl
<uint64_t> &Record
,
743 unsigned NameIndex
, Triple
&TT
);
744 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta
, Function
*F
,
745 ArrayRef
<uint64_t> Record
);
746 Error
parseValueSymbolTable(uint64_t Offset
= 0);
747 Error
parseGlobalValueSymbolTable();
748 Error
parseConstants();
749 Error
rememberAndSkipFunctionBodies();
750 Error
rememberAndSkipFunctionBody();
751 /// Save the positions of the Metadata blocks and skip parsing the blocks.
752 Error
rememberAndSkipMetadata();
753 Error
typeCheckLoadStoreInst(Type
*ValType
, Type
*PtrType
);
754 Error
parseFunctionBody(Function
*F
);
755 Error
globalCleanup();
756 Error
resolveGlobalAndIndirectSymbolInits();
757 Error
parseUseLists();
758 Error
findFunctionInStream(
760 DenseMap
<Function
*, uint64_t>::iterator DeferredFunctionInfoIterator
);
762 SyncScope::ID
getDecodedSyncScopeID(unsigned Val
);
765 /// Class to manage reading and parsing function summary index bitcode
767 class ModuleSummaryIndexBitcodeReader
: public BitcodeReaderBase
{
768 /// The module index built during parsing.
769 ModuleSummaryIndex
&TheIndex
;
771 /// Indicates whether we have encountered a global value summary section
772 /// yet during parsing.
773 bool SeenGlobalValSummary
= false;
775 /// Indicates whether we have already parsed the VST, used for error checking.
776 bool SeenValueSymbolTable
= false;
778 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
779 /// Used to enable on-demand parsing of the VST.
780 uint64_t VSTOffset
= 0;
782 // Map to save ValueId to ValueInfo association that was recorded in the
783 // ValueSymbolTable. It is used after the VST is parsed to convert
784 // call graph edges read from the function summary from referencing
785 // callees by their ValueId to using the ValueInfo instead, which is how
786 // they are recorded in the summary index being built.
787 // We save a GUID which refers to the same global as the ValueInfo, but
788 // ignoring the linkage, i.e. for values other than local linkage they are
790 DenseMap
<unsigned, std::pair
<ValueInfo
, GlobalValue::GUID
>>
791 ValueIdToValueInfoMap
;
793 /// Map populated during module path string table parsing, from the
794 /// module ID to a string reference owned by the index's module
795 /// path string table, used to correlate with combined index
797 DenseMap
<uint64_t, StringRef
> ModuleIdMap
;
799 /// Original source file name recorded in a bitcode record.
800 std::string SourceFileName
;
802 /// The string identifier given to this module by the client, normally the
803 /// path to the bitcode file.
804 StringRef ModulePath
;
806 /// For per-module summary indexes, the unique numerical identifier given to
807 /// this module by the client.
811 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
812 ModuleSummaryIndex
&TheIndex
,
813 StringRef ModulePath
, unsigned ModuleId
);
818 void setValueGUID(uint64_t ValueID
, StringRef ValueName
,
819 GlobalValue::LinkageTypes Linkage
,
820 StringRef SourceFileName
);
821 Error
parseValueSymbolTable(
823 DenseMap
<unsigned, GlobalValue::LinkageTypes
> &ValueIdToLinkageMap
);
824 std::vector
<ValueInfo
> makeRefList(ArrayRef
<uint64_t> Record
);
825 std::vector
<FunctionSummary::EdgeTy
> makeCallList(ArrayRef
<uint64_t> Record
,
826 bool IsOldProfileFormat
,
829 Error
parseEntireSummary(unsigned ID
);
830 Error
parseModuleStringTable();
831 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef
<uint64_t> Record
);
832 void parseTypeIdCompatibleVtableInfo(ArrayRef
<uint64_t> Record
, size_t &Slot
,
833 TypeIdCompatibleVtableInfo
&TypeId
);
835 std::pair
<ValueInfo
, GlobalValue::GUID
>
836 getValueInfoFromValueId(unsigned ValueId
);
838 void addThisModule();
839 ModuleSummaryIndex::ModuleInfo
*getThisModule();
842 } // end anonymous namespace
844 std::error_code
llvm::errorToErrorCodeAndEmitErrors(LLVMContext
&Ctx
,
848 handleAllErrors(std::move(Err
), [&](ErrorInfoBase
&EIB
) {
849 EC
= EIB
.convertToErrorCode();
850 Ctx
.emitError(EIB
.message());
854 return std::error_code();
857 BitcodeReader::BitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
858 StringRef ProducerIdentification
,
859 LLVMContext
&Context
)
860 : BitcodeReaderBase(std::move(Stream
), Strtab
), Context(Context
),
862 this->ProducerIdentification
= ProducerIdentification
;
865 Error
BitcodeReader::materializeForwardReferencedFunctions() {
866 if (WillMaterializeAllForwardRefs
)
867 return Error::success();
869 // Prevent recursion.
870 WillMaterializeAllForwardRefs
= true;
872 while (!BasicBlockFwdRefQueue
.empty()) {
873 Function
*F
= BasicBlockFwdRefQueue
.front();
874 BasicBlockFwdRefQueue
.pop_front();
875 assert(F
&& "Expected valid function");
876 if (!BasicBlockFwdRefs
.count(F
))
877 // Already materialized.
880 // Check for a function that isn't materializable to prevent an infinite
881 // loop. When parsing a blockaddress stored in a global variable, there
882 // isn't a trivial way to check if a function will have a body without a
883 // linear search through FunctionsWithBodies, so just check it here.
884 if (!F
->isMaterializable())
885 return error("Never resolved function from blockaddress");
887 // Try to materialize F.
888 if (Error Err
= materialize(F
))
891 assert(BasicBlockFwdRefs
.empty() && "Function missing from queue");
894 WillMaterializeAllForwardRefs
= false;
895 return Error::success();
898 //===----------------------------------------------------------------------===//
899 // Helper functions to implement forward reference resolution, etc.
900 //===----------------------------------------------------------------------===//
902 static bool hasImplicitComdat(size_t Val
) {
906 case 1: // Old WeakAnyLinkage
907 case 4: // Old LinkOnceAnyLinkage
908 case 10: // Old WeakODRLinkage
909 case 11: // Old LinkOnceODRLinkage
914 static GlobalValue::LinkageTypes
getDecodedLinkage(unsigned Val
) {
916 default: // Map unknown/new linkages to external
918 return GlobalValue::ExternalLinkage
;
920 return GlobalValue::AppendingLinkage
;
922 return GlobalValue::InternalLinkage
;
924 return GlobalValue::ExternalLinkage
; // Obsolete DLLImportLinkage
926 return GlobalValue::ExternalLinkage
; // Obsolete DLLExportLinkage
928 return GlobalValue::ExternalWeakLinkage
;
930 return GlobalValue::CommonLinkage
;
932 return GlobalValue::PrivateLinkage
;
934 return GlobalValue::AvailableExternallyLinkage
;
936 return GlobalValue::PrivateLinkage
; // Obsolete LinkerPrivateLinkage
938 return GlobalValue::PrivateLinkage
; // Obsolete LinkerPrivateWeakLinkage
940 return GlobalValue::ExternalLinkage
; // Obsolete LinkOnceODRAutoHideLinkage
941 case 1: // Old value with implicit comdat.
943 return GlobalValue::WeakAnyLinkage
;
944 case 10: // Old value with implicit comdat.
946 return GlobalValue::WeakODRLinkage
;
947 case 4: // Old value with implicit comdat.
949 return GlobalValue::LinkOnceAnyLinkage
;
950 case 11: // Old value with implicit comdat.
952 return GlobalValue::LinkOnceODRLinkage
;
956 static FunctionSummary::FFlags
getDecodedFFlags(uint64_t RawFlags
) {
957 FunctionSummary::FFlags Flags
;
958 Flags
.ReadNone
= RawFlags
& 0x1;
959 Flags
.ReadOnly
= (RawFlags
>> 1) & 0x1;
960 Flags
.NoRecurse
= (RawFlags
>> 2) & 0x1;
961 Flags
.ReturnDoesNotAlias
= (RawFlags
>> 3) & 0x1;
962 Flags
.NoInline
= (RawFlags
>> 4) & 0x1;
966 /// Decode the flags for GlobalValue in the summary.
967 static GlobalValueSummary::GVFlags
getDecodedGVSummaryFlags(uint64_t RawFlags
,
969 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
970 // like getDecodedLinkage() above. Any future change to the linkage enum and
971 // to getDecodedLinkage() will need to be taken into account here as above.
972 auto Linkage
= GlobalValue::LinkageTypes(RawFlags
& 0xF); // 4 bits
973 RawFlags
= RawFlags
>> 4;
974 bool NotEligibleToImport
= (RawFlags
& 0x1) || Version
< 3;
975 // The Live flag wasn't introduced until version 3. For dead stripping
976 // to work correctly on earlier versions, we must conservatively treat all
978 bool Live
= (RawFlags
& 0x2) || Version
< 3;
979 bool Local
= (RawFlags
& 0x4);
980 bool AutoHide
= (RawFlags
& 0x8);
982 return GlobalValueSummary::GVFlags(Linkage
, NotEligibleToImport
, Live
, Local
, AutoHide
);
985 // Decode the flags for GlobalVariable in the summary
986 static GlobalVarSummary::GVarFlags
getDecodedGVarFlags(uint64_t RawFlags
) {
987 return GlobalVarSummary::GVarFlags((RawFlags
& 0x1) ? true : false,
988 (RawFlags
& 0x2) ? true : false);
991 static GlobalValue::VisibilityTypes
getDecodedVisibility(unsigned Val
) {
993 default: // Map unknown visibilities to default.
994 case 0: return GlobalValue::DefaultVisibility
;
995 case 1: return GlobalValue::HiddenVisibility
;
996 case 2: return GlobalValue::ProtectedVisibility
;
1000 static GlobalValue::DLLStorageClassTypes
1001 getDecodedDLLStorageClass(unsigned Val
) {
1003 default: // Map unknown values to default.
1004 case 0: return GlobalValue::DefaultStorageClass
;
1005 case 1: return GlobalValue::DLLImportStorageClass
;
1006 case 2: return GlobalValue::DLLExportStorageClass
;
1010 static bool getDecodedDSOLocal(unsigned Val
) {
1012 default: // Map unknown values to preemptable.
1013 case 0: return false;
1014 case 1: return true;
1018 static GlobalVariable::ThreadLocalMode
getDecodedThreadLocalMode(unsigned Val
) {
1020 case 0: return GlobalVariable::NotThreadLocal
;
1021 default: // Map unknown non-zero value to general dynamic.
1022 case 1: return GlobalVariable::GeneralDynamicTLSModel
;
1023 case 2: return GlobalVariable::LocalDynamicTLSModel
;
1024 case 3: return GlobalVariable::InitialExecTLSModel
;
1025 case 4: return GlobalVariable::LocalExecTLSModel
;
1029 static GlobalVariable::UnnamedAddr
getDecodedUnnamedAddrType(unsigned Val
) {
1031 default: // Map unknown to UnnamedAddr::None.
1032 case 0: return GlobalVariable::UnnamedAddr::None
;
1033 case 1: return GlobalVariable::UnnamedAddr::Global
;
1034 case 2: return GlobalVariable::UnnamedAddr::Local
;
1038 static int getDecodedCastOpcode(unsigned Val
) {
1041 case bitc::CAST_TRUNC
: return Instruction::Trunc
;
1042 case bitc::CAST_ZEXT
: return Instruction::ZExt
;
1043 case bitc::CAST_SEXT
: return Instruction::SExt
;
1044 case bitc::CAST_FPTOUI
: return Instruction::FPToUI
;
1045 case bitc::CAST_FPTOSI
: return Instruction::FPToSI
;
1046 case bitc::CAST_UITOFP
: return Instruction::UIToFP
;
1047 case bitc::CAST_SITOFP
: return Instruction::SIToFP
;
1048 case bitc::CAST_FPTRUNC
: return Instruction::FPTrunc
;
1049 case bitc::CAST_FPEXT
: return Instruction::FPExt
;
1050 case bitc::CAST_PTRTOINT
: return Instruction::PtrToInt
;
1051 case bitc::CAST_INTTOPTR
: return Instruction::IntToPtr
;
1052 case bitc::CAST_BITCAST
: return Instruction::BitCast
;
1053 case bitc::CAST_ADDRSPACECAST
: return Instruction::AddrSpaceCast
;
1057 static int getDecodedUnaryOpcode(unsigned Val
, Type
*Ty
) {
1058 bool IsFP
= Ty
->isFPOrFPVectorTy();
1059 // UnOps are only valid for int/fp or vector of int/fp types
1060 if (!IsFP
&& !Ty
->isIntOrIntVectorTy())
1066 case bitc::UNOP_NEG
:
1067 return IsFP
? Instruction::FNeg
: -1;
1071 static int getDecodedBinaryOpcode(unsigned Val
, Type
*Ty
) {
1072 bool IsFP
= Ty
->isFPOrFPVectorTy();
1073 // BinOps are only valid for int/fp or vector of int/fp types
1074 if (!IsFP
&& !Ty
->isIntOrIntVectorTy())
1080 case bitc::BINOP_ADD
:
1081 return IsFP
? Instruction::FAdd
: Instruction::Add
;
1082 case bitc::BINOP_SUB
:
1083 return IsFP
? Instruction::FSub
: Instruction::Sub
;
1084 case bitc::BINOP_MUL
:
1085 return IsFP
? Instruction::FMul
: Instruction::Mul
;
1086 case bitc::BINOP_UDIV
:
1087 return IsFP
? -1 : Instruction::UDiv
;
1088 case bitc::BINOP_SDIV
:
1089 return IsFP
? Instruction::FDiv
: Instruction::SDiv
;
1090 case bitc::BINOP_UREM
:
1091 return IsFP
? -1 : Instruction::URem
;
1092 case bitc::BINOP_SREM
:
1093 return IsFP
? Instruction::FRem
: Instruction::SRem
;
1094 case bitc::BINOP_SHL
:
1095 return IsFP
? -1 : Instruction::Shl
;
1096 case bitc::BINOP_LSHR
:
1097 return IsFP
? -1 : Instruction::LShr
;
1098 case bitc::BINOP_ASHR
:
1099 return IsFP
? -1 : Instruction::AShr
;
1100 case bitc::BINOP_AND
:
1101 return IsFP
? -1 : Instruction::And
;
1102 case bitc::BINOP_OR
:
1103 return IsFP
? -1 : Instruction::Or
;
1104 case bitc::BINOP_XOR
:
1105 return IsFP
? -1 : Instruction::Xor
;
1109 static AtomicRMWInst::BinOp
getDecodedRMWOperation(unsigned Val
) {
1111 default: return AtomicRMWInst::BAD_BINOP
;
1112 case bitc::RMW_XCHG
: return AtomicRMWInst::Xchg
;
1113 case bitc::RMW_ADD
: return AtomicRMWInst::Add
;
1114 case bitc::RMW_SUB
: return AtomicRMWInst::Sub
;
1115 case bitc::RMW_AND
: return AtomicRMWInst::And
;
1116 case bitc::RMW_NAND
: return AtomicRMWInst::Nand
;
1117 case bitc::RMW_OR
: return AtomicRMWInst::Or
;
1118 case bitc::RMW_XOR
: return AtomicRMWInst::Xor
;
1119 case bitc::RMW_MAX
: return AtomicRMWInst::Max
;
1120 case bitc::RMW_MIN
: return AtomicRMWInst::Min
;
1121 case bitc::RMW_UMAX
: return AtomicRMWInst::UMax
;
1122 case bitc::RMW_UMIN
: return AtomicRMWInst::UMin
;
1123 case bitc::RMW_FADD
: return AtomicRMWInst::FAdd
;
1124 case bitc::RMW_FSUB
: return AtomicRMWInst::FSub
;
1128 static AtomicOrdering
getDecodedOrdering(unsigned Val
) {
1130 case bitc::ORDERING_NOTATOMIC
: return AtomicOrdering::NotAtomic
;
1131 case bitc::ORDERING_UNORDERED
: return AtomicOrdering::Unordered
;
1132 case bitc::ORDERING_MONOTONIC
: return AtomicOrdering::Monotonic
;
1133 case bitc::ORDERING_ACQUIRE
: return AtomicOrdering::Acquire
;
1134 case bitc::ORDERING_RELEASE
: return AtomicOrdering::Release
;
1135 case bitc::ORDERING_ACQREL
: return AtomicOrdering::AcquireRelease
;
1136 default: // Map unknown orderings to sequentially-consistent.
1137 case bitc::ORDERING_SEQCST
: return AtomicOrdering::SequentiallyConsistent
;
1141 static Comdat::SelectionKind
getDecodedComdatSelectionKind(unsigned Val
) {
1143 default: // Map unknown selection kinds to any.
1144 case bitc::COMDAT_SELECTION_KIND_ANY
:
1146 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH
:
1147 return Comdat::ExactMatch
;
1148 case bitc::COMDAT_SELECTION_KIND_LARGEST
:
1149 return Comdat::Largest
;
1150 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES
:
1151 return Comdat::NoDuplicates
;
1152 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE
:
1153 return Comdat::SameSize
;
1157 static FastMathFlags
getDecodedFastMathFlags(unsigned Val
) {
1159 if (0 != (Val
& bitc::UnsafeAlgebra
))
1161 if (0 != (Val
& bitc::AllowReassoc
))
1162 FMF
.setAllowReassoc();
1163 if (0 != (Val
& bitc::NoNaNs
))
1165 if (0 != (Val
& bitc::NoInfs
))
1167 if (0 != (Val
& bitc::NoSignedZeros
))
1168 FMF
.setNoSignedZeros();
1169 if (0 != (Val
& bitc::AllowReciprocal
))
1170 FMF
.setAllowReciprocal();
1171 if (0 != (Val
& bitc::AllowContract
))
1172 FMF
.setAllowContract(true);
1173 if (0 != (Val
& bitc::ApproxFunc
))
1174 FMF
.setApproxFunc();
1178 static void upgradeDLLImportExportLinkage(GlobalValue
*GV
, unsigned Val
) {
1180 case 5: GV
->setDLLStorageClass(GlobalValue::DLLImportStorageClass
); break;
1181 case 6: GV
->setDLLStorageClass(GlobalValue::DLLExportStorageClass
); break;
1185 Type
*BitcodeReader::getFullyStructuredTypeByID(unsigned ID
) {
1186 // The type table size is always specified correctly.
1187 if (ID
>= TypeList
.size())
1190 if (Type
*Ty
= TypeList
[ID
])
1193 // If we have a forward reference, the only possible case is when it is to a
1194 // named struct. Just create a placeholder for now.
1195 return TypeList
[ID
] = createIdentifiedStructType(Context
);
1198 StructType
*BitcodeReader::createIdentifiedStructType(LLVMContext
&Context
,
1200 auto *Ret
= StructType::create(Context
, Name
);
1201 IdentifiedStructTypes
.push_back(Ret
);
1205 StructType
*BitcodeReader::createIdentifiedStructType(LLVMContext
&Context
) {
1206 auto *Ret
= StructType::create(Context
);
1207 IdentifiedStructTypes
.push_back(Ret
);
1211 //===----------------------------------------------------------------------===//
1212 // Functions for parsing blocks from the bitcode file
1213 //===----------------------------------------------------------------------===//
1215 static uint64_t getRawAttributeMask(Attribute::AttrKind Val
) {
1217 case Attribute::EndAttrKinds
:
1218 llvm_unreachable("Synthetic enumerators which should never get here");
1220 case Attribute::None
: return 0;
1221 case Attribute::ZExt
: return 1 << 0;
1222 case Attribute::SExt
: return 1 << 1;
1223 case Attribute::NoReturn
: return 1 << 2;
1224 case Attribute::InReg
: return 1 << 3;
1225 case Attribute::StructRet
: return 1 << 4;
1226 case Attribute::NoUnwind
: return 1 << 5;
1227 case Attribute::NoAlias
: return 1 << 6;
1228 case Attribute::ByVal
: return 1 << 7;
1229 case Attribute::Nest
: return 1 << 8;
1230 case Attribute::ReadNone
: return 1 << 9;
1231 case Attribute::ReadOnly
: return 1 << 10;
1232 case Attribute::NoInline
: return 1 << 11;
1233 case Attribute::AlwaysInline
: return 1 << 12;
1234 case Attribute::OptimizeForSize
: return 1 << 13;
1235 case Attribute::StackProtect
: return 1 << 14;
1236 case Attribute::StackProtectReq
: return 1 << 15;
1237 case Attribute::Alignment
: return 31 << 16;
1238 case Attribute::NoCapture
: return 1 << 21;
1239 case Attribute::NoRedZone
: return 1 << 22;
1240 case Attribute::NoImplicitFloat
: return 1 << 23;
1241 case Attribute::Naked
: return 1 << 24;
1242 case Attribute::InlineHint
: return 1 << 25;
1243 case Attribute::StackAlignment
: return 7 << 26;
1244 case Attribute::ReturnsTwice
: return 1 << 29;
1245 case Attribute::UWTable
: return 1 << 30;
1246 case Attribute::NonLazyBind
: return 1U << 31;
1247 case Attribute::SanitizeAddress
: return 1ULL << 32;
1248 case Attribute::MinSize
: return 1ULL << 33;
1249 case Attribute::NoDuplicate
: return 1ULL << 34;
1250 case Attribute::StackProtectStrong
: return 1ULL << 35;
1251 case Attribute::SanitizeThread
: return 1ULL << 36;
1252 case Attribute::SanitizeMemory
: return 1ULL << 37;
1253 case Attribute::NoBuiltin
: return 1ULL << 38;
1254 case Attribute::Returned
: return 1ULL << 39;
1255 case Attribute::Cold
: return 1ULL << 40;
1256 case Attribute::Builtin
: return 1ULL << 41;
1257 case Attribute::OptimizeNone
: return 1ULL << 42;
1258 case Attribute::InAlloca
: return 1ULL << 43;
1259 case Attribute::NonNull
: return 1ULL << 44;
1260 case Attribute::JumpTable
: return 1ULL << 45;
1261 case Attribute::Convergent
: return 1ULL << 46;
1262 case Attribute::SafeStack
: return 1ULL << 47;
1263 case Attribute::NoRecurse
: return 1ULL << 48;
1264 case Attribute::InaccessibleMemOnly
: return 1ULL << 49;
1265 case Attribute::InaccessibleMemOrArgMemOnly
: return 1ULL << 50;
1266 case Attribute::SwiftSelf
: return 1ULL << 51;
1267 case Attribute::SwiftError
: return 1ULL << 52;
1268 case Attribute::WriteOnly
: return 1ULL << 53;
1269 case Attribute::Speculatable
: return 1ULL << 54;
1270 case Attribute::StrictFP
: return 1ULL << 55;
1271 case Attribute::SanitizeHWAddress
: return 1ULL << 56;
1272 case Attribute::NoCfCheck
: return 1ULL << 57;
1273 case Attribute::OptForFuzzing
: return 1ULL << 58;
1274 case Attribute::ShadowCallStack
: return 1ULL << 59;
1275 case Attribute::SpeculativeLoadHardening
:
1277 case Attribute::ImmArg
:
1279 case Attribute::WillReturn
:
1281 case Attribute::NoFree
:
1283 case Attribute::NoSync
:
1284 llvm_unreachable("nosync attribute not supported in raw format");
1286 case Attribute::Dereferenceable
:
1287 llvm_unreachable("dereferenceable attribute not supported in raw format");
1289 case Attribute::DereferenceableOrNull
:
1290 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1293 case Attribute::ArgMemOnly
:
1294 llvm_unreachable("argmemonly attribute not supported in raw format");
1296 case Attribute::AllocSize
:
1297 llvm_unreachable("allocsize not supported in raw format");
1300 llvm_unreachable("Unsupported attribute type");
1303 static void addRawAttributeValue(AttrBuilder
&B
, uint64_t Val
) {
1306 for (Attribute::AttrKind I
= Attribute::None
; I
!= Attribute::EndAttrKinds
;
1307 I
= Attribute::AttrKind(I
+ 1)) {
1308 if (I
== Attribute::Dereferenceable
||
1309 I
== Attribute::DereferenceableOrNull
||
1310 I
== Attribute::ArgMemOnly
||
1311 I
== Attribute::AllocSize
||
1312 I
== Attribute::NoSync
)
1314 if (uint64_t A
= (Val
& getRawAttributeMask(I
))) {
1315 if (I
== Attribute::Alignment
)
1316 B
.addAlignmentAttr(1ULL << ((A
>> 16) - 1));
1317 else if (I
== Attribute::StackAlignment
)
1318 B
.addStackAlignmentAttr(1ULL << ((A
>> 26)-1));
1325 /// This fills an AttrBuilder object with the LLVM attributes that have
1326 /// been decoded from the given integer. This function must stay in sync with
1327 /// 'encodeLLVMAttributesForBitcode'.
1328 static void decodeLLVMAttributesForBitcode(AttrBuilder
&B
,
1329 uint64_t EncodedAttrs
) {
1330 // FIXME: Remove in 4.0.
1332 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1333 // the bits above 31 down by 11 bits.
1334 unsigned Alignment
= (EncodedAttrs
& (0xffffULL
<< 16)) >> 16;
1335 assert((!Alignment
|| isPowerOf2_32(Alignment
)) &&
1336 "Alignment must be a power of two.");
1339 B
.addAlignmentAttr(Alignment
);
1340 addRawAttributeValue(B
, ((EncodedAttrs
& (0xfffffULL
<< 32)) >> 11) |
1341 (EncodedAttrs
& 0xffff));
1344 Error
BitcodeReader::parseAttributeBlock() {
1345 if (Error Err
= Stream
.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID
))
1348 if (!MAttributes
.empty())
1349 return error("Invalid multiple blocks");
1351 SmallVector
<uint64_t, 64> Record
;
1353 SmallVector
<AttributeList
, 8> Attrs
;
1355 // Read all the records.
1357 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
1359 return MaybeEntry
.takeError();
1360 BitstreamEntry Entry
= MaybeEntry
.get();
1362 switch (Entry
.Kind
) {
1363 case BitstreamEntry::SubBlock
: // Handled for us already.
1364 case BitstreamEntry::Error
:
1365 return error("Malformed block");
1366 case BitstreamEntry::EndBlock
:
1367 return Error::success();
1368 case BitstreamEntry::Record
:
1369 // The interesting case.
1375 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
1377 return MaybeRecord
.takeError();
1378 switch (MaybeRecord
.get()) {
1379 default: // Default behavior: ignore.
1381 case bitc::PARAMATTR_CODE_ENTRY_OLD
: // ENTRY: [paramidx0, attr0, ...]
1382 // FIXME: Remove in 4.0.
1383 if (Record
.size() & 1)
1384 return error("Invalid record");
1386 for (unsigned i
= 0, e
= Record
.size(); i
!= e
; i
+= 2) {
1388 decodeLLVMAttributesForBitcode(B
, Record
[i
+1]);
1389 Attrs
.push_back(AttributeList::get(Context
, Record
[i
], B
));
1392 MAttributes
.push_back(AttributeList::get(Context
, Attrs
));
1395 case bitc::PARAMATTR_CODE_ENTRY
: // ENTRY: [attrgrp0, attrgrp1, ...]
1396 for (unsigned i
= 0, e
= Record
.size(); i
!= e
; ++i
)
1397 Attrs
.push_back(MAttributeGroups
[Record
[i
]]);
1399 MAttributes
.push_back(AttributeList::get(Context
, Attrs
));
1406 // Returns Attribute::None on unrecognized codes.
1407 static Attribute::AttrKind
getAttrFromCode(uint64_t Code
) {
1410 return Attribute::None
;
1411 case bitc::ATTR_KIND_ALIGNMENT
:
1412 return Attribute::Alignment
;
1413 case bitc::ATTR_KIND_ALWAYS_INLINE
:
1414 return Attribute::AlwaysInline
;
1415 case bitc::ATTR_KIND_ARGMEMONLY
:
1416 return Attribute::ArgMemOnly
;
1417 case bitc::ATTR_KIND_BUILTIN
:
1418 return Attribute::Builtin
;
1419 case bitc::ATTR_KIND_BY_VAL
:
1420 return Attribute::ByVal
;
1421 case bitc::ATTR_KIND_IN_ALLOCA
:
1422 return Attribute::InAlloca
;
1423 case bitc::ATTR_KIND_COLD
:
1424 return Attribute::Cold
;
1425 case bitc::ATTR_KIND_CONVERGENT
:
1426 return Attribute::Convergent
;
1427 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY
:
1428 return Attribute::InaccessibleMemOnly
;
1429 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
:
1430 return Attribute::InaccessibleMemOrArgMemOnly
;
1431 case bitc::ATTR_KIND_INLINE_HINT
:
1432 return Attribute::InlineHint
;
1433 case bitc::ATTR_KIND_IN_REG
:
1434 return Attribute::InReg
;
1435 case bitc::ATTR_KIND_JUMP_TABLE
:
1436 return Attribute::JumpTable
;
1437 case bitc::ATTR_KIND_MIN_SIZE
:
1438 return Attribute::MinSize
;
1439 case bitc::ATTR_KIND_NAKED
:
1440 return Attribute::Naked
;
1441 case bitc::ATTR_KIND_NEST
:
1442 return Attribute::Nest
;
1443 case bitc::ATTR_KIND_NO_ALIAS
:
1444 return Attribute::NoAlias
;
1445 case bitc::ATTR_KIND_NO_BUILTIN
:
1446 return Attribute::NoBuiltin
;
1447 case bitc::ATTR_KIND_NO_CAPTURE
:
1448 return Attribute::NoCapture
;
1449 case bitc::ATTR_KIND_NO_DUPLICATE
:
1450 return Attribute::NoDuplicate
;
1451 case bitc::ATTR_KIND_NOFREE
:
1452 return Attribute::NoFree
;
1453 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT
:
1454 return Attribute::NoImplicitFloat
;
1455 case bitc::ATTR_KIND_NO_INLINE
:
1456 return Attribute::NoInline
;
1457 case bitc::ATTR_KIND_NO_RECURSE
:
1458 return Attribute::NoRecurse
;
1459 case bitc::ATTR_KIND_NON_LAZY_BIND
:
1460 return Attribute::NonLazyBind
;
1461 case bitc::ATTR_KIND_NON_NULL
:
1462 return Attribute::NonNull
;
1463 case bitc::ATTR_KIND_DEREFERENCEABLE
:
1464 return Attribute::Dereferenceable
;
1465 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL
:
1466 return Attribute::DereferenceableOrNull
;
1467 case bitc::ATTR_KIND_ALLOC_SIZE
:
1468 return Attribute::AllocSize
;
1469 case bitc::ATTR_KIND_NO_RED_ZONE
:
1470 return Attribute::NoRedZone
;
1471 case bitc::ATTR_KIND_NO_RETURN
:
1472 return Attribute::NoReturn
;
1473 case bitc::ATTR_KIND_NOSYNC
:
1474 return Attribute::NoSync
;
1475 case bitc::ATTR_KIND_NOCF_CHECK
:
1476 return Attribute::NoCfCheck
;
1477 case bitc::ATTR_KIND_NO_UNWIND
:
1478 return Attribute::NoUnwind
;
1479 case bitc::ATTR_KIND_OPT_FOR_FUZZING
:
1480 return Attribute::OptForFuzzing
;
1481 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE
:
1482 return Attribute::OptimizeForSize
;
1483 case bitc::ATTR_KIND_OPTIMIZE_NONE
:
1484 return Attribute::OptimizeNone
;
1485 case bitc::ATTR_KIND_READ_NONE
:
1486 return Attribute::ReadNone
;
1487 case bitc::ATTR_KIND_READ_ONLY
:
1488 return Attribute::ReadOnly
;
1489 case bitc::ATTR_KIND_RETURNED
:
1490 return Attribute::Returned
;
1491 case bitc::ATTR_KIND_RETURNS_TWICE
:
1492 return Attribute::ReturnsTwice
;
1493 case bitc::ATTR_KIND_S_EXT
:
1494 return Attribute::SExt
;
1495 case bitc::ATTR_KIND_SPECULATABLE
:
1496 return Attribute::Speculatable
;
1497 case bitc::ATTR_KIND_STACK_ALIGNMENT
:
1498 return Attribute::StackAlignment
;
1499 case bitc::ATTR_KIND_STACK_PROTECT
:
1500 return Attribute::StackProtect
;
1501 case bitc::ATTR_KIND_STACK_PROTECT_REQ
:
1502 return Attribute::StackProtectReq
;
1503 case bitc::ATTR_KIND_STACK_PROTECT_STRONG
:
1504 return Attribute::StackProtectStrong
;
1505 case bitc::ATTR_KIND_SAFESTACK
:
1506 return Attribute::SafeStack
;
1507 case bitc::ATTR_KIND_SHADOWCALLSTACK
:
1508 return Attribute::ShadowCallStack
;
1509 case bitc::ATTR_KIND_STRICT_FP
:
1510 return Attribute::StrictFP
;
1511 case bitc::ATTR_KIND_STRUCT_RET
:
1512 return Attribute::StructRet
;
1513 case bitc::ATTR_KIND_SANITIZE_ADDRESS
:
1514 return Attribute::SanitizeAddress
;
1515 case bitc::ATTR_KIND_SANITIZE_HWADDRESS
:
1516 return Attribute::SanitizeHWAddress
;
1517 case bitc::ATTR_KIND_SANITIZE_THREAD
:
1518 return Attribute::SanitizeThread
;
1519 case bitc::ATTR_KIND_SANITIZE_MEMORY
:
1520 return Attribute::SanitizeMemory
;
1521 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING
:
1522 return Attribute::SpeculativeLoadHardening
;
1523 case bitc::ATTR_KIND_SWIFT_ERROR
:
1524 return Attribute::SwiftError
;
1525 case bitc::ATTR_KIND_SWIFT_SELF
:
1526 return Attribute::SwiftSelf
;
1527 case bitc::ATTR_KIND_UW_TABLE
:
1528 return Attribute::UWTable
;
1529 case bitc::ATTR_KIND_WILLRETURN
:
1530 return Attribute::WillReturn
;
1531 case bitc::ATTR_KIND_WRITEONLY
:
1532 return Attribute::WriteOnly
;
1533 case bitc::ATTR_KIND_Z_EXT
:
1534 return Attribute::ZExt
;
1535 case bitc::ATTR_KIND_IMMARG
:
1536 return Attribute::ImmArg
;
1540 Error
BitcodeReader::parseAlignmentValue(uint64_t Exponent
,
1541 unsigned &Alignment
) {
1542 // Note: Alignment in bitcode files is incremented by 1, so that zero
1543 // can be used for default alignment.
1544 if (Exponent
> Value::MaxAlignmentExponent
+ 1)
1545 return error("Invalid alignment value");
1546 Alignment
= (1 << static_cast<unsigned>(Exponent
)) >> 1;
1547 return Error::success();
1550 Error
BitcodeReader::parseAttrKind(uint64_t Code
, Attribute::AttrKind
*Kind
) {
1551 *Kind
= getAttrFromCode(Code
);
1552 if (*Kind
== Attribute::None
)
1553 return error("Unknown attribute kind (" + Twine(Code
) + ")");
1554 return Error::success();
1557 Error
BitcodeReader::parseAttributeGroupBlock() {
1558 if (Error Err
= Stream
.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID
))
1561 if (!MAttributeGroups
.empty())
1562 return error("Invalid multiple blocks");
1564 SmallVector
<uint64_t, 64> Record
;
1566 // Read all the records.
1568 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
1570 return MaybeEntry
.takeError();
1571 BitstreamEntry Entry
= MaybeEntry
.get();
1573 switch (Entry
.Kind
) {
1574 case BitstreamEntry::SubBlock
: // Handled for us already.
1575 case BitstreamEntry::Error
:
1576 return error("Malformed block");
1577 case BitstreamEntry::EndBlock
:
1578 return Error::success();
1579 case BitstreamEntry::Record
:
1580 // The interesting case.
1586 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
1588 return MaybeRecord
.takeError();
1589 switch (MaybeRecord
.get()) {
1590 default: // Default behavior: ignore.
1592 case bitc::PARAMATTR_GRP_CODE_ENTRY
: { // ENTRY: [grpid, idx, a0, a1, ...]
1593 if (Record
.size() < 3)
1594 return error("Invalid record");
1596 uint64_t GrpID
= Record
[0];
1597 uint64_t Idx
= Record
[1]; // Index of the object this attribute refers to.
1600 for (unsigned i
= 2, e
= Record
.size(); i
!= e
; ++i
) {
1601 if (Record
[i
] == 0) { // Enum attribute
1602 Attribute::AttrKind Kind
;
1603 if (Error Err
= parseAttrKind(Record
[++i
], &Kind
))
1606 // Upgrade old-style byval attribute to one with a type, even if it's
1607 // nullptr. We will have to insert the real type when we associate
1608 // this AttributeList with a function.
1609 if (Kind
== Attribute::ByVal
)
1610 B
.addByValAttr(nullptr);
1612 B
.addAttribute(Kind
);
1613 } else if (Record
[i
] == 1) { // Integer attribute
1614 Attribute::AttrKind Kind
;
1615 if (Error Err
= parseAttrKind(Record
[++i
], &Kind
))
1617 if (Kind
== Attribute::Alignment
)
1618 B
.addAlignmentAttr(Record
[++i
]);
1619 else if (Kind
== Attribute::StackAlignment
)
1620 B
.addStackAlignmentAttr(Record
[++i
]);
1621 else if (Kind
== Attribute::Dereferenceable
)
1622 B
.addDereferenceableAttr(Record
[++i
]);
1623 else if (Kind
== Attribute::DereferenceableOrNull
)
1624 B
.addDereferenceableOrNullAttr(Record
[++i
]);
1625 else if (Kind
== Attribute::AllocSize
)
1626 B
.addAllocSizeAttrFromRawRepr(Record
[++i
]);
1627 } else if (Record
[i
] == 3 || Record
[i
] == 4) { // String attribute
1628 bool HasValue
= (Record
[i
++] == 4);
1629 SmallString
<64> KindStr
;
1630 SmallString
<64> ValStr
;
1632 while (Record
[i
] != 0 && i
!= e
)
1633 KindStr
+= Record
[i
++];
1634 assert(Record
[i
] == 0 && "Kind string not null terminated");
1637 // Has a value associated with it.
1638 ++i
; // Skip the '0' that terminates the "kind" string.
1639 while (Record
[i
] != 0 && i
!= e
)
1640 ValStr
+= Record
[i
++];
1641 assert(Record
[i
] == 0 && "Value string not null terminated");
1644 B
.addAttribute(KindStr
.str(), ValStr
.str());
1646 assert((Record
[i
] == 5 || Record
[i
] == 6) &&
1647 "Invalid attribute group entry");
1648 bool HasType
= Record
[i
] == 6;
1649 Attribute::AttrKind Kind
;
1650 if (Error Err
= parseAttrKind(Record
[++i
], &Kind
))
1652 if (Kind
== Attribute::ByVal
)
1653 B
.addByValAttr(HasType
? getTypeByID(Record
[++i
]) : nullptr);
1657 MAttributeGroups
[GrpID
] = AttributeList::get(Context
, Idx
, B
);
1664 Error
BitcodeReader::parseTypeTable() {
1665 if (Error Err
= Stream
.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW
))
1668 return parseTypeTableBody();
1671 Error
BitcodeReader::parseTypeTableBody() {
1672 if (!TypeList
.empty())
1673 return error("Invalid multiple blocks");
1675 SmallVector
<uint64_t, 64> Record
;
1676 unsigned NumRecords
= 0;
1678 SmallString
<64> TypeName
;
1680 // Read all the records for this type table.
1682 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
1684 return MaybeEntry
.takeError();
1685 BitstreamEntry Entry
= MaybeEntry
.get();
1687 switch (Entry
.Kind
) {
1688 case BitstreamEntry::SubBlock
: // Handled for us already.
1689 case BitstreamEntry::Error
:
1690 return error("Malformed block");
1691 case BitstreamEntry::EndBlock
:
1692 if (NumRecords
!= TypeList
.size())
1693 return error("Malformed block");
1694 return Error::success();
1695 case BitstreamEntry::Record
:
1696 // The interesting case.
1702 Type
*ResultTy
= nullptr;
1703 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
1705 return MaybeRecord
.takeError();
1706 switch (MaybeRecord
.get()) {
1708 return error("Invalid value");
1709 case bitc::TYPE_CODE_NUMENTRY
: // TYPE_CODE_NUMENTRY: [numentries]
1710 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1711 // type list. This allows us to reserve space.
1712 if (Record
.size() < 1)
1713 return error("Invalid record");
1714 TypeList
.resize(Record
[0]);
1716 case bitc::TYPE_CODE_VOID
: // VOID
1717 ResultTy
= Type::getVoidTy(Context
);
1719 case bitc::TYPE_CODE_HALF
: // HALF
1720 ResultTy
= Type::getHalfTy(Context
);
1722 case bitc::TYPE_CODE_FLOAT
: // FLOAT
1723 ResultTy
= Type::getFloatTy(Context
);
1725 case bitc::TYPE_CODE_DOUBLE
: // DOUBLE
1726 ResultTy
= Type::getDoubleTy(Context
);
1728 case bitc::TYPE_CODE_X86_FP80
: // X86_FP80
1729 ResultTy
= Type::getX86_FP80Ty(Context
);
1731 case bitc::TYPE_CODE_FP128
: // FP128
1732 ResultTy
= Type::getFP128Ty(Context
);
1734 case bitc::TYPE_CODE_PPC_FP128
: // PPC_FP128
1735 ResultTy
= Type::getPPC_FP128Ty(Context
);
1737 case bitc::TYPE_CODE_LABEL
: // LABEL
1738 ResultTy
= Type::getLabelTy(Context
);
1740 case bitc::TYPE_CODE_METADATA
: // METADATA
1741 ResultTy
= Type::getMetadataTy(Context
);
1743 case bitc::TYPE_CODE_X86_MMX
: // X86_MMX
1744 ResultTy
= Type::getX86_MMXTy(Context
);
1746 case bitc::TYPE_CODE_TOKEN
: // TOKEN
1747 ResultTy
= Type::getTokenTy(Context
);
1749 case bitc::TYPE_CODE_INTEGER
: { // INTEGER: [width]
1750 if (Record
.size() < 1)
1751 return error("Invalid record");
1753 uint64_t NumBits
= Record
[0];
1754 if (NumBits
< IntegerType::MIN_INT_BITS
||
1755 NumBits
> IntegerType::MAX_INT_BITS
)
1756 return error("Bitwidth for integer type out of range");
1757 ResultTy
= IntegerType::get(Context
, NumBits
);
1760 case bitc::TYPE_CODE_POINTER
: { // POINTER: [pointee type] or
1761 // [pointee type, address space]
1762 if (Record
.size() < 1)
1763 return error("Invalid record");
1764 unsigned AddressSpace
= 0;
1765 if (Record
.size() == 2)
1766 AddressSpace
= Record
[1];
1767 ResultTy
= getTypeByID(Record
[0]);
1769 !PointerType::isValidElementType(ResultTy
))
1770 return error("Invalid type");
1771 ResultTy
= PointerType::get(ResultTy
, AddressSpace
);
1774 case bitc::TYPE_CODE_FUNCTION_OLD
: {
1775 // FIXME: attrid is dead, remove it in LLVM 4.0
1776 // FUNCTION: [vararg, attrid, retty, paramty x N]
1777 if (Record
.size() < 3)
1778 return error("Invalid record");
1779 SmallVector
<Type
*, 8> ArgTys
;
1780 for (unsigned i
= 3, e
= Record
.size(); i
!= e
; ++i
) {
1781 if (Type
*T
= getTypeByID(Record
[i
]))
1782 ArgTys
.push_back(T
);
1787 ResultTy
= getTypeByID(Record
[2]);
1788 if (!ResultTy
|| ArgTys
.size() < Record
.size()-3)
1789 return error("Invalid type");
1791 ResultTy
= FunctionType::get(ResultTy
, ArgTys
, Record
[0]);
1794 case bitc::TYPE_CODE_FUNCTION
: {
1795 // FUNCTION: [vararg, retty, paramty x N]
1796 if (Record
.size() < 2)
1797 return error("Invalid record");
1798 SmallVector
<Type
*, 8> ArgTys
;
1799 for (unsigned i
= 2, e
= Record
.size(); i
!= e
; ++i
) {
1800 if (Type
*T
= getTypeByID(Record
[i
])) {
1801 if (!FunctionType::isValidArgumentType(T
))
1802 return error("Invalid function argument type");
1803 ArgTys
.push_back(T
);
1809 ResultTy
= getTypeByID(Record
[1]);
1810 if (!ResultTy
|| ArgTys
.size() < Record
.size()-2)
1811 return error("Invalid type");
1813 ResultTy
= FunctionType::get(ResultTy
, ArgTys
, Record
[0]);
1816 case bitc::TYPE_CODE_STRUCT_ANON
: { // STRUCT: [ispacked, eltty x N]
1817 if (Record
.size() < 1)
1818 return error("Invalid record");
1819 SmallVector
<Type
*, 8> EltTys
;
1820 for (unsigned i
= 1, e
= Record
.size(); i
!= e
; ++i
) {
1821 if (Type
*T
= getTypeByID(Record
[i
]))
1822 EltTys
.push_back(T
);
1826 if (EltTys
.size() != Record
.size()-1)
1827 return error("Invalid type");
1828 ResultTy
= StructType::get(Context
, EltTys
, Record
[0]);
1831 case bitc::TYPE_CODE_STRUCT_NAME
: // STRUCT_NAME: [strchr x N]
1832 if (convertToString(Record
, 0, TypeName
))
1833 return error("Invalid record");
1836 case bitc::TYPE_CODE_STRUCT_NAMED
: { // STRUCT: [ispacked, eltty x N]
1837 if (Record
.size() < 1)
1838 return error("Invalid record");
1840 if (NumRecords
>= TypeList
.size())
1841 return error("Invalid TYPE table");
1843 // Check to see if this was forward referenced, if so fill in the temp.
1844 StructType
*Res
= cast_or_null
<StructType
>(TypeList
[NumRecords
]);
1846 Res
->setName(TypeName
);
1847 TypeList
[NumRecords
] = nullptr;
1848 } else // Otherwise, create a new struct.
1849 Res
= createIdentifiedStructType(Context
, TypeName
);
1852 SmallVector
<Type
*, 8> EltTys
;
1853 for (unsigned i
= 1, e
= Record
.size(); i
!= e
; ++i
) {
1854 if (Type
*T
= getTypeByID(Record
[i
]))
1855 EltTys
.push_back(T
);
1859 if (EltTys
.size() != Record
.size()-1)
1860 return error("Invalid record");
1861 Res
->setBody(EltTys
, Record
[0]);
1865 case bitc::TYPE_CODE_OPAQUE
: { // OPAQUE: []
1866 if (Record
.size() != 1)
1867 return error("Invalid record");
1869 if (NumRecords
>= TypeList
.size())
1870 return error("Invalid TYPE table");
1872 // Check to see if this was forward referenced, if so fill in the temp.
1873 StructType
*Res
= cast_or_null
<StructType
>(TypeList
[NumRecords
]);
1875 Res
->setName(TypeName
);
1876 TypeList
[NumRecords
] = nullptr;
1877 } else // Otherwise, create a new struct with no body.
1878 Res
= createIdentifiedStructType(Context
, TypeName
);
1883 case bitc::TYPE_CODE_ARRAY
: // ARRAY: [numelts, eltty]
1884 if (Record
.size() < 2)
1885 return error("Invalid record");
1886 ResultTy
= getTypeByID(Record
[1]);
1887 if (!ResultTy
|| !ArrayType::isValidElementType(ResultTy
))
1888 return error("Invalid type");
1889 ResultTy
= ArrayType::get(ResultTy
, Record
[0]);
1891 case bitc::TYPE_CODE_VECTOR
: // VECTOR: [numelts, eltty] or
1892 // [numelts, eltty, scalable]
1893 if (Record
.size() < 2)
1894 return error("Invalid record");
1896 return error("Invalid vector length");
1897 ResultTy
= getTypeByID(Record
[1]);
1898 if (!ResultTy
|| !StructType::isValidElementType(ResultTy
))
1899 return error("Invalid type");
1900 bool Scalable
= Record
.size() > 2 ? Record
[2] : false;
1901 ResultTy
= VectorType::get(ResultTy
, Record
[0], Scalable
);
1905 if (NumRecords
>= TypeList
.size())
1906 return error("Invalid TYPE table");
1907 if (TypeList
[NumRecords
])
1909 "Invalid TYPE table: Only named structs can be forward referenced");
1910 assert(ResultTy
&& "Didn't read a type?");
1911 TypeList
[NumRecords
++] = ResultTy
;
1915 Error
BitcodeReader::parseOperandBundleTags() {
1916 if (Error Err
= Stream
.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
))
1919 if (!BundleTags
.empty())
1920 return error("Invalid multiple blocks");
1922 SmallVector
<uint64_t, 64> Record
;
1925 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
1927 return MaybeEntry
.takeError();
1928 BitstreamEntry Entry
= MaybeEntry
.get();
1930 switch (Entry
.Kind
) {
1931 case BitstreamEntry::SubBlock
: // Handled for us already.
1932 case BitstreamEntry::Error
:
1933 return error("Malformed block");
1934 case BitstreamEntry::EndBlock
:
1935 return Error::success();
1936 case BitstreamEntry::Record
:
1937 // The interesting case.
1941 // Tags are implicitly mapped to integers by their order.
1943 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
1945 return MaybeRecord
.takeError();
1946 if (MaybeRecord
.get() != bitc::OPERAND_BUNDLE_TAG
)
1947 return error("Invalid record");
1949 // OPERAND_BUNDLE_TAG: [strchr x N]
1950 BundleTags
.emplace_back();
1951 if (convertToString(Record
, 0, BundleTags
.back()))
1952 return error("Invalid record");
1957 Error
BitcodeReader::parseSyncScopeNames() {
1958 if (Error Err
= Stream
.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID
))
1962 return error("Invalid multiple synchronization scope names blocks");
1964 SmallVector
<uint64_t, 64> Record
;
1966 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
1968 return MaybeEntry
.takeError();
1969 BitstreamEntry Entry
= MaybeEntry
.get();
1971 switch (Entry
.Kind
) {
1972 case BitstreamEntry::SubBlock
: // Handled for us already.
1973 case BitstreamEntry::Error
:
1974 return error("Malformed block");
1975 case BitstreamEntry::EndBlock
:
1977 return error("Invalid empty synchronization scope names block");
1978 return Error::success();
1979 case BitstreamEntry::Record
:
1980 // The interesting case.
1984 // Synchronization scope names are implicitly mapped to synchronization
1985 // scope IDs by their order.
1987 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
1989 return MaybeRecord
.takeError();
1990 if (MaybeRecord
.get() != bitc::SYNC_SCOPE_NAME
)
1991 return error("Invalid record");
1993 SmallString
<16> SSN
;
1994 if (convertToString(Record
, 0, SSN
))
1995 return error("Invalid record");
1997 SSIDs
.push_back(Context
.getOrInsertSyncScopeID(SSN
));
2002 /// Associate a value with its name from the given index in the provided record.
2003 Expected
<Value
*> BitcodeReader::recordValue(SmallVectorImpl
<uint64_t> &Record
,
2004 unsigned NameIndex
, Triple
&TT
) {
2005 SmallString
<128> ValueName
;
2006 if (convertToString(Record
, NameIndex
, ValueName
))
2007 return error("Invalid record");
2008 unsigned ValueID
= Record
[0];
2009 if (ValueID
>= ValueList
.size() || !ValueList
[ValueID
])
2010 return error("Invalid record");
2011 Value
*V
= ValueList
[ValueID
];
2013 StringRef
NameStr(ValueName
.data(), ValueName
.size());
2014 if (NameStr
.find_first_of(0) != StringRef::npos
)
2015 return error("Invalid value name");
2016 V
->setName(NameStr
);
2017 auto *GO
= dyn_cast
<GlobalObject
>(V
);
2019 if (GO
->getComdat() == reinterpret_cast<Comdat
*>(1)) {
2020 if (TT
.supportsCOMDAT())
2021 GO
->setComdat(TheModule
->getOrInsertComdat(V
->getName()));
2023 GO
->setComdat(nullptr);
2029 /// Helper to note and return the current location, and jump to the given
2031 static Expected
<uint64_t> jumpToValueSymbolTable(uint64_t Offset
,
2032 BitstreamCursor
&Stream
) {
2033 // Save the current parsing location so we can jump back at the end
2035 uint64_t CurrentBit
= Stream
.GetCurrentBitNo();
2036 if (Error JumpFailed
= Stream
.JumpToBit(Offset
* 32))
2037 return std::move(JumpFailed
);
2038 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advance();
2040 return MaybeEntry
.takeError();
2041 assert(MaybeEntry
.get().Kind
== BitstreamEntry::SubBlock
);
2042 assert(MaybeEntry
.get().ID
== bitc::VALUE_SYMTAB_BLOCK_ID
);
2046 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta
,
2048 ArrayRef
<uint64_t> Record
) {
2049 // Note that we subtract 1 here because the offset is relative to one word
2050 // before the start of the identification or module block, which was
2051 // historically always the start of the regular bitcode header.
2052 uint64_t FuncWordOffset
= Record
[1] - 1;
2053 uint64_t FuncBitOffset
= FuncWordOffset
* 32;
2054 DeferredFunctionInfo
[F
] = FuncBitOffset
+ FuncBitcodeOffsetDelta
;
2055 // Set the LastFunctionBlockBit to point to the last function block.
2056 // Later when parsing is resumed after function materialization,
2057 // we can simply skip that last function block.
2058 if (FuncBitOffset
> LastFunctionBlockBit
)
2059 LastFunctionBlockBit
= FuncBitOffset
;
2062 /// Read a new-style GlobalValue symbol table.
2063 Error
BitcodeReader::parseGlobalValueSymbolTable() {
2064 unsigned FuncBitcodeOffsetDelta
=
2065 Stream
.getAbbrevIDWidth() + bitc::BlockIDWidth
;
2067 if (Error Err
= Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
2070 SmallVector
<uint64_t, 64> Record
;
2072 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2074 return MaybeEntry
.takeError();
2075 BitstreamEntry Entry
= MaybeEntry
.get();
2077 switch (Entry
.Kind
) {
2078 case BitstreamEntry::SubBlock
:
2079 case BitstreamEntry::Error
:
2080 return error("Malformed block");
2081 case BitstreamEntry::EndBlock
:
2082 return Error::success();
2083 case BitstreamEntry::Record
:
2088 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2090 return MaybeRecord
.takeError();
2091 switch (MaybeRecord
.get()) {
2092 case bitc::VST_CODE_FNENTRY
: // [valueid, offset]
2093 setDeferredFunctionInfo(FuncBitcodeOffsetDelta
,
2094 cast
<Function
>(ValueList
[Record
[0]]), Record
);
2100 /// Parse the value symbol table at either the current parsing location or
2101 /// at the given bit offset if provided.
2102 Error
BitcodeReader::parseValueSymbolTable(uint64_t Offset
) {
2103 uint64_t CurrentBit
;
2104 // Pass in the Offset to distinguish between calling for the module-level
2105 // VST (where we want to jump to the VST offset) and the function-level
2106 // VST (where we don't).
2108 Expected
<uint64_t> MaybeCurrentBit
= jumpToValueSymbolTable(Offset
, Stream
);
2109 if (!MaybeCurrentBit
)
2110 return MaybeCurrentBit
.takeError();
2111 CurrentBit
= MaybeCurrentBit
.get();
2112 // If this module uses a string table, read this as a module-level VST.
2114 if (Error Err
= parseGlobalValueSymbolTable())
2116 if (Error JumpFailed
= Stream
.JumpToBit(CurrentBit
))
2118 return Error::success();
2120 // Otherwise, the VST will be in a similar format to a function-level VST,
2121 // and will contain symbol names.
2124 // Compute the delta between the bitcode indices in the VST (the word offset
2125 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2126 // expected by the lazy reader. The reader's EnterSubBlock expects to have
2127 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2128 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2129 // just before entering the VST subblock because: 1) the EnterSubBlock
2130 // changes the AbbrevID width; 2) the VST block is nested within the same
2131 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2132 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2133 // jump to the FUNCTION_BLOCK using this offset later, we don't want
2134 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2135 unsigned FuncBitcodeOffsetDelta
=
2136 Stream
.getAbbrevIDWidth() + bitc::BlockIDWidth
;
2138 if (Error Err
= Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
2141 SmallVector
<uint64_t, 64> Record
;
2143 Triple
TT(TheModule
->getTargetTriple());
2145 // Read all the records for this value table.
2146 SmallString
<128> ValueName
;
2149 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2151 return MaybeEntry
.takeError();
2152 BitstreamEntry Entry
= MaybeEntry
.get();
2154 switch (Entry
.Kind
) {
2155 case BitstreamEntry::SubBlock
: // Handled for us already.
2156 case BitstreamEntry::Error
:
2157 return error("Malformed block");
2158 case BitstreamEntry::EndBlock
:
2160 if (Error JumpFailed
= Stream
.JumpToBit(CurrentBit
))
2162 return Error::success();
2163 case BitstreamEntry::Record
:
2164 // The interesting case.
2170 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2172 return MaybeRecord
.takeError();
2173 switch (MaybeRecord
.get()) {
2174 default: // Default behavior: unknown type.
2176 case bitc::VST_CODE_ENTRY
: { // VST_CODE_ENTRY: [valueid, namechar x N]
2177 Expected
<Value
*> ValOrErr
= recordValue(Record
, 1, TT
);
2178 if (Error Err
= ValOrErr
.takeError())
2183 case bitc::VST_CODE_FNENTRY
: {
2184 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2185 Expected
<Value
*> ValOrErr
= recordValue(Record
, 2, TT
);
2186 if (Error Err
= ValOrErr
.takeError())
2188 Value
*V
= ValOrErr
.get();
2190 // Ignore function offsets emitted for aliases of functions in older
2191 // versions of LLVM.
2192 if (auto *F
= dyn_cast
<Function
>(V
))
2193 setDeferredFunctionInfo(FuncBitcodeOffsetDelta
, F
, Record
);
2196 case bitc::VST_CODE_BBENTRY
: {
2197 if (convertToString(Record
, 1, ValueName
))
2198 return error("Invalid record");
2199 BasicBlock
*BB
= getBasicBlock(Record
[0]);
2201 return error("Invalid record");
2203 BB
->setName(StringRef(ValueName
.data(), ValueName
.size()));
2211 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2213 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V
) {
2218 // There is no such thing as -0 with integers. "-0" really means MININT.
2222 /// Resolve all of the initializers for global values and aliases that we can.
2223 Error
BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2224 std::vector
<std::pair
<GlobalVariable
*, unsigned>> GlobalInitWorklist
;
2225 std::vector
<std::pair
<GlobalIndirectSymbol
*, unsigned>>
2226 IndirectSymbolInitWorklist
;
2227 std::vector
<std::pair
<Function
*, unsigned>> FunctionPrefixWorklist
;
2228 std::vector
<std::pair
<Function
*, unsigned>> FunctionPrologueWorklist
;
2229 std::vector
<std::pair
<Function
*, unsigned>> FunctionPersonalityFnWorklist
;
2231 GlobalInitWorklist
.swap(GlobalInits
);
2232 IndirectSymbolInitWorklist
.swap(IndirectSymbolInits
);
2233 FunctionPrefixWorklist
.swap(FunctionPrefixes
);
2234 FunctionPrologueWorklist
.swap(FunctionPrologues
);
2235 FunctionPersonalityFnWorklist
.swap(FunctionPersonalityFns
);
2237 while (!GlobalInitWorklist
.empty()) {
2238 unsigned ValID
= GlobalInitWorklist
.back().second
;
2239 if (ValID
>= ValueList
.size()) {
2240 // Not ready to resolve this yet, it requires something later in the file.
2241 GlobalInits
.push_back(GlobalInitWorklist
.back());
2243 if (Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]))
2244 GlobalInitWorklist
.back().first
->setInitializer(C
);
2246 return error("Expected a constant");
2248 GlobalInitWorklist
.pop_back();
2251 while (!IndirectSymbolInitWorklist
.empty()) {
2252 unsigned ValID
= IndirectSymbolInitWorklist
.back().second
;
2253 if (ValID
>= ValueList
.size()) {
2254 IndirectSymbolInits
.push_back(IndirectSymbolInitWorklist
.back());
2256 Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]);
2258 return error("Expected a constant");
2259 GlobalIndirectSymbol
*GIS
= IndirectSymbolInitWorklist
.back().first
;
2260 if (isa
<GlobalAlias
>(GIS
) && C
->getType() != GIS
->getType())
2261 return error("Alias and aliasee types don't match");
2262 GIS
->setIndirectSymbol(C
);
2264 IndirectSymbolInitWorklist
.pop_back();
2267 while (!FunctionPrefixWorklist
.empty()) {
2268 unsigned ValID
= FunctionPrefixWorklist
.back().second
;
2269 if (ValID
>= ValueList
.size()) {
2270 FunctionPrefixes
.push_back(FunctionPrefixWorklist
.back());
2272 if (Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]))
2273 FunctionPrefixWorklist
.back().first
->setPrefixData(C
);
2275 return error("Expected a constant");
2277 FunctionPrefixWorklist
.pop_back();
2280 while (!FunctionPrologueWorklist
.empty()) {
2281 unsigned ValID
= FunctionPrologueWorklist
.back().second
;
2282 if (ValID
>= ValueList
.size()) {
2283 FunctionPrologues
.push_back(FunctionPrologueWorklist
.back());
2285 if (Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]))
2286 FunctionPrologueWorklist
.back().first
->setPrologueData(C
);
2288 return error("Expected a constant");
2290 FunctionPrologueWorklist
.pop_back();
2293 while (!FunctionPersonalityFnWorklist
.empty()) {
2294 unsigned ValID
= FunctionPersonalityFnWorklist
.back().second
;
2295 if (ValID
>= ValueList
.size()) {
2296 FunctionPersonalityFns
.push_back(FunctionPersonalityFnWorklist
.back());
2298 if (Constant
*C
= dyn_cast_or_null
<Constant
>(ValueList
[ValID
]))
2299 FunctionPersonalityFnWorklist
.back().first
->setPersonalityFn(C
);
2301 return error("Expected a constant");
2303 FunctionPersonalityFnWorklist
.pop_back();
2306 return Error::success();
2309 static APInt
readWideAPInt(ArrayRef
<uint64_t> Vals
, unsigned TypeBits
) {
2310 SmallVector
<uint64_t, 8> Words(Vals
.size());
2311 transform(Vals
, Words
.begin(),
2312 BitcodeReader::decodeSignRotatedValue
);
2314 return APInt(TypeBits
, Words
);
2317 Error
BitcodeReader::parseConstants() {
2318 if (Error Err
= Stream
.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID
))
2321 SmallVector
<uint64_t, 64> Record
;
2323 // Read all the records for this value table.
2324 Type
*CurTy
= Type::getInt32Ty(Context
);
2325 Type
*CurFullTy
= Type::getInt32Ty(Context
);
2326 unsigned NextCstNo
= ValueList
.size();
2329 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2331 return MaybeEntry
.takeError();
2332 BitstreamEntry Entry
= MaybeEntry
.get();
2334 switch (Entry
.Kind
) {
2335 case BitstreamEntry::SubBlock
: // Handled for us already.
2336 case BitstreamEntry::Error
:
2337 return error("Malformed block");
2338 case BitstreamEntry::EndBlock
:
2339 if (NextCstNo
!= ValueList
.size())
2340 return error("Invalid constant reference");
2342 // Once all the constants have been read, go through and resolve forward
2344 ValueList
.resolveConstantForwardRefs();
2345 return Error::success();
2346 case BitstreamEntry::Record
:
2347 // The interesting case.
2353 Type
*VoidType
= Type::getVoidTy(Context
);
2355 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
2357 return MaybeBitCode
.takeError();
2358 switch (unsigned BitCode
= MaybeBitCode
.get()) {
2359 default: // Default behavior: unknown constant
2360 case bitc::CST_CODE_UNDEF
: // UNDEF
2361 V
= UndefValue::get(CurTy
);
2363 case bitc::CST_CODE_SETTYPE
: // SETTYPE: [typeid]
2365 return error("Invalid record");
2366 if (Record
[0] >= TypeList
.size() || !TypeList
[Record
[0]])
2367 return error("Invalid record");
2368 if (TypeList
[Record
[0]] == VoidType
)
2369 return error("Invalid constant type");
2370 CurFullTy
= TypeList
[Record
[0]];
2371 CurTy
= flattenPointerTypes(CurFullTy
);
2372 continue; // Skip the ValueList manipulation.
2373 case bitc::CST_CODE_NULL
: // NULL
2374 V
= Constant::getNullValue(CurTy
);
2376 case bitc::CST_CODE_INTEGER
: // INTEGER: [intval]
2377 if (!CurTy
->isIntegerTy() || Record
.empty())
2378 return error("Invalid record");
2379 V
= ConstantInt::get(CurTy
, decodeSignRotatedValue(Record
[0]));
2381 case bitc::CST_CODE_WIDE_INTEGER
: {// WIDE_INTEGER: [n x intval]
2382 if (!CurTy
->isIntegerTy() || Record
.empty())
2383 return error("Invalid record");
2386 readWideAPInt(Record
, cast
<IntegerType
>(CurTy
)->getBitWidth());
2387 V
= ConstantInt::get(Context
, VInt
);
2391 case bitc::CST_CODE_FLOAT
: { // FLOAT: [fpval]
2393 return error("Invalid record");
2394 if (CurTy
->isHalfTy())
2395 V
= ConstantFP::get(Context
, APFloat(APFloat::IEEEhalf(),
2396 APInt(16, (uint16_t)Record
[0])));
2397 else if (CurTy
->isFloatTy())
2398 V
= ConstantFP::get(Context
, APFloat(APFloat::IEEEsingle(),
2399 APInt(32, (uint32_t)Record
[0])));
2400 else if (CurTy
->isDoubleTy())
2401 V
= ConstantFP::get(Context
, APFloat(APFloat::IEEEdouble(),
2402 APInt(64, Record
[0])));
2403 else if (CurTy
->isX86_FP80Ty()) {
2404 // Bits are not stored the same way as a normal i80 APInt, compensate.
2405 uint64_t Rearrange
[2];
2406 Rearrange
[0] = (Record
[1] & 0xffffLL
) | (Record
[0] << 16);
2407 Rearrange
[1] = Record
[0] >> 48;
2408 V
= ConstantFP::get(Context
, APFloat(APFloat::x87DoubleExtended(),
2409 APInt(80, Rearrange
)));
2410 } else if (CurTy
->isFP128Ty())
2411 V
= ConstantFP::get(Context
, APFloat(APFloat::IEEEquad(),
2412 APInt(128, Record
)));
2413 else if (CurTy
->isPPC_FP128Ty())
2414 V
= ConstantFP::get(Context
, APFloat(APFloat::PPCDoubleDouble(),
2415 APInt(128, Record
)));
2417 V
= UndefValue::get(CurTy
);
2421 case bitc::CST_CODE_AGGREGATE
: {// AGGREGATE: [n x value number]
2423 return error("Invalid record");
2425 unsigned Size
= Record
.size();
2426 SmallVector
<Constant
*, 16> Elts
;
2428 if (StructType
*STy
= dyn_cast
<StructType
>(CurTy
)) {
2429 for (unsigned i
= 0; i
!= Size
; ++i
)
2430 Elts
.push_back(ValueList
.getConstantFwdRef(Record
[i
],
2431 STy
->getElementType(i
)));
2432 V
= ConstantStruct::get(STy
, Elts
);
2433 } else if (ArrayType
*ATy
= dyn_cast
<ArrayType
>(CurTy
)) {
2434 Type
*EltTy
= ATy
->getElementType();
2435 for (unsigned i
= 0; i
!= Size
; ++i
)
2436 Elts
.push_back(ValueList
.getConstantFwdRef(Record
[i
], EltTy
));
2437 V
= ConstantArray::get(ATy
, Elts
);
2438 } else if (VectorType
*VTy
= dyn_cast
<VectorType
>(CurTy
)) {
2439 Type
*EltTy
= VTy
->getElementType();
2440 for (unsigned i
= 0; i
!= Size
; ++i
)
2441 Elts
.push_back(ValueList
.getConstantFwdRef(Record
[i
], EltTy
));
2442 V
= ConstantVector::get(Elts
);
2444 V
= UndefValue::get(CurTy
);
2448 case bitc::CST_CODE_STRING
: // STRING: [values]
2449 case bitc::CST_CODE_CSTRING
: { // CSTRING: [values]
2451 return error("Invalid record");
2453 SmallString
<16> Elts(Record
.begin(), Record
.end());
2454 V
= ConstantDataArray::getString(Context
, Elts
,
2455 BitCode
== bitc::CST_CODE_CSTRING
);
2458 case bitc::CST_CODE_DATA
: {// DATA: [n x value]
2460 return error("Invalid record");
2462 Type
*EltTy
= cast
<SequentialType
>(CurTy
)->getElementType();
2463 if (EltTy
->isIntegerTy(8)) {
2464 SmallVector
<uint8_t, 16> Elts(Record
.begin(), Record
.end());
2465 if (isa
<VectorType
>(CurTy
))
2466 V
= ConstantDataVector::get(Context
, Elts
);
2468 V
= ConstantDataArray::get(Context
, Elts
);
2469 } else if (EltTy
->isIntegerTy(16)) {
2470 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
2471 if (isa
<VectorType
>(CurTy
))
2472 V
= ConstantDataVector::get(Context
, Elts
);
2474 V
= ConstantDataArray::get(Context
, Elts
);
2475 } else if (EltTy
->isIntegerTy(32)) {
2476 SmallVector
<uint32_t, 16> Elts(Record
.begin(), Record
.end());
2477 if (isa
<VectorType
>(CurTy
))
2478 V
= ConstantDataVector::get(Context
, Elts
);
2480 V
= ConstantDataArray::get(Context
, Elts
);
2481 } else if (EltTy
->isIntegerTy(64)) {
2482 SmallVector
<uint64_t, 16> Elts(Record
.begin(), Record
.end());
2483 if (isa
<VectorType
>(CurTy
))
2484 V
= ConstantDataVector::get(Context
, Elts
);
2486 V
= ConstantDataArray::get(Context
, Elts
);
2487 } else if (EltTy
->isHalfTy()) {
2488 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
2489 if (isa
<VectorType
>(CurTy
))
2490 V
= ConstantDataVector::getFP(Context
, Elts
);
2492 V
= ConstantDataArray::getFP(Context
, Elts
);
2493 } else if (EltTy
->isFloatTy()) {
2494 SmallVector
<uint32_t, 16> Elts(Record
.begin(), Record
.end());
2495 if (isa
<VectorType
>(CurTy
))
2496 V
= ConstantDataVector::getFP(Context
, Elts
);
2498 V
= ConstantDataArray::getFP(Context
, Elts
);
2499 } else if (EltTy
->isDoubleTy()) {
2500 SmallVector
<uint64_t, 16> Elts(Record
.begin(), Record
.end());
2501 if (isa
<VectorType
>(CurTy
))
2502 V
= ConstantDataVector::getFP(Context
, Elts
);
2504 V
= ConstantDataArray::getFP(Context
, Elts
);
2506 return error("Invalid type for value");
2510 case bitc::CST_CODE_CE_UNOP
: { // CE_UNOP: [opcode, opval]
2511 if (Record
.size() < 2)
2512 return error("Invalid record");
2513 int Opc
= getDecodedUnaryOpcode(Record
[0], CurTy
);
2515 V
= UndefValue::get(CurTy
); // Unknown unop.
2517 Constant
*LHS
= ValueList
.getConstantFwdRef(Record
[1], CurTy
);
2519 V
= ConstantExpr::get(Opc
, LHS
, Flags
);
2523 case bitc::CST_CODE_CE_BINOP
: { // CE_BINOP: [opcode, opval, opval]
2524 if (Record
.size() < 3)
2525 return error("Invalid record");
2526 int Opc
= getDecodedBinaryOpcode(Record
[0], CurTy
);
2528 V
= UndefValue::get(CurTy
); // Unknown binop.
2530 Constant
*LHS
= ValueList
.getConstantFwdRef(Record
[1], CurTy
);
2531 Constant
*RHS
= ValueList
.getConstantFwdRef(Record
[2], CurTy
);
2533 if (Record
.size() >= 4) {
2534 if (Opc
== Instruction::Add
||
2535 Opc
== Instruction::Sub
||
2536 Opc
== Instruction::Mul
||
2537 Opc
== Instruction::Shl
) {
2538 if (Record
[3] & (1 << bitc::OBO_NO_SIGNED_WRAP
))
2539 Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
2540 if (Record
[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP
))
2541 Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
2542 } else if (Opc
== Instruction::SDiv
||
2543 Opc
== Instruction::UDiv
||
2544 Opc
== Instruction::LShr
||
2545 Opc
== Instruction::AShr
) {
2546 if (Record
[3] & (1 << bitc::PEO_EXACT
))
2547 Flags
|= SDivOperator::IsExact
;
2550 V
= ConstantExpr::get(Opc
, LHS
, RHS
, Flags
);
2554 case bitc::CST_CODE_CE_CAST
: { // CE_CAST: [opcode, opty, opval]
2555 if (Record
.size() < 3)
2556 return error("Invalid record");
2557 int Opc
= getDecodedCastOpcode(Record
[0]);
2559 V
= UndefValue::get(CurTy
); // Unknown cast.
2561 Type
*OpTy
= getTypeByID(Record
[1]);
2563 return error("Invalid record");
2564 Constant
*Op
= ValueList
.getConstantFwdRef(Record
[2], OpTy
);
2565 V
= UpgradeBitCastExpr(Opc
, Op
, CurTy
);
2566 if (!V
) V
= ConstantExpr::getCast(Opc
, Op
, CurTy
);
2570 case bitc::CST_CODE_CE_INBOUNDS_GEP
: // [ty, n x operands]
2571 case bitc::CST_CODE_CE_GEP
: // [ty, n x operands]
2572 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX
: { // [ty, flags, n x
2575 Type
*PointeeType
= nullptr;
2576 if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX
||
2578 PointeeType
= getTypeByID(Record
[OpNum
++]);
2580 bool InBounds
= false;
2581 Optional
<unsigned> InRangeIndex
;
2582 if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX
) {
2583 uint64_t Op
= Record
[OpNum
++];
2585 InRangeIndex
= Op
>> 1;
2586 } else if (BitCode
== bitc::CST_CODE_CE_INBOUNDS_GEP
)
2589 SmallVector
<Constant
*, 16> Elts
;
2590 Type
*Elt0FullTy
= nullptr;
2591 while (OpNum
!= Record
.size()) {
2593 Elt0FullTy
= getFullyStructuredTypeByID(Record
[OpNum
]);
2594 Type
*ElTy
= getTypeByID(Record
[OpNum
++]);
2596 return error("Invalid record");
2597 Elts
.push_back(ValueList
.getConstantFwdRef(Record
[OpNum
++], ElTy
));
2600 if (Elts
.size() < 1)
2601 return error("Invalid gep with no operands");
2603 Type
*ImplicitPointeeType
=
2604 getPointerElementFlatType(Elt0FullTy
->getScalarType());
2606 PointeeType
= ImplicitPointeeType
;
2607 else if (PointeeType
!= ImplicitPointeeType
)
2608 return error("Explicit gep operator type does not match pointee type "
2609 "of pointer operand");
2611 ArrayRef
<Constant
*> Indices(Elts
.begin() + 1, Elts
.end());
2612 V
= ConstantExpr::getGetElementPtr(PointeeType
, Elts
[0], Indices
,
2613 InBounds
, InRangeIndex
);
2616 case bitc::CST_CODE_CE_SELECT
: { // CE_SELECT: [opval#, opval#, opval#]
2617 if (Record
.size() < 3)
2618 return error("Invalid record");
2620 Type
*SelectorTy
= Type::getInt1Ty(Context
);
2622 // The selector might be an i1 or an <n x i1>
2623 // Get the type from the ValueList before getting a forward ref.
2624 if (VectorType
*VTy
= dyn_cast
<VectorType
>(CurTy
))
2625 if (Value
*V
= ValueList
[Record
[0]])
2626 if (SelectorTy
!= V
->getType())
2627 SelectorTy
= VectorType::get(SelectorTy
, VTy
->getNumElements());
2629 V
= ConstantExpr::getSelect(ValueList
.getConstantFwdRef(Record
[0],
2631 ValueList
.getConstantFwdRef(Record
[1],CurTy
),
2632 ValueList
.getConstantFwdRef(Record
[2],CurTy
));
2635 case bitc::CST_CODE_CE_EXTRACTELT
2636 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2637 if (Record
.size() < 3)
2638 return error("Invalid record");
2640 dyn_cast_or_null
<VectorType
>(getTypeByID(Record
[0]));
2642 return error("Invalid record");
2643 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[1], OpTy
);
2644 Constant
*Op1
= nullptr;
2645 if (Record
.size() == 4) {
2646 Type
*IdxTy
= getTypeByID(Record
[2]);
2648 return error("Invalid record");
2649 Op1
= ValueList
.getConstantFwdRef(Record
[3], IdxTy
);
2650 } else // TODO: Remove with llvm 4.0
2651 Op1
= ValueList
.getConstantFwdRef(Record
[2], Type::getInt32Ty(Context
));
2653 return error("Invalid record");
2654 V
= ConstantExpr::getExtractElement(Op0
, Op1
);
2657 case bitc::CST_CODE_CE_INSERTELT
2658 : { // CE_INSERTELT: [opval, opval, opty, opval]
2659 VectorType
*OpTy
= dyn_cast
<VectorType
>(CurTy
);
2660 if (Record
.size() < 3 || !OpTy
)
2661 return error("Invalid record");
2662 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[0], OpTy
);
2663 Constant
*Op1
= ValueList
.getConstantFwdRef(Record
[1],
2664 OpTy
->getElementType());
2665 Constant
*Op2
= nullptr;
2666 if (Record
.size() == 4) {
2667 Type
*IdxTy
= getTypeByID(Record
[2]);
2669 return error("Invalid record");
2670 Op2
= ValueList
.getConstantFwdRef(Record
[3], IdxTy
);
2671 } else // TODO: Remove with llvm 4.0
2672 Op2
= ValueList
.getConstantFwdRef(Record
[2], Type::getInt32Ty(Context
));
2674 return error("Invalid record");
2675 V
= ConstantExpr::getInsertElement(Op0
, Op1
, Op2
);
2678 case bitc::CST_CODE_CE_SHUFFLEVEC
: { // CE_SHUFFLEVEC: [opval, opval, opval]
2679 VectorType
*OpTy
= dyn_cast
<VectorType
>(CurTy
);
2680 if (Record
.size() < 3 || !OpTy
)
2681 return error("Invalid record");
2682 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[0], OpTy
);
2683 Constant
*Op1
= ValueList
.getConstantFwdRef(Record
[1], OpTy
);
2684 Type
*ShufTy
= VectorType::get(Type::getInt32Ty(Context
),
2685 OpTy
->getNumElements());
2686 Constant
*Op2
= ValueList
.getConstantFwdRef(Record
[2], ShufTy
);
2687 V
= ConstantExpr::getShuffleVector(Op0
, Op1
, Op2
);
2690 case bitc::CST_CODE_CE_SHUFVEC_EX
: { // [opty, opval, opval, opval]
2691 VectorType
*RTy
= dyn_cast
<VectorType
>(CurTy
);
2693 dyn_cast_or_null
<VectorType
>(getTypeByID(Record
[0]));
2694 if (Record
.size() < 4 || !RTy
|| !OpTy
)
2695 return error("Invalid record");
2696 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[1], OpTy
);
2697 Constant
*Op1
= ValueList
.getConstantFwdRef(Record
[2], OpTy
);
2698 Type
*ShufTy
= VectorType::get(Type::getInt32Ty(Context
),
2699 RTy
->getNumElements());
2700 Constant
*Op2
= ValueList
.getConstantFwdRef(Record
[3], ShufTy
);
2701 V
= ConstantExpr::getShuffleVector(Op0
, Op1
, Op2
);
2704 case bitc::CST_CODE_CE_CMP
: { // CE_CMP: [opty, opval, opval, pred]
2705 if (Record
.size() < 4)
2706 return error("Invalid record");
2707 Type
*OpTy
= getTypeByID(Record
[0]);
2709 return error("Invalid record");
2710 Constant
*Op0
= ValueList
.getConstantFwdRef(Record
[1], OpTy
);
2711 Constant
*Op1
= ValueList
.getConstantFwdRef(Record
[2], OpTy
);
2713 if (OpTy
->isFPOrFPVectorTy())
2714 V
= ConstantExpr::getFCmp(Record
[3], Op0
, Op1
);
2716 V
= ConstantExpr::getICmp(Record
[3], Op0
, Op1
);
2719 // This maintains backward compatibility, pre-asm dialect keywords.
2720 // FIXME: Remove with the 4.0 release.
2721 case bitc::CST_CODE_INLINEASM_OLD
: {
2722 if (Record
.size() < 2)
2723 return error("Invalid record");
2724 std::string AsmStr
, ConstrStr
;
2725 bool HasSideEffects
= Record
[0] & 1;
2726 bool IsAlignStack
= Record
[0] >> 1;
2727 unsigned AsmStrSize
= Record
[1];
2728 if (2+AsmStrSize
>= Record
.size())
2729 return error("Invalid record");
2730 unsigned ConstStrSize
= Record
[2+AsmStrSize
];
2731 if (3+AsmStrSize
+ConstStrSize
> Record
.size())
2732 return error("Invalid record");
2734 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
2735 AsmStr
+= (char)Record
[2+i
];
2736 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
2737 ConstrStr
+= (char)Record
[3+AsmStrSize
+i
];
2738 UpgradeInlineAsmString(&AsmStr
);
2740 cast
<FunctionType
>(getPointerElementFlatType(CurFullTy
)), AsmStr
,
2741 ConstrStr
, HasSideEffects
, IsAlignStack
);
2744 // This version adds support for the asm dialect keywords (e.g.,
2746 case bitc::CST_CODE_INLINEASM
: {
2747 if (Record
.size() < 2)
2748 return error("Invalid record");
2749 std::string AsmStr
, ConstrStr
;
2750 bool HasSideEffects
= Record
[0] & 1;
2751 bool IsAlignStack
= (Record
[0] >> 1) & 1;
2752 unsigned AsmDialect
= Record
[0] >> 2;
2753 unsigned AsmStrSize
= Record
[1];
2754 if (2+AsmStrSize
>= Record
.size())
2755 return error("Invalid record");
2756 unsigned ConstStrSize
= Record
[2+AsmStrSize
];
2757 if (3+AsmStrSize
+ConstStrSize
> Record
.size())
2758 return error("Invalid record");
2760 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
2761 AsmStr
+= (char)Record
[2+i
];
2762 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
2763 ConstrStr
+= (char)Record
[3+AsmStrSize
+i
];
2764 UpgradeInlineAsmString(&AsmStr
);
2766 cast
<FunctionType
>(getPointerElementFlatType(CurFullTy
)), AsmStr
,
2767 ConstrStr
, HasSideEffects
, IsAlignStack
,
2768 InlineAsm::AsmDialect(AsmDialect
));
2771 case bitc::CST_CODE_BLOCKADDRESS
:{
2772 if (Record
.size() < 3)
2773 return error("Invalid record");
2774 Type
*FnTy
= getTypeByID(Record
[0]);
2776 return error("Invalid record");
2778 dyn_cast_or_null
<Function
>(ValueList
.getConstantFwdRef(Record
[1],FnTy
));
2780 return error("Invalid record");
2782 // If the function is already parsed we can insert the block address right
2785 unsigned BBID
= Record
[2];
2787 // Invalid reference to entry block.
2788 return error("Invalid ID");
2790 Function::iterator BBI
= Fn
->begin(), BBE
= Fn
->end();
2791 for (size_t I
= 0, E
= BBID
; I
!= E
; ++I
) {
2793 return error("Invalid ID");
2798 // Otherwise insert a placeholder and remember it so it can be inserted
2799 // when the function is parsed.
2800 auto &FwdBBs
= BasicBlockFwdRefs
[Fn
];
2802 BasicBlockFwdRefQueue
.push_back(Fn
);
2803 if (FwdBBs
.size() < BBID
+ 1)
2804 FwdBBs
.resize(BBID
+ 1);
2806 FwdBBs
[BBID
] = BasicBlock::Create(Context
);
2809 V
= BlockAddress::get(Fn
, BB
);
2814 assert(V
->getType() == flattenPointerTypes(CurFullTy
) &&
2815 "Incorrect fully structured type provided for Constant");
2816 ValueList
.assignValue(V
, NextCstNo
, CurFullTy
);
2821 Error
BitcodeReader::parseUseLists() {
2822 if (Error Err
= Stream
.EnterSubBlock(bitc::USELIST_BLOCK_ID
))
2825 // Read all the records.
2826 SmallVector
<uint64_t, 64> Record
;
2829 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2831 return MaybeEntry
.takeError();
2832 BitstreamEntry Entry
= MaybeEntry
.get();
2834 switch (Entry
.Kind
) {
2835 case BitstreamEntry::SubBlock
: // Handled for us already.
2836 case BitstreamEntry::Error
:
2837 return error("Malformed block");
2838 case BitstreamEntry::EndBlock
:
2839 return Error::success();
2840 case BitstreamEntry::Record
:
2841 // The interesting case.
2845 // Read a use list record.
2848 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2850 return MaybeRecord
.takeError();
2851 switch (MaybeRecord
.get()) {
2852 default: // Default behavior: unknown type.
2854 case bitc::USELIST_CODE_BB
:
2857 case bitc::USELIST_CODE_DEFAULT
: {
2858 unsigned RecordLength
= Record
.size();
2859 if (RecordLength
< 3)
2860 // Records should have at least an ID and two indexes.
2861 return error("Invalid record");
2862 unsigned ID
= Record
.back();
2867 assert(ID
< FunctionBBs
.size() && "Basic block not found");
2868 V
= FunctionBBs
[ID
];
2871 unsigned NumUses
= 0;
2872 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
2873 for (const Use
&U
: V
->materialized_uses()) {
2874 if (++NumUses
> Record
.size())
2876 Order
[&U
] = Record
[NumUses
- 1];
2878 if (Order
.size() != Record
.size() || NumUses
> Record
.size())
2879 // Mismatches can happen if the functions are being materialized lazily
2880 // (out-of-order), or a value has been upgraded.
2883 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
2884 return Order
.lookup(&L
) < Order
.lookup(&R
);
2892 /// When we see the block for metadata, remember where it is and then skip it.
2893 /// This lets us lazily deserialize the metadata.
2894 Error
BitcodeReader::rememberAndSkipMetadata() {
2895 // Save the current stream state.
2896 uint64_t CurBit
= Stream
.GetCurrentBitNo();
2897 DeferredMetadataInfo
.push_back(CurBit
);
2899 // Skip over the block for now.
2900 if (Error Err
= Stream
.SkipBlock())
2902 return Error::success();
2905 Error
BitcodeReader::materializeMetadata() {
2906 for (uint64_t BitPos
: DeferredMetadataInfo
) {
2907 // Move the bit stream to the saved position.
2908 if (Error JumpFailed
= Stream
.JumpToBit(BitPos
))
2910 if (Error Err
= MDLoader
->parseModuleMetadata())
2914 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2916 if (Metadata
*Val
= TheModule
->getModuleFlag("Linker Options")) {
2917 NamedMDNode
*LinkerOpts
=
2918 TheModule
->getOrInsertNamedMetadata("llvm.linker.options");
2919 for (const MDOperand
&MDOptions
: cast
<MDNode
>(Val
)->operands())
2920 LinkerOpts
->addOperand(cast
<MDNode
>(MDOptions
));
2923 DeferredMetadataInfo
.clear();
2924 return Error::success();
2927 void BitcodeReader::setStripDebugInfo() { StripDebugInfo
= true; }
2929 /// When we see the block for a function body, remember where it is and then
2930 /// skip it. This lets us lazily deserialize the functions.
2931 Error
BitcodeReader::rememberAndSkipFunctionBody() {
2932 // Get the function we are talking about.
2933 if (FunctionsWithBodies
.empty())
2934 return error("Insufficient function protos");
2936 Function
*Fn
= FunctionsWithBodies
.back();
2937 FunctionsWithBodies
.pop_back();
2939 // Save the current stream state.
2940 uint64_t CurBit
= Stream
.GetCurrentBitNo();
2942 (DeferredFunctionInfo
[Fn
] == 0 || DeferredFunctionInfo
[Fn
] == CurBit
) &&
2943 "Mismatch between VST and scanned function offsets");
2944 DeferredFunctionInfo
[Fn
] = CurBit
;
2946 // Skip over the function block for now.
2947 if (Error Err
= Stream
.SkipBlock())
2949 return Error::success();
2952 Error
BitcodeReader::globalCleanup() {
2953 // Patch the initializers for globals and aliases up.
2954 if (Error Err
= resolveGlobalAndIndirectSymbolInits())
2956 if (!GlobalInits
.empty() || !IndirectSymbolInits
.empty())
2957 return error("Malformed global initializer set");
2959 // Look for intrinsic functions which need to be upgraded at some point
2960 for (Function
&F
: *TheModule
) {
2961 MDLoader
->upgradeDebugIntrinsics(F
);
2963 if (UpgradeIntrinsicFunction(&F
, NewFn
))
2964 UpgradedIntrinsics
[&F
] = NewFn
;
2965 else if (auto Remangled
= Intrinsic::remangleIntrinsicFunction(&F
))
2966 // Some types could be renamed during loading if several modules are
2967 // loaded in the same LLVMContext (LTO scenario). In this case we should
2968 // remangle intrinsics names as well.
2969 RemangledIntrinsics
[&F
] = Remangled
.getValue();
2972 // Look for global variables which need to be renamed.
2973 std::vector
<std::pair
<GlobalVariable
*, GlobalVariable
*>> UpgradedVariables
;
2974 for (GlobalVariable
&GV
: TheModule
->globals())
2975 if (GlobalVariable
*Upgraded
= UpgradeGlobalVariable(&GV
))
2976 UpgradedVariables
.emplace_back(&GV
, Upgraded
);
2977 for (auto &Pair
: UpgradedVariables
) {
2978 Pair
.first
->eraseFromParent();
2979 TheModule
->getGlobalList().push_back(Pair
.second
);
2982 // Force deallocation of memory for these vectors to favor the client that
2983 // want lazy deserialization.
2984 std::vector
<std::pair
<GlobalVariable
*, unsigned>>().swap(GlobalInits
);
2985 std::vector
<std::pair
<GlobalIndirectSymbol
*, unsigned>>().swap(
2986 IndirectSymbolInits
);
2987 return Error::success();
2990 /// Support for lazy parsing of function bodies. This is required if we
2991 /// either have an old bitcode file without a VST forward declaration record,
2992 /// or if we have an anonymous function being materialized, since anonymous
2993 /// functions do not have a name and are therefore not in the VST.
2994 Error
BitcodeReader::rememberAndSkipFunctionBodies() {
2995 if (Error JumpFailed
= Stream
.JumpToBit(NextUnreadBit
))
2998 if (Stream
.AtEndOfStream())
2999 return error("Could not find function in stream");
3001 if (!SeenFirstFunctionBody
)
3002 return error("Trying to materialize functions before seeing function blocks");
3004 // An old bitcode file with the symbol table at the end would have
3005 // finished the parse greedily.
3006 assert(SeenValueSymbolTable
);
3008 SmallVector
<uint64_t, 64> Record
;
3011 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
3013 return MaybeEntry
.takeError();
3014 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
3016 switch (Entry
.Kind
) {
3018 return error("Expect SubBlock");
3019 case BitstreamEntry::SubBlock
:
3022 return error("Expect function block");
3023 case bitc::FUNCTION_BLOCK_ID
:
3024 if (Error Err
= rememberAndSkipFunctionBody())
3026 NextUnreadBit
= Stream
.GetCurrentBitNo();
3027 return Error::success();
3033 bool BitcodeReaderBase::readBlockInfo() {
3034 Expected
<Optional
<BitstreamBlockInfo
>> MaybeNewBlockInfo
=
3035 Stream
.ReadBlockInfoBlock();
3036 if (!MaybeNewBlockInfo
)
3037 return true; // FIXME Handle the error.
3038 Optional
<BitstreamBlockInfo
> NewBlockInfo
=
3039 std::move(MaybeNewBlockInfo
.get());
3042 BlockInfo
= std::move(*NewBlockInfo
);
3046 Error
BitcodeReader::parseComdatRecord(ArrayRef
<uint64_t> Record
) {
3047 // v1: [selection_kind, name]
3048 // v2: [strtab_offset, strtab_size, selection_kind]
3050 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
3053 return error("Invalid record");
3054 Comdat::SelectionKind SK
= getDecodedComdatSelectionKind(Record
[0]);
3055 std::string OldFormatName
;
3057 if (Record
.size() < 2)
3058 return error("Invalid record");
3059 unsigned ComdatNameSize
= Record
[1];
3060 OldFormatName
.reserve(ComdatNameSize
);
3061 for (unsigned i
= 0; i
!= ComdatNameSize
; ++i
)
3062 OldFormatName
+= (char)Record
[2 + i
];
3063 Name
= OldFormatName
;
3065 Comdat
*C
= TheModule
->getOrInsertComdat(Name
);
3066 C
->setSelectionKind(SK
);
3067 ComdatList
.push_back(C
);
3068 return Error::success();
3071 static void inferDSOLocal(GlobalValue
*GV
) {
3072 // infer dso_local from linkage and visibility if it is not encoded.
3073 if (GV
->hasLocalLinkage() ||
3074 (!GV
->hasDefaultVisibility() && !GV
->hasExternalWeakLinkage()))
3075 GV
->setDSOLocal(true);
3078 Error
BitcodeReader::parseGlobalVarRecord(ArrayRef
<uint64_t> Record
) {
3079 // v1: [pointer type, isconst, initid, linkage, alignment, section,
3080 // visibility, threadlocal, unnamed_addr, externally_initialized,
3081 // dllstorageclass, comdat, attributes, preemption specifier,
3082 // partition strtab offset, partition strtab size] (name in VST)
3083 // v2: [strtab_offset, strtab_size, v1]
3085 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
3087 if (Record
.size() < 6)
3088 return error("Invalid record");
3089 Type
*FullTy
= getFullyStructuredTypeByID(Record
[0]);
3090 Type
*Ty
= flattenPointerTypes(FullTy
);
3092 return error("Invalid record");
3093 bool isConstant
= Record
[1] & 1;
3094 bool explicitType
= Record
[1] & 2;
3095 unsigned AddressSpace
;
3097 AddressSpace
= Record
[1] >> 2;
3099 if (!Ty
->isPointerTy())
3100 return error("Invalid type for value");
3101 AddressSpace
= cast
<PointerType
>(Ty
)->getAddressSpace();
3102 std::tie(FullTy
, Ty
) = getPointerElementTypes(FullTy
);
3105 uint64_t RawLinkage
= Record
[3];
3106 GlobalValue::LinkageTypes Linkage
= getDecodedLinkage(RawLinkage
);
3108 if (Error Err
= parseAlignmentValue(Record
[4], Alignment
))
3110 std::string Section
;
3112 if (Record
[5] - 1 >= SectionTable
.size())
3113 return error("Invalid ID");
3114 Section
= SectionTable
[Record
[5] - 1];
3116 GlobalValue::VisibilityTypes Visibility
= GlobalValue::DefaultVisibility
;
3117 // Local linkage must have default visibility.
3118 if (Record
.size() > 6 && !GlobalValue::isLocalLinkage(Linkage
))
3119 // FIXME: Change to an error if non-default in 4.0.
3120 Visibility
= getDecodedVisibility(Record
[6]);
3122 GlobalVariable::ThreadLocalMode TLM
= GlobalVariable::NotThreadLocal
;
3123 if (Record
.size() > 7)
3124 TLM
= getDecodedThreadLocalMode(Record
[7]);
3126 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
3127 if (Record
.size() > 8)
3128 UnnamedAddr
= getDecodedUnnamedAddrType(Record
[8]);
3130 bool ExternallyInitialized
= false;
3131 if (Record
.size() > 9)
3132 ExternallyInitialized
= Record
[9];
3134 GlobalVariable
*NewGV
=
3135 new GlobalVariable(*TheModule
, Ty
, isConstant
, Linkage
, nullptr, Name
,
3136 nullptr, TLM
, AddressSpace
, ExternallyInitialized
);
3137 NewGV
->setAlignment(Alignment
);
3138 if (!Section
.empty())
3139 NewGV
->setSection(Section
);
3140 NewGV
->setVisibility(Visibility
);
3141 NewGV
->setUnnamedAddr(UnnamedAddr
);
3143 if (Record
.size() > 10)
3144 NewGV
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[10]));
3146 upgradeDLLImportExportLinkage(NewGV
, RawLinkage
);
3148 FullTy
= PointerType::get(FullTy
, AddressSpace
);
3149 assert(NewGV
->getType() == flattenPointerTypes(FullTy
) &&
3150 "Incorrect fully specified type for GlobalVariable");
3151 ValueList
.push_back(NewGV
, FullTy
);
3153 // Remember which value to use for the global initializer.
3154 if (unsigned InitID
= Record
[2])
3155 GlobalInits
.push_back(std::make_pair(NewGV
, InitID
- 1));
3157 if (Record
.size() > 11) {
3158 if (unsigned ComdatID
= Record
[11]) {
3159 if (ComdatID
> ComdatList
.size())
3160 return error("Invalid global variable comdat ID");
3161 NewGV
->setComdat(ComdatList
[ComdatID
- 1]);
3163 } else if (hasImplicitComdat(RawLinkage
)) {
3164 NewGV
->setComdat(reinterpret_cast<Comdat
*>(1));
3167 if (Record
.size() > 12) {
3168 auto AS
= getAttributes(Record
[12]).getFnAttributes();
3169 NewGV
->setAttributes(AS
);
3172 if (Record
.size() > 13) {
3173 NewGV
->setDSOLocal(getDecodedDSOLocal(Record
[13]));
3175 inferDSOLocal(NewGV
);
3177 // Check whether we have enough values to read a partition name.
3178 if (Record
.size() > 15)
3179 NewGV
->setPartition(StringRef(Strtab
.data() + Record
[14], Record
[15]));
3181 return Error::success();
3184 Error
BitcodeReader::parseFunctionRecord(ArrayRef
<uint64_t> Record
) {
3185 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3186 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3187 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
3188 // v2: [strtab_offset, strtab_size, v1]
3190 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
3192 if (Record
.size() < 8)
3193 return error("Invalid record");
3194 Type
*FullFTy
= getFullyStructuredTypeByID(Record
[0]);
3195 Type
*FTy
= flattenPointerTypes(FullFTy
);
3197 return error("Invalid record");
3198 if (isa
<PointerType
>(FTy
))
3199 std::tie(FullFTy
, FTy
) = getPointerElementTypes(FullFTy
);
3201 if (!isa
<FunctionType
>(FTy
))
3202 return error("Invalid type for value");
3203 auto CC
= static_cast<CallingConv::ID
>(Record
[1]);
3204 if (CC
& ~CallingConv::MaxID
)
3205 return error("Invalid calling convention ID");
3207 unsigned AddrSpace
= TheModule
->getDataLayout().getProgramAddressSpace();
3208 if (Record
.size() > 16)
3209 AddrSpace
= Record
[16];
3212 Function::Create(cast
<FunctionType
>(FTy
), GlobalValue::ExternalLinkage
,
3213 AddrSpace
, Name
, TheModule
);
3215 assert(Func
->getFunctionType() == flattenPointerTypes(FullFTy
) &&
3216 "Incorrect fully specified type provided for function");
3217 FunctionTypes
[Func
] = cast
<FunctionType
>(FullFTy
);
3219 Func
->setCallingConv(CC
);
3220 bool isProto
= Record
[2];
3221 uint64_t RawLinkage
= Record
[3];
3222 Func
->setLinkage(getDecodedLinkage(RawLinkage
));
3223 Func
->setAttributes(getAttributes(Record
[4]));
3225 // Upgrade any old-style byval without a type by propagating the argument's
3226 // pointee type. There should be no opaque pointers where the byval type is
3228 for (unsigned i
= 0; i
!= Func
->arg_size(); ++i
) {
3229 if (!Func
->hasParamAttribute(i
, Attribute::ByVal
))
3232 Type
*PTy
= cast
<FunctionType
>(FullFTy
)->getParamType(i
);
3233 Func
->removeParamAttr(i
, Attribute::ByVal
);
3234 Func
->addParamAttr(i
, Attribute::getWithByValType(
3235 Context
, getPointerElementFlatType(PTy
)));
3239 if (Error Err
= parseAlignmentValue(Record
[5], Alignment
))
3241 Func
->setAlignment(Alignment
);
3243 if (Record
[6] - 1 >= SectionTable
.size())
3244 return error("Invalid ID");
3245 Func
->setSection(SectionTable
[Record
[6] - 1]);
3247 // Local linkage must have default visibility.
3248 if (!Func
->hasLocalLinkage())
3249 // FIXME: Change to an error if non-default in 4.0.
3250 Func
->setVisibility(getDecodedVisibility(Record
[7]));
3251 if (Record
.size() > 8 && Record
[8]) {
3252 if (Record
[8] - 1 >= GCTable
.size())
3253 return error("Invalid ID");
3254 Func
->setGC(GCTable
[Record
[8] - 1]);
3256 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
3257 if (Record
.size() > 9)
3258 UnnamedAddr
= getDecodedUnnamedAddrType(Record
[9]);
3259 Func
->setUnnamedAddr(UnnamedAddr
);
3260 if (Record
.size() > 10 && Record
[10] != 0)
3261 FunctionPrologues
.push_back(std::make_pair(Func
, Record
[10] - 1));
3263 if (Record
.size() > 11)
3264 Func
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[11]));
3266 upgradeDLLImportExportLinkage(Func
, RawLinkage
);
3268 if (Record
.size() > 12) {
3269 if (unsigned ComdatID
= Record
[12]) {
3270 if (ComdatID
> ComdatList
.size())
3271 return error("Invalid function comdat ID");
3272 Func
->setComdat(ComdatList
[ComdatID
- 1]);
3274 } else if (hasImplicitComdat(RawLinkage
)) {
3275 Func
->setComdat(reinterpret_cast<Comdat
*>(1));
3278 if (Record
.size() > 13 && Record
[13] != 0)
3279 FunctionPrefixes
.push_back(std::make_pair(Func
, Record
[13] - 1));
3281 if (Record
.size() > 14 && Record
[14] != 0)
3282 FunctionPersonalityFns
.push_back(std::make_pair(Func
, Record
[14] - 1));
3284 if (Record
.size() > 15) {
3285 Func
->setDSOLocal(getDecodedDSOLocal(Record
[15]));
3287 inferDSOLocal(Func
);
3289 // Record[16] is the address space number.
3291 // Check whether we have enough values to read a partition name.
3292 if (Record
.size() > 18)
3293 Func
->setPartition(StringRef(Strtab
.data() + Record
[17], Record
[18]));
3295 Type
*FullTy
= PointerType::get(FullFTy
, AddrSpace
);
3296 assert(Func
->getType() == flattenPointerTypes(FullTy
) &&
3297 "Incorrect fully specified type provided for Function");
3298 ValueList
.push_back(Func
, FullTy
);
3300 // If this is a function with a body, remember the prototype we are
3301 // creating now, so that we can match up the body with them later.
3303 Func
->setIsMaterializable(true);
3304 FunctionsWithBodies
.push_back(Func
);
3305 DeferredFunctionInfo
[Func
] = 0;
3307 return Error::success();
3310 Error
BitcodeReader::parseGlobalIndirectSymbolRecord(
3311 unsigned BitCode
, ArrayRef
<uint64_t> Record
) {
3312 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3313 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3314 // dllstorageclass, threadlocal, unnamed_addr,
3315 // preemption specifier] (name in VST)
3316 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3317 // visibility, dllstorageclass, threadlocal, unnamed_addr,
3318 // preemption specifier] (name in VST)
3319 // v2: [strtab_offset, strtab_size, v1]
3321 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
3323 bool NewRecord
= BitCode
!= bitc::MODULE_CODE_ALIAS_OLD
;
3324 if (Record
.size() < (3 + (unsigned)NewRecord
))
3325 return error("Invalid record");
3327 Type
*FullTy
= getFullyStructuredTypeByID(Record
[OpNum
++]);
3328 Type
*Ty
= flattenPointerTypes(FullTy
);
3330 return error("Invalid record");
3334 auto *PTy
= dyn_cast
<PointerType
>(Ty
);
3336 return error("Invalid type for value");
3337 std::tie(FullTy
, Ty
) = getPointerElementTypes(FullTy
);
3338 AddrSpace
= PTy
->getAddressSpace();
3340 AddrSpace
= Record
[OpNum
++];
3343 auto Val
= Record
[OpNum
++];
3344 auto Linkage
= Record
[OpNum
++];
3345 GlobalIndirectSymbol
*NewGA
;
3346 if (BitCode
== bitc::MODULE_CODE_ALIAS
||
3347 BitCode
== bitc::MODULE_CODE_ALIAS_OLD
)
3348 NewGA
= GlobalAlias::create(Ty
, AddrSpace
, getDecodedLinkage(Linkage
), Name
,
3351 NewGA
= GlobalIFunc::create(Ty
, AddrSpace
, getDecodedLinkage(Linkage
), Name
,
3352 nullptr, TheModule
);
3354 assert(NewGA
->getValueType() == flattenPointerTypes(FullTy
) &&
3355 "Incorrect fully structured type provided for GlobalIndirectSymbol");
3356 // Old bitcode files didn't have visibility field.
3357 // Local linkage must have default visibility.
3358 if (OpNum
!= Record
.size()) {
3359 auto VisInd
= OpNum
++;
3360 if (!NewGA
->hasLocalLinkage())
3361 // FIXME: Change to an error if non-default in 4.0.
3362 NewGA
->setVisibility(getDecodedVisibility(Record
[VisInd
]));
3364 if (BitCode
== bitc::MODULE_CODE_ALIAS
||
3365 BitCode
== bitc::MODULE_CODE_ALIAS_OLD
) {
3366 if (OpNum
!= Record
.size())
3367 NewGA
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[OpNum
++]));
3369 upgradeDLLImportExportLinkage(NewGA
, Linkage
);
3370 if (OpNum
!= Record
.size())
3371 NewGA
->setThreadLocalMode(getDecodedThreadLocalMode(Record
[OpNum
++]));
3372 if (OpNum
!= Record
.size())
3373 NewGA
->setUnnamedAddr(getDecodedUnnamedAddrType(Record
[OpNum
++]));
3375 if (OpNum
!= Record
.size())
3376 NewGA
->setDSOLocal(getDecodedDSOLocal(Record
[OpNum
++]));
3377 inferDSOLocal(NewGA
);
3379 // Check whether we have enough values to read a partition name.
3380 if (OpNum
+ 1 < Record
.size()) {
3381 NewGA
->setPartition(
3382 StringRef(Strtab
.data() + Record
[OpNum
], Record
[OpNum
+ 1]));
3386 FullTy
= PointerType::get(FullTy
, AddrSpace
);
3387 assert(NewGA
->getType() == flattenPointerTypes(FullTy
) &&
3388 "Incorrect fully structured type provided for GlobalIndirectSymbol");
3389 ValueList
.push_back(NewGA
, FullTy
);
3390 IndirectSymbolInits
.push_back(std::make_pair(NewGA
, Val
));
3391 return Error::success();
3394 Error
BitcodeReader::parseModule(uint64_t ResumeBit
,
3395 bool ShouldLazyLoadMetadata
) {
3397 if (Error JumpFailed
= Stream
.JumpToBit(ResumeBit
))
3399 } else if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
3402 SmallVector
<uint64_t, 64> Record
;
3404 // Read all the records for this module.
3406 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
3408 return MaybeEntry
.takeError();
3409 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
3411 switch (Entry
.Kind
) {
3412 case BitstreamEntry::Error
:
3413 return error("Malformed block");
3414 case BitstreamEntry::EndBlock
:
3415 return globalCleanup();
3417 case BitstreamEntry::SubBlock
:
3419 default: // Skip unknown content.
3420 if (Error Err
= Stream
.SkipBlock())
3423 case bitc::BLOCKINFO_BLOCK_ID
:
3424 if (readBlockInfo())
3425 return error("Malformed block");
3427 case bitc::PARAMATTR_BLOCK_ID
:
3428 if (Error Err
= parseAttributeBlock())
3431 case bitc::PARAMATTR_GROUP_BLOCK_ID
:
3432 if (Error Err
= parseAttributeGroupBlock())
3435 case bitc::TYPE_BLOCK_ID_NEW
:
3436 if (Error Err
= parseTypeTable())
3439 case bitc::VALUE_SYMTAB_BLOCK_ID
:
3440 if (!SeenValueSymbolTable
) {
3441 // Either this is an old form VST without function index and an
3442 // associated VST forward declaration record (which would have caused
3443 // the VST to be jumped to and parsed before it was encountered
3444 // normally in the stream), or there were no function blocks to
3445 // trigger an earlier parsing of the VST.
3446 assert(VSTOffset
== 0 || FunctionsWithBodies
.empty());
3447 if (Error Err
= parseValueSymbolTable())
3449 SeenValueSymbolTable
= true;
3451 // We must have had a VST forward declaration record, which caused
3452 // the parser to jump to and parse the VST earlier.
3453 assert(VSTOffset
> 0);
3454 if (Error Err
= Stream
.SkipBlock())
3458 case bitc::CONSTANTS_BLOCK_ID
:
3459 if (Error Err
= parseConstants())
3461 if (Error Err
= resolveGlobalAndIndirectSymbolInits())
3464 case bitc::METADATA_BLOCK_ID
:
3465 if (ShouldLazyLoadMetadata
) {
3466 if (Error Err
= rememberAndSkipMetadata())
3470 assert(DeferredMetadataInfo
.empty() && "Unexpected deferred metadata");
3471 if (Error Err
= MDLoader
->parseModuleMetadata())
3474 case bitc::METADATA_KIND_BLOCK_ID
:
3475 if (Error Err
= MDLoader
->parseMetadataKinds())
3478 case bitc::FUNCTION_BLOCK_ID
:
3479 // If this is the first function body we've seen, reverse the
3480 // FunctionsWithBodies list.
3481 if (!SeenFirstFunctionBody
) {
3482 std::reverse(FunctionsWithBodies
.begin(), FunctionsWithBodies
.end());
3483 if (Error Err
= globalCleanup())
3485 SeenFirstFunctionBody
= true;
3488 if (VSTOffset
> 0) {
3489 // If we have a VST forward declaration record, make sure we
3490 // parse the VST now if we haven't already. It is needed to
3491 // set up the DeferredFunctionInfo vector for lazy reading.
3492 if (!SeenValueSymbolTable
) {
3493 if (Error Err
= BitcodeReader::parseValueSymbolTable(VSTOffset
))
3495 SeenValueSymbolTable
= true;
3496 // Fall through so that we record the NextUnreadBit below.
3497 // This is necessary in case we have an anonymous function that
3498 // is later materialized. Since it will not have a VST entry we
3499 // need to fall back to the lazy parse to find its offset.
3501 // If we have a VST forward declaration record, but have already
3502 // parsed the VST (just above, when the first function body was
3503 // encountered here), then we are resuming the parse after
3504 // materializing functions. The ResumeBit points to the
3505 // start of the last function block recorded in the
3506 // DeferredFunctionInfo map. Skip it.
3507 if (Error Err
= Stream
.SkipBlock())
3513 // Support older bitcode files that did not have the function
3514 // index in the VST, nor a VST forward declaration record, as
3515 // well as anonymous functions that do not have VST entries.
3516 // Build the DeferredFunctionInfo vector on the fly.
3517 if (Error Err
= rememberAndSkipFunctionBody())
3520 // Suspend parsing when we reach the function bodies. Subsequent
3521 // materialization calls will resume it when necessary. If the bitcode
3522 // file is old, the symbol table will be at the end instead and will not
3523 // have been seen yet. In this case, just finish the parse now.
3524 if (SeenValueSymbolTable
) {
3525 NextUnreadBit
= Stream
.GetCurrentBitNo();
3526 // After the VST has been parsed, we need to make sure intrinsic name
3527 // are auto-upgraded.
3528 return globalCleanup();
3531 case bitc::USELIST_BLOCK_ID
:
3532 if (Error Err
= parseUseLists())
3535 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
:
3536 if (Error Err
= parseOperandBundleTags())
3539 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID
:
3540 if (Error Err
= parseSyncScopeNames())
3546 case BitstreamEntry::Record
:
3547 // The interesting case.
3552 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
3554 return MaybeBitCode
.takeError();
3555 switch (unsigned BitCode
= MaybeBitCode
.get()) {
3556 default: break; // Default behavior, ignore unknown content.
3557 case bitc::MODULE_CODE_VERSION
: {
3558 Expected
<unsigned> VersionOrErr
= parseVersionRecord(Record
);
3560 return VersionOrErr
.takeError();
3561 UseRelativeIDs
= *VersionOrErr
>= 1;
3564 case bitc::MODULE_CODE_TRIPLE
: { // TRIPLE: [strchr x N]
3566 if (convertToString(Record
, 0, S
))
3567 return error("Invalid record");
3568 TheModule
->setTargetTriple(S
);
3571 case bitc::MODULE_CODE_DATALAYOUT
: { // DATALAYOUT: [strchr x N]
3573 if (convertToString(Record
, 0, S
))
3574 return error("Invalid record");
3575 TheModule
->setDataLayout(S
);
3578 case bitc::MODULE_CODE_ASM
: { // ASM: [strchr x N]
3580 if (convertToString(Record
, 0, S
))
3581 return error("Invalid record");
3582 TheModule
->setModuleInlineAsm(S
);
3585 case bitc::MODULE_CODE_DEPLIB
: { // DEPLIB: [strchr x N]
3586 // FIXME: Remove in 4.0.
3588 if (convertToString(Record
, 0, S
))
3589 return error("Invalid record");
3593 case bitc::MODULE_CODE_SECTIONNAME
: { // SECTIONNAME: [strchr x N]
3595 if (convertToString(Record
, 0, S
))
3596 return error("Invalid record");
3597 SectionTable
.push_back(S
);
3600 case bitc::MODULE_CODE_GCNAME
: { // SECTIONNAME: [strchr x N]
3602 if (convertToString(Record
, 0, S
))
3603 return error("Invalid record");
3604 GCTable
.push_back(S
);
3607 case bitc::MODULE_CODE_COMDAT
:
3608 if (Error Err
= parseComdatRecord(Record
))
3611 case bitc::MODULE_CODE_GLOBALVAR
:
3612 if (Error Err
= parseGlobalVarRecord(Record
))
3615 case bitc::MODULE_CODE_FUNCTION
:
3616 if (Error Err
= parseFunctionRecord(Record
))
3619 case bitc::MODULE_CODE_IFUNC
:
3620 case bitc::MODULE_CODE_ALIAS
:
3621 case bitc::MODULE_CODE_ALIAS_OLD
:
3622 if (Error Err
= parseGlobalIndirectSymbolRecord(BitCode
, Record
))
3625 /// MODULE_CODE_VSTOFFSET: [offset]
3626 case bitc::MODULE_CODE_VSTOFFSET
:
3627 if (Record
.size() < 1)
3628 return error("Invalid record");
3629 // Note that we subtract 1 here because the offset is relative to one word
3630 // before the start of the identification or module block, which was
3631 // historically always the start of the regular bitcode header.
3632 VSTOffset
= Record
[0] - 1;
3634 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3635 case bitc::MODULE_CODE_SOURCE_FILENAME
:
3636 SmallString
<128> ValueName
;
3637 if (convertToString(Record
, 0, ValueName
))
3638 return error("Invalid record");
3639 TheModule
->setSourceFileName(ValueName
);
3646 Error
BitcodeReader::parseBitcodeInto(Module
*M
, bool ShouldLazyLoadMetadata
,
3649 MDLoader
= MetadataLoader(Stream
, *M
, ValueList
, IsImporting
,
3650 [&](unsigned ID
) { return getTypeByID(ID
); });
3651 return parseModule(0, ShouldLazyLoadMetadata
);
3654 Error
BitcodeReader::typeCheckLoadStoreInst(Type
*ValType
, Type
*PtrType
) {
3655 if (!isa
<PointerType
>(PtrType
))
3656 return error("Load/Store operand is not a pointer type");
3657 Type
*ElemType
= cast
<PointerType
>(PtrType
)->getElementType();
3659 if (ValType
&& ValType
!= ElemType
)
3660 return error("Explicit load/store type does not match pointee "
3661 "type of pointer operand");
3662 if (!PointerType::isLoadableOrStorableType(ElemType
))
3663 return error("Cannot load/store from pointer");
3664 return Error::success();
3667 void BitcodeReader::propagateByValTypes(CallBase
*CB
,
3668 ArrayRef
<Type
*> ArgsFullTys
) {
3669 for (unsigned i
= 0; i
!= CB
->arg_size(); ++i
) {
3670 if (!CB
->paramHasAttr(i
, Attribute::ByVal
))
3673 CB
->removeParamAttr(i
, Attribute::ByVal
);
3675 i
, Attribute::getWithByValType(
3676 Context
, getPointerElementFlatType(ArgsFullTys
[i
])));
3680 /// Lazily parse the specified function body block.
3681 Error
BitcodeReader::parseFunctionBody(Function
*F
) {
3682 if (Error Err
= Stream
.EnterSubBlock(bitc::FUNCTION_BLOCK_ID
))
3685 // Unexpected unresolved metadata when parsing function.
3686 if (MDLoader
->hasFwdRefs())
3687 return error("Invalid function metadata: incoming forward references");
3689 InstructionList
.clear();
3690 unsigned ModuleValueListSize
= ValueList
.size();
3691 unsigned ModuleMDLoaderSize
= MDLoader
->size();
3693 // Add all the function arguments to the value table.
3695 FunctionType
*FullFTy
= FunctionTypes
[F
];
3696 for (Argument
&I
: F
->args()) {
3697 assert(I
.getType() == flattenPointerTypes(FullFTy
->getParamType(ArgNo
)) &&
3698 "Incorrect fully specified type for Function Argument");
3699 ValueList
.push_back(&I
, FullFTy
->getParamType(ArgNo
++));
3701 unsigned NextValueNo
= ValueList
.size();
3702 BasicBlock
*CurBB
= nullptr;
3703 unsigned CurBBNo
= 0;
3706 auto getLastInstruction
= [&]() -> Instruction
* {
3707 if (CurBB
&& !CurBB
->empty())
3708 return &CurBB
->back();
3709 else if (CurBBNo
&& FunctionBBs
[CurBBNo
- 1] &&
3710 !FunctionBBs
[CurBBNo
- 1]->empty())
3711 return &FunctionBBs
[CurBBNo
- 1]->back();
3715 std::vector
<OperandBundleDef
> OperandBundles
;
3717 // Read all the records.
3718 SmallVector
<uint64_t, 64> Record
;
3721 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
3723 return MaybeEntry
.takeError();
3724 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
3726 switch (Entry
.Kind
) {
3727 case BitstreamEntry::Error
:
3728 return error("Malformed block");
3729 case BitstreamEntry::EndBlock
:
3730 goto OutOfRecordLoop
;
3732 case BitstreamEntry::SubBlock
:
3734 default: // Skip unknown content.
3735 if (Error Err
= Stream
.SkipBlock())
3738 case bitc::CONSTANTS_BLOCK_ID
:
3739 if (Error Err
= parseConstants())
3741 NextValueNo
= ValueList
.size();
3743 case bitc::VALUE_SYMTAB_BLOCK_ID
:
3744 if (Error Err
= parseValueSymbolTable())
3747 case bitc::METADATA_ATTACHMENT_ID
:
3748 if (Error Err
= MDLoader
->parseMetadataAttachment(*F
, InstructionList
))
3751 case bitc::METADATA_BLOCK_ID
:
3752 assert(DeferredMetadataInfo
.empty() &&
3753 "Must read all module-level metadata before function-level");
3754 if (Error Err
= MDLoader
->parseFunctionMetadata())
3757 case bitc::USELIST_BLOCK_ID
:
3758 if (Error Err
= parseUseLists())
3764 case BitstreamEntry::Record
:
3765 // The interesting case.
3771 Instruction
*I
= nullptr;
3772 Type
*FullTy
= nullptr;
3773 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
3775 return MaybeBitCode
.takeError();
3776 switch (unsigned BitCode
= MaybeBitCode
.get()) {
3777 default: // Default behavior: reject
3778 return error("Invalid value");
3779 case bitc::FUNC_CODE_DECLAREBLOCKS
: { // DECLAREBLOCKS: [nblocks]
3780 if (Record
.size() < 1 || Record
[0] == 0)
3781 return error("Invalid record");
3782 // Create all the basic blocks for the function.
3783 FunctionBBs
.resize(Record
[0]);
3785 // See if anything took the address of blocks in this function.
3786 auto BBFRI
= BasicBlockFwdRefs
.find(F
);
3787 if (BBFRI
== BasicBlockFwdRefs
.end()) {
3788 for (unsigned i
= 0, e
= FunctionBBs
.size(); i
!= e
; ++i
)
3789 FunctionBBs
[i
] = BasicBlock::Create(Context
, "", F
);
3791 auto &BBRefs
= BBFRI
->second
;
3792 // Check for invalid basic block references.
3793 if (BBRefs
.size() > FunctionBBs
.size())
3794 return error("Invalid ID");
3795 assert(!BBRefs
.empty() && "Unexpected empty array");
3796 assert(!BBRefs
.front() && "Invalid reference to entry block");
3797 for (unsigned I
= 0, E
= FunctionBBs
.size(), RE
= BBRefs
.size(); I
!= E
;
3799 if (I
< RE
&& BBRefs
[I
]) {
3800 BBRefs
[I
]->insertInto(F
);
3801 FunctionBBs
[I
] = BBRefs
[I
];
3803 FunctionBBs
[I
] = BasicBlock::Create(Context
, "", F
);
3806 // Erase from the table.
3807 BasicBlockFwdRefs
.erase(BBFRI
);
3810 CurBB
= FunctionBBs
[0];
3814 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN
: // DEBUG_LOC_AGAIN
3815 // This record indicates that the last instruction is at the same
3816 // location as the previous instruction with a location.
3817 I
= getLastInstruction();
3820 return error("Invalid record");
3821 I
->setDebugLoc(LastLoc
);
3825 case bitc::FUNC_CODE_DEBUG_LOC
: { // DEBUG_LOC: [line, col, scope, ia]
3826 I
= getLastInstruction();
3827 if (!I
|| Record
.size() < 4)
3828 return error("Invalid record");
3830 unsigned Line
= Record
[0], Col
= Record
[1];
3831 unsigned ScopeID
= Record
[2], IAID
= Record
[3];
3832 bool isImplicitCode
= Record
.size() == 5 && Record
[4];
3834 MDNode
*Scope
= nullptr, *IA
= nullptr;
3836 Scope
= dyn_cast_or_null
<MDNode
>(
3837 MDLoader
->getMetadataFwdRefOrLoad(ScopeID
- 1));
3839 return error("Invalid record");
3842 IA
= dyn_cast_or_null
<MDNode
>(
3843 MDLoader
->getMetadataFwdRefOrLoad(IAID
- 1));
3845 return error("Invalid record");
3847 LastLoc
= DebugLoc::get(Line
, Col
, Scope
, IA
, isImplicitCode
);
3848 I
->setDebugLoc(LastLoc
);
3852 case bitc::FUNC_CODE_INST_UNOP
: { // UNOP: [opval, ty, opcode]
3855 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
) ||
3856 OpNum
+1 > Record
.size())
3857 return error("Invalid record");
3859 int Opc
= getDecodedUnaryOpcode(Record
[OpNum
++], LHS
->getType());
3861 return error("Invalid record");
3862 I
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
3863 InstructionList
.push_back(I
);
3864 if (OpNum
< Record
.size()) {
3865 if (isa
<FPMathOperator
>(I
)) {
3866 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
3868 I
->setFastMathFlags(FMF
);
3873 case bitc::FUNC_CODE_INST_BINOP
: { // BINOP: [opval, ty, opval, opcode]
3876 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
) ||
3877 popValue(Record
, OpNum
, NextValueNo
, LHS
->getType(), RHS
) ||
3878 OpNum
+1 > Record
.size())
3879 return error("Invalid record");
3881 int Opc
= getDecodedBinaryOpcode(Record
[OpNum
++], LHS
->getType());
3883 return error("Invalid record");
3884 I
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
3885 InstructionList
.push_back(I
);
3886 if (OpNum
< Record
.size()) {
3887 if (Opc
== Instruction::Add
||
3888 Opc
== Instruction::Sub
||
3889 Opc
== Instruction::Mul
||
3890 Opc
== Instruction::Shl
) {
3891 if (Record
[OpNum
] & (1 << bitc::OBO_NO_SIGNED_WRAP
))
3892 cast
<BinaryOperator
>(I
)->setHasNoSignedWrap(true);
3893 if (Record
[OpNum
] & (1 << bitc::OBO_NO_UNSIGNED_WRAP
))
3894 cast
<BinaryOperator
>(I
)->setHasNoUnsignedWrap(true);
3895 } else if (Opc
== Instruction::SDiv
||
3896 Opc
== Instruction::UDiv
||
3897 Opc
== Instruction::LShr
||
3898 Opc
== Instruction::AShr
) {
3899 if (Record
[OpNum
] & (1 << bitc::PEO_EXACT
))
3900 cast
<BinaryOperator
>(I
)->setIsExact(true);
3901 } else if (isa
<FPMathOperator
>(I
)) {
3902 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
3904 I
->setFastMathFlags(FMF
);
3910 case bitc::FUNC_CODE_INST_CAST
: { // CAST: [opval, opty, destty, castopc]
3913 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
) ||
3914 OpNum
+2 != Record
.size())
3915 return error("Invalid record");
3917 FullTy
= getFullyStructuredTypeByID(Record
[OpNum
]);
3918 Type
*ResTy
= flattenPointerTypes(FullTy
);
3919 int Opc
= getDecodedCastOpcode(Record
[OpNum
+ 1]);
3920 if (Opc
== -1 || !ResTy
)
3921 return error("Invalid record");
3922 Instruction
*Temp
= nullptr;
3923 if ((I
= UpgradeBitCastInst(Opc
, Op
, ResTy
, Temp
))) {
3925 InstructionList
.push_back(Temp
);
3926 CurBB
->getInstList().push_back(Temp
);
3929 auto CastOp
= (Instruction::CastOps
)Opc
;
3930 if (!CastInst::castIsValid(CastOp
, Op
, ResTy
))
3931 return error("Invalid cast");
3932 I
= CastInst::Create(CastOp
, Op
, ResTy
);
3934 InstructionList
.push_back(I
);
3937 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD
:
3938 case bitc::FUNC_CODE_INST_GEP_OLD
:
3939 case bitc::FUNC_CODE_INST_GEP
: { // GEP: type, [n x operands]
3945 if (BitCode
== bitc::FUNC_CODE_INST_GEP
) {
3946 InBounds
= Record
[OpNum
++];
3947 FullTy
= getFullyStructuredTypeByID(Record
[OpNum
++]);
3948 Ty
= flattenPointerTypes(FullTy
);
3950 InBounds
= BitCode
== bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD
;
3955 Type
*FullBaseTy
= nullptr;
3956 if (getValueTypePair(Record
, OpNum
, NextValueNo
, BasePtr
, &FullBaseTy
))
3957 return error("Invalid record");
3960 std::tie(FullTy
, Ty
) =
3961 getPointerElementTypes(FullBaseTy
->getScalarType());
3962 } else if (Ty
!= getPointerElementFlatType(FullBaseTy
->getScalarType()))
3964 "Explicit gep type does not match pointee type of pointer operand");
3966 SmallVector
<Value
*, 16> GEPIdx
;
3967 while (OpNum
!= Record
.size()) {
3969 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
3970 return error("Invalid record");
3971 GEPIdx
.push_back(Op
);
3974 I
= GetElementPtrInst::Create(Ty
, BasePtr
, GEPIdx
);
3975 FullTy
= GetElementPtrInst::getGEPReturnType(FullTy
, I
, GEPIdx
);
3977 InstructionList
.push_back(I
);
3979 cast
<GetElementPtrInst
>(I
)->setIsInBounds(true);
3983 case bitc::FUNC_CODE_INST_EXTRACTVAL
: {
3984 // EXTRACTVAL: [opty, opval, n x indices]
3987 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Agg
, &FullTy
))
3988 return error("Invalid record");
3990 unsigned RecSize
= Record
.size();
3991 if (OpNum
== RecSize
)
3992 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3994 SmallVector
<unsigned, 4> EXTRACTVALIdx
;
3995 for (; OpNum
!= RecSize
; ++OpNum
) {
3996 bool IsArray
= FullTy
->isArrayTy();
3997 bool IsStruct
= FullTy
->isStructTy();
3998 uint64_t Index
= Record
[OpNum
];
4000 if (!IsStruct
&& !IsArray
)
4001 return error("EXTRACTVAL: Invalid type");
4002 if ((unsigned)Index
!= Index
)
4003 return error("Invalid value");
4004 if (IsStruct
&& Index
>= FullTy
->getStructNumElements())
4005 return error("EXTRACTVAL: Invalid struct index");
4006 if (IsArray
&& Index
>= FullTy
->getArrayNumElements())
4007 return error("EXTRACTVAL: Invalid array index");
4008 EXTRACTVALIdx
.push_back((unsigned)Index
);
4011 FullTy
= FullTy
->getStructElementType(Index
);
4013 FullTy
= FullTy
->getArrayElementType();
4016 I
= ExtractValueInst::Create(Agg
, EXTRACTVALIdx
);
4017 InstructionList
.push_back(I
);
4021 case bitc::FUNC_CODE_INST_INSERTVAL
: {
4022 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4025 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Agg
, &FullTy
))
4026 return error("Invalid record");
4028 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
))
4029 return error("Invalid record");
4031 unsigned RecSize
= Record
.size();
4032 if (OpNum
== RecSize
)
4033 return error("INSERTVAL: Invalid instruction with 0 indices");
4035 SmallVector
<unsigned, 4> INSERTVALIdx
;
4036 Type
*CurTy
= Agg
->getType();
4037 for (; OpNum
!= RecSize
; ++OpNum
) {
4038 bool IsArray
= CurTy
->isArrayTy();
4039 bool IsStruct
= CurTy
->isStructTy();
4040 uint64_t Index
= Record
[OpNum
];
4042 if (!IsStruct
&& !IsArray
)
4043 return error("INSERTVAL: Invalid type");
4044 if ((unsigned)Index
!= Index
)
4045 return error("Invalid value");
4046 if (IsStruct
&& Index
>= CurTy
->getStructNumElements())
4047 return error("INSERTVAL: Invalid struct index");
4048 if (IsArray
&& Index
>= CurTy
->getArrayNumElements())
4049 return error("INSERTVAL: Invalid array index");
4051 INSERTVALIdx
.push_back((unsigned)Index
);
4053 CurTy
= CurTy
->getStructElementType(Index
);
4055 CurTy
= CurTy
->getArrayElementType();
4058 if (CurTy
!= Val
->getType())
4059 return error("Inserted value type doesn't match aggregate type");
4061 I
= InsertValueInst::Create(Agg
, Val
, INSERTVALIdx
);
4062 InstructionList
.push_back(I
);
4066 case bitc::FUNC_CODE_INST_SELECT
: { // SELECT: [opval, ty, opval, opval]
4067 // obsolete form of select
4068 // handles select i1 ... in old bitcode
4070 Value
*TrueVal
, *FalseVal
, *Cond
;
4071 if (getValueTypePair(Record
, OpNum
, NextValueNo
, TrueVal
, &FullTy
) ||
4072 popValue(Record
, OpNum
, NextValueNo
, TrueVal
->getType(), FalseVal
) ||
4073 popValue(Record
, OpNum
, NextValueNo
, Type::getInt1Ty(Context
), Cond
))
4074 return error("Invalid record");
4076 I
= SelectInst::Create(Cond
, TrueVal
, FalseVal
);
4077 InstructionList
.push_back(I
);
4081 case bitc::FUNC_CODE_INST_VSELECT
: {// VSELECT: [ty,opval,opval,predty,pred]
4082 // new form of select
4083 // handles select i1 or select [N x i1]
4085 Value
*TrueVal
, *FalseVal
, *Cond
;
4086 if (getValueTypePair(Record
, OpNum
, NextValueNo
, TrueVal
, &FullTy
) ||
4087 popValue(Record
, OpNum
, NextValueNo
, TrueVal
->getType(), FalseVal
) ||
4088 getValueTypePair(Record
, OpNum
, NextValueNo
, Cond
))
4089 return error("Invalid record");
4091 // select condition can be either i1 or [N x i1]
4092 if (VectorType
* vector_type
=
4093 dyn_cast
<VectorType
>(Cond
->getType())) {
4095 if (vector_type
->getElementType() != Type::getInt1Ty(Context
))
4096 return error("Invalid type for value");
4099 if (Cond
->getType() != Type::getInt1Ty(Context
))
4100 return error("Invalid type for value");
4103 I
= SelectInst::Create(Cond
, TrueVal
, FalseVal
);
4104 InstructionList
.push_back(I
);
4105 if (OpNum
< Record
.size() && isa
<FPMathOperator
>(I
)) {
4106 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
4108 I
->setFastMathFlags(FMF
);
4113 case bitc::FUNC_CODE_INST_EXTRACTELT
: { // EXTRACTELT: [opty, opval, opval]
4116 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec
, &FullTy
) ||
4117 getValueTypePair(Record
, OpNum
, NextValueNo
, Idx
))
4118 return error("Invalid record");
4119 if (!Vec
->getType()->isVectorTy())
4120 return error("Invalid type for value");
4121 I
= ExtractElementInst::Create(Vec
, Idx
);
4122 FullTy
= FullTy
->getVectorElementType();
4123 InstructionList
.push_back(I
);
4127 case bitc::FUNC_CODE_INST_INSERTELT
: { // INSERTELT: [ty, opval,opval,opval]
4129 Value
*Vec
, *Elt
, *Idx
;
4130 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec
, &FullTy
))
4131 return error("Invalid record");
4132 if (!Vec
->getType()->isVectorTy())
4133 return error("Invalid type for value");
4134 if (popValue(Record
, OpNum
, NextValueNo
,
4135 cast
<VectorType
>(Vec
->getType())->getElementType(), Elt
) ||
4136 getValueTypePair(Record
, OpNum
, NextValueNo
, Idx
))
4137 return error("Invalid record");
4138 I
= InsertElementInst::Create(Vec
, Elt
, Idx
);
4139 InstructionList
.push_back(I
);
4143 case bitc::FUNC_CODE_INST_SHUFFLEVEC
: {// SHUFFLEVEC: [opval,ty,opval,opval]
4145 Value
*Vec1
, *Vec2
, *Mask
;
4146 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec1
, &FullTy
) ||
4147 popValue(Record
, OpNum
, NextValueNo
, Vec1
->getType(), Vec2
))
4148 return error("Invalid record");
4150 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Mask
))
4151 return error("Invalid record");
4152 if (!Vec1
->getType()->isVectorTy() || !Vec2
->getType()->isVectorTy())
4153 return error("Invalid type for value");
4154 I
= new ShuffleVectorInst(Vec1
, Vec2
, Mask
);
4155 FullTy
= VectorType::get(FullTy
->getVectorElementType(),
4156 Mask
->getType()->getVectorNumElements());
4157 InstructionList
.push_back(I
);
4161 case bitc::FUNC_CODE_INST_CMP
: // CMP: [opty, opval, opval, pred]
4162 // Old form of ICmp/FCmp returning bool
4163 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4164 // both legal on vectors but had different behaviour.
4165 case bitc::FUNC_CODE_INST_CMP2
: { // CMP2: [opty, opval, opval, pred]
4166 // FCmp/ICmp returning bool or vector of bool
4170 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
) ||
4171 popValue(Record
, OpNum
, NextValueNo
, LHS
->getType(), RHS
))
4172 return error("Invalid record");
4174 unsigned PredVal
= Record
[OpNum
];
4175 bool IsFP
= LHS
->getType()->isFPOrFPVectorTy();
4177 if (IsFP
&& Record
.size() > OpNum
+1)
4178 FMF
= getDecodedFastMathFlags(Record
[++OpNum
]);
4180 if (OpNum
+1 != Record
.size())
4181 return error("Invalid record");
4183 if (LHS
->getType()->isFPOrFPVectorTy())
4184 I
= new FCmpInst((FCmpInst::Predicate
)PredVal
, LHS
, RHS
);
4186 I
= new ICmpInst((ICmpInst::Predicate
)PredVal
, LHS
, RHS
);
4189 I
->setFastMathFlags(FMF
);
4190 InstructionList
.push_back(I
);
4194 case bitc::FUNC_CODE_INST_RET
: // RET: [opty,opval<optional>]
4196 unsigned Size
= Record
.size();
4198 I
= ReturnInst::Create(Context
);
4199 InstructionList
.push_back(I
);
4204 Value
*Op
= nullptr;
4205 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
4206 return error("Invalid record");
4207 if (OpNum
!= Record
.size())
4208 return error("Invalid record");
4210 I
= ReturnInst::Create(Context
, Op
);
4211 InstructionList
.push_back(I
);
4214 case bitc::FUNC_CODE_INST_BR
: { // BR: [bb#, bb#, opval] or [bb#]
4215 if (Record
.size() != 1 && Record
.size() != 3)
4216 return error("Invalid record");
4217 BasicBlock
*TrueDest
= getBasicBlock(Record
[0]);
4219 return error("Invalid record");
4221 if (Record
.size() == 1) {
4222 I
= BranchInst::Create(TrueDest
);
4223 InstructionList
.push_back(I
);
4226 BasicBlock
*FalseDest
= getBasicBlock(Record
[1]);
4227 Value
*Cond
= getValue(Record
, 2, NextValueNo
,
4228 Type::getInt1Ty(Context
));
4229 if (!FalseDest
|| !Cond
)
4230 return error("Invalid record");
4231 I
= BranchInst::Create(TrueDest
, FalseDest
, Cond
);
4232 InstructionList
.push_back(I
);
4236 case bitc::FUNC_CODE_INST_CLEANUPRET
: { // CLEANUPRET: [val] or [val,bb#]
4237 if (Record
.size() != 1 && Record
.size() != 2)
4238 return error("Invalid record");
4241 getValue(Record
, Idx
++, NextValueNo
, Type::getTokenTy(Context
));
4243 return error("Invalid record");
4244 BasicBlock
*UnwindDest
= nullptr;
4245 if (Record
.size() == 2) {
4246 UnwindDest
= getBasicBlock(Record
[Idx
++]);
4248 return error("Invalid record");
4251 I
= CleanupReturnInst::Create(CleanupPad
, UnwindDest
);
4252 InstructionList
.push_back(I
);
4255 case bitc::FUNC_CODE_INST_CATCHRET
: { // CATCHRET: [val,bb#]
4256 if (Record
.size() != 2)
4257 return error("Invalid record");
4260 getValue(Record
, Idx
++, NextValueNo
, Type::getTokenTy(Context
));
4262 return error("Invalid record");
4263 BasicBlock
*BB
= getBasicBlock(Record
[Idx
++]);
4265 return error("Invalid record");
4267 I
= CatchReturnInst::Create(CatchPad
, BB
);
4268 InstructionList
.push_back(I
);
4271 case bitc::FUNC_CODE_INST_CATCHSWITCH
: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4272 // We must have, at minimum, the outer scope and the number of arguments.
4273 if (Record
.size() < 2)
4274 return error("Invalid record");
4279 getValue(Record
, Idx
++, NextValueNo
, Type::getTokenTy(Context
));
4281 unsigned NumHandlers
= Record
[Idx
++];
4283 SmallVector
<BasicBlock
*, 2> Handlers
;
4284 for (unsigned Op
= 0; Op
!= NumHandlers
; ++Op
) {
4285 BasicBlock
*BB
= getBasicBlock(Record
[Idx
++]);
4287 return error("Invalid record");
4288 Handlers
.push_back(BB
);
4291 BasicBlock
*UnwindDest
= nullptr;
4292 if (Idx
+ 1 == Record
.size()) {
4293 UnwindDest
= getBasicBlock(Record
[Idx
++]);
4295 return error("Invalid record");
4298 if (Record
.size() != Idx
)
4299 return error("Invalid record");
4302 CatchSwitchInst::Create(ParentPad
, UnwindDest
, NumHandlers
);
4303 for (BasicBlock
*Handler
: Handlers
)
4304 CatchSwitch
->addHandler(Handler
);
4306 InstructionList
.push_back(I
);
4309 case bitc::FUNC_CODE_INST_CATCHPAD
:
4310 case bitc::FUNC_CODE_INST_CLEANUPPAD
: { // [tok,num,(ty,val)*]
4311 // We must have, at minimum, the outer scope and the number of arguments.
4312 if (Record
.size() < 2)
4313 return error("Invalid record");
4318 getValue(Record
, Idx
++, NextValueNo
, Type::getTokenTy(Context
));
4320 unsigned NumArgOperands
= Record
[Idx
++];
4322 SmallVector
<Value
*, 2> Args
;
4323 for (unsigned Op
= 0; Op
!= NumArgOperands
; ++Op
) {
4325 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
))
4326 return error("Invalid record");
4327 Args
.push_back(Val
);
4330 if (Record
.size() != Idx
)
4331 return error("Invalid record");
4333 if (BitCode
== bitc::FUNC_CODE_INST_CLEANUPPAD
)
4334 I
= CleanupPadInst::Create(ParentPad
, Args
);
4336 I
= CatchPadInst::Create(ParentPad
, Args
);
4337 InstructionList
.push_back(I
);
4340 case bitc::FUNC_CODE_INST_SWITCH
: { // SWITCH: [opty, op0, op1, ...]
4342 if ((Record
[0] >> 16) == SWITCH_INST_MAGIC
) {
4343 // "New" SwitchInst format with case ranges. The changes to write this
4344 // format were reverted but we still recognize bitcode that uses it.
4345 // Hopefully someday we will have support for case ranges and can use
4346 // this format again.
4348 Type
*OpTy
= getTypeByID(Record
[1]);
4349 unsigned ValueBitWidth
= cast
<IntegerType
>(OpTy
)->getBitWidth();
4351 Value
*Cond
= getValue(Record
, 2, NextValueNo
, OpTy
);
4352 BasicBlock
*Default
= getBasicBlock(Record
[3]);
4353 if (!OpTy
|| !Cond
|| !Default
)
4354 return error("Invalid record");
4356 unsigned NumCases
= Record
[4];
4358 SwitchInst
*SI
= SwitchInst::Create(Cond
, Default
, NumCases
);
4359 InstructionList
.push_back(SI
);
4361 unsigned CurIdx
= 5;
4362 for (unsigned i
= 0; i
!= NumCases
; ++i
) {
4363 SmallVector
<ConstantInt
*, 1> CaseVals
;
4364 unsigned NumItems
= Record
[CurIdx
++];
4365 for (unsigned ci
= 0; ci
!= NumItems
; ++ci
) {
4366 bool isSingleNumber
= Record
[CurIdx
++];
4369 unsigned ActiveWords
= 1;
4370 if (ValueBitWidth
> 64)
4371 ActiveWords
= Record
[CurIdx
++];
4372 Low
= readWideAPInt(makeArrayRef(&Record
[CurIdx
], ActiveWords
),
4374 CurIdx
+= ActiveWords
;
4376 if (!isSingleNumber
) {
4378 if (ValueBitWidth
> 64)
4379 ActiveWords
= Record
[CurIdx
++];
4380 APInt High
= readWideAPInt(
4381 makeArrayRef(&Record
[CurIdx
], ActiveWords
), ValueBitWidth
);
4382 CurIdx
+= ActiveWords
;
4384 // FIXME: It is not clear whether values in the range should be
4385 // compared as signed or unsigned values. The partially
4386 // implemented changes that used this format in the past used
4387 // unsigned comparisons.
4388 for ( ; Low
.ule(High
); ++Low
)
4389 CaseVals
.push_back(ConstantInt::get(Context
, Low
));
4391 CaseVals
.push_back(ConstantInt::get(Context
, Low
));
4393 BasicBlock
*DestBB
= getBasicBlock(Record
[CurIdx
++]);
4394 for (SmallVector
<ConstantInt
*, 1>::iterator cvi
= CaseVals
.begin(),
4395 cve
= CaseVals
.end(); cvi
!= cve
; ++cvi
)
4396 SI
->addCase(*cvi
, DestBB
);
4402 // Old SwitchInst format without case ranges.
4404 if (Record
.size() < 3 || (Record
.size() & 1) == 0)
4405 return error("Invalid record");
4406 Type
*OpTy
= getTypeByID(Record
[0]);
4407 Value
*Cond
= getValue(Record
, 1, NextValueNo
, OpTy
);
4408 BasicBlock
*Default
= getBasicBlock(Record
[2]);
4409 if (!OpTy
|| !Cond
|| !Default
)
4410 return error("Invalid record");
4411 unsigned NumCases
= (Record
.size()-3)/2;
4412 SwitchInst
*SI
= SwitchInst::Create(Cond
, Default
, NumCases
);
4413 InstructionList
.push_back(SI
);
4414 for (unsigned i
= 0, e
= NumCases
; i
!= e
; ++i
) {
4415 ConstantInt
*CaseVal
=
4416 dyn_cast_or_null
<ConstantInt
>(getFnValueByID(Record
[3+i
*2], OpTy
));
4417 BasicBlock
*DestBB
= getBasicBlock(Record
[1+3+i
*2]);
4418 if (!CaseVal
|| !DestBB
) {
4420 return error("Invalid record");
4422 SI
->addCase(CaseVal
, DestBB
);
4427 case bitc::FUNC_CODE_INST_INDIRECTBR
: { // INDIRECTBR: [opty, op0, op1, ...]
4428 if (Record
.size() < 2)
4429 return error("Invalid record");
4430 Type
*OpTy
= getTypeByID(Record
[0]);
4431 Value
*Address
= getValue(Record
, 1, NextValueNo
, OpTy
);
4432 if (!OpTy
|| !Address
)
4433 return error("Invalid record");
4434 unsigned NumDests
= Record
.size()-2;
4435 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, NumDests
);
4436 InstructionList
.push_back(IBI
);
4437 for (unsigned i
= 0, e
= NumDests
; i
!= e
; ++i
) {
4438 if (BasicBlock
*DestBB
= getBasicBlock(Record
[2+i
])) {
4439 IBI
->addDestination(DestBB
);
4442 return error("Invalid record");
4449 case bitc::FUNC_CODE_INST_INVOKE
: {
4450 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4451 if (Record
.size() < 4)
4452 return error("Invalid record");
4454 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
4455 unsigned CCInfo
= Record
[OpNum
++];
4456 BasicBlock
*NormalBB
= getBasicBlock(Record
[OpNum
++]);
4457 BasicBlock
*UnwindBB
= getBasicBlock(Record
[OpNum
++]);
4459 FunctionType
*FTy
= nullptr;
4460 FunctionType
*FullFTy
= nullptr;
4461 if ((CCInfo
>> 13) & 1) {
4463 dyn_cast
<FunctionType
>(getFullyStructuredTypeByID(Record
[OpNum
++]));
4465 return error("Explicit invoke type is not a function type");
4466 FTy
= cast
<FunctionType
>(flattenPointerTypes(FullFTy
));
4470 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
, &FullTy
))
4471 return error("Invalid record");
4473 PointerType
*CalleeTy
= dyn_cast
<PointerType
>(Callee
->getType());
4475 return error("Callee is not a pointer");
4478 dyn_cast
<FunctionType
>(cast
<PointerType
>(FullTy
)->getElementType());
4480 return error("Callee is not of pointer to function type");
4481 FTy
= cast
<FunctionType
>(flattenPointerTypes(FullFTy
));
4482 } else if (getPointerElementFlatType(FullTy
) != FTy
)
4483 return error("Explicit invoke type does not match pointee type of "
4485 if (Record
.size() < FTy
->getNumParams() + OpNum
)
4486 return error("Insufficient operands to call");
4488 SmallVector
<Value
*, 16> Ops
;
4489 SmallVector
<Type
*, 16> ArgsFullTys
;
4490 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
4491 Ops
.push_back(getValue(Record
, OpNum
, NextValueNo
,
4492 FTy
->getParamType(i
)));
4493 ArgsFullTys
.push_back(FullFTy
->getParamType(i
));
4495 return error("Invalid record");
4498 if (!FTy
->isVarArg()) {
4499 if (Record
.size() != OpNum
)
4500 return error("Invalid record");
4502 // Read type/value pairs for varargs params.
4503 while (OpNum
!= Record
.size()) {
4506 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, &FullTy
))
4507 return error("Invalid record");
4509 ArgsFullTys
.push_back(FullTy
);
4513 I
= InvokeInst::Create(FTy
, Callee
, NormalBB
, UnwindBB
, Ops
,
4515 FullTy
= FullFTy
->getReturnType();
4516 OperandBundles
.clear();
4517 InstructionList
.push_back(I
);
4518 cast
<InvokeInst
>(I
)->setCallingConv(
4519 static_cast<CallingConv::ID
>(CallingConv::MaxID
& CCInfo
));
4520 cast
<InvokeInst
>(I
)->setAttributes(PAL
);
4521 propagateByValTypes(cast
<CallBase
>(I
), ArgsFullTys
);
4525 case bitc::FUNC_CODE_INST_RESUME
: { // RESUME: [opval]
4527 Value
*Val
= nullptr;
4528 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
))
4529 return error("Invalid record");
4530 I
= ResumeInst::Create(Val
);
4531 InstructionList
.push_back(I
);
4534 case bitc::FUNC_CODE_INST_CALLBR
: {
4535 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4537 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
4538 unsigned CCInfo
= Record
[OpNum
++];
4540 BasicBlock
*DefaultDest
= getBasicBlock(Record
[OpNum
++]);
4541 unsigned NumIndirectDests
= Record
[OpNum
++];
4542 SmallVector
<BasicBlock
*, 16> IndirectDests
;
4543 for (unsigned i
= 0, e
= NumIndirectDests
; i
!= e
; ++i
)
4544 IndirectDests
.push_back(getBasicBlock(Record
[OpNum
++]));
4546 FunctionType
*FTy
= nullptr;
4547 FunctionType
*FullFTy
= nullptr;
4548 if ((CCInfo
>> bitc::CALL_EXPLICIT_TYPE
) & 1) {
4550 dyn_cast
<FunctionType
>(getFullyStructuredTypeByID(Record
[OpNum
++]));
4552 return error("Explicit call type is not a function type");
4553 FTy
= cast
<FunctionType
>(flattenPointerTypes(FullFTy
));
4557 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
, &FullTy
))
4558 return error("Invalid record");
4560 PointerType
*OpTy
= dyn_cast
<PointerType
>(Callee
->getType());
4562 return error("Callee is not a pointer type");
4565 dyn_cast
<FunctionType
>(cast
<PointerType
>(FullTy
)->getElementType());
4567 return error("Callee is not of pointer to function type");
4568 FTy
= cast
<FunctionType
>(flattenPointerTypes(FullFTy
));
4569 } else if (getPointerElementFlatType(FullTy
) != FTy
)
4570 return error("Explicit call type does not match pointee type of "
4572 if (Record
.size() < FTy
->getNumParams() + OpNum
)
4573 return error("Insufficient operands to call");
4575 SmallVector
<Value
*, 16> Args
;
4576 // Read the fixed params.
4577 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
4578 if (FTy
->getParamType(i
)->isLabelTy())
4579 Args
.push_back(getBasicBlock(Record
[OpNum
]));
4581 Args
.push_back(getValue(Record
, OpNum
, NextValueNo
,
4582 FTy
->getParamType(i
)));
4584 return error("Invalid record");
4587 // Read type/value pairs for varargs params.
4588 if (!FTy
->isVarArg()) {
4589 if (OpNum
!= Record
.size())
4590 return error("Invalid record");
4592 while (OpNum
!= Record
.size()) {
4594 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
4595 return error("Invalid record");
4600 I
= CallBrInst::Create(FTy
, Callee
, DefaultDest
, IndirectDests
, Args
,
4602 FullTy
= FullFTy
->getReturnType();
4603 OperandBundles
.clear();
4604 InstructionList
.push_back(I
);
4605 cast
<CallBrInst
>(I
)->setCallingConv(
4606 static_cast<CallingConv::ID
>((0x7ff & CCInfo
) >> bitc::CALL_CCONV
));
4607 cast
<CallBrInst
>(I
)->setAttributes(PAL
);
4610 case bitc::FUNC_CODE_INST_UNREACHABLE
: // UNREACHABLE
4611 I
= new UnreachableInst(Context
);
4612 InstructionList
.push_back(I
);
4614 case bitc::FUNC_CODE_INST_PHI
: { // PHI: [ty, val0,bb0, ...]
4615 if (Record
.size() < 1 || ((Record
.size()-1)&1))
4616 return error("Invalid record");
4617 FullTy
= getFullyStructuredTypeByID(Record
[0]);
4618 Type
*Ty
= flattenPointerTypes(FullTy
);
4620 return error("Invalid record");
4622 PHINode
*PN
= PHINode::Create(Ty
, (Record
.size()-1)/2);
4623 InstructionList
.push_back(PN
);
4625 for (unsigned i
= 0, e
= Record
.size()-1; i
!= e
; i
+= 2) {
4627 // With the new function encoding, it is possible that operands have
4628 // negative IDs (for forward references). Use a signed VBR
4629 // representation to keep the encoding small.
4631 V
= getValueSigned(Record
, 1+i
, NextValueNo
, Ty
);
4633 V
= getValue(Record
, 1+i
, NextValueNo
, Ty
);
4634 BasicBlock
*BB
= getBasicBlock(Record
[2+i
]);
4636 return error("Invalid record");
4637 PN
->addIncoming(V
, BB
);
4643 case bitc::FUNC_CODE_INST_LANDINGPAD
:
4644 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD
: {
4645 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4647 if (BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD
) {
4648 if (Record
.size() < 3)
4649 return error("Invalid record");
4651 assert(BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD_OLD
);
4652 if (Record
.size() < 4)
4653 return error("Invalid record");
4655 FullTy
= getFullyStructuredTypeByID(Record
[Idx
++]);
4656 Type
*Ty
= flattenPointerTypes(FullTy
);
4658 return error("Invalid record");
4659 if (BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD_OLD
) {
4660 Value
*PersFn
= nullptr;
4661 if (getValueTypePair(Record
, Idx
, NextValueNo
, PersFn
))
4662 return error("Invalid record");
4664 if (!F
->hasPersonalityFn())
4665 F
->setPersonalityFn(cast
<Constant
>(PersFn
));
4666 else if (F
->getPersonalityFn() != cast
<Constant
>(PersFn
))
4667 return error("Personality function mismatch");
4670 bool IsCleanup
= !!Record
[Idx
++];
4671 unsigned NumClauses
= Record
[Idx
++];
4672 LandingPadInst
*LP
= LandingPadInst::Create(Ty
, NumClauses
);
4673 LP
->setCleanup(IsCleanup
);
4674 for (unsigned J
= 0; J
!= NumClauses
; ++J
) {
4675 LandingPadInst::ClauseType CT
=
4676 LandingPadInst::ClauseType(Record
[Idx
++]); (void)CT
;
4679 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
)) {
4681 return error("Invalid record");
4684 assert((CT
!= LandingPadInst::Catch
||
4685 !isa
<ArrayType
>(Val
->getType())) &&
4686 "Catch clause has a invalid type!");
4687 assert((CT
!= LandingPadInst::Filter
||
4688 isa
<ArrayType
>(Val
->getType())) &&
4689 "Filter clause has invalid type!");
4690 LP
->addClause(cast
<Constant
>(Val
));
4694 InstructionList
.push_back(I
);
4698 case bitc::FUNC_CODE_INST_ALLOCA
: { // ALLOCA: [instty, opty, op, align]
4699 if (Record
.size() != 4)
4700 return error("Invalid record");
4701 uint64_t AlignRecord
= Record
[3];
4702 const uint64_t InAllocaMask
= uint64_t(1) << 5;
4703 const uint64_t ExplicitTypeMask
= uint64_t(1) << 6;
4704 const uint64_t SwiftErrorMask
= uint64_t(1) << 7;
4705 const uint64_t FlagMask
= InAllocaMask
| ExplicitTypeMask
|
4707 bool InAlloca
= AlignRecord
& InAllocaMask
;
4708 bool SwiftError
= AlignRecord
& SwiftErrorMask
;
4709 FullTy
= getFullyStructuredTypeByID(Record
[0]);
4710 Type
*Ty
= flattenPointerTypes(FullTy
);
4711 if ((AlignRecord
& ExplicitTypeMask
) == 0) {
4712 auto *PTy
= dyn_cast_or_null
<PointerType
>(Ty
);
4714 return error("Old-style alloca with a non-pointer type");
4715 std::tie(FullTy
, Ty
) = getPointerElementTypes(FullTy
);
4717 Type
*OpTy
= getTypeByID(Record
[1]);
4718 Value
*Size
= getFnValueByID(Record
[2], OpTy
);
4720 if (Error Err
= parseAlignmentValue(AlignRecord
& ~FlagMask
, Align
)) {
4724 return error("Invalid record");
4726 // FIXME: Make this an optional field.
4727 const DataLayout
&DL
= TheModule
->getDataLayout();
4728 unsigned AS
= DL
.getAllocaAddrSpace();
4730 AllocaInst
*AI
= new AllocaInst(Ty
, AS
, Size
, Align
);
4731 AI
->setUsedWithInAlloca(InAlloca
);
4732 AI
->setSwiftError(SwiftError
);
4734 FullTy
= PointerType::get(FullTy
, AS
);
4735 InstructionList
.push_back(I
);
4738 case bitc::FUNC_CODE_INST_LOAD
: { // LOAD: [opty, op, align, vol]
4741 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, &FullTy
) ||
4742 (OpNum
+ 2 != Record
.size() && OpNum
+ 3 != Record
.size()))
4743 return error("Invalid record");
4745 if (!isa
<PointerType
>(Op
->getType()))
4746 return error("Load operand is not a pointer type");
4749 if (OpNum
+ 3 == Record
.size()) {
4750 FullTy
= getFullyStructuredTypeByID(Record
[OpNum
++]);
4751 Ty
= flattenPointerTypes(FullTy
);
4753 std::tie(FullTy
, Ty
) = getPointerElementTypes(FullTy
);
4755 if (Error Err
= typeCheckLoadStoreInst(Ty
, Op
->getType()))
4759 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
4761 I
= new LoadInst(Ty
, Op
, "", Record
[OpNum
+ 1], Align
);
4762 InstructionList
.push_back(I
);
4765 case bitc::FUNC_CODE_INST_LOADATOMIC
: {
4766 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
4769 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, &FullTy
) ||
4770 (OpNum
+ 4 != Record
.size() && OpNum
+ 5 != Record
.size()))
4771 return error("Invalid record");
4773 if (!isa
<PointerType
>(Op
->getType()))
4774 return error("Load operand is not a pointer type");
4777 if (OpNum
+ 5 == Record
.size()) {
4778 FullTy
= getFullyStructuredTypeByID(Record
[OpNum
++]);
4779 Ty
= flattenPointerTypes(FullTy
);
4781 std::tie(FullTy
, Ty
) = getPointerElementTypes(FullTy
);
4783 if (Error Err
= typeCheckLoadStoreInst(Ty
, Op
->getType()))
4786 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
4787 if (Ordering
== AtomicOrdering::NotAtomic
||
4788 Ordering
== AtomicOrdering::Release
||
4789 Ordering
== AtomicOrdering::AcquireRelease
)
4790 return error("Invalid record");
4791 if (Ordering
!= AtomicOrdering::NotAtomic
&& Record
[OpNum
] == 0)
4792 return error("Invalid record");
4793 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
4796 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
4798 I
= new LoadInst(Ty
, Op
, "", Record
[OpNum
+ 1], Align
, Ordering
, SSID
);
4799 InstructionList
.push_back(I
);
4802 case bitc::FUNC_CODE_INST_STORE
:
4803 case bitc::FUNC_CODE_INST_STORE_OLD
: { // STORE2:[ptrty, ptr, val, align, vol]
4807 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, &FullTy
) ||
4808 (BitCode
== bitc::FUNC_CODE_INST_STORE
4809 ? getValueTypePair(Record
, OpNum
, NextValueNo
, Val
)
4810 : popValue(Record
, OpNum
, NextValueNo
,
4811 getPointerElementFlatType(FullTy
), Val
)) ||
4812 OpNum
+ 2 != Record
.size())
4813 return error("Invalid record");
4815 if (Error Err
= typeCheckLoadStoreInst(Val
->getType(), Ptr
->getType()))
4818 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
4820 I
= new StoreInst(Val
, Ptr
, Record
[OpNum
+1], Align
);
4821 InstructionList
.push_back(I
);
4824 case bitc::FUNC_CODE_INST_STOREATOMIC
:
4825 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD
: {
4826 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
4830 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, &FullTy
) ||
4831 !isa
<PointerType
>(Ptr
->getType()) ||
4832 (BitCode
== bitc::FUNC_CODE_INST_STOREATOMIC
4833 ? getValueTypePair(Record
, OpNum
, NextValueNo
, Val
)
4834 : popValue(Record
, OpNum
, NextValueNo
,
4835 getPointerElementFlatType(FullTy
), Val
)) ||
4836 OpNum
+ 4 != Record
.size())
4837 return error("Invalid record");
4839 if (Error Err
= typeCheckLoadStoreInst(Val
->getType(), Ptr
->getType()))
4841 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
4842 if (Ordering
== AtomicOrdering::NotAtomic
||
4843 Ordering
== AtomicOrdering::Acquire
||
4844 Ordering
== AtomicOrdering::AcquireRelease
)
4845 return error("Invalid record");
4846 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
4847 if (Ordering
!= AtomicOrdering::NotAtomic
&& Record
[OpNum
] == 0)
4848 return error("Invalid record");
4851 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
4853 I
= new StoreInst(Val
, Ptr
, Record
[OpNum
+1], Align
, Ordering
, SSID
);
4854 InstructionList
.push_back(I
);
4857 case bitc::FUNC_CODE_INST_CMPXCHG_OLD
:
4858 case bitc::FUNC_CODE_INST_CMPXCHG
: {
4859 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
4860 // failureordering?, isweak?]
4862 Value
*Ptr
, *Cmp
, *New
;
4863 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, &FullTy
))
4864 return error("Invalid record");
4866 if (!isa
<PointerType
>(Ptr
->getType()))
4867 return error("Cmpxchg operand is not a pointer type");
4869 if (BitCode
== bitc::FUNC_CODE_INST_CMPXCHG
) {
4870 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Cmp
, &FullTy
))
4871 return error("Invalid record");
4872 } else if (popValue(Record
, OpNum
, NextValueNo
,
4873 getPointerElementFlatType(FullTy
), Cmp
))
4874 return error("Invalid record");
4876 FullTy
= cast
<PointerType
>(FullTy
)->getElementType();
4878 if (popValue(Record
, OpNum
, NextValueNo
, Cmp
->getType(), New
) ||
4879 Record
.size() < OpNum
+ 3 || Record
.size() > OpNum
+ 5)
4880 return error("Invalid record");
4882 AtomicOrdering SuccessOrdering
= getDecodedOrdering(Record
[OpNum
+ 1]);
4883 if (SuccessOrdering
== AtomicOrdering::NotAtomic
||
4884 SuccessOrdering
== AtomicOrdering::Unordered
)
4885 return error("Invalid record");
4886 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 2]);
4888 if (Error Err
= typeCheckLoadStoreInst(Cmp
->getType(), Ptr
->getType()))
4890 AtomicOrdering FailureOrdering
;
4891 if (Record
.size() < 7)
4893 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering
);
4895 FailureOrdering
= getDecodedOrdering(Record
[OpNum
+ 3]);
4897 I
= new AtomicCmpXchgInst(Ptr
, Cmp
, New
, SuccessOrdering
, FailureOrdering
,
4899 FullTy
= StructType::get(Context
, {FullTy
, Type::getInt1Ty(Context
)});
4900 cast
<AtomicCmpXchgInst
>(I
)->setVolatile(Record
[OpNum
]);
4902 if (Record
.size() < 8) {
4903 // Before weak cmpxchgs existed, the instruction simply returned the
4904 // value loaded from memory, so bitcode files from that era will be
4905 // expecting the first component of a modern cmpxchg.
4906 CurBB
->getInstList().push_back(I
);
4907 I
= ExtractValueInst::Create(I
, 0);
4908 FullTy
= cast
<StructType
>(FullTy
)->getElementType(0);
4910 cast
<AtomicCmpXchgInst
>(I
)->setWeak(Record
[OpNum
+4]);
4913 InstructionList
.push_back(I
);
4916 case bitc::FUNC_CODE_INST_ATOMICRMW
: {
4917 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
4920 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, &FullTy
) ||
4921 !isa
<PointerType
>(Ptr
->getType()) ||
4922 popValue(Record
, OpNum
, NextValueNo
,
4923 getPointerElementFlatType(FullTy
), Val
) ||
4924 OpNum
+ 4 != Record
.size())
4925 return error("Invalid record");
4926 AtomicRMWInst::BinOp Operation
= getDecodedRMWOperation(Record
[OpNum
]);
4927 if (Operation
< AtomicRMWInst::FIRST_BINOP
||
4928 Operation
> AtomicRMWInst::LAST_BINOP
)
4929 return error("Invalid record");
4930 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
4931 if (Ordering
== AtomicOrdering::NotAtomic
||
4932 Ordering
== AtomicOrdering::Unordered
)
4933 return error("Invalid record");
4934 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
4935 I
= new AtomicRMWInst(Operation
, Ptr
, Val
, Ordering
, SSID
);
4936 FullTy
= getPointerElementFlatType(FullTy
);
4937 cast
<AtomicRMWInst
>(I
)->setVolatile(Record
[OpNum
+1]);
4938 InstructionList
.push_back(I
);
4941 case bitc::FUNC_CODE_INST_FENCE
: { // FENCE:[ordering, ssid]
4942 if (2 != Record
.size())
4943 return error("Invalid record");
4944 AtomicOrdering Ordering
= getDecodedOrdering(Record
[0]);
4945 if (Ordering
== AtomicOrdering::NotAtomic
||
4946 Ordering
== AtomicOrdering::Unordered
||
4947 Ordering
== AtomicOrdering::Monotonic
)
4948 return error("Invalid record");
4949 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[1]);
4950 I
= new FenceInst(Context
, Ordering
, SSID
);
4951 InstructionList
.push_back(I
);
4954 case bitc::FUNC_CODE_INST_CALL
: {
4955 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4956 if (Record
.size() < 3)
4957 return error("Invalid record");
4960 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
4961 unsigned CCInfo
= Record
[OpNum
++];
4964 if ((CCInfo
>> bitc::CALL_FMF
) & 1) {
4965 FMF
= getDecodedFastMathFlags(Record
[OpNum
++]);
4967 return error("Fast math flags indicator set for call with no FMF");
4970 FunctionType
*FTy
= nullptr;
4971 FunctionType
*FullFTy
= nullptr;
4972 if ((CCInfo
>> bitc::CALL_EXPLICIT_TYPE
) & 1) {
4974 dyn_cast
<FunctionType
>(getFullyStructuredTypeByID(Record
[OpNum
++]));
4976 return error("Explicit call type is not a function type");
4977 FTy
= cast
<FunctionType
>(flattenPointerTypes(FullFTy
));
4981 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
, &FullTy
))
4982 return error("Invalid record");
4984 PointerType
*OpTy
= dyn_cast
<PointerType
>(Callee
->getType());
4986 return error("Callee is not a pointer type");
4989 dyn_cast
<FunctionType
>(cast
<PointerType
>(FullTy
)->getElementType());
4991 return error("Callee is not of pointer to function type");
4992 FTy
= cast
<FunctionType
>(flattenPointerTypes(FullFTy
));
4993 } else if (getPointerElementFlatType(FullTy
) != FTy
)
4994 return error("Explicit call type does not match pointee type of "
4996 if (Record
.size() < FTy
->getNumParams() + OpNum
)
4997 return error("Insufficient operands to call");
4999 SmallVector
<Value
*, 16> Args
;
5000 SmallVector
<Type
*, 16> ArgsFullTys
;
5001 // Read the fixed params.
5002 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
5003 if (FTy
->getParamType(i
)->isLabelTy())
5004 Args
.push_back(getBasicBlock(Record
[OpNum
]));
5006 Args
.push_back(getValue(Record
, OpNum
, NextValueNo
,
5007 FTy
->getParamType(i
)));
5008 ArgsFullTys
.push_back(FullFTy
->getParamType(i
));
5010 return error("Invalid record");
5013 // Read type/value pairs for varargs params.
5014 if (!FTy
->isVarArg()) {
5015 if (OpNum
!= Record
.size())
5016 return error("Invalid record");
5018 while (OpNum
!= Record
.size()) {
5021 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, &FullTy
))
5022 return error("Invalid record");
5024 ArgsFullTys
.push_back(FullTy
);
5028 I
= CallInst::Create(FTy
, Callee
, Args
, OperandBundles
);
5029 FullTy
= FullFTy
->getReturnType();
5030 OperandBundles
.clear();
5031 InstructionList
.push_back(I
);
5032 cast
<CallInst
>(I
)->setCallingConv(
5033 static_cast<CallingConv::ID
>((0x7ff & CCInfo
) >> bitc::CALL_CCONV
));
5034 CallInst::TailCallKind TCK
= CallInst::TCK_None
;
5035 if (CCInfo
& 1 << bitc::CALL_TAIL
)
5036 TCK
= CallInst::TCK_Tail
;
5037 if (CCInfo
& (1 << bitc::CALL_MUSTTAIL
))
5038 TCK
= CallInst::TCK_MustTail
;
5039 if (CCInfo
& (1 << bitc::CALL_NOTAIL
))
5040 TCK
= CallInst::TCK_NoTail
;
5041 cast
<CallInst
>(I
)->setTailCallKind(TCK
);
5042 cast
<CallInst
>(I
)->setAttributes(PAL
);
5043 propagateByValTypes(cast
<CallBase
>(I
), ArgsFullTys
);
5045 if (!isa
<FPMathOperator
>(I
))
5046 return error("Fast-math-flags specified for call without "
5047 "floating-point scalar or vector return type");
5048 I
->setFastMathFlags(FMF
);
5052 case bitc::FUNC_CODE_INST_VAARG
: { // VAARG: [valistty, valist, instty]
5053 if (Record
.size() < 3)
5054 return error("Invalid record");
5055 Type
*OpTy
= getTypeByID(Record
[0]);
5056 Value
*Op
= getValue(Record
, 1, NextValueNo
, OpTy
);
5057 FullTy
= getFullyStructuredTypeByID(Record
[2]);
5058 Type
*ResTy
= flattenPointerTypes(FullTy
);
5059 if (!OpTy
|| !Op
|| !ResTy
)
5060 return error("Invalid record");
5061 I
= new VAArgInst(Op
, ResTy
);
5062 InstructionList
.push_back(I
);
5066 case bitc::FUNC_CODE_OPERAND_BUNDLE
: {
5067 // A call or an invoke can be optionally prefixed with some variable
5068 // number of operand bundle blocks. These blocks are read into
5069 // OperandBundles and consumed at the next call or invoke instruction.
5071 if (Record
.size() < 1 || Record
[0] >= BundleTags
.size())
5072 return error("Invalid record");
5074 std::vector
<Value
*> Inputs
;
5077 while (OpNum
!= Record
.size()) {
5079 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
))
5080 return error("Invalid record");
5081 Inputs
.push_back(Op
);
5084 OperandBundles
.emplace_back(BundleTags
[Record
[0]], std::move(Inputs
));
5089 // Add instruction to end of current BB. If there is no current BB, reject
5093 return error("Invalid instruction with no BB");
5095 if (!OperandBundles
.empty()) {
5097 return error("Operand bundles found with no consumer");
5099 CurBB
->getInstList().push_back(I
);
5101 // If this was a terminator instruction, move to the next block.
5102 if (I
->isTerminator()) {
5104 CurBB
= CurBBNo
< FunctionBBs
.size() ? FunctionBBs
[CurBBNo
] : nullptr;
5107 // Non-void values get registered in the value table for future use.
5108 if (I
&& !I
->getType()->isVoidTy()) {
5110 FullTy
= I
->getType();
5112 !FullTy
->isPointerTy() && !isa
<StructType
>(FullTy
) &&
5113 !isa
<ArrayType
>(FullTy
) &&
5114 (!isa
<VectorType
>(FullTy
) ||
5115 FullTy
->getVectorElementType()->isFloatingPointTy() ||
5116 FullTy
->getVectorElementType()->isIntegerTy()) &&
5117 "Structured types must be assigned with corresponding non-opaque "
5121 assert(I
->getType() == flattenPointerTypes(FullTy
) &&
5122 "Incorrect fully structured type provided for Instruction");
5123 ValueList
.assignValue(I
, NextValueNo
++, FullTy
);
5129 if (!OperandBundles
.empty())
5130 return error("Operand bundles found with no consumer");
5132 // Check the function list for unresolved values.
5133 if (Argument
*A
= dyn_cast
<Argument
>(ValueList
.back())) {
5134 if (!A
->getParent()) {
5135 // We found at least one unresolved value. Nuke them all to avoid leaks.
5136 for (unsigned i
= ModuleValueListSize
, e
= ValueList
.size(); i
!= e
; ++i
){
5137 if ((A
= dyn_cast_or_null
<Argument
>(ValueList
[i
])) && !A
->getParent()) {
5138 A
->replaceAllUsesWith(UndefValue::get(A
->getType()));
5142 return error("Never resolved value found in function");
5146 // Unexpected unresolved metadata about to be dropped.
5147 if (MDLoader
->hasFwdRefs())
5148 return error("Invalid function metadata: outgoing forward refs");
5150 // Trim the value list down to the size it was before we parsed this function.
5151 ValueList
.shrinkTo(ModuleValueListSize
);
5152 MDLoader
->shrinkTo(ModuleMDLoaderSize
);
5153 std::vector
<BasicBlock
*>().swap(FunctionBBs
);
5154 return Error::success();
5157 /// Find the function body in the bitcode stream
5158 Error
BitcodeReader::findFunctionInStream(
5160 DenseMap
<Function
*, uint64_t>::iterator DeferredFunctionInfoIterator
) {
5161 while (DeferredFunctionInfoIterator
->second
== 0) {
5162 // This is the fallback handling for the old format bitcode that
5163 // didn't contain the function index in the VST, or when we have
5164 // an anonymous function which would not have a VST entry.
5165 // Assert that we have one of those two cases.
5166 assert(VSTOffset
== 0 || !F
->hasName());
5167 // Parse the next body in the stream and set its position in the
5168 // DeferredFunctionInfo map.
5169 if (Error Err
= rememberAndSkipFunctionBodies())
5172 return Error::success();
5175 SyncScope::ID
BitcodeReader::getDecodedSyncScopeID(unsigned Val
) {
5176 if (Val
== SyncScope::SingleThread
|| Val
== SyncScope::System
)
5177 return SyncScope::ID(Val
);
5178 if (Val
>= SSIDs
.size())
5179 return SyncScope::System
; // Map unknown synchronization scopes to system.
5183 //===----------------------------------------------------------------------===//
5184 // GVMaterializer implementation
5185 //===----------------------------------------------------------------------===//
5187 Error
BitcodeReader::materialize(GlobalValue
*GV
) {
5188 Function
*F
= dyn_cast
<Function
>(GV
);
5189 // If it's not a function or is already material, ignore the request.
5190 if (!F
|| !F
->isMaterializable())
5191 return Error::success();
5193 DenseMap
<Function
*, uint64_t>::iterator DFII
= DeferredFunctionInfo
.find(F
);
5194 assert(DFII
!= DeferredFunctionInfo
.end() && "Deferred function not found!");
5195 // If its position is recorded as 0, its body is somewhere in the stream
5196 // but we haven't seen it yet.
5197 if (DFII
->second
== 0)
5198 if (Error Err
= findFunctionInStream(F
, DFII
))
5201 // Materialize metadata before parsing any function bodies.
5202 if (Error Err
= materializeMetadata())
5205 // Move the bit stream to the saved position of the deferred function body.
5206 if (Error JumpFailed
= Stream
.JumpToBit(DFII
->second
))
5208 if (Error Err
= parseFunctionBody(F
))
5210 F
->setIsMaterializable(false);
5215 // Upgrade any old intrinsic calls in the function.
5216 for (auto &I
: UpgradedIntrinsics
) {
5217 for (auto UI
= I
.first
->materialized_user_begin(), UE
= I
.first
->user_end();
5221 if (CallInst
*CI
= dyn_cast
<CallInst
>(U
))
5222 UpgradeIntrinsicCall(CI
, I
.second
);
5226 // Update calls to the remangled intrinsics
5227 for (auto &I
: RemangledIntrinsics
)
5228 for (auto UI
= I
.first
->materialized_user_begin(), UE
= I
.first
->user_end();
5230 // Don't expect any other users than call sites
5231 CallSite(*UI
++).setCalledFunction(I
.second
);
5233 // Finish fn->subprogram upgrade for materialized functions.
5234 if (DISubprogram
*SP
= MDLoader
->lookupSubprogramForFunction(F
))
5235 F
->setSubprogram(SP
);
5237 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
5238 if (!MDLoader
->isStrippingTBAA()) {
5239 for (auto &I
: instructions(F
)) {
5240 MDNode
*TBAA
= I
.getMetadata(LLVMContext::MD_tbaa
);
5241 if (!TBAA
|| TBAAVerifyHelper
.visitTBAAMetadata(I
, TBAA
))
5243 MDLoader
->setStripTBAA(true);
5244 stripTBAA(F
->getParent());
5248 // Bring in any functions that this function forward-referenced via
5250 return materializeForwardReferencedFunctions();
5253 Error
BitcodeReader::materializeModule() {
5254 if (Error Err
= materializeMetadata())
5257 // Promise to materialize all forward references.
5258 WillMaterializeAllForwardRefs
= true;
5260 // Iterate over the module, deserializing any functions that are still on
5262 for (Function
&F
: *TheModule
) {
5263 if (Error Err
= materialize(&F
))
5266 // At this point, if there are any function bodies, parse the rest of
5267 // the bits in the module past the last function block we have recorded
5268 // through either lazy scanning or the VST.
5269 if (LastFunctionBlockBit
|| NextUnreadBit
)
5270 if (Error Err
= parseModule(LastFunctionBlockBit
> NextUnreadBit
5271 ? LastFunctionBlockBit
5275 // Check that all block address forward references got resolved (as we
5277 if (!BasicBlockFwdRefs
.empty())
5278 return error("Never resolved function from blockaddress");
5280 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5281 // delete the old functions to clean up. We can't do this unless the entire
5282 // module is materialized because there could always be another function body
5283 // with calls to the old function.
5284 for (auto &I
: UpgradedIntrinsics
) {
5285 for (auto *U
: I
.first
->users()) {
5286 if (CallInst
*CI
= dyn_cast
<CallInst
>(U
))
5287 UpgradeIntrinsicCall(CI
, I
.second
);
5289 if (!I
.first
->use_empty())
5290 I
.first
->replaceAllUsesWith(I
.second
);
5291 I
.first
->eraseFromParent();
5293 UpgradedIntrinsics
.clear();
5294 // Do the same for remangled intrinsics
5295 for (auto &I
: RemangledIntrinsics
) {
5296 I
.first
->replaceAllUsesWith(I
.second
);
5297 I
.first
->eraseFromParent();
5299 RemangledIntrinsics
.clear();
5301 UpgradeDebugInfo(*TheModule
);
5303 UpgradeModuleFlags(*TheModule
);
5305 UpgradeRetainReleaseMarker(*TheModule
);
5307 return Error::success();
5310 std::vector
<StructType
*> BitcodeReader::getIdentifiedStructTypes() const {
5311 return IdentifiedStructTypes
;
5314 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5315 BitstreamCursor Cursor
, StringRef Strtab
, ModuleSummaryIndex
&TheIndex
,
5316 StringRef ModulePath
, unsigned ModuleId
)
5317 : BitcodeReaderBase(std::move(Cursor
), Strtab
), TheIndex(TheIndex
),
5318 ModulePath(ModulePath
), ModuleId(ModuleId
) {}
5320 void ModuleSummaryIndexBitcodeReader::addThisModule() {
5321 TheIndex
.addModule(ModulePath
, ModuleId
);
5324 ModuleSummaryIndex::ModuleInfo
*
5325 ModuleSummaryIndexBitcodeReader::getThisModule() {
5326 return TheIndex
.getModule(ModulePath
);
5329 std::pair
<ValueInfo
, GlobalValue::GUID
>
5330 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId
) {
5331 auto VGI
= ValueIdToValueInfoMap
[ValueId
];
5336 void ModuleSummaryIndexBitcodeReader::setValueGUID(
5337 uint64_t ValueID
, StringRef ValueName
, GlobalValue::LinkageTypes Linkage
,
5338 StringRef SourceFileName
) {
5339 std::string GlobalId
=
5340 GlobalValue::getGlobalIdentifier(ValueName
, Linkage
, SourceFileName
);
5341 auto ValueGUID
= GlobalValue::getGUID(GlobalId
);
5342 auto OriginalNameID
= ValueGUID
;
5343 if (GlobalValue::isLocalLinkage(Linkage
))
5344 OriginalNameID
= GlobalValue::getGUID(ValueName
);
5345 if (PrintSummaryGUIDs
)
5346 dbgs() << "GUID " << ValueGUID
<< "(" << OriginalNameID
<< ") is "
5347 << ValueName
<< "\n";
5349 // UseStrtab is false for legacy summary formats and value names are
5350 // created on stack. In that case we save the name in a string saver in
5351 // the index so that the value name can be recorded.
5352 ValueIdToValueInfoMap
[ValueID
] = std::make_pair(
5353 TheIndex
.getOrInsertValueInfo(
5355 UseStrtab
? ValueName
: TheIndex
.saveString(ValueName
)),
5359 // Specialized value symbol table parser used when reading module index
5360 // blocks where we don't actually create global values. The parsed information
5361 // is saved in the bitcode reader for use when later parsing summaries.
5362 Error
ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5364 DenseMap
<unsigned, GlobalValue::LinkageTypes
> &ValueIdToLinkageMap
) {
5365 // With a strtab the VST is not required to parse the summary.
5367 return Error::success();
5369 assert(Offset
> 0 && "Expected non-zero VST offset");
5370 Expected
<uint64_t> MaybeCurrentBit
= jumpToValueSymbolTable(Offset
, Stream
);
5371 if (!MaybeCurrentBit
)
5372 return MaybeCurrentBit
.takeError();
5373 uint64_t CurrentBit
= MaybeCurrentBit
.get();
5375 if (Error Err
= Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
5378 SmallVector
<uint64_t, 64> Record
;
5380 // Read all the records for this value table.
5381 SmallString
<128> ValueName
;
5384 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
5386 return MaybeEntry
.takeError();
5387 BitstreamEntry Entry
= MaybeEntry
.get();
5389 switch (Entry
.Kind
) {
5390 case BitstreamEntry::SubBlock
: // Handled for us already.
5391 case BitstreamEntry::Error
:
5392 return error("Malformed block");
5393 case BitstreamEntry::EndBlock
:
5394 // Done parsing VST, jump back to wherever we came from.
5395 if (Error JumpFailed
= Stream
.JumpToBit(CurrentBit
))
5397 return Error::success();
5398 case BitstreamEntry::Record
:
5399 // The interesting case.
5405 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
5407 return MaybeRecord
.takeError();
5408 switch (MaybeRecord
.get()) {
5409 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5411 case bitc::VST_CODE_ENTRY
: { // VST_CODE_ENTRY: [valueid, namechar x N]
5412 if (convertToString(Record
, 1, ValueName
))
5413 return error("Invalid record");
5414 unsigned ValueID
= Record
[0];
5415 assert(!SourceFileName
.empty());
5416 auto VLI
= ValueIdToLinkageMap
.find(ValueID
);
5417 assert(VLI
!= ValueIdToLinkageMap
.end() &&
5418 "No linkage found for VST entry?");
5419 auto Linkage
= VLI
->second
;
5420 setValueGUID(ValueID
, ValueName
, Linkage
, SourceFileName
);
5424 case bitc::VST_CODE_FNENTRY
: {
5425 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5426 if (convertToString(Record
, 2, ValueName
))
5427 return error("Invalid record");
5428 unsigned ValueID
= Record
[0];
5429 assert(!SourceFileName
.empty());
5430 auto VLI
= ValueIdToLinkageMap
.find(ValueID
);
5431 assert(VLI
!= ValueIdToLinkageMap
.end() &&
5432 "No linkage found for VST entry?");
5433 auto Linkage
= VLI
->second
;
5434 setValueGUID(ValueID
, ValueName
, Linkage
, SourceFileName
);
5438 case bitc::VST_CODE_COMBINED_ENTRY
: {
5439 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5440 unsigned ValueID
= Record
[0];
5441 GlobalValue::GUID RefGUID
= Record
[1];
5442 // The "original name", which is the second value of the pair will be
5443 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5444 ValueIdToValueInfoMap
[ValueID
] =
5445 std::make_pair(TheIndex
.getOrInsertValueInfo(RefGUID
), RefGUID
);
5452 // Parse just the blocks needed for building the index out of the module.
5453 // At the end of this routine the module Index is populated with a map
5454 // from global value id to GlobalValueSummary objects.
5455 Error
ModuleSummaryIndexBitcodeReader::parseModule() {
5456 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
5459 SmallVector
<uint64_t, 64> Record
;
5460 DenseMap
<unsigned, GlobalValue::LinkageTypes
> ValueIdToLinkageMap
;
5461 unsigned ValueId
= 0;
5463 // Read the index for this module.
5465 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
5467 return MaybeEntry
.takeError();
5468 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
5470 switch (Entry
.Kind
) {
5471 case BitstreamEntry::Error
:
5472 return error("Malformed block");
5473 case BitstreamEntry::EndBlock
:
5474 return Error::success();
5476 case BitstreamEntry::SubBlock
:
5478 default: // Skip unknown content.
5479 if (Error Err
= Stream
.SkipBlock())
5482 case bitc::BLOCKINFO_BLOCK_ID
:
5483 // Need to parse these to get abbrev ids (e.g. for VST)
5484 if (readBlockInfo())
5485 return error("Malformed block");
5487 case bitc::VALUE_SYMTAB_BLOCK_ID
:
5488 // Should have been parsed earlier via VSTOffset, unless there
5489 // is no summary section.
5490 assert(((SeenValueSymbolTable
&& VSTOffset
> 0) ||
5491 !SeenGlobalValSummary
) &&
5492 "Expected early VST parse via VSTOffset record");
5493 if (Error Err
= Stream
.SkipBlock())
5496 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID
:
5497 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
:
5498 // Add the module if it is a per-module index (has a source file name).
5499 if (!SourceFileName
.empty())
5501 assert(!SeenValueSymbolTable
&&
5502 "Already read VST when parsing summary block?");
5503 // We might not have a VST if there were no values in the
5504 // summary. An empty summary block generated when we are
5505 // performing ThinLTO compiles so we don't later invoke
5506 // the regular LTO process on them.
5507 if (VSTOffset
> 0) {
5508 if (Error Err
= parseValueSymbolTable(VSTOffset
, ValueIdToLinkageMap
))
5510 SeenValueSymbolTable
= true;
5512 SeenGlobalValSummary
= true;
5513 if (Error Err
= parseEntireSummary(Entry
.ID
))
5516 case bitc::MODULE_STRTAB_BLOCK_ID
:
5517 if (Error Err
= parseModuleStringTable())
5523 case BitstreamEntry::Record
: {
5525 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
5527 return MaybeBitCode
.takeError();
5528 switch (MaybeBitCode
.get()) {
5530 break; // Default behavior, ignore unknown content.
5531 case bitc::MODULE_CODE_VERSION
: {
5532 if (Error Err
= parseVersionRecord(Record
).takeError())
5536 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5537 case bitc::MODULE_CODE_SOURCE_FILENAME
: {
5538 SmallString
<128> ValueName
;
5539 if (convertToString(Record
, 0, ValueName
))
5540 return error("Invalid record");
5541 SourceFileName
= ValueName
.c_str();
5544 /// MODULE_CODE_HASH: [5*i32]
5545 case bitc::MODULE_CODE_HASH
: {
5546 if (Record
.size() != 5)
5547 return error("Invalid hash length " + Twine(Record
.size()).str());
5548 auto &Hash
= getThisModule()->second
.second
;
5550 for (auto &Val
: Record
) {
5551 assert(!(Val
>> 32) && "Unexpected high bits set");
5556 /// MODULE_CODE_VSTOFFSET: [offset]
5557 case bitc::MODULE_CODE_VSTOFFSET
:
5558 if (Record
.size() < 1)
5559 return error("Invalid record");
5560 // Note that we subtract 1 here because the offset is relative to one
5561 // word before the start of the identification or module block, which
5562 // was historically always the start of the regular bitcode header.
5563 VSTOffset
= Record
[0] - 1;
5565 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
5566 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
5567 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
5568 // v2: [strtab offset, strtab size, v1]
5569 case bitc::MODULE_CODE_GLOBALVAR
:
5570 case bitc::MODULE_CODE_FUNCTION
:
5571 case bitc::MODULE_CODE_ALIAS
: {
5573 ArrayRef
<uint64_t> GVRecord
;
5574 std::tie(Name
, GVRecord
) = readNameFromStrtab(Record
);
5575 if (GVRecord
.size() <= 3)
5576 return error("Invalid record");
5577 uint64_t RawLinkage
= GVRecord
[3];
5578 GlobalValue::LinkageTypes Linkage
= getDecodedLinkage(RawLinkage
);
5580 ValueIdToLinkageMap
[ValueId
++] = Linkage
;
5584 setValueGUID(ValueId
++, Name
, Linkage
, SourceFileName
);
5594 std::vector
<ValueInfo
>
5595 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef
<uint64_t> Record
) {
5596 std::vector
<ValueInfo
> Ret
;
5597 Ret
.reserve(Record
.size());
5598 for (uint64_t RefValueId
: Record
)
5599 Ret
.push_back(getValueInfoFromValueId(RefValueId
).first
);
5603 std::vector
<FunctionSummary::EdgeTy
>
5604 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef
<uint64_t> Record
,
5605 bool IsOldProfileFormat
,
5606 bool HasProfile
, bool HasRelBF
) {
5607 std::vector
<FunctionSummary::EdgeTy
> Ret
;
5608 Ret
.reserve(Record
.size());
5609 for (unsigned I
= 0, E
= Record
.size(); I
!= E
; ++I
) {
5610 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
5612 ValueInfo Callee
= getValueInfoFromValueId(Record
[I
]).first
;
5613 if (IsOldProfileFormat
) {
5614 I
+= 1; // Skip old callsitecount field
5616 I
+= 1; // Skip old profilecount field
5617 } else if (HasProfile
)
5618 Hotness
= static_cast<CalleeInfo::HotnessType
>(Record
[++I
]);
5620 RelBF
= Record
[++I
];
5621 Ret
.push_back(FunctionSummary::EdgeTy
{Callee
, CalleeInfo(Hotness
, RelBF
)});
5627 parseWholeProgramDevirtResolutionByArg(ArrayRef
<uint64_t> Record
, size_t &Slot
,
5628 WholeProgramDevirtResolution
&Wpd
) {
5629 uint64_t ArgNum
= Record
[Slot
++];
5630 WholeProgramDevirtResolution::ByArg
&B
=
5631 Wpd
.ResByArg
[{Record
.begin() + Slot
, Record
.begin() + Slot
+ ArgNum
}];
5635 static_cast<WholeProgramDevirtResolution::ByArg::Kind
>(Record
[Slot
++]);
5636 B
.Info
= Record
[Slot
++];
5637 B
.Byte
= Record
[Slot
++];
5638 B
.Bit
= Record
[Slot
++];
5641 static void parseWholeProgramDevirtResolution(ArrayRef
<uint64_t> Record
,
5642 StringRef Strtab
, size_t &Slot
,
5643 TypeIdSummary
&TypeId
) {
5644 uint64_t Id
= Record
[Slot
++];
5645 WholeProgramDevirtResolution
&Wpd
= TypeId
.WPDRes
[Id
];
5647 Wpd
.TheKind
= static_cast<WholeProgramDevirtResolution::Kind
>(Record
[Slot
++]);
5648 Wpd
.SingleImplName
= {Strtab
.data() + Record
[Slot
],
5649 static_cast<size_t>(Record
[Slot
+ 1])};
5652 uint64_t ResByArgNum
= Record
[Slot
++];
5653 for (uint64_t I
= 0; I
!= ResByArgNum
; ++I
)
5654 parseWholeProgramDevirtResolutionByArg(Record
, Slot
, Wpd
);
5657 static void parseTypeIdSummaryRecord(ArrayRef
<uint64_t> Record
,
5659 ModuleSummaryIndex
&TheIndex
) {
5661 TypeIdSummary
&TypeId
= TheIndex
.getOrInsertTypeIdSummary(
5662 {Strtab
.data() + Record
[Slot
], static_cast<size_t>(Record
[Slot
+ 1])});
5665 TypeId
.TTRes
.TheKind
= static_cast<TypeTestResolution::Kind
>(Record
[Slot
++]);
5666 TypeId
.TTRes
.SizeM1BitWidth
= Record
[Slot
++];
5667 TypeId
.TTRes
.AlignLog2
= Record
[Slot
++];
5668 TypeId
.TTRes
.SizeM1
= Record
[Slot
++];
5669 TypeId
.TTRes
.BitMask
= Record
[Slot
++];
5670 TypeId
.TTRes
.InlineBits
= Record
[Slot
++];
5672 while (Slot
< Record
.size())
5673 parseWholeProgramDevirtResolution(Record
, Strtab
, Slot
, TypeId
);
5676 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
5677 ArrayRef
<uint64_t> Record
, size_t &Slot
,
5678 TypeIdCompatibleVtableInfo
&TypeId
) {
5679 uint64_t Offset
= Record
[Slot
++];
5680 ValueInfo Callee
= getValueInfoFromValueId(Record
[Slot
++]).first
;
5681 TypeId
.push_back({Offset
, Callee
});
5684 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
5685 ArrayRef
<uint64_t> Record
) {
5687 TypeIdCompatibleVtableInfo
&TypeId
=
5688 TheIndex
.getOrInsertTypeIdCompatibleVtableSummary(
5689 {Strtab
.data() + Record
[Slot
],
5690 static_cast<size_t>(Record
[Slot
+ 1])});
5693 while (Slot
< Record
.size())
5694 parseTypeIdCompatibleVtableInfo(Record
, Slot
, TypeId
);
5697 static void setSpecialRefs(std::vector
<ValueInfo
> &Refs
, unsigned ROCnt
,
5699 // Readonly and writeonly refs are in the end of the refs list.
5700 assert(ROCnt
+ WOCnt
<= Refs
.size());
5701 unsigned FirstWORef
= Refs
.size() - WOCnt
;
5702 unsigned RefNo
= FirstWORef
- ROCnt
;
5703 for (; RefNo
< FirstWORef
; ++RefNo
)
5704 Refs
[RefNo
].setReadOnly();
5705 for (; RefNo
< Refs
.size(); ++RefNo
)
5706 Refs
[RefNo
].setWriteOnly();
5709 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
5710 // objects in the index.
5711 Error
ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID
) {
5712 if (Error Err
= Stream
.EnterSubBlock(ID
))
5714 SmallVector
<uint64_t, 64> Record
;
5718 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
5720 return MaybeEntry
.takeError();
5721 BitstreamEntry Entry
= MaybeEntry
.get();
5723 if (Entry
.Kind
!= BitstreamEntry::Record
)
5724 return error("Invalid Summary Block: record for version expected");
5725 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
5727 return MaybeRecord
.takeError();
5728 if (MaybeRecord
.get() != bitc::FS_VERSION
)
5729 return error("Invalid Summary Block: version expected");
5731 const uint64_t Version
= Record
[0];
5732 const bool IsOldProfileFormat
= Version
== 1;
5733 if (Version
< 1 || Version
> 7)
5734 return error("Invalid summary version " + Twine(Version
) +
5735 ". Version should be in the range [1-7].");
5738 // Keep around the last seen summary to be used when we see an optional
5739 // "OriginalName" attachement.
5740 GlobalValueSummary
*LastSeenSummary
= nullptr;
5741 GlobalValue::GUID LastSeenGUID
= 0;
5743 // We can expect to see any number of type ID information records before
5744 // each function summary records; these variables store the information
5745 // collected so far so that it can be used to create the summary object.
5746 std::vector
<GlobalValue::GUID
> PendingTypeTests
;
5747 std::vector
<FunctionSummary::VFuncId
> PendingTypeTestAssumeVCalls
,
5748 PendingTypeCheckedLoadVCalls
;
5749 std::vector
<FunctionSummary::ConstVCall
> PendingTypeTestAssumeConstVCalls
,
5750 PendingTypeCheckedLoadConstVCalls
;
5753 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
5755 return MaybeEntry
.takeError();
5756 BitstreamEntry Entry
= MaybeEntry
.get();
5758 switch (Entry
.Kind
) {
5759 case BitstreamEntry::SubBlock
: // Handled for us already.
5760 case BitstreamEntry::Error
:
5761 return error("Malformed block");
5762 case BitstreamEntry::EndBlock
:
5763 return Error::success();
5764 case BitstreamEntry::Record
:
5765 // The interesting case.
5769 // Read a record. The record format depends on whether this
5770 // is a per-module index or a combined index file. In the per-module
5771 // case the records contain the associated value's ID for correlation
5772 // with VST entries. In the combined index the correlation is done
5773 // via the bitcode offset of the summary records (which were saved
5774 // in the combined index VST entries). The records also contain
5775 // information used for ThinLTO renaming and importing.
5777 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
5779 return MaybeBitCode
.takeError();
5780 switch (unsigned BitCode
= MaybeBitCode
.get()) {
5781 default: // Default behavior: ignore.
5783 case bitc::FS_FLAGS
: { // [flags]
5784 uint64_t Flags
= Record
[0];
5786 assert(Flags
<= 0x1f && "Unexpected bits in flag");
5788 // 1 bit: WithGlobalValueDeadStripping flag.
5789 // Set on combined index only.
5791 TheIndex
.setWithGlobalValueDeadStripping();
5792 // 1 bit: SkipModuleByDistributedBackend flag.
5793 // Set on combined index only.
5795 TheIndex
.setSkipModuleByDistributedBackend();
5796 // 1 bit: HasSyntheticEntryCounts flag.
5797 // Set on combined index only.
5799 TheIndex
.setHasSyntheticEntryCounts();
5800 // 1 bit: DisableSplitLTOUnit flag.
5801 // Set on per module indexes. It is up to the client to validate
5802 // the consistency of this flag across modules being linked.
5804 TheIndex
.setEnableSplitLTOUnit();
5805 // 1 bit: PartiallySplitLTOUnits flag.
5806 // Set on combined index only.
5808 TheIndex
.setPartiallySplitLTOUnits();
5811 case bitc::FS_VALUE_GUID
: { // [valueid, refguid]
5812 uint64_t ValueID
= Record
[0];
5813 GlobalValue::GUID RefGUID
= Record
[1];
5814 ValueIdToValueInfoMap
[ValueID
] =
5815 std::make_pair(TheIndex
.getOrInsertValueInfo(RefGUID
), RefGUID
);
5818 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5819 // numrefs x valueid, n x (valueid)]
5820 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
5821 // numrefs x valueid,
5822 // n x (valueid, hotness)]
5823 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
5824 // numrefs x valueid,
5825 // n x (valueid, relblockfreq)]
5826 case bitc::FS_PERMODULE
:
5827 case bitc::FS_PERMODULE_RELBF
:
5828 case bitc::FS_PERMODULE_PROFILE
: {
5829 unsigned ValueID
= Record
[0];
5830 uint64_t RawFlags
= Record
[1];
5831 unsigned InstCount
= Record
[2];
5832 uint64_t RawFunFlags
= 0;
5833 unsigned NumRefs
= Record
[3];
5834 unsigned NumRORefs
= 0, NumWORefs
= 0;
5835 int RefListStartIndex
= 4;
5837 RawFunFlags
= Record
[3];
5838 NumRefs
= Record
[4];
5839 RefListStartIndex
= 5;
5841 NumRORefs
= Record
[5];
5842 RefListStartIndex
= 6;
5844 NumWORefs
= Record
[6];
5845 RefListStartIndex
= 7;
5850 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5851 // The module path string ref set in the summary must be owned by the
5852 // index's module string table. Since we don't have a module path
5853 // string table section in the per-module index, we create a single
5854 // module path string table entry with an empty (0) ID to take
5856 int CallGraphEdgeStartIndex
= RefListStartIndex
+ NumRefs
;
5857 assert(Record
.size() >= RefListStartIndex
+ NumRefs
&&
5858 "Record size inconsistent with number of references");
5859 std::vector
<ValueInfo
> Refs
= makeRefList(
5860 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
5861 bool HasProfile
= (BitCode
== bitc::FS_PERMODULE_PROFILE
);
5862 bool HasRelBF
= (BitCode
== bitc::FS_PERMODULE_RELBF
);
5863 std::vector
<FunctionSummary::EdgeTy
> Calls
= makeCallList(
5864 ArrayRef
<uint64_t>(Record
).slice(CallGraphEdgeStartIndex
),
5865 IsOldProfileFormat
, HasProfile
, HasRelBF
);
5866 setSpecialRefs(Refs
, NumRORefs
, NumWORefs
);
5867 auto FS
= llvm::make_unique
<FunctionSummary
>(
5868 Flags
, InstCount
, getDecodedFFlags(RawFunFlags
), /*EntryCount=*/0,
5869 std::move(Refs
), std::move(Calls
), std::move(PendingTypeTests
),
5870 std::move(PendingTypeTestAssumeVCalls
),
5871 std::move(PendingTypeCheckedLoadVCalls
),
5872 std::move(PendingTypeTestAssumeConstVCalls
),
5873 std::move(PendingTypeCheckedLoadConstVCalls
));
5874 PendingTypeTests
.clear();
5875 PendingTypeTestAssumeVCalls
.clear();
5876 PendingTypeCheckedLoadVCalls
.clear();
5877 PendingTypeTestAssumeConstVCalls
.clear();
5878 PendingTypeCheckedLoadConstVCalls
.clear();
5879 auto VIAndOriginalGUID
= getValueInfoFromValueId(ValueID
);
5880 FS
->setModulePath(getThisModule()->first());
5881 FS
->setOriginalName(VIAndOriginalGUID
.second
);
5882 TheIndex
.addGlobalValueSummary(VIAndOriginalGUID
.first
, std::move(FS
));
5885 // FS_ALIAS: [valueid, flags, valueid]
5886 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5887 // they expect all aliasee summaries to be available.
5888 case bitc::FS_ALIAS
: {
5889 unsigned ValueID
= Record
[0];
5890 uint64_t RawFlags
= Record
[1];
5891 unsigned AliaseeID
= Record
[2];
5892 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5893 auto AS
= llvm::make_unique
<AliasSummary
>(Flags
);
5894 // The module path string ref set in the summary must be owned by the
5895 // index's module string table. Since we don't have a module path
5896 // string table section in the per-module index, we create a single
5897 // module path string table entry with an empty (0) ID to take
5899 AS
->setModulePath(getThisModule()->first());
5901 auto AliaseeVI
= getValueInfoFromValueId(AliaseeID
).first
;
5902 auto AliaseeInModule
= TheIndex
.findSummaryInModule(AliaseeVI
, ModulePath
);
5903 if (!AliaseeInModule
)
5904 return error("Alias expects aliasee summary to be parsed");
5905 AS
->setAliasee(AliaseeVI
, AliaseeInModule
);
5907 auto GUID
= getValueInfoFromValueId(ValueID
);
5908 AS
->setOriginalName(GUID
.second
);
5909 TheIndex
.addGlobalValueSummary(GUID
.first
, std::move(AS
));
5912 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
5913 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS
: {
5914 unsigned ValueID
= Record
[0];
5915 uint64_t RawFlags
= Record
[1];
5916 unsigned RefArrayStart
= 2;
5917 GlobalVarSummary::GVarFlags
GVF(/* ReadOnly */ false,
5918 /* WriteOnly */ false);
5919 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5921 GVF
= getDecodedGVarFlags(Record
[2]);
5924 std::vector
<ValueInfo
> Refs
=
5925 makeRefList(ArrayRef
<uint64_t>(Record
).slice(RefArrayStart
));
5927 llvm::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
5928 FS
->setModulePath(getThisModule()->first());
5929 auto GUID
= getValueInfoFromValueId(ValueID
);
5930 FS
->setOriginalName(GUID
.second
);
5931 TheIndex
.addGlobalValueSummary(GUID
.first
, std::move(FS
));
5934 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
5935 // numrefs, numrefs x valueid,
5936 // n x (valueid, offset)]
5937 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
: {
5938 unsigned ValueID
= Record
[0];
5939 uint64_t RawFlags
= Record
[1];
5940 GlobalVarSummary::GVarFlags GVF
= getDecodedGVarFlags(Record
[2]);
5941 unsigned NumRefs
= Record
[3];
5942 unsigned RefListStartIndex
= 4;
5943 unsigned VTableListStartIndex
= RefListStartIndex
+ NumRefs
;
5944 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
5945 std::vector
<ValueInfo
> Refs
= makeRefList(
5946 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
5947 VTableFuncList VTableFuncs
;
5948 for (unsigned I
= VTableListStartIndex
, E
= Record
.size(); I
!= E
; ++I
) {
5949 ValueInfo Callee
= getValueInfoFromValueId(Record
[I
]).first
;
5950 uint64_t Offset
= Record
[++I
];
5951 VTableFuncs
.push_back({Callee
, Offset
});
5954 llvm::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
5955 VS
->setModulePath(getThisModule()->first());
5956 VS
->setVTableFuncs(VTableFuncs
);
5957 auto GUID
= getValueInfoFromValueId(ValueID
);
5958 VS
->setOriginalName(GUID
.second
);
5959 TheIndex
.addGlobalValueSummary(GUID
.first
, std::move(VS
));
5962 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
5963 // numrefs x valueid, n x (valueid)]
5964 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
5965 // numrefs x valueid, n x (valueid, hotness)]
5966 case bitc::FS_COMBINED
:
5967 case bitc::FS_COMBINED_PROFILE
: {
5968 unsigned ValueID
= Record
[0];
5969 uint64_t ModuleId
= Record
[1];
5970 uint64_t RawFlags
= Record
[2];
5971 unsigned InstCount
= Record
[3];
5972 uint64_t RawFunFlags
= 0;
5973 uint64_t EntryCount
= 0;
5974 unsigned NumRefs
= Record
[4];
5975 unsigned NumRORefs
= 0, NumWORefs
= 0;
5976 int RefListStartIndex
= 5;
5979 RawFunFlags
= Record
[4];
5980 RefListStartIndex
= 6;
5981 size_t NumRefsIndex
= 5;
5983 unsigned NumRORefsOffset
= 1;
5984 RefListStartIndex
= 7;
5987 EntryCount
= Record
[5];
5988 RefListStartIndex
= 8;
5990 RefListStartIndex
= 9;
5991 NumWORefs
= Record
[8];
5992 NumRORefsOffset
= 2;
5995 NumRORefs
= Record
[RefListStartIndex
- NumRORefsOffset
];
5997 NumRefs
= Record
[NumRefsIndex
];
6000 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
6001 int CallGraphEdgeStartIndex
= RefListStartIndex
+ NumRefs
;
6002 assert(Record
.size() >= RefListStartIndex
+ NumRefs
&&
6003 "Record size inconsistent with number of references");
6004 std::vector
<ValueInfo
> Refs
= makeRefList(
6005 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
6006 bool HasProfile
= (BitCode
== bitc::FS_COMBINED_PROFILE
);
6007 std::vector
<FunctionSummary::EdgeTy
> Edges
= makeCallList(
6008 ArrayRef
<uint64_t>(Record
).slice(CallGraphEdgeStartIndex
),
6009 IsOldProfileFormat
, HasProfile
, false);
6010 ValueInfo VI
= getValueInfoFromValueId(ValueID
).first
;
6011 setSpecialRefs(Refs
, NumRORefs
, NumWORefs
);
6012 auto FS
= llvm::make_unique
<FunctionSummary
>(
6013 Flags
, InstCount
, getDecodedFFlags(RawFunFlags
), EntryCount
,
6014 std::move(Refs
), std::move(Edges
), std::move(PendingTypeTests
),
6015 std::move(PendingTypeTestAssumeVCalls
),
6016 std::move(PendingTypeCheckedLoadVCalls
),
6017 std::move(PendingTypeTestAssumeConstVCalls
),
6018 std::move(PendingTypeCheckedLoadConstVCalls
));
6019 PendingTypeTests
.clear();
6020 PendingTypeTestAssumeVCalls
.clear();
6021 PendingTypeCheckedLoadVCalls
.clear();
6022 PendingTypeTestAssumeConstVCalls
.clear();
6023 PendingTypeCheckedLoadConstVCalls
.clear();
6024 LastSeenSummary
= FS
.get();
6025 LastSeenGUID
= VI
.getGUID();
6026 FS
->setModulePath(ModuleIdMap
[ModuleId
]);
6027 TheIndex
.addGlobalValueSummary(VI
, std::move(FS
));
6030 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6031 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6032 // they expect all aliasee summaries to be available.
6033 case bitc::FS_COMBINED_ALIAS
: {
6034 unsigned ValueID
= Record
[0];
6035 uint64_t ModuleId
= Record
[1];
6036 uint64_t RawFlags
= Record
[2];
6037 unsigned AliaseeValueId
= Record
[3];
6038 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
6039 auto AS
= llvm::make_unique
<AliasSummary
>(Flags
);
6040 LastSeenSummary
= AS
.get();
6041 AS
->setModulePath(ModuleIdMap
[ModuleId
]);
6043 auto AliaseeVI
= getValueInfoFromValueId(AliaseeValueId
).first
;
6044 auto AliaseeInModule
= TheIndex
.findSummaryInModule(AliaseeVI
, AS
->modulePath());
6045 AS
->setAliasee(AliaseeVI
, AliaseeInModule
);
6047 ValueInfo VI
= getValueInfoFromValueId(ValueID
).first
;
6048 LastSeenGUID
= VI
.getGUID();
6049 TheIndex
.addGlobalValueSummary(VI
, std::move(AS
));
6052 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6053 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS
: {
6054 unsigned ValueID
= Record
[0];
6055 uint64_t ModuleId
= Record
[1];
6056 uint64_t RawFlags
= Record
[2];
6057 unsigned RefArrayStart
= 3;
6058 GlobalVarSummary::GVarFlags
GVF(/* ReadOnly */ false,
6059 /* WriteOnly */ false);
6060 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
6062 GVF
= getDecodedGVarFlags(Record
[3]);
6065 std::vector
<ValueInfo
> Refs
=
6066 makeRefList(ArrayRef
<uint64_t>(Record
).slice(RefArrayStart
));
6068 llvm::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
6069 LastSeenSummary
= FS
.get();
6070 FS
->setModulePath(ModuleIdMap
[ModuleId
]);
6071 ValueInfo VI
= getValueInfoFromValueId(ValueID
).first
;
6072 LastSeenGUID
= VI
.getGUID();
6073 TheIndex
.addGlobalValueSummary(VI
, std::move(FS
));
6076 // FS_COMBINED_ORIGINAL_NAME: [original_name]
6077 case bitc::FS_COMBINED_ORIGINAL_NAME
: {
6078 uint64_t OriginalName
= Record
[0];
6079 if (!LastSeenSummary
)
6080 return error("Name attachment that does not follow a combined record");
6081 LastSeenSummary
->setOriginalName(OriginalName
);
6082 TheIndex
.addOriginalName(LastSeenGUID
, OriginalName
);
6083 // Reset the LastSeenSummary
6084 LastSeenSummary
= nullptr;
6088 case bitc::FS_TYPE_TESTS
:
6089 assert(PendingTypeTests
.empty());
6090 PendingTypeTests
.insert(PendingTypeTests
.end(), Record
.begin(),
6094 case bitc::FS_TYPE_TEST_ASSUME_VCALLS
:
6095 assert(PendingTypeTestAssumeVCalls
.empty());
6096 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
6097 PendingTypeTestAssumeVCalls
.push_back({Record
[I
], Record
[I
+1]});
6100 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS
:
6101 assert(PendingTypeCheckedLoadVCalls
.empty());
6102 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
6103 PendingTypeCheckedLoadVCalls
.push_back({Record
[I
], Record
[I
+1]});
6106 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL
:
6107 PendingTypeTestAssumeConstVCalls
.push_back(
6108 {{Record
[0], Record
[1]}, {Record
.begin() + 2, Record
.end()}});
6111 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL
:
6112 PendingTypeCheckedLoadConstVCalls
.push_back(
6113 {{Record
[0], Record
[1]}, {Record
.begin() + 2, Record
.end()}});
6116 case bitc::FS_CFI_FUNCTION_DEFS
: {
6117 std::set
<std::string
> &CfiFunctionDefs
= TheIndex
.cfiFunctionDefs();
6118 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
6119 CfiFunctionDefs
.insert(
6120 {Strtab
.data() + Record
[I
], static_cast<size_t>(Record
[I
+ 1])});
6124 case bitc::FS_CFI_FUNCTION_DECLS
: {
6125 std::set
<std::string
> &CfiFunctionDecls
= TheIndex
.cfiFunctionDecls();
6126 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
6127 CfiFunctionDecls
.insert(
6128 {Strtab
.data() + Record
[I
], static_cast<size_t>(Record
[I
+ 1])});
6132 case bitc::FS_TYPE_ID
:
6133 parseTypeIdSummaryRecord(Record
, Strtab
, TheIndex
);
6136 case bitc::FS_TYPE_ID_METADATA
:
6137 parseTypeIdCompatibleVtableSummaryRecord(Record
);
6141 llvm_unreachable("Exit infinite loop");
6144 // Parse the module string table block into the Index.
6145 // This populates the ModulePathStringTable map in the index.
6146 Error
ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6147 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID
))
6150 SmallVector
<uint64_t, 64> Record
;
6152 SmallString
<128> ModulePath
;
6153 ModuleSummaryIndex::ModuleInfo
*LastSeenModule
= nullptr;
6156 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
6158 return MaybeEntry
.takeError();
6159 BitstreamEntry Entry
= MaybeEntry
.get();
6161 switch (Entry
.Kind
) {
6162 case BitstreamEntry::SubBlock
: // Handled for us already.
6163 case BitstreamEntry::Error
:
6164 return error("Malformed block");
6165 case BitstreamEntry::EndBlock
:
6166 return Error::success();
6167 case BitstreamEntry::Record
:
6168 // The interesting case.
6173 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
6175 return MaybeRecord
.takeError();
6176 switch (MaybeRecord
.get()) {
6177 default: // Default behavior: ignore.
6179 case bitc::MST_CODE_ENTRY
: {
6180 // MST_ENTRY: [modid, namechar x N]
6181 uint64_t ModuleId
= Record
[0];
6183 if (convertToString(Record
, 1, ModulePath
))
6184 return error("Invalid record");
6186 LastSeenModule
= TheIndex
.addModule(ModulePath
, ModuleId
);
6187 ModuleIdMap
[ModuleId
] = LastSeenModule
->first();
6192 /// MST_CODE_HASH: [5*i32]
6193 case bitc::MST_CODE_HASH
: {
6194 if (Record
.size() != 5)
6195 return error("Invalid hash length " + Twine(Record
.size()).str());
6196 if (!LastSeenModule
)
6197 return error("Invalid hash that does not follow a module path");
6199 for (auto &Val
: Record
) {
6200 assert(!(Val
>> 32) && "Unexpected high bits set");
6201 LastSeenModule
->second
.second
[Pos
++] = Val
;
6203 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
6204 LastSeenModule
= nullptr;
6209 llvm_unreachable("Exit infinite loop");
6214 // FIXME: This class is only here to support the transition to llvm::Error. It
6215 // will be removed once this transition is complete. Clients should prefer to
6216 // deal with the Error value directly, rather than converting to error_code.
6217 class BitcodeErrorCategoryType
: public std::error_category
{
6218 const char *name() const noexcept override
{
6219 return "llvm.bitcode";
6222 std::string
message(int IE
) const override
{
6223 BitcodeError E
= static_cast<BitcodeError
>(IE
);
6225 case BitcodeError::CorruptedBitcode
:
6226 return "Corrupted bitcode";
6228 llvm_unreachable("Unknown error type!");
6232 } // end anonymous namespace
6234 static ManagedStatic
<BitcodeErrorCategoryType
> ErrorCategory
;
6236 const std::error_category
&llvm::BitcodeErrorCategory() {
6237 return *ErrorCategory
;
6240 static Expected
<StringRef
> readBlobInRecord(BitstreamCursor
&Stream
,
6241 unsigned Block
, unsigned RecordID
) {
6242 if (Error Err
= Stream
.EnterSubBlock(Block
))
6243 return std::move(Err
);
6247 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
6249 return MaybeEntry
.takeError();
6250 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
6252 switch (Entry
.Kind
) {
6253 case BitstreamEntry::EndBlock
:
6256 case BitstreamEntry::Error
:
6257 return error("Malformed block");
6259 case BitstreamEntry::SubBlock
:
6260 if (Error Err
= Stream
.SkipBlock())
6261 return std::move(Err
);
6264 case BitstreamEntry::Record
:
6266 SmallVector
<uint64_t, 1> Record
;
6267 Expected
<unsigned> MaybeRecord
=
6268 Stream
.readRecord(Entry
.ID
, Record
, &Blob
);
6270 return MaybeRecord
.takeError();
6271 if (MaybeRecord
.get() == RecordID
)
6278 //===----------------------------------------------------------------------===//
6279 // External interface
6280 //===----------------------------------------------------------------------===//
6282 Expected
<std::vector
<BitcodeModule
>>
6283 llvm::getBitcodeModuleList(MemoryBufferRef Buffer
) {
6284 auto FOrErr
= getBitcodeFileContents(Buffer
);
6286 return FOrErr
.takeError();
6287 return std::move(FOrErr
->Mods
);
6290 Expected
<BitcodeFileContents
>
6291 llvm::getBitcodeFileContents(MemoryBufferRef Buffer
) {
6292 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
6294 return StreamOrErr
.takeError();
6295 BitstreamCursor
&Stream
= *StreamOrErr
;
6297 BitcodeFileContents F
;
6299 uint64_t BCBegin
= Stream
.getCurrentByteNo();
6301 // We may be consuming bitcode from a client that leaves garbage at the end
6302 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
6303 // the end that there cannot possibly be another module, stop looking.
6304 if (BCBegin
+ 8 >= Stream
.getBitcodeBytes().size())
6307 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
6309 return MaybeEntry
.takeError();
6310 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
6312 switch (Entry
.Kind
) {
6313 case BitstreamEntry::EndBlock
:
6314 case BitstreamEntry::Error
:
6315 return error("Malformed block");
6317 case BitstreamEntry::SubBlock
: {
6318 uint64_t IdentificationBit
= -1ull;
6319 if (Entry
.ID
== bitc::IDENTIFICATION_BLOCK_ID
) {
6320 IdentificationBit
= Stream
.GetCurrentBitNo() - BCBegin
* 8;
6321 if (Error Err
= Stream
.SkipBlock())
6322 return std::move(Err
);
6325 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
6327 return MaybeEntry
.takeError();
6328 Entry
= MaybeEntry
.get();
6331 if (Entry
.Kind
!= BitstreamEntry::SubBlock
||
6332 Entry
.ID
!= bitc::MODULE_BLOCK_ID
)
6333 return error("Malformed block");
6336 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
) {
6337 uint64_t ModuleBit
= Stream
.GetCurrentBitNo() - BCBegin
* 8;
6338 if (Error Err
= Stream
.SkipBlock())
6339 return std::move(Err
);
6341 F
.Mods
.push_back({Stream
.getBitcodeBytes().slice(
6342 BCBegin
, Stream
.getCurrentByteNo() - BCBegin
),
6343 Buffer
.getBufferIdentifier(), IdentificationBit
,
6348 if (Entry
.ID
== bitc::STRTAB_BLOCK_ID
) {
6349 Expected
<StringRef
> Strtab
=
6350 readBlobInRecord(Stream
, bitc::STRTAB_BLOCK_ID
, bitc::STRTAB_BLOB
);
6352 return Strtab
.takeError();
6353 // This string table is used by every preceding bitcode module that does
6354 // not have its own string table. A bitcode file may have multiple
6355 // string tables if it was created by binary concatenation, for example
6356 // with "llvm-cat -b".
6357 for (auto I
= F
.Mods
.rbegin(), E
= F
.Mods
.rend(); I
!= E
; ++I
) {
6358 if (!I
->Strtab
.empty())
6360 I
->Strtab
= *Strtab
;
6362 // Similarly, the string table is used by every preceding symbol table;
6363 // normally there will be just one unless the bitcode file was created
6364 // by binary concatenation.
6365 if (!F
.Symtab
.empty() && F
.StrtabForSymtab
.empty())
6366 F
.StrtabForSymtab
= *Strtab
;
6370 if (Entry
.ID
== bitc::SYMTAB_BLOCK_ID
) {
6371 Expected
<StringRef
> SymtabOrErr
=
6372 readBlobInRecord(Stream
, bitc::SYMTAB_BLOCK_ID
, bitc::SYMTAB_BLOB
);
6374 return SymtabOrErr
.takeError();
6376 // We can expect the bitcode file to have multiple symbol tables if it
6377 // was created by binary concatenation. In that case we silently
6378 // ignore any subsequent symbol tables, which is fine because this is a
6379 // low level function. The client is expected to notice that the number
6380 // of modules in the symbol table does not match the number of modules
6381 // in the input file and regenerate the symbol table.
6382 if (F
.Symtab
.empty())
6383 F
.Symtab
= *SymtabOrErr
;
6387 if (Error Err
= Stream
.SkipBlock())
6388 return std::move(Err
);
6391 case BitstreamEntry::Record
:
6392 if (Expected
<unsigned> StreamFailed
= Stream
.skipRecord(Entry
.ID
))
6395 return StreamFailed
.takeError();
6400 /// Get a lazy one-at-time loading module from bitcode.
6402 /// This isn't always used in a lazy context. In particular, it's also used by
6403 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
6404 /// in forward-referenced functions from block address references.
6406 /// \param[in] MaterializeAll Set to \c true if we should materialize
6408 Expected
<std::unique_ptr
<Module
>>
6409 BitcodeModule::getModuleImpl(LLVMContext
&Context
, bool MaterializeAll
,
6410 bool ShouldLazyLoadMetadata
, bool IsImporting
) {
6411 BitstreamCursor
Stream(Buffer
);
6413 std::string ProducerIdentification
;
6414 if (IdentificationBit
!= -1ull) {
6415 if (Error JumpFailed
= Stream
.JumpToBit(IdentificationBit
))
6416 return std::move(JumpFailed
);
6417 Expected
<std::string
> ProducerIdentificationOrErr
=
6418 readIdentificationBlock(Stream
);
6419 if (!ProducerIdentificationOrErr
)
6420 return ProducerIdentificationOrErr
.takeError();
6422 ProducerIdentification
= *ProducerIdentificationOrErr
;
6425 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
6426 return std::move(JumpFailed
);
6427 auto *R
= new BitcodeReader(std::move(Stream
), Strtab
, ProducerIdentification
,
6430 std::unique_ptr
<Module
> M
=
6431 llvm::make_unique
<Module
>(ModuleIdentifier
, Context
);
6432 M
->setMaterializer(R
);
6434 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6436 R
->parseBitcodeInto(M
.get(), ShouldLazyLoadMetadata
, IsImporting
))
6437 return std::move(Err
);
6439 if (MaterializeAll
) {
6440 // Read in the entire module, and destroy the BitcodeReader.
6441 if (Error Err
= M
->materializeAll())
6442 return std::move(Err
);
6444 // Resolve forward references from blockaddresses.
6445 if (Error Err
= R
->materializeForwardReferencedFunctions())
6446 return std::move(Err
);
6448 return std::move(M
);
6451 Expected
<std::unique_ptr
<Module
>>
6452 BitcodeModule::getLazyModule(LLVMContext
&Context
, bool ShouldLazyLoadMetadata
,
6454 return getModuleImpl(Context
, false, ShouldLazyLoadMetadata
, IsImporting
);
6457 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
6458 // We don't use ModuleIdentifier here because the client may need to control the
6459 // module path used in the combined summary (e.g. when reading summaries for
6460 // regular LTO modules).
6461 Error
BitcodeModule::readSummary(ModuleSummaryIndex
&CombinedIndex
,
6462 StringRef ModulePath
, uint64_t ModuleId
) {
6463 BitstreamCursor
Stream(Buffer
);
6464 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
6467 ModuleSummaryIndexBitcodeReader
R(std::move(Stream
), Strtab
, CombinedIndex
,
6468 ModulePath
, ModuleId
);
6469 return R
.parseModule();
6472 // Parse the specified bitcode buffer, returning the function info index.
6473 Expected
<std::unique_ptr
<ModuleSummaryIndex
>> BitcodeModule::getSummary() {
6474 BitstreamCursor
Stream(Buffer
);
6475 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
6476 return std::move(JumpFailed
);
6478 auto Index
= llvm::make_unique
<ModuleSummaryIndex
>(/*HaveGVs=*/false);
6479 ModuleSummaryIndexBitcodeReader
R(std::move(Stream
), Strtab
, *Index
,
6480 ModuleIdentifier
, 0);
6482 if (Error Err
= R
.parseModule())
6483 return std::move(Err
);
6485 return std::move(Index
);
6488 static Expected
<bool> getEnableSplitLTOUnitFlag(BitstreamCursor
&Stream
,
6490 if (Error Err
= Stream
.EnterSubBlock(ID
))
6491 return std::move(Err
);
6492 SmallVector
<uint64_t, 64> Record
;
6495 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
6497 return MaybeEntry
.takeError();
6498 BitstreamEntry Entry
= MaybeEntry
.get();
6500 switch (Entry
.Kind
) {
6501 case BitstreamEntry::SubBlock
: // Handled for us already.
6502 case BitstreamEntry::Error
:
6503 return error("Malformed block");
6504 case BitstreamEntry::EndBlock
:
6505 // If no flags record found, conservatively return true to mimic
6506 // behavior before this flag was added.
6508 case BitstreamEntry::Record
:
6509 // The interesting case.
6513 // Look for the FS_FLAGS record.
6515 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
6517 return MaybeBitCode
.takeError();
6518 switch (MaybeBitCode
.get()) {
6519 default: // Default behavior: ignore.
6521 case bitc::FS_FLAGS
: { // [flags]
6522 uint64_t Flags
= Record
[0];
6524 assert(Flags
<= 0x1f && "Unexpected bits in flag");
6530 llvm_unreachable("Exit infinite loop");
6533 // Check if the given bitcode buffer contains a global value summary block.
6534 Expected
<BitcodeLTOInfo
> BitcodeModule::getLTOInfo() {
6535 BitstreamCursor
Stream(Buffer
);
6536 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
6537 return std::move(JumpFailed
);
6539 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
6540 return std::move(Err
);
6543 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
6545 return MaybeEntry
.takeError();
6546 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
6548 switch (Entry
.Kind
) {
6549 case BitstreamEntry::Error
:
6550 return error("Malformed block");
6551 case BitstreamEntry::EndBlock
:
6552 return BitcodeLTOInfo
{/*IsThinLTO=*/false, /*HasSummary=*/false,
6553 /*EnableSplitLTOUnit=*/false};
6555 case BitstreamEntry::SubBlock
:
6556 if (Entry
.ID
== bitc::GLOBALVAL_SUMMARY_BLOCK_ID
) {
6557 Expected
<bool> EnableSplitLTOUnit
=
6558 getEnableSplitLTOUnitFlag(Stream
, Entry
.ID
);
6559 if (!EnableSplitLTOUnit
)
6560 return EnableSplitLTOUnit
.takeError();
6561 return BitcodeLTOInfo
{/*IsThinLTO=*/true, /*HasSummary=*/true,
6562 *EnableSplitLTOUnit
};
6565 if (Entry
.ID
== bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
) {
6566 Expected
<bool> EnableSplitLTOUnit
=
6567 getEnableSplitLTOUnitFlag(Stream
, Entry
.ID
);
6568 if (!EnableSplitLTOUnit
)
6569 return EnableSplitLTOUnit
.takeError();
6570 return BitcodeLTOInfo
{/*IsThinLTO=*/false, /*HasSummary=*/true,
6571 *EnableSplitLTOUnit
};
6574 // Ignore other sub-blocks.
6575 if (Error Err
= Stream
.SkipBlock())
6576 return std::move(Err
);
6579 case BitstreamEntry::Record
:
6580 if (Expected
<unsigned> StreamFailed
= Stream
.skipRecord(Entry
.ID
))
6583 return StreamFailed
.takeError();
6588 static Expected
<BitcodeModule
> getSingleModule(MemoryBufferRef Buffer
) {
6589 Expected
<std::vector
<BitcodeModule
>> MsOrErr
= getBitcodeModuleList(Buffer
);
6591 return MsOrErr
.takeError();
6593 if (MsOrErr
->size() != 1)
6594 return error("Expected a single module");
6596 return (*MsOrErr
)[0];
6599 Expected
<std::unique_ptr
<Module
>>
6600 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer
, LLVMContext
&Context
,
6601 bool ShouldLazyLoadMetadata
, bool IsImporting
) {
6602 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6604 return BM
.takeError();
6606 return BM
->getLazyModule(Context
, ShouldLazyLoadMetadata
, IsImporting
);
6609 Expected
<std::unique_ptr
<Module
>> llvm::getOwningLazyBitcodeModule(
6610 std::unique_ptr
<MemoryBuffer
> &&Buffer
, LLVMContext
&Context
,
6611 bool ShouldLazyLoadMetadata
, bool IsImporting
) {
6612 auto MOrErr
= getLazyBitcodeModule(*Buffer
, Context
, ShouldLazyLoadMetadata
,
6615 (*MOrErr
)->setOwnedMemoryBuffer(std::move(Buffer
));
6619 Expected
<std::unique_ptr
<Module
>>
6620 BitcodeModule::parseModule(LLVMContext
&Context
) {
6621 return getModuleImpl(Context
, true, false, false);
6622 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6623 // written. We must defer until the Module has been fully materialized.
6626 Expected
<std::unique_ptr
<Module
>> llvm::parseBitcodeFile(MemoryBufferRef Buffer
,
6627 LLVMContext
&Context
) {
6628 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6630 return BM
.takeError();
6632 return BM
->parseModule(Context
);
6635 Expected
<std::string
> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer
) {
6636 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
6638 return StreamOrErr
.takeError();
6640 return readTriple(*StreamOrErr
);
6643 Expected
<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer
) {
6644 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
6646 return StreamOrErr
.takeError();
6648 return hasObjCCategory(*StreamOrErr
);
6651 Expected
<std::string
> llvm::getBitcodeProducerString(MemoryBufferRef Buffer
) {
6652 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
6654 return StreamOrErr
.takeError();
6656 return readIdentificationCode(*StreamOrErr
);
6659 Error
llvm::readModuleSummaryIndex(MemoryBufferRef Buffer
,
6660 ModuleSummaryIndex
&CombinedIndex
,
6661 uint64_t ModuleId
) {
6662 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6664 return BM
.takeError();
6666 return BM
->readSummary(CombinedIndex
, BM
->getModuleIdentifier(), ModuleId
);
6669 Expected
<std::unique_ptr
<ModuleSummaryIndex
>>
6670 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer
) {
6671 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6673 return BM
.takeError();
6675 return BM
->getSummary();
6678 Expected
<BitcodeLTOInfo
> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer
) {
6679 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
6681 return BM
.takeError();
6683 return BM
->getLTOInfo();
6686 Expected
<std::unique_ptr
<ModuleSummaryIndex
>>
6687 llvm::getModuleSummaryIndexForFile(StringRef Path
,
6688 bool IgnoreEmptyThinLTOIndexFile
) {
6689 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> FileOrErr
=
6690 MemoryBuffer::getFileOrSTDIN(Path
);
6692 return errorCodeToError(FileOrErr
.getError());
6693 if (IgnoreEmptyThinLTOIndexFile
&& !(*FileOrErr
)->getBufferSize())
6695 return getModuleSummaryIndex(**FileOrErr
);