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/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Bitcode/BitcodeCommon.h"
22 #include "llvm/Bitcode/LLVMBitCodes.h"
23 #include "llvm/Bitstream/BitstreamReader.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/Argument.h"
26 #include "llvm/IR/AttributeMask.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/AutoUpgrade.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Comdat.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/ConstantRangeList.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/GetElementPtrTypeIterator.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalIFunc.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/IntrinsicsAArch64.h"
55 #include "llvm/IR/IntrinsicsARM.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/Metadata.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/ModuleSummaryIndex.h"
60 #include "llvm/IR/Operator.h"
61 #include "llvm/IR/ProfDataUtils.h"
62 #include "llvm/IR/Type.h"
63 #include "llvm/IR/Value.h"
64 #include "llvm/IR/Verifier.h"
65 #include "llvm/Support/AtomicOrdering.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/Error.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/ErrorOr.h"
73 #include "llvm/Support/MathExtras.h"
74 #include "llvm/Support/MemoryBuffer.h"
75 #include "llvm/Support/ModRef.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include "llvm/TargetParser/Triple.h"
88 #include <system_error>
95 static cl::opt
<bool> PrintSummaryGUIDs(
96 "print-summary-global-ids", cl::init(false), cl::Hidden
,
98 "Print the global id for each value when reading the module summary"));
100 static cl::opt
<bool> ExpandConstantExprs(
101 "expand-constant-exprs", cl::Hidden
,
103 "Expand constant expressions to instructions for testing purposes"));
105 /// Load bitcode directly into RemoveDIs format (use debug records instead
106 /// of debug intrinsics). UNSET is treated as FALSE, so the default action
107 /// is to do nothing. Individual tools can override this to incrementally add
108 /// support for the RemoveDIs format.
109 cl::opt
<cl::boolOrDefault
> LoadBitcodeIntoNewDbgInfoFormat(
110 "load-bitcode-into-experimental-debuginfo-iterators", cl::Hidden
,
111 cl::desc("Load bitcode directly into the new debug info format (regardless "
112 "of input format)"));
113 extern cl::opt
<bool> UseNewDbgInfoFormat
;
114 extern cl::opt
<cl::boolOrDefault
> PreserveInputDbgFormat
;
115 extern bool WriteNewDbgInfoFormatToBitcode
;
116 extern cl::opt
<bool> WriteNewDbgInfoFormat
;
121 SWITCH_INST_MAGIC
= 0x4B5 // May 2012 => 1205 => Hex
124 } // end anonymous namespace
126 static Error
error(const Twine
&Message
) {
127 return make_error
<StringError
>(
128 Message
, make_error_code(BitcodeError::CorruptedBitcode
));
131 static Error
hasInvalidBitcodeHeader(BitstreamCursor
&Stream
) {
132 if (!Stream
.canSkipToPos(4))
133 return createStringError(std::errc::illegal_byte_sequence
,
134 "file too small to contain bitcode header");
135 for (unsigned C
: {'B', 'C'})
136 if (Expected
<SimpleBitstreamCursor::word_t
> Res
= Stream
.Read(8)) {
138 return createStringError(std::errc::illegal_byte_sequence
,
139 "file doesn't start with bitcode header");
141 return Res
.takeError();
142 for (unsigned C
: {0x0, 0xC, 0xE, 0xD})
143 if (Expected
<SimpleBitstreamCursor::word_t
> Res
= Stream
.Read(4)) {
145 return createStringError(std::errc::illegal_byte_sequence
,
146 "file doesn't start with bitcode header");
148 return Res
.takeError();
149 return Error::success();
152 static Expected
<BitstreamCursor
> initStream(MemoryBufferRef Buffer
) {
153 const unsigned char *BufPtr
= (const unsigned char *)Buffer
.getBufferStart();
154 const unsigned char *BufEnd
= BufPtr
+ Buffer
.getBufferSize();
156 if (Buffer
.getBufferSize() & 3)
157 return error("Invalid bitcode signature");
159 // If we have a wrapper header, parse it and ignore the non-bc file contents.
160 // The magic number is 0x0B17C0DE stored in little endian.
161 if (isBitcodeWrapper(BufPtr
, BufEnd
))
162 if (SkipBitcodeWrapperHeader(BufPtr
, BufEnd
, true))
163 return error("Invalid bitcode wrapper header");
165 BitstreamCursor
Stream(ArrayRef
<uint8_t>(BufPtr
, BufEnd
));
166 if (Error Err
= hasInvalidBitcodeHeader(Stream
))
167 return std::move(Err
);
169 return std::move(Stream
);
172 /// Convert a string from a record into an std::string, return true on failure.
173 template <typename StrTy
>
174 static bool convertToString(ArrayRef
<uint64_t> Record
, unsigned Idx
,
176 if (Idx
> Record
.size())
179 Result
.append(Record
.begin() + Idx
, Record
.end());
183 // Strip all the TBAA attachment for the module.
184 static void stripTBAA(Module
*M
) {
186 if (F
.isMaterializable())
188 for (auto &I
: instructions(F
))
189 I
.setMetadata(LLVMContext::MD_tbaa
, nullptr);
193 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
194 /// "epoch" encoded in the bitcode, and return the producer name if any.
195 static Expected
<std::string
> readIdentificationBlock(BitstreamCursor
&Stream
) {
196 if (Error Err
= Stream
.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID
))
197 return std::move(Err
);
199 // Read all the records.
200 SmallVector
<uint64_t, 64> Record
;
202 std::string ProducerIdentification
;
205 BitstreamEntry Entry
;
206 if (Error E
= Stream
.advance().moveInto(Entry
))
209 switch (Entry
.Kind
) {
211 case BitstreamEntry::Error
:
212 return error("Malformed block");
213 case BitstreamEntry::EndBlock
:
214 return ProducerIdentification
;
215 case BitstreamEntry::Record
:
216 // The interesting case.
222 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
224 return MaybeBitCode
.takeError();
225 switch (MaybeBitCode
.get()) {
226 default: // Default behavior: reject
227 return error("Invalid value");
228 case bitc::IDENTIFICATION_CODE_STRING
: // IDENTIFICATION: [strchr x N]
229 convertToString(Record
, 0, ProducerIdentification
);
231 case bitc::IDENTIFICATION_CODE_EPOCH
: { // EPOCH: [epoch#]
232 unsigned epoch
= (unsigned)Record
[0];
233 if (epoch
!= bitc::BITCODE_CURRENT_EPOCH
) {
235 Twine("Incompatible epoch: Bitcode '") + Twine(epoch
) +
236 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH
) + "'");
243 static Expected
<std::string
> readIdentificationCode(BitstreamCursor
&Stream
) {
244 // We expect a number of well-defined blocks, though we don't necessarily
245 // need to understand them all.
247 if (Stream
.AtEndOfStream())
250 BitstreamEntry Entry
;
251 if (Error E
= Stream
.advance().moveInto(Entry
))
254 switch (Entry
.Kind
) {
255 case BitstreamEntry::EndBlock
:
256 case BitstreamEntry::Error
:
257 return error("Malformed block");
259 case BitstreamEntry::SubBlock
:
260 if (Entry
.ID
== bitc::IDENTIFICATION_BLOCK_ID
)
261 return readIdentificationBlock(Stream
);
263 // Ignore other sub-blocks.
264 if (Error Err
= Stream
.SkipBlock())
265 return std::move(Err
);
267 case BitstreamEntry::Record
:
268 if (Error E
= Stream
.skipRecord(Entry
.ID
).takeError())
275 static Expected
<bool> hasObjCCategoryInModule(BitstreamCursor
&Stream
) {
276 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
277 return std::move(Err
);
279 SmallVector
<uint64_t, 64> Record
;
280 // Read all the records for this module.
283 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
285 return MaybeEntry
.takeError();
286 BitstreamEntry Entry
= MaybeEntry
.get();
288 switch (Entry
.Kind
) {
289 case BitstreamEntry::SubBlock
: // Handled for us already.
290 case BitstreamEntry::Error
:
291 return error("Malformed block");
292 case BitstreamEntry::EndBlock
:
294 case BitstreamEntry::Record
:
295 // The interesting case.
300 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
302 return MaybeRecord
.takeError();
303 switch (MaybeRecord
.get()) {
305 break; // Default behavior, ignore unknown content.
306 case bitc::MODULE_CODE_SECTIONNAME
: { // SECTIONNAME: [strchr x N]
308 if (convertToString(Record
, 0, S
))
309 return error("Invalid section name record");
310 // Check for the i386 and other (x86_64, ARM) conventions
311 if (S
.find("__DATA,__objc_catlist") != std::string::npos
||
312 S
.find("__OBJC,__category") != std::string::npos
||
313 S
.find("__TEXT,__swift") != std::string::npos
)
320 llvm_unreachable("Exit infinite loop");
323 static Expected
<bool> hasObjCCategory(BitstreamCursor
&Stream
) {
324 // We expect a number of well-defined blocks, though we don't necessarily
325 // need to understand them all.
327 BitstreamEntry Entry
;
328 if (Error E
= Stream
.advance().moveInto(Entry
))
331 switch (Entry
.Kind
) {
332 case BitstreamEntry::Error
:
333 return error("Malformed block");
334 case BitstreamEntry::EndBlock
:
337 case BitstreamEntry::SubBlock
:
338 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
)
339 return hasObjCCategoryInModule(Stream
);
341 // Ignore other sub-blocks.
342 if (Error Err
= Stream
.SkipBlock())
343 return std::move(Err
);
346 case BitstreamEntry::Record
:
347 if (Error E
= Stream
.skipRecord(Entry
.ID
).takeError())
354 static Expected
<std::string
> readModuleTriple(BitstreamCursor
&Stream
) {
355 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
356 return std::move(Err
);
358 SmallVector
<uint64_t, 64> Record
;
362 // Read all the records for this module.
364 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
366 return MaybeEntry
.takeError();
367 BitstreamEntry Entry
= MaybeEntry
.get();
369 switch (Entry
.Kind
) {
370 case BitstreamEntry::SubBlock
: // Handled for us already.
371 case BitstreamEntry::Error
:
372 return error("Malformed block");
373 case BitstreamEntry::EndBlock
:
375 case BitstreamEntry::Record
:
376 // The interesting case.
381 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
383 return MaybeRecord
.takeError();
384 switch (MaybeRecord
.get()) {
385 default: break; // Default behavior, ignore unknown content.
386 case bitc::MODULE_CODE_TRIPLE
: { // TRIPLE: [strchr x N]
388 if (convertToString(Record
, 0, S
))
389 return error("Invalid triple record");
396 llvm_unreachable("Exit infinite loop");
399 static Expected
<std::string
> readTriple(BitstreamCursor
&Stream
) {
400 // We expect a number of well-defined blocks, though we don't necessarily
401 // need to understand them all.
403 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advance();
405 return MaybeEntry
.takeError();
406 BitstreamEntry Entry
= MaybeEntry
.get();
408 switch (Entry
.Kind
) {
409 case BitstreamEntry::Error
:
410 return error("Malformed block");
411 case BitstreamEntry::EndBlock
:
414 case BitstreamEntry::SubBlock
:
415 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
)
416 return readModuleTriple(Stream
);
418 // Ignore other sub-blocks.
419 if (Error Err
= Stream
.SkipBlock())
420 return std::move(Err
);
423 case BitstreamEntry::Record
:
424 if (llvm::Expected
<unsigned> Skipped
= Stream
.skipRecord(Entry
.ID
))
427 return Skipped
.takeError();
434 class BitcodeReaderBase
{
436 BitcodeReaderBase(BitstreamCursor Stream
, StringRef Strtab
)
437 : Stream(std::move(Stream
)), Strtab(Strtab
) {
438 this->Stream
.setBlockInfo(&BlockInfo
);
441 BitstreamBlockInfo BlockInfo
;
442 BitstreamCursor Stream
;
445 /// In version 2 of the bitcode we store names of global values and comdats in
446 /// a string table rather than in the VST.
447 bool UseStrtab
= false;
449 Expected
<unsigned> parseVersionRecord(ArrayRef
<uint64_t> Record
);
451 /// If this module uses a string table, pop the reference to the string table
452 /// and return the referenced string and the rest of the record. Otherwise
453 /// just return the record itself.
454 std::pair
<StringRef
, ArrayRef
<uint64_t>>
455 readNameFromStrtab(ArrayRef
<uint64_t> Record
);
457 Error
readBlockInfo();
459 // Contains an arbitrary and optional string identifying the bitcode producer
460 std::string ProducerIdentification
;
462 Error
error(const Twine
&Message
);
465 } // end anonymous namespace
467 Error
BitcodeReaderBase::error(const Twine
&Message
) {
468 std::string FullMsg
= Message
.str();
469 if (!ProducerIdentification
.empty())
470 FullMsg
+= " (Producer: '" + ProducerIdentification
+ "' Reader: 'LLVM " +
471 LLVM_VERSION_STRING
"')";
472 return ::error(FullMsg
);
476 BitcodeReaderBase::parseVersionRecord(ArrayRef
<uint64_t> Record
) {
478 return error("Invalid version record");
479 unsigned ModuleVersion
= Record
[0];
480 if (ModuleVersion
> 2)
481 return error("Invalid value");
482 UseStrtab
= ModuleVersion
>= 2;
483 return ModuleVersion
;
486 std::pair
<StringRef
, ArrayRef
<uint64_t>>
487 BitcodeReaderBase::readNameFromStrtab(ArrayRef
<uint64_t> Record
) {
490 // Invalid reference. Let the caller complain about the record being empty.
491 if (Record
[0] + Record
[1] > Strtab
.size())
493 return {StringRef(Strtab
.data() + Record
[0], Record
[1]), Record
.slice(2)};
498 /// This represents a constant expression or constant aggregate using a custom
499 /// structure internal to the bitcode reader. Later, this structure will be
500 /// expanded by materializeValue() either into a constant expression/aggregate,
501 /// or into an instruction sequence at the point of use. This allows us to
502 /// upgrade bitcode using constant expressions even if this kind of constant
503 /// expression is no longer supported.
504 class BitcodeConstant final
: public Value
,
505 TrailingObjects
<BitcodeConstant
, unsigned> {
506 friend TrailingObjects
;
508 // Value subclass ID: Pick largest possible value to avoid any clashes.
509 static constexpr uint8_t SubclassID
= 255;
512 // Opcodes used for non-expressions. This includes constant aggregates
513 // (struct, array, vector) that might need expansion, as well as non-leaf
514 // constants that don't need expansion (no_cfi, dso_local, blockaddress),
515 // but still go through BitcodeConstant to avoid different uselist orders
516 // between the two cases.
517 static constexpr uint8_t ConstantStructOpcode
= 255;
518 static constexpr uint8_t ConstantArrayOpcode
= 254;
519 static constexpr uint8_t ConstantVectorOpcode
= 253;
520 static constexpr uint8_t NoCFIOpcode
= 252;
521 static constexpr uint8_t DSOLocalEquivalentOpcode
= 251;
522 static constexpr uint8_t BlockAddressOpcode
= 250;
523 static constexpr uint8_t ConstantPtrAuthOpcode
= 249;
524 static constexpr uint8_t FirstSpecialOpcode
= ConstantPtrAuthOpcode
;
526 // Separate struct to make passing different number of parameters to
527 // BitcodeConstant::create() more convenient.
531 unsigned BlockAddressBB
= 0;
532 Type
*SrcElemTy
= nullptr;
533 std::optional
<ConstantRange
> InRange
;
535 ExtraInfo(uint8_t Opcode
, uint8_t Flags
= 0, Type
*SrcElemTy
= nullptr,
536 std::optional
<ConstantRange
> InRange
= std::nullopt
)
537 : Opcode(Opcode
), Flags(Flags
), SrcElemTy(SrcElemTy
),
538 InRange(std::move(InRange
)) {}
540 ExtraInfo(uint8_t Opcode
, uint8_t Flags
, unsigned BlockAddressBB
)
541 : Opcode(Opcode
), Flags(Flags
), BlockAddressBB(BlockAddressBB
) {}
546 unsigned NumOperands
;
547 unsigned BlockAddressBB
;
548 Type
*SrcElemTy
; // GEP source element type.
549 std::optional
<ConstantRange
> InRange
; // GEP inrange attribute.
552 BitcodeConstant(Type
*Ty
, const ExtraInfo
&Info
, ArrayRef
<unsigned> OpIDs
)
553 : Value(Ty
, SubclassID
), Opcode(Info
.Opcode
), Flags(Info
.Flags
),
554 NumOperands(OpIDs
.size()), BlockAddressBB(Info
.BlockAddressBB
),
555 SrcElemTy(Info
.SrcElemTy
), InRange(Info
.InRange
) {
556 std::uninitialized_copy(OpIDs
.begin(), OpIDs
.end(),
557 getTrailingObjects
<unsigned>());
560 BitcodeConstant
&operator=(const BitcodeConstant
&) = delete;
563 static BitcodeConstant
*create(BumpPtrAllocator
&A
, Type
*Ty
,
564 const ExtraInfo
&Info
,
565 ArrayRef
<unsigned> OpIDs
) {
566 void *Mem
= A
.Allocate(totalSizeToAlloc
<unsigned>(OpIDs
.size()),
567 alignof(BitcodeConstant
));
568 return new (Mem
) BitcodeConstant(Ty
, Info
, OpIDs
);
571 static bool classof(const Value
*V
) { return V
->getValueID() == SubclassID
; }
573 ArrayRef
<unsigned> getOperandIDs() const {
574 return ArrayRef(getTrailingObjects
<unsigned>(), NumOperands
);
577 std::optional
<ConstantRange
> getInRange() const {
578 assert(Opcode
== Instruction::GetElementPtr
);
582 const char *getOpcodeName() const {
583 return Instruction::getOpcodeName(Opcode
);
587 class BitcodeReader
: public BitcodeReaderBase
, public GVMaterializer
{
588 LLVMContext
&Context
;
589 Module
*TheModule
= nullptr;
590 // Next offset to start scanning for lazy parsing of function bodies.
591 uint64_t NextUnreadBit
= 0;
592 // Last function offset found in the VST.
593 uint64_t LastFunctionBlockBit
= 0;
594 bool SeenValueSymbolTable
= false;
595 uint64_t VSTOffset
= 0;
597 std::vector
<std::string
> SectionTable
;
598 std::vector
<std::string
> GCTable
;
600 std::vector
<Type
*> TypeList
;
601 /// Track type IDs of contained types. Order is the same as the contained
602 /// types of a Type*. This is used during upgrades of typed pointer IR in
603 /// opaque pointer mode.
604 DenseMap
<unsigned, SmallVector
<unsigned, 1>> ContainedTypeIDs
;
605 /// In some cases, we need to create a type ID for a type that was not
606 /// explicitly encoded in the bitcode, or we don't know about at the current
607 /// point. For example, a global may explicitly encode the value type ID, but
608 /// not have a type ID for the pointer to value type, for which we create a
609 /// virtual type ID instead. This map stores the new type ID that was created
610 /// for the given pair of Type and contained type ID.
611 DenseMap
<std::pair
<Type
*, unsigned>, unsigned> VirtualTypeIDs
;
612 DenseMap
<Function
*, unsigned> FunctionTypeIDs
;
613 /// Allocator for BitcodeConstants. This should come before ValueList,
614 /// because the ValueList might hold ValueHandles to these constants, so
615 /// ValueList must be destroyed before Alloc.
616 BumpPtrAllocator Alloc
;
617 BitcodeReaderValueList ValueList
;
618 std::optional
<MetadataLoader
> MDLoader
;
619 std::vector
<Comdat
*> ComdatList
;
620 DenseSet
<GlobalObject
*> ImplicitComdatObjects
;
621 SmallVector
<Instruction
*, 64> InstructionList
;
623 std::vector
<std::pair
<GlobalVariable
*, unsigned>> GlobalInits
;
624 std::vector
<std::pair
<GlobalValue
*, unsigned>> IndirectSymbolInits
;
626 struct FunctionOperandInfo
{
628 unsigned PersonalityFn
;
632 std::vector
<FunctionOperandInfo
> FunctionOperands
;
634 /// The set of attributes by index. Index zero in the file is for null, and
635 /// is thus not represented here. As such all indices are off by one.
636 std::vector
<AttributeList
> MAttributes
;
638 /// The set of attribute groups.
639 std::map
<unsigned, AttributeList
> MAttributeGroups
;
641 /// While parsing a function body, this is a list of the basic blocks for the
643 std::vector
<BasicBlock
*> FunctionBBs
;
645 // When reading the module header, this list is populated with functions that
646 // have bodies later in the file.
647 std::vector
<Function
*> FunctionsWithBodies
;
649 // When intrinsic functions are encountered which require upgrading they are
650 // stored here with their replacement function.
651 using UpdatedIntrinsicMap
= DenseMap
<Function
*, Function
*>;
652 UpdatedIntrinsicMap UpgradedIntrinsics
;
654 // Several operations happen after the module header has been read, but
655 // before function bodies are processed. This keeps track of whether
656 // we've done this yet.
657 bool SeenFirstFunctionBody
= false;
659 /// When function bodies are initially scanned, this map contains info about
660 /// where to find deferred function body in the stream.
661 DenseMap
<Function
*, uint64_t> DeferredFunctionInfo
;
663 /// When Metadata block is initially scanned when parsing the module, we may
664 /// choose to defer parsing of the metadata. This vector contains info about
665 /// which Metadata blocks are deferred.
666 std::vector
<uint64_t> DeferredMetadataInfo
;
668 /// These are basic blocks forward-referenced by block addresses. They are
669 /// inserted lazily into functions when they're loaded. The basic block ID is
670 /// its index into the vector.
671 DenseMap
<Function
*, std::vector
<BasicBlock
*>> BasicBlockFwdRefs
;
672 std::deque
<Function
*> BasicBlockFwdRefQueue
;
674 /// These are Functions that contain BlockAddresses which refer a different
675 /// Function. When parsing the different Function, queue Functions that refer
676 /// to the different Function. Those Functions must be materialized in order
677 /// to resolve their BlockAddress constants before the different Function
678 /// gets moved into another Module.
679 std::vector
<Function
*> BackwardRefFunctions
;
681 /// Indicates that we are using a new encoding for instruction operands where
682 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
683 /// instruction number, for a more compact encoding. Some instruction
684 /// operands are not relative to the instruction ID: basic block numbers, and
685 /// types. Once the old style function blocks have been phased out, we would
686 /// not need this flag.
687 bool UseRelativeIDs
= false;
689 /// True if all functions will be materialized, negating the need to process
690 /// (e.g.) blockaddress forward references.
691 bool WillMaterializeAllForwardRefs
= false;
693 /// Tracks whether we have seen debug intrinsics or records in this bitcode;
694 /// seeing both in a single module is currently a fatal error.
695 bool SeenDebugIntrinsic
= false;
696 bool SeenDebugRecord
= false;
698 bool StripDebugInfo
= false;
699 TBAAVerifier TBAAVerifyHelper
;
701 std::vector
<std::string
> BundleTags
;
702 SmallVector
<SyncScope::ID
, 8> SSIDs
;
704 std::optional
<ValueTypeCallbackTy
> ValueTypeCallback
;
707 BitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
708 StringRef ProducerIdentification
, LLVMContext
&Context
);
710 Error
materializeForwardReferencedFunctions();
712 Error
materialize(GlobalValue
*GV
) override
;
713 Error
materializeModule() override
;
714 std::vector
<StructType
*> getIdentifiedStructTypes() const override
;
716 /// Main interface to parsing a bitcode buffer.
717 /// \returns true if an error occurred.
718 Error
parseBitcodeInto(Module
*M
, bool ShouldLazyLoadMetadata
,
719 bool IsImporting
, ParserCallbacks Callbacks
= {});
721 static uint64_t decodeSignRotatedValue(uint64_t V
);
723 /// Materialize any deferred Metadata block.
724 Error
materializeMetadata() override
;
726 void setStripDebugInfo() override
;
729 std::vector
<StructType
*> IdentifiedStructTypes
;
730 StructType
*createIdentifiedStructType(LLVMContext
&Context
, StringRef Name
);
731 StructType
*createIdentifiedStructType(LLVMContext
&Context
);
733 static constexpr unsigned InvalidTypeID
= ~0u;
735 Type
*getTypeByID(unsigned ID
);
736 Type
*getPtrElementTypeByID(unsigned ID
);
737 unsigned getContainedTypeID(unsigned ID
, unsigned Idx
= 0);
738 unsigned getVirtualTypeID(Type
*Ty
, ArrayRef
<unsigned> ContainedTypeIDs
= {});
740 void callValueTypeCallback(Value
*F
, unsigned TypeID
);
741 Expected
<Value
*> materializeValue(unsigned ValID
, BasicBlock
*InsertBB
);
742 Expected
<Constant
*> getValueForInitializer(unsigned ID
);
744 Value
*getFnValueByID(unsigned ID
, Type
*Ty
, unsigned TyID
,
745 BasicBlock
*ConstExprInsertBB
) {
746 if (Ty
&& Ty
->isMetadataTy())
747 return MetadataAsValue::get(Ty
->getContext(), getFnMetadataByID(ID
));
748 return ValueList
.getValueFwdRef(ID
, Ty
, TyID
, ConstExprInsertBB
);
751 Metadata
*getFnMetadataByID(unsigned ID
) {
752 return MDLoader
->getMetadataFwdRefOrLoad(ID
);
755 BasicBlock
*getBasicBlock(unsigned ID
) const {
756 if (ID
>= FunctionBBs
.size()) return nullptr; // Invalid ID
757 return FunctionBBs
[ID
];
760 AttributeList
getAttributes(unsigned i
) const {
761 if (i
-1 < MAttributes
.size())
762 return MAttributes
[i
-1];
763 return AttributeList();
766 /// Read a value/type pair out of the specified record from slot 'Slot'.
767 /// Increment Slot past the number of slots used in the record. Return true on
769 bool getValueTypePair(const SmallVectorImpl
<uint64_t> &Record
, unsigned &Slot
,
770 unsigned InstNum
, Value
*&ResVal
, unsigned &TypeID
,
771 BasicBlock
*ConstExprInsertBB
) {
772 if (Slot
== Record
.size()) return true;
773 unsigned ValNo
= (unsigned)Record
[Slot
++];
774 // Adjust the ValNo, if it was encoded relative to the InstNum.
776 ValNo
= InstNum
- ValNo
;
777 if (ValNo
< InstNum
) {
778 // If this is not a forward reference, just return the value we already
780 TypeID
= ValueList
.getTypeID(ValNo
);
781 ResVal
= getFnValueByID(ValNo
, nullptr, TypeID
, ConstExprInsertBB
);
782 assert((!ResVal
|| ResVal
->getType() == getTypeByID(TypeID
)) &&
783 "Incorrect type ID stored for value");
784 return ResVal
== nullptr;
786 if (Slot
== Record
.size())
789 TypeID
= (unsigned)Record
[Slot
++];
790 ResVal
= getFnValueByID(ValNo
, getTypeByID(TypeID
), TypeID
,
792 return ResVal
== nullptr;
795 bool getValueOrMetadata(const SmallVectorImpl
<uint64_t> &Record
,
796 unsigned &Slot
, unsigned InstNum
, Value
*&ResVal
,
797 BasicBlock
*ConstExprInsertBB
) {
798 if (Slot
== Record
.size())
800 unsigned ValID
= Record
[Slot
++];
801 if (ValID
!= static_cast<unsigned>(bitc::OB_METADATA
)) {
803 return getValueTypePair(Record
, --Slot
, InstNum
, ResVal
, TypeId
,
806 if (Slot
== Record
.size())
808 unsigned ValNo
= InstNum
- (unsigned)Record
[Slot
++];
809 ResVal
= MetadataAsValue::get(Context
, getFnMetadataByID(ValNo
));
813 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
814 /// past the number of slots used by the value in the record. Return true if
815 /// there is an error.
816 bool popValue(const SmallVectorImpl
<uint64_t> &Record
, unsigned &Slot
,
817 unsigned InstNum
, Type
*Ty
, unsigned TyID
, Value
*&ResVal
,
818 BasicBlock
*ConstExprInsertBB
) {
819 if (getValue(Record
, Slot
, InstNum
, Ty
, TyID
, ResVal
, ConstExprInsertBB
))
821 // All values currently take a single record slot.
826 /// Like popValue, but does not increment the Slot number.
827 bool getValue(const SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
828 unsigned InstNum
, Type
*Ty
, unsigned TyID
, Value
*&ResVal
,
829 BasicBlock
*ConstExprInsertBB
) {
830 ResVal
= getValue(Record
, Slot
, InstNum
, Ty
, TyID
, ConstExprInsertBB
);
831 return ResVal
== nullptr;
834 /// Version of getValue that returns ResVal directly, or 0 if there is an
836 Value
*getValue(const SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
837 unsigned InstNum
, Type
*Ty
, unsigned TyID
,
838 BasicBlock
*ConstExprInsertBB
) {
839 if (Slot
== Record
.size()) return nullptr;
840 unsigned ValNo
= (unsigned)Record
[Slot
];
841 // Adjust the ValNo, if it was encoded relative to the InstNum.
843 ValNo
= InstNum
- ValNo
;
844 return getFnValueByID(ValNo
, Ty
, TyID
, ConstExprInsertBB
);
847 /// Like getValue, but decodes signed VBRs.
848 Value
*getValueSigned(const SmallVectorImpl
<uint64_t> &Record
, unsigned Slot
,
849 unsigned InstNum
, Type
*Ty
, unsigned TyID
,
850 BasicBlock
*ConstExprInsertBB
) {
851 if (Slot
== Record
.size()) return nullptr;
852 unsigned ValNo
= (unsigned)decodeSignRotatedValue(Record
[Slot
]);
853 // Adjust the ValNo, if it was encoded relative to the InstNum.
855 ValNo
= InstNum
- ValNo
;
856 return getFnValueByID(ValNo
, Ty
, TyID
, ConstExprInsertBB
);
859 Expected
<ConstantRange
> readConstantRange(ArrayRef
<uint64_t> Record
,
862 if (Record
.size() - OpNum
< 2)
863 return error("Too few records for range");
865 unsigned LowerActiveWords
= Record
[OpNum
];
866 unsigned UpperActiveWords
= Record
[OpNum
++] >> 32;
867 if (Record
.size() - OpNum
< LowerActiveWords
+ UpperActiveWords
)
868 return error("Too few records for range");
870 readWideAPInt(ArrayRef(&Record
[OpNum
], LowerActiveWords
), BitWidth
);
871 OpNum
+= LowerActiveWords
;
873 readWideAPInt(ArrayRef(&Record
[OpNum
], UpperActiveWords
), BitWidth
);
874 OpNum
+= UpperActiveWords
;
875 return ConstantRange(Lower
, Upper
);
877 int64_t Start
= BitcodeReader::decodeSignRotatedValue(Record
[OpNum
++]);
878 int64_t End
= BitcodeReader::decodeSignRotatedValue(Record
[OpNum
++]);
879 return ConstantRange(APInt(BitWidth
, Start
, true),
880 APInt(BitWidth
, End
, true));
884 Expected
<ConstantRange
>
885 readBitWidthAndConstantRange(ArrayRef
<uint64_t> Record
, unsigned &OpNum
) {
886 if (Record
.size() - OpNum
< 1)
887 return error("Too few records for range");
888 unsigned BitWidth
= Record
[OpNum
++];
889 return readConstantRange(Record
, OpNum
, BitWidth
);
892 /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
893 /// corresponding argument's pointee type. Also upgrades intrinsics that now
894 /// require an elementtype attribute.
895 Error
propagateAttributeTypes(CallBase
*CB
, ArrayRef
<unsigned> ArgsTys
);
897 /// Converts alignment exponent (i.e. power of two (or zero)) to the
898 /// corresponding alignment to use. If alignment is too large, returns
899 /// a corresponding error code.
900 Error
parseAlignmentValue(uint64_t Exponent
, MaybeAlign
&Alignment
);
901 Error
parseAttrKind(uint64_t Code
, Attribute::AttrKind
*Kind
);
902 Error
parseModule(uint64_t ResumeBit
, bool ShouldLazyLoadMetadata
= false,
903 ParserCallbacks Callbacks
= {});
905 Error
parseComdatRecord(ArrayRef
<uint64_t> Record
);
906 Error
parseGlobalVarRecord(ArrayRef
<uint64_t> Record
);
907 Error
parseFunctionRecord(ArrayRef
<uint64_t> Record
);
908 Error
parseGlobalIndirectSymbolRecord(unsigned BitCode
,
909 ArrayRef
<uint64_t> Record
);
911 Error
parseAttributeBlock();
912 Error
parseAttributeGroupBlock();
913 Error
parseTypeTable();
914 Error
parseTypeTableBody();
915 Error
parseOperandBundleTags();
916 Error
parseSyncScopeNames();
918 Expected
<Value
*> recordValue(SmallVectorImpl
<uint64_t> &Record
,
919 unsigned NameIndex
, Triple
&TT
);
920 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta
, Function
*F
,
921 ArrayRef
<uint64_t> Record
);
922 Error
parseValueSymbolTable(uint64_t Offset
= 0);
923 Error
parseGlobalValueSymbolTable();
924 Error
parseConstants();
925 Error
rememberAndSkipFunctionBodies();
926 Error
rememberAndSkipFunctionBody();
927 /// Save the positions of the Metadata blocks and skip parsing the blocks.
928 Error
rememberAndSkipMetadata();
929 Error
typeCheckLoadStoreInst(Type
*ValType
, Type
*PtrType
);
930 Error
parseFunctionBody(Function
*F
);
931 Error
globalCleanup();
932 Error
resolveGlobalAndIndirectSymbolInits();
933 Error
parseUseLists();
934 Error
findFunctionInStream(
936 DenseMap
<Function
*, uint64_t>::iterator DeferredFunctionInfoIterator
);
938 SyncScope::ID
getDecodedSyncScopeID(unsigned Val
);
941 /// Class to manage reading and parsing function summary index bitcode
943 class ModuleSummaryIndexBitcodeReader
: public BitcodeReaderBase
{
944 /// The module index built during parsing.
945 ModuleSummaryIndex
&TheIndex
;
947 /// Indicates whether we have encountered a global value summary section
948 /// yet during parsing.
949 bool SeenGlobalValSummary
= false;
951 /// Indicates whether we have already parsed the VST, used for error checking.
952 bool SeenValueSymbolTable
= false;
954 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
955 /// Used to enable on-demand parsing of the VST.
956 uint64_t VSTOffset
= 0;
958 // Map to save ValueId to ValueInfo association that was recorded in the
959 // ValueSymbolTable. It is used after the VST is parsed to convert
960 // call graph edges read from the function summary from referencing
961 // callees by their ValueId to using the ValueInfo instead, which is how
962 // they are recorded in the summary index being built.
963 // We save a GUID which refers to the same global as the ValueInfo, but
964 // ignoring the linkage, i.e. for values other than local linkage they are
965 // identical (this is the second member). ValueInfo has the real GUID.
966 DenseMap
<unsigned, std::pair
<ValueInfo
, GlobalValue::GUID
>>
967 ValueIdToValueInfoMap
;
969 /// Map populated during module path string table parsing, from the
970 /// module ID to a string reference owned by the index's module
971 /// path string table, used to correlate with combined index
973 DenseMap
<uint64_t, StringRef
> ModuleIdMap
;
975 /// Original source file name recorded in a bitcode record.
976 std::string SourceFileName
;
978 /// The string identifier given to this module by the client, normally the
979 /// path to the bitcode file.
980 StringRef ModulePath
;
982 /// Callback to ask whether a symbol is the prevailing copy when invoked
983 /// during combined index building.
984 std::function
<bool(GlobalValue::GUID
)> IsPrevailing
;
986 /// Saves the stack ids from the STACK_IDS record to consult when adding stack
987 /// ids from the lists in the callsite and alloc entries to the index.
988 std::vector
<uint64_t> StackIds
;
990 /// Linearized radix tree of allocation contexts. See the description above
991 /// the CallStackRadixTreeBuilder class in ProfileData/MemProf.h for format.
992 std::vector
<uint64_t> RadixArray
;
995 ModuleSummaryIndexBitcodeReader(
996 BitstreamCursor Stream
, StringRef Strtab
, ModuleSummaryIndex
&TheIndex
,
997 StringRef ModulePath
,
998 std::function
<bool(GlobalValue::GUID
)> IsPrevailing
= nullptr);
1000 Error
parseModule();
1003 void setValueGUID(uint64_t ValueID
, StringRef ValueName
,
1004 GlobalValue::LinkageTypes Linkage
,
1005 StringRef SourceFileName
);
1006 Error
parseValueSymbolTable(
1008 DenseMap
<unsigned, GlobalValue::LinkageTypes
> &ValueIdToLinkageMap
);
1009 SmallVector
<ValueInfo
, 0> makeRefList(ArrayRef
<uint64_t> Record
);
1010 SmallVector
<FunctionSummary::EdgeTy
, 0>
1011 makeCallList(ArrayRef
<uint64_t> Record
, bool IsOldProfileFormat
,
1012 bool HasProfile
, bool HasRelBF
);
1013 Error
parseEntireSummary(unsigned ID
);
1014 Error
parseModuleStringTable();
1015 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef
<uint64_t> Record
);
1016 void parseTypeIdCompatibleVtableInfo(ArrayRef
<uint64_t> Record
, size_t &Slot
,
1017 TypeIdCompatibleVtableInfo
&TypeId
);
1018 std::vector
<FunctionSummary::ParamAccess
>
1019 parseParamAccesses(ArrayRef
<uint64_t> Record
);
1020 SmallVector
<unsigned> parseAllocInfoContext(ArrayRef
<uint64_t> Record
,
1023 template <bool AllowNullValueInfo
= false>
1024 std::pair
<ValueInfo
, GlobalValue::GUID
>
1025 getValueInfoFromValueId(unsigned ValueId
);
1027 void addThisModule();
1028 ModuleSummaryIndex::ModuleInfo
*getThisModule();
1031 } // end anonymous namespace
1033 std::error_code
llvm::errorToErrorCodeAndEmitErrors(LLVMContext
&Ctx
,
1037 handleAllErrors(std::move(Err
), [&](ErrorInfoBase
&EIB
) {
1038 EC
= EIB
.convertToErrorCode();
1039 Ctx
.emitError(EIB
.message());
1043 return std::error_code();
1046 BitcodeReader::BitcodeReader(BitstreamCursor Stream
, StringRef Strtab
,
1047 StringRef ProducerIdentification
,
1048 LLVMContext
&Context
)
1049 : BitcodeReaderBase(std::move(Stream
), Strtab
), Context(Context
),
1050 ValueList(this->Stream
.SizeInBytes(),
1051 [this](unsigned ValID
, BasicBlock
*InsertBB
) {
1052 return materializeValue(ValID
, InsertBB
);
1054 this->ProducerIdentification
= std::string(ProducerIdentification
);
1057 Error
BitcodeReader::materializeForwardReferencedFunctions() {
1058 if (WillMaterializeAllForwardRefs
)
1059 return Error::success();
1061 // Prevent recursion.
1062 WillMaterializeAllForwardRefs
= true;
1064 while (!BasicBlockFwdRefQueue
.empty()) {
1065 Function
*F
= BasicBlockFwdRefQueue
.front();
1066 BasicBlockFwdRefQueue
.pop_front();
1067 assert(F
&& "Expected valid function");
1068 if (!BasicBlockFwdRefs
.count(F
))
1069 // Already materialized.
1072 // Check for a function that isn't materializable to prevent an infinite
1073 // loop. When parsing a blockaddress stored in a global variable, there
1074 // isn't a trivial way to check if a function will have a body without a
1075 // linear search through FunctionsWithBodies, so just check it here.
1076 if (!F
->isMaterializable())
1077 return error("Never resolved function from blockaddress");
1079 // Try to materialize F.
1080 if (Error Err
= materialize(F
))
1083 assert(BasicBlockFwdRefs
.empty() && "Function missing from queue");
1085 for (Function
*F
: BackwardRefFunctions
)
1086 if (Error Err
= materialize(F
))
1088 BackwardRefFunctions
.clear();
1091 WillMaterializeAllForwardRefs
= false;
1092 return Error::success();
1095 //===----------------------------------------------------------------------===//
1096 // Helper functions to implement forward reference resolution, etc.
1097 //===----------------------------------------------------------------------===//
1099 static bool hasImplicitComdat(size_t Val
) {
1103 case 1: // Old WeakAnyLinkage
1104 case 4: // Old LinkOnceAnyLinkage
1105 case 10: // Old WeakODRLinkage
1106 case 11: // Old LinkOnceODRLinkage
1111 static GlobalValue::LinkageTypes
getDecodedLinkage(unsigned Val
) {
1113 default: // Map unknown/new linkages to external
1115 return GlobalValue::ExternalLinkage
;
1117 return GlobalValue::AppendingLinkage
;
1119 return GlobalValue::InternalLinkage
;
1121 return GlobalValue::ExternalLinkage
; // Obsolete DLLImportLinkage
1123 return GlobalValue::ExternalLinkage
; // Obsolete DLLExportLinkage
1125 return GlobalValue::ExternalWeakLinkage
;
1127 return GlobalValue::CommonLinkage
;
1129 return GlobalValue::PrivateLinkage
;
1131 return GlobalValue::AvailableExternallyLinkage
;
1133 return GlobalValue::PrivateLinkage
; // Obsolete LinkerPrivateLinkage
1135 return GlobalValue::PrivateLinkage
; // Obsolete LinkerPrivateWeakLinkage
1137 return GlobalValue::ExternalLinkage
; // Obsolete LinkOnceODRAutoHideLinkage
1138 case 1: // Old value with implicit comdat.
1140 return GlobalValue::WeakAnyLinkage
;
1141 case 10: // Old value with implicit comdat.
1143 return GlobalValue::WeakODRLinkage
;
1144 case 4: // Old value with implicit comdat.
1146 return GlobalValue::LinkOnceAnyLinkage
;
1147 case 11: // Old value with implicit comdat.
1149 return GlobalValue::LinkOnceODRLinkage
;
1153 static FunctionSummary::FFlags
getDecodedFFlags(uint64_t RawFlags
) {
1154 FunctionSummary::FFlags Flags
;
1155 Flags
.ReadNone
= RawFlags
& 0x1;
1156 Flags
.ReadOnly
= (RawFlags
>> 1) & 0x1;
1157 Flags
.NoRecurse
= (RawFlags
>> 2) & 0x1;
1158 Flags
.ReturnDoesNotAlias
= (RawFlags
>> 3) & 0x1;
1159 Flags
.NoInline
= (RawFlags
>> 4) & 0x1;
1160 Flags
.AlwaysInline
= (RawFlags
>> 5) & 0x1;
1161 Flags
.NoUnwind
= (RawFlags
>> 6) & 0x1;
1162 Flags
.MayThrow
= (RawFlags
>> 7) & 0x1;
1163 Flags
.HasUnknownCall
= (RawFlags
>> 8) & 0x1;
1164 Flags
.MustBeUnreachable
= (RawFlags
>> 9) & 0x1;
1168 // Decode the flags for GlobalValue in the summary. The bits for each attribute:
1170 // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1171 // visibility: [8, 10).
1172 static GlobalValueSummary::GVFlags
getDecodedGVSummaryFlags(uint64_t RawFlags
,
1174 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
1175 // like getDecodedLinkage() above. Any future change to the linkage enum and
1176 // to getDecodedLinkage() will need to be taken into account here as above.
1177 auto Linkage
= GlobalValue::LinkageTypes(RawFlags
& 0xF); // 4 bits
1178 auto Visibility
= GlobalValue::VisibilityTypes((RawFlags
>> 8) & 3); // 2 bits
1179 auto IK
= GlobalValueSummary::ImportKind((RawFlags
>> 10) & 1); // 1 bit
1180 RawFlags
= RawFlags
>> 4;
1181 bool NotEligibleToImport
= (RawFlags
& 0x1) || Version
< 3;
1182 // The Live flag wasn't introduced until version 3. For dead stripping
1183 // to work correctly on earlier versions, we must conservatively treat all
1185 bool Live
= (RawFlags
& 0x2) || Version
< 3;
1186 bool Local
= (RawFlags
& 0x4);
1187 bool AutoHide
= (RawFlags
& 0x8);
1189 return GlobalValueSummary::GVFlags(Linkage
, Visibility
, NotEligibleToImport
,
1190 Live
, Local
, AutoHide
, IK
);
1193 // Decode the flags for GlobalVariable in the summary
1194 static GlobalVarSummary::GVarFlags
getDecodedGVarFlags(uint64_t RawFlags
) {
1195 return GlobalVarSummary::GVarFlags(
1196 (RawFlags
& 0x1) ? true : false, (RawFlags
& 0x2) ? true : false,
1197 (RawFlags
& 0x4) ? true : false,
1198 (GlobalObject::VCallVisibility
)(RawFlags
>> 3));
1201 static std::pair
<CalleeInfo::HotnessType
, bool>
1202 getDecodedHotnessCallEdgeInfo(uint64_t RawFlags
) {
1203 CalleeInfo::HotnessType Hotness
=
1204 static_cast<CalleeInfo::HotnessType
>(RawFlags
& 0x7); // 3 bits
1205 bool HasTailCall
= (RawFlags
& 0x8); // 1 bit
1206 return {Hotness
, HasTailCall
};
1209 static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags
, uint64_t &RelBF
,
1210 bool &HasTailCall
) {
1211 static constexpr uint64_t RelBlockFreqMask
=
1212 (1 << CalleeInfo::RelBlockFreqBits
) - 1;
1213 RelBF
= RawFlags
& RelBlockFreqMask
; // RelBlockFreqBits bits
1214 HasTailCall
= (RawFlags
& (1 << CalleeInfo::RelBlockFreqBits
)); // 1 bit
1217 static GlobalValue::VisibilityTypes
getDecodedVisibility(unsigned Val
) {
1219 default: // Map unknown visibilities to default.
1220 case 0: return GlobalValue::DefaultVisibility
;
1221 case 1: return GlobalValue::HiddenVisibility
;
1222 case 2: return GlobalValue::ProtectedVisibility
;
1226 static GlobalValue::DLLStorageClassTypes
1227 getDecodedDLLStorageClass(unsigned Val
) {
1229 default: // Map unknown values to default.
1230 case 0: return GlobalValue::DefaultStorageClass
;
1231 case 1: return GlobalValue::DLLImportStorageClass
;
1232 case 2: return GlobalValue::DLLExportStorageClass
;
1236 static bool getDecodedDSOLocal(unsigned Val
) {
1238 default: // Map unknown values to preemptable.
1239 case 0: return false;
1240 case 1: return true;
1244 static std::optional
<CodeModel::Model
> getDecodedCodeModel(unsigned Val
) {
1247 return CodeModel::Tiny
;
1249 return CodeModel::Small
;
1251 return CodeModel::Kernel
;
1253 return CodeModel::Medium
;
1255 return CodeModel::Large
;
1261 static GlobalVariable::ThreadLocalMode
getDecodedThreadLocalMode(unsigned Val
) {
1263 case 0: return GlobalVariable::NotThreadLocal
;
1264 default: // Map unknown non-zero value to general dynamic.
1265 case 1: return GlobalVariable::GeneralDynamicTLSModel
;
1266 case 2: return GlobalVariable::LocalDynamicTLSModel
;
1267 case 3: return GlobalVariable::InitialExecTLSModel
;
1268 case 4: return GlobalVariable::LocalExecTLSModel
;
1272 static GlobalVariable::UnnamedAddr
getDecodedUnnamedAddrType(unsigned Val
) {
1274 default: // Map unknown to UnnamedAddr::None.
1275 case 0: return GlobalVariable::UnnamedAddr::None
;
1276 case 1: return GlobalVariable::UnnamedAddr::Global
;
1277 case 2: return GlobalVariable::UnnamedAddr::Local
;
1281 static int getDecodedCastOpcode(unsigned Val
) {
1284 case bitc::CAST_TRUNC
: return Instruction::Trunc
;
1285 case bitc::CAST_ZEXT
: return Instruction::ZExt
;
1286 case bitc::CAST_SEXT
: return Instruction::SExt
;
1287 case bitc::CAST_FPTOUI
: return Instruction::FPToUI
;
1288 case bitc::CAST_FPTOSI
: return Instruction::FPToSI
;
1289 case bitc::CAST_UITOFP
: return Instruction::UIToFP
;
1290 case bitc::CAST_SITOFP
: return Instruction::SIToFP
;
1291 case bitc::CAST_FPTRUNC
: return Instruction::FPTrunc
;
1292 case bitc::CAST_FPEXT
: return Instruction::FPExt
;
1293 case bitc::CAST_PTRTOINT
: return Instruction::PtrToInt
;
1294 case bitc::CAST_INTTOPTR
: return Instruction::IntToPtr
;
1295 case bitc::CAST_BITCAST
: return Instruction::BitCast
;
1296 case bitc::CAST_ADDRSPACECAST
: return Instruction::AddrSpaceCast
;
1300 static int getDecodedUnaryOpcode(unsigned Val
, Type
*Ty
) {
1301 bool IsFP
= Ty
->isFPOrFPVectorTy();
1302 // UnOps are only valid for int/fp or vector of int/fp types
1303 if (!IsFP
&& !Ty
->isIntOrIntVectorTy())
1309 case bitc::UNOP_FNEG
:
1310 return IsFP
? Instruction::FNeg
: -1;
1314 static int getDecodedBinaryOpcode(unsigned Val
, Type
*Ty
) {
1315 bool IsFP
= Ty
->isFPOrFPVectorTy();
1316 // BinOps are only valid for int/fp or vector of int/fp types
1317 if (!IsFP
&& !Ty
->isIntOrIntVectorTy())
1323 case bitc::BINOP_ADD
:
1324 return IsFP
? Instruction::FAdd
: Instruction::Add
;
1325 case bitc::BINOP_SUB
:
1326 return IsFP
? Instruction::FSub
: Instruction::Sub
;
1327 case bitc::BINOP_MUL
:
1328 return IsFP
? Instruction::FMul
: Instruction::Mul
;
1329 case bitc::BINOP_UDIV
:
1330 return IsFP
? -1 : Instruction::UDiv
;
1331 case bitc::BINOP_SDIV
:
1332 return IsFP
? Instruction::FDiv
: Instruction::SDiv
;
1333 case bitc::BINOP_UREM
:
1334 return IsFP
? -1 : Instruction::URem
;
1335 case bitc::BINOP_SREM
:
1336 return IsFP
? Instruction::FRem
: Instruction::SRem
;
1337 case bitc::BINOP_SHL
:
1338 return IsFP
? -1 : Instruction::Shl
;
1339 case bitc::BINOP_LSHR
:
1340 return IsFP
? -1 : Instruction::LShr
;
1341 case bitc::BINOP_ASHR
:
1342 return IsFP
? -1 : Instruction::AShr
;
1343 case bitc::BINOP_AND
:
1344 return IsFP
? -1 : Instruction::And
;
1345 case bitc::BINOP_OR
:
1346 return IsFP
? -1 : Instruction::Or
;
1347 case bitc::BINOP_XOR
:
1348 return IsFP
? -1 : Instruction::Xor
;
1352 static AtomicRMWInst::BinOp
getDecodedRMWOperation(unsigned Val
) {
1354 default: return AtomicRMWInst::BAD_BINOP
;
1355 case bitc::RMW_XCHG
: return AtomicRMWInst::Xchg
;
1356 case bitc::RMW_ADD
: return AtomicRMWInst::Add
;
1357 case bitc::RMW_SUB
: return AtomicRMWInst::Sub
;
1358 case bitc::RMW_AND
: return AtomicRMWInst::And
;
1359 case bitc::RMW_NAND
: return AtomicRMWInst::Nand
;
1360 case bitc::RMW_OR
: return AtomicRMWInst::Or
;
1361 case bitc::RMW_XOR
: return AtomicRMWInst::Xor
;
1362 case bitc::RMW_MAX
: return AtomicRMWInst::Max
;
1363 case bitc::RMW_MIN
: return AtomicRMWInst::Min
;
1364 case bitc::RMW_UMAX
: return AtomicRMWInst::UMax
;
1365 case bitc::RMW_UMIN
: return AtomicRMWInst::UMin
;
1366 case bitc::RMW_FADD
: return AtomicRMWInst::FAdd
;
1367 case bitc::RMW_FSUB
: return AtomicRMWInst::FSub
;
1368 case bitc::RMW_FMAX
: return AtomicRMWInst::FMax
;
1369 case bitc::RMW_FMIN
: return AtomicRMWInst::FMin
;
1370 case bitc::RMW_UINC_WRAP
:
1371 return AtomicRMWInst::UIncWrap
;
1372 case bitc::RMW_UDEC_WRAP
:
1373 return AtomicRMWInst::UDecWrap
;
1374 case bitc::RMW_USUB_COND
:
1375 return AtomicRMWInst::USubCond
;
1376 case bitc::RMW_USUB_SAT
:
1377 return AtomicRMWInst::USubSat
;
1381 static AtomicOrdering
getDecodedOrdering(unsigned Val
) {
1383 case bitc::ORDERING_NOTATOMIC
: return AtomicOrdering::NotAtomic
;
1384 case bitc::ORDERING_UNORDERED
: return AtomicOrdering::Unordered
;
1385 case bitc::ORDERING_MONOTONIC
: return AtomicOrdering::Monotonic
;
1386 case bitc::ORDERING_ACQUIRE
: return AtomicOrdering::Acquire
;
1387 case bitc::ORDERING_RELEASE
: return AtomicOrdering::Release
;
1388 case bitc::ORDERING_ACQREL
: return AtomicOrdering::AcquireRelease
;
1389 default: // Map unknown orderings to sequentially-consistent.
1390 case bitc::ORDERING_SEQCST
: return AtomicOrdering::SequentiallyConsistent
;
1394 static Comdat::SelectionKind
getDecodedComdatSelectionKind(unsigned Val
) {
1396 default: // Map unknown selection kinds to any.
1397 case bitc::COMDAT_SELECTION_KIND_ANY
:
1399 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH
:
1400 return Comdat::ExactMatch
;
1401 case bitc::COMDAT_SELECTION_KIND_LARGEST
:
1402 return Comdat::Largest
;
1403 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES
:
1404 return Comdat::NoDeduplicate
;
1405 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE
:
1406 return Comdat::SameSize
;
1410 static FastMathFlags
getDecodedFastMathFlags(unsigned Val
) {
1412 if (0 != (Val
& bitc::UnsafeAlgebra
))
1414 if (0 != (Val
& bitc::AllowReassoc
))
1415 FMF
.setAllowReassoc();
1416 if (0 != (Val
& bitc::NoNaNs
))
1418 if (0 != (Val
& bitc::NoInfs
))
1420 if (0 != (Val
& bitc::NoSignedZeros
))
1421 FMF
.setNoSignedZeros();
1422 if (0 != (Val
& bitc::AllowReciprocal
))
1423 FMF
.setAllowReciprocal();
1424 if (0 != (Val
& bitc::AllowContract
))
1425 FMF
.setAllowContract(true);
1426 if (0 != (Val
& bitc::ApproxFunc
))
1427 FMF
.setApproxFunc();
1431 static void upgradeDLLImportExportLinkage(GlobalValue
*GV
, unsigned Val
) {
1432 // A GlobalValue with local linkage cannot have a DLL storage class.
1433 if (GV
->hasLocalLinkage())
1436 case 5: GV
->setDLLStorageClass(GlobalValue::DLLImportStorageClass
); break;
1437 case 6: GV
->setDLLStorageClass(GlobalValue::DLLExportStorageClass
); break;
1441 Type
*BitcodeReader::getTypeByID(unsigned ID
) {
1442 // The type table size is always specified correctly.
1443 if (ID
>= TypeList
.size())
1446 if (Type
*Ty
= TypeList
[ID
])
1449 // If we have a forward reference, the only possible case is when it is to a
1450 // named struct. Just create a placeholder for now.
1451 return TypeList
[ID
] = createIdentifiedStructType(Context
);
1454 unsigned BitcodeReader::getContainedTypeID(unsigned ID
, unsigned Idx
) {
1455 auto It
= ContainedTypeIDs
.find(ID
);
1456 if (It
== ContainedTypeIDs
.end())
1457 return InvalidTypeID
;
1459 if (Idx
>= It
->second
.size())
1460 return InvalidTypeID
;
1462 return It
->second
[Idx
];
1465 Type
*BitcodeReader::getPtrElementTypeByID(unsigned ID
) {
1466 if (ID
>= TypeList
.size())
1469 Type
*Ty
= TypeList
[ID
];
1470 if (!Ty
->isPointerTy())
1473 return getTypeByID(getContainedTypeID(ID
, 0));
1476 unsigned BitcodeReader::getVirtualTypeID(Type
*Ty
,
1477 ArrayRef
<unsigned> ChildTypeIDs
) {
1478 unsigned ChildTypeID
= ChildTypeIDs
.empty() ? InvalidTypeID
: ChildTypeIDs
[0];
1479 auto CacheKey
= std::make_pair(Ty
, ChildTypeID
);
1480 auto It
= VirtualTypeIDs
.find(CacheKey
);
1481 if (It
!= VirtualTypeIDs
.end()) {
1482 // The cmpxchg return value is the only place we need more than one
1483 // contained type ID, however the second one will always be the same (i1),
1484 // so we don't need to include it in the cache key. This asserts that the
1485 // contained types are indeed as expected and there are no collisions.
1486 assert((ChildTypeIDs
.empty() ||
1487 ContainedTypeIDs
[It
->second
] == ChildTypeIDs
) &&
1488 "Incorrect cached contained type IDs");
1492 unsigned TypeID
= TypeList
.size();
1493 TypeList
.push_back(Ty
);
1494 if (!ChildTypeIDs
.empty())
1495 append_range(ContainedTypeIDs
[TypeID
], ChildTypeIDs
);
1496 VirtualTypeIDs
.insert({CacheKey
, TypeID
});
1500 static GEPNoWrapFlags
toGEPNoWrapFlags(uint64_t Flags
) {
1502 if (Flags
& (1 << bitc::GEP_INBOUNDS
))
1503 NW
|= GEPNoWrapFlags::inBounds();
1504 if (Flags
& (1 << bitc::GEP_NUSW
))
1505 NW
|= GEPNoWrapFlags::noUnsignedSignedWrap();
1506 if (Flags
& (1 << bitc::GEP_NUW
))
1507 NW
|= GEPNoWrapFlags::noUnsignedWrap();
1511 static bool isConstExprSupported(const BitcodeConstant
*BC
) {
1512 uint8_t Opcode
= BC
->Opcode
;
1514 // These are not real constant expressions, always consider them supported.
1515 if (Opcode
>= BitcodeConstant::FirstSpecialOpcode
)
1518 // If -expand-constant-exprs is set, we want to consider all expressions
1520 if (ExpandConstantExprs
)
1523 if (Instruction::isBinaryOp(Opcode
))
1524 return ConstantExpr::isSupportedBinOp(Opcode
);
1526 if (Instruction::isCast(Opcode
))
1527 return ConstantExpr::isSupportedCastOp(Opcode
);
1529 if (Opcode
== Instruction::GetElementPtr
)
1530 return ConstantExpr::isSupportedGetElementPtr(BC
->SrcElemTy
);
1533 case Instruction::FNeg
:
1534 case Instruction::Select
:
1535 case Instruction::ICmp
:
1536 case Instruction::FCmp
:
1543 Expected
<Value
*> BitcodeReader::materializeValue(unsigned StartValID
,
1544 BasicBlock
*InsertBB
) {
1545 // Quickly handle the case where there is no BitcodeConstant to resolve.
1546 if (StartValID
< ValueList
.size() && ValueList
[StartValID
] &&
1547 !isa
<BitcodeConstant
>(ValueList
[StartValID
]))
1548 return ValueList
[StartValID
];
1550 SmallDenseMap
<unsigned, Value
*> MaterializedValues
;
1551 SmallVector
<unsigned> Worklist
;
1552 Worklist
.push_back(StartValID
);
1553 while (!Worklist
.empty()) {
1554 unsigned ValID
= Worklist
.back();
1555 if (MaterializedValues
.count(ValID
)) {
1556 // Duplicate expression that was already handled.
1557 Worklist
.pop_back();
1561 if (ValID
>= ValueList
.size() || !ValueList
[ValID
])
1562 return error("Invalid value ID");
1564 Value
*V
= ValueList
[ValID
];
1565 auto *BC
= dyn_cast
<BitcodeConstant
>(V
);
1567 MaterializedValues
.insert({ValID
, V
});
1568 Worklist
.pop_back();
1572 // Iterate in reverse, so values will get popped from the worklist in
1574 SmallVector
<Value
*> Ops
;
1575 for (unsigned OpID
: reverse(BC
->getOperandIDs())) {
1576 auto It
= MaterializedValues
.find(OpID
);
1577 if (It
!= MaterializedValues
.end())
1578 Ops
.push_back(It
->second
);
1580 Worklist
.push_back(OpID
);
1583 // Some expressions have not been resolved yet, handle them first and then
1584 // revisit this one.
1585 if (Ops
.size() != BC
->getOperandIDs().size())
1587 std::reverse(Ops
.begin(), Ops
.end());
1589 SmallVector
<Constant
*> ConstOps
;
1590 for (Value
*Op
: Ops
)
1591 if (auto *C
= dyn_cast
<Constant
>(Op
))
1592 ConstOps
.push_back(C
);
1594 // Materialize as constant expression if possible.
1595 if (isConstExprSupported(BC
) && ConstOps
.size() == Ops
.size()) {
1597 if (Instruction::isCast(BC
->Opcode
)) {
1598 C
= UpgradeBitCastExpr(BC
->Opcode
, ConstOps
[0], BC
->getType());
1600 C
= ConstantExpr::getCast(BC
->Opcode
, ConstOps
[0], BC
->getType());
1601 } else if (Instruction::isBinaryOp(BC
->Opcode
)) {
1602 C
= ConstantExpr::get(BC
->Opcode
, ConstOps
[0], ConstOps
[1], BC
->Flags
);
1604 switch (BC
->Opcode
) {
1605 case BitcodeConstant::ConstantPtrAuthOpcode
: {
1606 auto *Key
= dyn_cast
<ConstantInt
>(ConstOps
[1]);
1608 return error("ptrauth key operand must be ConstantInt");
1610 auto *Disc
= dyn_cast
<ConstantInt
>(ConstOps
[2]);
1612 return error("ptrauth disc operand must be ConstantInt");
1614 C
= ConstantPtrAuth::get(ConstOps
[0], Key
, Disc
, ConstOps
[3]);
1617 case BitcodeConstant::NoCFIOpcode
: {
1618 auto *GV
= dyn_cast
<GlobalValue
>(ConstOps
[0]);
1620 return error("no_cfi operand must be GlobalValue");
1621 C
= NoCFIValue::get(GV
);
1624 case BitcodeConstant::DSOLocalEquivalentOpcode
: {
1625 auto *GV
= dyn_cast
<GlobalValue
>(ConstOps
[0]);
1627 return error("dso_local operand must be GlobalValue");
1628 C
= DSOLocalEquivalent::get(GV
);
1631 case BitcodeConstant::BlockAddressOpcode
: {
1632 Function
*Fn
= dyn_cast
<Function
>(ConstOps
[0]);
1634 return error("blockaddress operand must be a function");
1636 // If the function is already parsed we can insert the block address
1639 unsigned BBID
= BC
->BlockAddressBB
;
1641 // Invalid reference to entry block.
1642 return error("Invalid ID");
1644 Function::iterator BBI
= Fn
->begin(), BBE
= Fn
->end();
1645 for (size_t I
= 0, E
= BBID
; I
!= E
; ++I
) {
1647 return error("Invalid ID");
1652 // Otherwise insert a placeholder and remember it so it can be
1653 // inserted when the function is parsed.
1654 auto &FwdBBs
= BasicBlockFwdRefs
[Fn
];
1656 BasicBlockFwdRefQueue
.push_back(Fn
);
1657 if (FwdBBs
.size() < BBID
+ 1)
1658 FwdBBs
.resize(BBID
+ 1);
1660 FwdBBs
[BBID
] = BasicBlock::Create(Context
);
1663 C
= BlockAddress::get(Fn
, BB
);
1666 case BitcodeConstant::ConstantStructOpcode
: {
1667 auto *ST
= cast
<StructType
>(BC
->getType());
1668 if (ST
->getNumElements() != ConstOps
.size())
1669 return error("Invalid number of elements in struct initializer");
1671 for (const auto [Ty
, Op
] : zip(ST
->elements(), ConstOps
))
1672 if (Op
->getType() != Ty
)
1673 return error("Incorrect type in struct initializer");
1675 C
= ConstantStruct::get(ST
, ConstOps
);
1678 case BitcodeConstant::ConstantArrayOpcode
: {
1679 auto *AT
= cast
<ArrayType
>(BC
->getType());
1680 if (AT
->getNumElements() != ConstOps
.size())
1681 return error("Invalid number of elements in array initializer");
1683 for (Constant
*Op
: ConstOps
)
1684 if (Op
->getType() != AT
->getElementType())
1685 return error("Incorrect type in array initializer");
1687 C
= ConstantArray::get(AT
, ConstOps
);
1690 case BitcodeConstant::ConstantVectorOpcode
: {
1691 auto *VT
= cast
<FixedVectorType
>(BC
->getType());
1692 if (VT
->getNumElements() != ConstOps
.size())
1693 return error("Invalid number of elements in vector initializer");
1695 for (Constant
*Op
: ConstOps
)
1696 if (Op
->getType() != VT
->getElementType())
1697 return error("Incorrect type in vector initializer");
1699 C
= ConstantVector::get(ConstOps
);
1702 case Instruction::GetElementPtr
:
1703 C
= ConstantExpr::getGetElementPtr(
1704 BC
->SrcElemTy
, ConstOps
[0], ArrayRef(ConstOps
).drop_front(),
1705 toGEPNoWrapFlags(BC
->Flags
), BC
->getInRange());
1707 case Instruction::ExtractElement
:
1708 C
= ConstantExpr::getExtractElement(ConstOps
[0], ConstOps
[1]);
1710 case Instruction::InsertElement
:
1711 C
= ConstantExpr::getInsertElement(ConstOps
[0], ConstOps
[1],
1714 case Instruction::ShuffleVector
: {
1715 SmallVector
<int, 16> Mask
;
1716 ShuffleVectorInst::getShuffleMask(ConstOps
[2], Mask
);
1717 C
= ConstantExpr::getShuffleVector(ConstOps
[0], ConstOps
[1], Mask
);
1721 llvm_unreachable("Unhandled bitcode constant");
1725 // Cache resolved constant.
1726 ValueList
.replaceValueWithoutRAUW(ValID
, C
);
1727 MaterializedValues
.insert({ValID
, C
});
1728 Worklist
.pop_back();
1733 return error(Twine("Value referenced by initializer is an unsupported "
1734 "constant expression of type ") +
1735 BC
->getOpcodeName());
1737 // Materialize as instructions if necessary.
1739 if (Instruction::isCast(BC
->Opcode
)) {
1740 I
= CastInst::Create((Instruction::CastOps
)BC
->Opcode
, Ops
[0],
1741 BC
->getType(), "constexpr", InsertBB
);
1742 } else if (Instruction::isUnaryOp(BC
->Opcode
)) {
1743 I
= UnaryOperator::Create((Instruction::UnaryOps
)BC
->Opcode
, Ops
[0],
1744 "constexpr", InsertBB
);
1745 } else if (Instruction::isBinaryOp(BC
->Opcode
)) {
1746 I
= BinaryOperator::Create((Instruction::BinaryOps
)BC
->Opcode
, Ops
[0],
1747 Ops
[1], "constexpr", InsertBB
);
1748 if (isa
<OverflowingBinaryOperator
>(I
)) {
1749 if (BC
->Flags
& OverflowingBinaryOperator::NoSignedWrap
)
1750 I
->setHasNoSignedWrap();
1751 if (BC
->Flags
& OverflowingBinaryOperator::NoUnsignedWrap
)
1752 I
->setHasNoUnsignedWrap();
1754 if (isa
<PossiblyExactOperator
>(I
) &&
1755 (BC
->Flags
& PossiblyExactOperator::IsExact
))
1758 switch (BC
->Opcode
) {
1759 case BitcodeConstant::ConstantVectorOpcode
: {
1760 Type
*IdxTy
= Type::getInt32Ty(BC
->getContext());
1761 Value
*V
= PoisonValue::get(BC
->getType());
1762 for (auto Pair
: enumerate(Ops
)) {
1763 Value
*Idx
= ConstantInt::get(IdxTy
, Pair
.index());
1764 V
= InsertElementInst::Create(V
, Pair
.value(), Idx
, "constexpr.ins",
1767 I
= cast
<Instruction
>(V
);
1770 case BitcodeConstant::ConstantStructOpcode
:
1771 case BitcodeConstant::ConstantArrayOpcode
: {
1772 Value
*V
= PoisonValue::get(BC
->getType());
1773 for (auto Pair
: enumerate(Ops
))
1774 V
= InsertValueInst::Create(V
, Pair
.value(), Pair
.index(),
1775 "constexpr.ins", InsertBB
);
1776 I
= cast
<Instruction
>(V
);
1779 case Instruction::ICmp
:
1780 case Instruction::FCmp
:
1781 I
= CmpInst::Create((Instruction::OtherOps
)BC
->Opcode
,
1782 (CmpInst::Predicate
)BC
->Flags
, Ops
[0], Ops
[1],
1783 "constexpr", InsertBB
);
1785 case Instruction::GetElementPtr
:
1786 I
= GetElementPtrInst::Create(BC
->SrcElemTy
, Ops
[0],
1787 ArrayRef(Ops
).drop_front(), "constexpr",
1789 cast
<GetElementPtrInst
>(I
)->setNoWrapFlags(toGEPNoWrapFlags(BC
->Flags
));
1791 case Instruction::Select
:
1792 I
= SelectInst::Create(Ops
[0], Ops
[1], Ops
[2], "constexpr", InsertBB
);
1794 case Instruction::ExtractElement
:
1795 I
= ExtractElementInst::Create(Ops
[0], Ops
[1], "constexpr", InsertBB
);
1797 case Instruction::InsertElement
:
1798 I
= InsertElementInst::Create(Ops
[0], Ops
[1], Ops
[2], "constexpr",
1801 case Instruction::ShuffleVector
:
1802 I
= new ShuffleVectorInst(Ops
[0], Ops
[1], Ops
[2], "constexpr",
1806 llvm_unreachable("Unhandled bitcode constant");
1810 MaterializedValues
.insert({ValID
, I
});
1811 Worklist
.pop_back();
1814 return MaterializedValues
[StartValID
];
1817 Expected
<Constant
*> BitcodeReader::getValueForInitializer(unsigned ID
) {
1818 Expected
<Value
*> MaybeV
= materializeValue(ID
, /* InsertBB */ nullptr);
1820 return MaybeV
.takeError();
1822 // Result must be Constant if InsertBB is nullptr.
1823 return cast
<Constant
>(MaybeV
.get());
1826 StructType
*BitcodeReader::createIdentifiedStructType(LLVMContext
&Context
,
1828 auto *Ret
= StructType::create(Context
, Name
);
1829 IdentifiedStructTypes
.push_back(Ret
);
1833 StructType
*BitcodeReader::createIdentifiedStructType(LLVMContext
&Context
) {
1834 auto *Ret
= StructType::create(Context
);
1835 IdentifiedStructTypes
.push_back(Ret
);
1839 //===----------------------------------------------------------------------===//
1840 // Functions for parsing blocks from the bitcode file
1841 //===----------------------------------------------------------------------===//
1843 static uint64_t getRawAttributeMask(Attribute::AttrKind Val
) {
1845 case Attribute::EndAttrKinds
:
1846 case Attribute::EmptyKey
:
1847 case Attribute::TombstoneKey
:
1848 llvm_unreachable("Synthetic enumerators which should never get here");
1850 case Attribute::None
: return 0;
1851 case Attribute::ZExt
: return 1 << 0;
1852 case Attribute::SExt
: return 1 << 1;
1853 case Attribute::NoReturn
: return 1 << 2;
1854 case Attribute::InReg
: return 1 << 3;
1855 case Attribute::StructRet
: return 1 << 4;
1856 case Attribute::NoUnwind
: return 1 << 5;
1857 case Attribute::NoAlias
: return 1 << 6;
1858 case Attribute::ByVal
: return 1 << 7;
1859 case Attribute::Nest
: return 1 << 8;
1860 case Attribute::ReadNone
: return 1 << 9;
1861 case Attribute::ReadOnly
: return 1 << 10;
1862 case Attribute::NoInline
: return 1 << 11;
1863 case Attribute::AlwaysInline
: return 1 << 12;
1864 case Attribute::OptimizeForSize
: return 1 << 13;
1865 case Attribute::StackProtect
: return 1 << 14;
1866 case Attribute::StackProtectReq
: return 1 << 15;
1867 case Attribute::Alignment
: return 31 << 16;
1868 // 1ULL << 21 is NoCapture, which is upgraded separately.
1869 case Attribute::NoRedZone
: return 1 << 22;
1870 case Attribute::NoImplicitFloat
: return 1 << 23;
1871 case Attribute::Naked
: return 1 << 24;
1872 case Attribute::InlineHint
: return 1 << 25;
1873 case Attribute::StackAlignment
: return 7 << 26;
1874 case Attribute::ReturnsTwice
: return 1 << 29;
1875 case Attribute::UWTable
: return 1 << 30;
1876 case Attribute::NonLazyBind
: return 1U << 31;
1877 case Attribute::SanitizeAddress
: return 1ULL << 32;
1878 case Attribute::MinSize
: return 1ULL << 33;
1879 case Attribute::NoDuplicate
: return 1ULL << 34;
1880 case Attribute::StackProtectStrong
: return 1ULL << 35;
1881 case Attribute::SanitizeThread
: return 1ULL << 36;
1882 case Attribute::SanitizeMemory
: return 1ULL << 37;
1883 case Attribute::NoBuiltin
: return 1ULL << 38;
1884 case Attribute::Returned
: return 1ULL << 39;
1885 case Attribute::Cold
: return 1ULL << 40;
1886 case Attribute::Builtin
: return 1ULL << 41;
1887 case Attribute::OptimizeNone
: return 1ULL << 42;
1888 case Attribute::InAlloca
: return 1ULL << 43;
1889 case Attribute::NonNull
: return 1ULL << 44;
1890 case Attribute::JumpTable
: return 1ULL << 45;
1891 case Attribute::Convergent
: return 1ULL << 46;
1892 case Attribute::SafeStack
: return 1ULL << 47;
1893 case Attribute::NoRecurse
: return 1ULL << 48;
1894 // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately.
1895 // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately.
1896 case Attribute::SwiftSelf
: return 1ULL << 51;
1897 case Attribute::SwiftError
: return 1ULL << 52;
1898 case Attribute::WriteOnly
: return 1ULL << 53;
1899 case Attribute::Speculatable
: return 1ULL << 54;
1900 case Attribute::StrictFP
: return 1ULL << 55;
1901 case Attribute::SanitizeHWAddress
: return 1ULL << 56;
1902 case Attribute::NoCfCheck
: return 1ULL << 57;
1903 case Attribute::OptForFuzzing
: return 1ULL << 58;
1904 case Attribute::ShadowCallStack
: return 1ULL << 59;
1905 case Attribute::SpeculativeLoadHardening
:
1907 case Attribute::ImmArg
:
1909 case Attribute::WillReturn
:
1911 case Attribute::NoFree
:
1914 // Other attributes are not supported in the raw format,
1915 // as we ran out of space.
1918 llvm_unreachable("Unsupported attribute type");
1921 static void addRawAttributeValue(AttrBuilder
&B
, uint64_t Val
) {
1924 for (Attribute::AttrKind I
= Attribute::None
; I
!= Attribute::EndAttrKinds
;
1925 I
= Attribute::AttrKind(I
+ 1)) {
1926 if (uint64_t A
= (Val
& getRawAttributeMask(I
))) {
1927 if (I
== Attribute::Alignment
)
1928 B
.addAlignmentAttr(1ULL << ((A
>> 16) - 1));
1929 else if (I
== Attribute::StackAlignment
)
1930 B
.addStackAlignmentAttr(1ULL << ((A
>> 26)-1));
1931 else if (Attribute::isTypeAttrKind(I
))
1932 B
.addTypeAttr(I
, nullptr); // Type will be auto-upgraded.
1939 /// This fills an AttrBuilder object with the LLVM attributes that have
1940 /// been decoded from the given integer. This function must stay in sync with
1941 /// 'encodeLLVMAttributesForBitcode'.
1942 static void decodeLLVMAttributesForBitcode(AttrBuilder
&B
,
1943 uint64_t EncodedAttrs
,
1945 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1946 // the bits above 31 down by 11 bits.
1947 unsigned Alignment
= (EncodedAttrs
& (0xffffULL
<< 16)) >> 16;
1948 assert((!Alignment
|| isPowerOf2_32(Alignment
)) &&
1949 "Alignment must be a power of two.");
1952 B
.addAlignmentAttr(Alignment
);
1954 uint64_t Attrs
= ((EncodedAttrs
& (0xfffffULL
<< 32)) >> 11) |
1955 (EncodedAttrs
& 0xffff);
1957 if (AttrIdx
== AttributeList::FunctionIndex
) {
1958 // Upgrade old memory attributes.
1959 MemoryEffects ME
= MemoryEffects::unknown();
1960 if (Attrs
& (1ULL << 9)) {
1962 Attrs
&= ~(1ULL << 9);
1963 ME
&= MemoryEffects::none();
1965 if (Attrs
& (1ULL << 10)) {
1967 Attrs
&= ~(1ULL << 10);
1968 ME
&= MemoryEffects::readOnly();
1970 if (Attrs
& (1ULL << 49)) {
1971 // InaccessibleMemOnly
1972 Attrs
&= ~(1ULL << 49);
1973 ME
&= MemoryEffects::inaccessibleMemOnly();
1975 if (Attrs
& (1ULL << 50)) {
1976 // InaccessibleMemOrArgMemOnly
1977 Attrs
&= ~(1ULL << 50);
1978 ME
&= MemoryEffects::inaccessibleOrArgMemOnly();
1980 if (Attrs
& (1ULL << 53)) {
1982 Attrs
&= ~(1ULL << 53);
1983 ME
&= MemoryEffects::writeOnly();
1985 if (ME
!= MemoryEffects::unknown())
1986 B
.addMemoryAttr(ME
);
1989 // Upgrade nocapture to captures(none).
1990 if (Attrs
& (1ULL << 21)) {
1991 Attrs
&= ~(1ULL << 21);
1992 B
.addCapturesAttr(CaptureInfo::none());
1995 addRawAttributeValue(B
, Attrs
);
1998 Error
BitcodeReader::parseAttributeBlock() {
1999 if (Error Err
= Stream
.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID
))
2002 if (!MAttributes
.empty())
2003 return error("Invalid multiple blocks");
2005 SmallVector
<uint64_t, 64> Record
;
2007 SmallVector
<AttributeList
, 8> Attrs
;
2009 // Read all the records.
2011 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2013 return MaybeEntry
.takeError();
2014 BitstreamEntry Entry
= MaybeEntry
.get();
2016 switch (Entry
.Kind
) {
2017 case BitstreamEntry::SubBlock
: // Handled for us already.
2018 case BitstreamEntry::Error
:
2019 return error("Malformed block");
2020 case BitstreamEntry::EndBlock
:
2021 return Error::success();
2022 case BitstreamEntry::Record
:
2023 // The interesting case.
2029 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2031 return MaybeRecord
.takeError();
2032 switch (MaybeRecord
.get()) {
2033 default: // Default behavior: ignore.
2035 case bitc::PARAMATTR_CODE_ENTRY_OLD
: // ENTRY: [paramidx0, attr0, ...]
2036 // Deprecated, but still needed to read old bitcode files.
2037 if (Record
.size() & 1)
2038 return error("Invalid parameter attribute record");
2040 for (unsigned i
= 0, e
= Record
.size(); i
!= e
; i
+= 2) {
2041 AttrBuilder
B(Context
);
2042 decodeLLVMAttributesForBitcode(B
, Record
[i
+1], Record
[i
]);
2043 Attrs
.push_back(AttributeList::get(Context
, Record
[i
], B
));
2046 MAttributes
.push_back(AttributeList::get(Context
, Attrs
));
2049 case bitc::PARAMATTR_CODE_ENTRY
: // ENTRY: [attrgrp0, attrgrp1, ...]
2050 for (uint64_t Val
: Record
)
2051 Attrs
.push_back(MAttributeGroups
[Val
]);
2053 MAttributes
.push_back(AttributeList::get(Context
, Attrs
));
2060 // Returns Attribute::None on unrecognized codes.
2061 static Attribute::AttrKind
getAttrFromCode(uint64_t Code
) {
2064 return Attribute::None
;
2065 case bitc::ATTR_KIND_ALIGNMENT
:
2066 return Attribute::Alignment
;
2067 case bitc::ATTR_KIND_ALWAYS_INLINE
:
2068 return Attribute::AlwaysInline
;
2069 case bitc::ATTR_KIND_BUILTIN
:
2070 return Attribute::Builtin
;
2071 case bitc::ATTR_KIND_BY_VAL
:
2072 return Attribute::ByVal
;
2073 case bitc::ATTR_KIND_IN_ALLOCA
:
2074 return Attribute::InAlloca
;
2075 case bitc::ATTR_KIND_COLD
:
2076 return Attribute::Cold
;
2077 case bitc::ATTR_KIND_CONVERGENT
:
2078 return Attribute::Convergent
;
2079 case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
:
2080 return Attribute::DisableSanitizerInstrumentation
;
2081 case bitc::ATTR_KIND_ELEMENTTYPE
:
2082 return Attribute::ElementType
;
2083 case bitc::ATTR_KIND_FNRETTHUNK_EXTERN
:
2084 return Attribute::FnRetThunkExtern
;
2085 case bitc::ATTR_KIND_INLINE_HINT
:
2086 return Attribute::InlineHint
;
2087 case bitc::ATTR_KIND_IN_REG
:
2088 return Attribute::InReg
;
2089 case bitc::ATTR_KIND_JUMP_TABLE
:
2090 return Attribute::JumpTable
;
2091 case bitc::ATTR_KIND_MEMORY
:
2092 return Attribute::Memory
;
2093 case bitc::ATTR_KIND_NOFPCLASS
:
2094 return Attribute::NoFPClass
;
2095 case bitc::ATTR_KIND_MIN_SIZE
:
2096 return Attribute::MinSize
;
2097 case bitc::ATTR_KIND_NAKED
:
2098 return Attribute::Naked
;
2099 case bitc::ATTR_KIND_NEST
:
2100 return Attribute::Nest
;
2101 case bitc::ATTR_KIND_NO_ALIAS
:
2102 return Attribute::NoAlias
;
2103 case bitc::ATTR_KIND_NO_BUILTIN
:
2104 return Attribute::NoBuiltin
;
2105 case bitc::ATTR_KIND_NO_CALLBACK
:
2106 return Attribute::NoCallback
;
2107 case bitc::ATTR_KIND_NO_DIVERGENCE_SOURCE
:
2108 return Attribute::NoDivergenceSource
;
2109 case bitc::ATTR_KIND_NO_DUPLICATE
:
2110 return Attribute::NoDuplicate
;
2111 case bitc::ATTR_KIND_NOFREE
:
2112 return Attribute::NoFree
;
2113 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT
:
2114 return Attribute::NoImplicitFloat
;
2115 case bitc::ATTR_KIND_NO_INLINE
:
2116 return Attribute::NoInline
;
2117 case bitc::ATTR_KIND_NO_RECURSE
:
2118 return Attribute::NoRecurse
;
2119 case bitc::ATTR_KIND_NO_MERGE
:
2120 return Attribute::NoMerge
;
2121 case bitc::ATTR_KIND_NON_LAZY_BIND
:
2122 return Attribute::NonLazyBind
;
2123 case bitc::ATTR_KIND_NON_NULL
:
2124 return Attribute::NonNull
;
2125 case bitc::ATTR_KIND_DEREFERENCEABLE
:
2126 return Attribute::Dereferenceable
;
2127 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL
:
2128 return Attribute::DereferenceableOrNull
;
2129 case bitc::ATTR_KIND_ALLOC_ALIGN
:
2130 return Attribute::AllocAlign
;
2131 case bitc::ATTR_KIND_ALLOC_KIND
:
2132 return Attribute::AllocKind
;
2133 case bitc::ATTR_KIND_ALLOC_SIZE
:
2134 return Attribute::AllocSize
;
2135 case bitc::ATTR_KIND_ALLOCATED_POINTER
:
2136 return Attribute::AllocatedPointer
;
2137 case bitc::ATTR_KIND_NO_RED_ZONE
:
2138 return Attribute::NoRedZone
;
2139 case bitc::ATTR_KIND_NO_RETURN
:
2140 return Attribute::NoReturn
;
2141 case bitc::ATTR_KIND_NOSYNC
:
2142 return Attribute::NoSync
;
2143 case bitc::ATTR_KIND_NOCF_CHECK
:
2144 return Attribute::NoCfCheck
;
2145 case bitc::ATTR_KIND_NO_PROFILE
:
2146 return Attribute::NoProfile
;
2147 case bitc::ATTR_KIND_SKIP_PROFILE
:
2148 return Attribute::SkipProfile
;
2149 case bitc::ATTR_KIND_NO_UNWIND
:
2150 return Attribute::NoUnwind
;
2151 case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS
:
2152 return Attribute::NoSanitizeBounds
;
2153 case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE
:
2154 return Attribute::NoSanitizeCoverage
;
2155 case bitc::ATTR_KIND_NULL_POINTER_IS_VALID
:
2156 return Attribute::NullPointerIsValid
;
2157 case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
:
2158 return Attribute::OptimizeForDebugging
;
2159 case bitc::ATTR_KIND_OPT_FOR_FUZZING
:
2160 return Attribute::OptForFuzzing
;
2161 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE
:
2162 return Attribute::OptimizeForSize
;
2163 case bitc::ATTR_KIND_OPTIMIZE_NONE
:
2164 return Attribute::OptimizeNone
;
2165 case bitc::ATTR_KIND_READ_NONE
:
2166 return Attribute::ReadNone
;
2167 case bitc::ATTR_KIND_READ_ONLY
:
2168 return Attribute::ReadOnly
;
2169 case bitc::ATTR_KIND_RETURNED
:
2170 return Attribute::Returned
;
2171 case bitc::ATTR_KIND_RETURNS_TWICE
:
2172 return Attribute::ReturnsTwice
;
2173 case bitc::ATTR_KIND_S_EXT
:
2174 return Attribute::SExt
;
2175 case bitc::ATTR_KIND_SPECULATABLE
:
2176 return Attribute::Speculatable
;
2177 case bitc::ATTR_KIND_STACK_ALIGNMENT
:
2178 return Attribute::StackAlignment
;
2179 case bitc::ATTR_KIND_STACK_PROTECT
:
2180 return Attribute::StackProtect
;
2181 case bitc::ATTR_KIND_STACK_PROTECT_REQ
:
2182 return Attribute::StackProtectReq
;
2183 case bitc::ATTR_KIND_STACK_PROTECT_STRONG
:
2184 return Attribute::StackProtectStrong
;
2185 case bitc::ATTR_KIND_SAFESTACK
:
2186 return Attribute::SafeStack
;
2187 case bitc::ATTR_KIND_SHADOWCALLSTACK
:
2188 return Attribute::ShadowCallStack
;
2189 case bitc::ATTR_KIND_STRICT_FP
:
2190 return Attribute::StrictFP
;
2191 case bitc::ATTR_KIND_STRUCT_RET
:
2192 return Attribute::StructRet
;
2193 case bitc::ATTR_KIND_SANITIZE_ADDRESS
:
2194 return Attribute::SanitizeAddress
;
2195 case bitc::ATTR_KIND_SANITIZE_HWADDRESS
:
2196 return Attribute::SanitizeHWAddress
;
2197 case bitc::ATTR_KIND_SANITIZE_THREAD
:
2198 return Attribute::SanitizeThread
;
2199 case bitc::ATTR_KIND_SANITIZE_TYPE
:
2200 return Attribute::SanitizeType
;
2201 case bitc::ATTR_KIND_SANITIZE_MEMORY
:
2202 return Attribute::SanitizeMemory
;
2203 case bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
:
2204 return Attribute::SanitizeNumericalStability
;
2205 case bitc::ATTR_KIND_SANITIZE_REALTIME
:
2206 return Attribute::SanitizeRealtime
;
2207 case bitc::ATTR_KIND_SANITIZE_REALTIME_BLOCKING
:
2208 return Attribute::SanitizeRealtimeBlocking
;
2209 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING
:
2210 return Attribute::SpeculativeLoadHardening
;
2211 case bitc::ATTR_KIND_SWIFT_ERROR
:
2212 return Attribute::SwiftError
;
2213 case bitc::ATTR_KIND_SWIFT_SELF
:
2214 return Attribute::SwiftSelf
;
2215 case bitc::ATTR_KIND_SWIFT_ASYNC
:
2216 return Attribute::SwiftAsync
;
2217 case bitc::ATTR_KIND_UW_TABLE
:
2218 return Attribute::UWTable
;
2219 case bitc::ATTR_KIND_VSCALE_RANGE
:
2220 return Attribute::VScaleRange
;
2221 case bitc::ATTR_KIND_WILLRETURN
:
2222 return Attribute::WillReturn
;
2223 case bitc::ATTR_KIND_WRITEONLY
:
2224 return Attribute::WriteOnly
;
2225 case bitc::ATTR_KIND_Z_EXT
:
2226 return Attribute::ZExt
;
2227 case bitc::ATTR_KIND_IMMARG
:
2228 return Attribute::ImmArg
;
2229 case bitc::ATTR_KIND_SANITIZE_MEMTAG
:
2230 return Attribute::SanitizeMemTag
;
2231 case bitc::ATTR_KIND_PREALLOCATED
:
2232 return Attribute::Preallocated
;
2233 case bitc::ATTR_KIND_NOUNDEF
:
2234 return Attribute::NoUndef
;
2235 case bitc::ATTR_KIND_BYREF
:
2236 return Attribute::ByRef
;
2237 case bitc::ATTR_KIND_MUSTPROGRESS
:
2238 return Attribute::MustProgress
;
2239 case bitc::ATTR_KIND_HOT
:
2240 return Attribute::Hot
;
2241 case bitc::ATTR_KIND_PRESPLIT_COROUTINE
:
2242 return Attribute::PresplitCoroutine
;
2243 case bitc::ATTR_KIND_WRITABLE
:
2244 return Attribute::Writable
;
2245 case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
:
2246 return Attribute::CoroDestroyOnlyWhenComplete
;
2247 case bitc::ATTR_KIND_DEAD_ON_UNWIND
:
2248 return Attribute::DeadOnUnwind
;
2249 case bitc::ATTR_KIND_RANGE
:
2250 return Attribute::Range
;
2251 case bitc::ATTR_KIND_INITIALIZES
:
2252 return Attribute::Initializes
;
2253 case bitc::ATTR_KIND_CORO_ELIDE_SAFE
:
2254 return Attribute::CoroElideSafe
;
2255 case bitc::ATTR_KIND_NO_EXT
:
2256 return Attribute::NoExt
;
2257 case bitc::ATTR_KIND_CAPTURES
:
2258 return Attribute::Captures
;
2262 Error
BitcodeReader::parseAlignmentValue(uint64_t Exponent
,
2263 MaybeAlign
&Alignment
) {
2264 // Note: Alignment in bitcode files is incremented by 1, so that zero
2265 // can be used for default alignment.
2266 if (Exponent
> Value::MaxAlignmentExponent
+ 1)
2267 return error("Invalid alignment value");
2268 Alignment
= decodeMaybeAlign(Exponent
);
2269 return Error::success();
2272 Error
BitcodeReader::parseAttrKind(uint64_t Code
, Attribute::AttrKind
*Kind
) {
2273 *Kind
= getAttrFromCode(Code
);
2274 if (*Kind
== Attribute::None
)
2275 return error("Unknown attribute kind (" + Twine(Code
) + ")");
2276 return Error::success();
2279 static bool upgradeOldMemoryAttribute(MemoryEffects
&ME
, uint64_t EncodedKind
) {
2280 switch (EncodedKind
) {
2281 case bitc::ATTR_KIND_READ_NONE
:
2282 ME
&= MemoryEffects::none();
2284 case bitc::ATTR_KIND_READ_ONLY
:
2285 ME
&= MemoryEffects::readOnly();
2287 case bitc::ATTR_KIND_WRITEONLY
:
2288 ME
&= MemoryEffects::writeOnly();
2290 case bitc::ATTR_KIND_ARGMEMONLY
:
2291 ME
&= MemoryEffects::argMemOnly();
2293 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY
:
2294 ME
&= MemoryEffects::inaccessibleMemOnly();
2296 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
:
2297 ME
&= MemoryEffects::inaccessibleOrArgMemOnly();
2304 Error
BitcodeReader::parseAttributeGroupBlock() {
2305 if (Error Err
= Stream
.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID
))
2308 if (!MAttributeGroups
.empty())
2309 return error("Invalid multiple blocks");
2311 SmallVector
<uint64_t, 64> Record
;
2313 // Read all the records.
2315 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2317 return MaybeEntry
.takeError();
2318 BitstreamEntry Entry
= MaybeEntry
.get();
2320 switch (Entry
.Kind
) {
2321 case BitstreamEntry::SubBlock
: // Handled for us already.
2322 case BitstreamEntry::Error
:
2323 return error("Malformed block");
2324 case BitstreamEntry::EndBlock
:
2325 return Error::success();
2326 case BitstreamEntry::Record
:
2327 // The interesting case.
2333 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2335 return MaybeRecord
.takeError();
2336 switch (MaybeRecord
.get()) {
2337 default: // Default behavior: ignore.
2339 case bitc::PARAMATTR_GRP_CODE_ENTRY
: { // ENTRY: [grpid, idx, a0, a1, ...]
2340 if (Record
.size() < 3)
2341 return error("Invalid grp record");
2343 uint64_t GrpID
= Record
[0];
2344 uint64_t Idx
= Record
[1]; // Index of the object this attribute refers to.
2346 AttrBuilder
B(Context
);
2347 MemoryEffects ME
= MemoryEffects::unknown();
2348 for (unsigned i
= 2, e
= Record
.size(); i
!= e
; ++i
) {
2349 if (Record
[i
] == 0) { // Enum attribute
2350 Attribute::AttrKind Kind
;
2351 uint64_t EncodedKind
= Record
[++i
];
2352 if (Idx
== AttributeList::FunctionIndex
&&
2353 upgradeOldMemoryAttribute(ME
, EncodedKind
))
2356 if (EncodedKind
== bitc::ATTR_KIND_NO_CAPTURE
) {
2357 B
.addCapturesAttr(CaptureInfo::none());
2361 if (Error Err
= parseAttrKind(EncodedKind
, &Kind
))
2364 // Upgrade old-style byval attribute to one with a type, even if it's
2365 // nullptr. We will have to insert the real type when we associate
2366 // this AttributeList with a function.
2367 if (Kind
== Attribute::ByVal
)
2368 B
.addByValAttr(nullptr);
2369 else if (Kind
== Attribute::StructRet
)
2370 B
.addStructRetAttr(nullptr);
2371 else if (Kind
== Attribute::InAlloca
)
2372 B
.addInAllocaAttr(nullptr);
2373 else if (Kind
== Attribute::UWTable
)
2374 B
.addUWTableAttr(UWTableKind::Default
);
2375 else if (Attribute::isEnumAttrKind(Kind
))
2376 B
.addAttribute(Kind
);
2378 return error("Not an enum attribute");
2379 } else if (Record
[i
] == 1) { // Integer attribute
2380 Attribute::AttrKind Kind
;
2381 if (Error Err
= parseAttrKind(Record
[++i
], &Kind
))
2383 if (!Attribute::isIntAttrKind(Kind
))
2384 return error("Not an int attribute");
2385 if (Kind
== Attribute::Alignment
)
2386 B
.addAlignmentAttr(Record
[++i
]);
2387 else if (Kind
== Attribute::StackAlignment
)
2388 B
.addStackAlignmentAttr(Record
[++i
]);
2389 else if (Kind
== Attribute::Dereferenceable
)
2390 B
.addDereferenceableAttr(Record
[++i
]);
2391 else if (Kind
== Attribute::DereferenceableOrNull
)
2392 B
.addDereferenceableOrNullAttr(Record
[++i
]);
2393 else if (Kind
== Attribute::AllocSize
)
2394 B
.addAllocSizeAttrFromRawRepr(Record
[++i
]);
2395 else if (Kind
== Attribute::VScaleRange
)
2396 B
.addVScaleRangeAttrFromRawRepr(Record
[++i
]);
2397 else if (Kind
== Attribute::UWTable
)
2398 B
.addUWTableAttr(UWTableKind(Record
[++i
]));
2399 else if (Kind
== Attribute::AllocKind
)
2400 B
.addAllocKindAttr(static_cast<AllocFnKind
>(Record
[++i
]));
2401 else if (Kind
== Attribute::Memory
)
2402 B
.addMemoryAttr(MemoryEffects::createFromIntValue(Record
[++i
]));
2403 else if (Kind
== Attribute::Captures
)
2404 B
.addCapturesAttr(CaptureInfo::createFromIntValue(Record
[++i
]));
2405 else if (Kind
== Attribute::NoFPClass
)
2407 static_cast<FPClassTest
>(Record
[++i
] & fcAllFlags
));
2408 } else if (Record
[i
] == 3 || Record
[i
] == 4) { // String attribute
2409 bool HasValue
= (Record
[i
++] == 4);
2410 SmallString
<64> KindStr
;
2411 SmallString
<64> ValStr
;
2413 while (Record
[i
] != 0 && i
!= e
)
2414 KindStr
+= Record
[i
++];
2415 assert(Record
[i
] == 0 && "Kind string not null terminated");
2418 // Has a value associated with it.
2419 ++i
; // Skip the '0' that terminates the "kind" string.
2420 while (Record
[i
] != 0 && i
!= e
)
2421 ValStr
+= Record
[i
++];
2422 assert(Record
[i
] == 0 && "Value string not null terminated");
2425 B
.addAttribute(KindStr
.str(), ValStr
.str());
2426 } else if (Record
[i
] == 5 || Record
[i
] == 6) {
2427 bool HasType
= Record
[i
] == 6;
2428 Attribute::AttrKind Kind
;
2429 if (Error Err
= parseAttrKind(Record
[++i
], &Kind
))
2431 if (!Attribute::isTypeAttrKind(Kind
))
2432 return error("Not a type attribute");
2434 B
.addTypeAttr(Kind
, HasType
? getTypeByID(Record
[++i
]) : nullptr);
2435 } else if (Record
[i
] == 7) {
2436 Attribute::AttrKind Kind
;
2439 if (Error Err
= parseAttrKind(Record
[i
++], &Kind
))
2441 if (!Attribute::isConstantRangeAttrKind(Kind
))
2442 return error("Not a ConstantRange attribute");
2444 Expected
<ConstantRange
> MaybeCR
=
2445 readBitWidthAndConstantRange(Record
, i
);
2447 return MaybeCR
.takeError();
2450 B
.addConstantRangeAttr(Kind
, MaybeCR
.get());
2451 } else if (Record
[i
] == 8) {
2452 Attribute::AttrKind Kind
;
2455 if (Error Err
= parseAttrKind(Record
[i
++], &Kind
))
2457 if (!Attribute::isConstantRangeListAttrKind(Kind
))
2458 return error("Not a constant range list attribute");
2460 SmallVector
<ConstantRange
, 2> Val
;
2462 return error("Too few records for constant range list");
2463 unsigned RangeSize
= Record
[i
++];
2464 unsigned BitWidth
= Record
[i
++];
2465 for (unsigned Idx
= 0; Idx
< RangeSize
; ++Idx
) {
2466 Expected
<ConstantRange
> MaybeCR
=
2467 readConstantRange(Record
, i
, BitWidth
);
2469 return MaybeCR
.takeError();
2470 Val
.push_back(MaybeCR
.get());
2474 if (!ConstantRangeList::isOrderedRanges(Val
))
2475 return error("Invalid (unordered or overlapping) range list");
2476 B
.addConstantRangeListAttr(Kind
, Val
);
2478 return error("Invalid attribute group entry");
2482 if (ME
!= MemoryEffects::unknown())
2483 B
.addMemoryAttr(ME
);
2485 UpgradeAttributes(B
);
2486 MAttributeGroups
[GrpID
] = AttributeList::get(Context
, Idx
, B
);
2493 Error
BitcodeReader::parseTypeTable() {
2494 if (Error Err
= Stream
.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW
))
2497 return parseTypeTableBody();
2500 Error
BitcodeReader::parseTypeTableBody() {
2501 if (!TypeList
.empty())
2502 return error("Invalid multiple blocks");
2504 SmallVector
<uint64_t, 64> Record
;
2505 unsigned NumRecords
= 0;
2507 SmallString
<64> TypeName
;
2509 // Read all the records for this type table.
2511 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2513 return MaybeEntry
.takeError();
2514 BitstreamEntry Entry
= MaybeEntry
.get();
2516 switch (Entry
.Kind
) {
2517 case BitstreamEntry::SubBlock
: // Handled for us already.
2518 case BitstreamEntry::Error
:
2519 return error("Malformed block");
2520 case BitstreamEntry::EndBlock
:
2521 if (NumRecords
!= TypeList
.size())
2522 return error("Malformed block");
2523 return Error::success();
2524 case BitstreamEntry::Record
:
2525 // The interesting case.
2531 Type
*ResultTy
= nullptr;
2532 SmallVector
<unsigned> ContainedIDs
;
2533 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2535 return MaybeRecord
.takeError();
2536 switch (MaybeRecord
.get()) {
2538 return error("Invalid value");
2539 case bitc::TYPE_CODE_NUMENTRY
: // TYPE_CODE_NUMENTRY: [numentries]
2540 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2541 // type list. This allows us to reserve space.
2543 return error("Invalid numentry record");
2544 TypeList
.resize(Record
[0]);
2546 case bitc::TYPE_CODE_VOID
: // VOID
2547 ResultTy
= Type::getVoidTy(Context
);
2549 case bitc::TYPE_CODE_HALF
: // HALF
2550 ResultTy
= Type::getHalfTy(Context
);
2552 case bitc::TYPE_CODE_BFLOAT
: // BFLOAT
2553 ResultTy
= Type::getBFloatTy(Context
);
2555 case bitc::TYPE_CODE_FLOAT
: // FLOAT
2556 ResultTy
= Type::getFloatTy(Context
);
2558 case bitc::TYPE_CODE_DOUBLE
: // DOUBLE
2559 ResultTy
= Type::getDoubleTy(Context
);
2561 case bitc::TYPE_CODE_X86_FP80
: // X86_FP80
2562 ResultTy
= Type::getX86_FP80Ty(Context
);
2564 case bitc::TYPE_CODE_FP128
: // FP128
2565 ResultTy
= Type::getFP128Ty(Context
);
2567 case bitc::TYPE_CODE_PPC_FP128
: // PPC_FP128
2568 ResultTy
= Type::getPPC_FP128Ty(Context
);
2570 case bitc::TYPE_CODE_LABEL
: // LABEL
2571 ResultTy
= Type::getLabelTy(Context
);
2573 case bitc::TYPE_CODE_METADATA
: // METADATA
2574 ResultTy
= Type::getMetadataTy(Context
);
2576 case bitc::TYPE_CODE_X86_MMX
: // X86_MMX
2577 // Deprecated: decodes as <1 x i64>
2579 llvm::FixedVectorType::get(llvm::IntegerType::get(Context
, 64), 1);
2581 case bitc::TYPE_CODE_X86_AMX
: // X86_AMX
2582 ResultTy
= Type::getX86_AMXTy(Context
);
2584 case bitc::TYPE_CODE_TOKEN
: // TOKEN
2585 ResultTy
= Type::getTokenTy(Context
);
2587 case bitc::TYPE_CODE_INTEGER
: { // INTEGER: [width]
2589 return error("Invalid integer record");
2591 uint64_t NumBits
= Record
[0];
2592 if (NumBits
< IntegerType::MIN_INT_BITS
||
2593 NumBits
> IntegerType::MAX_INT_BITS
)
2594 return error("Bitwidth for integer type out of range");
2595 ResultTy
= IntegerType::get(Context
, NumBits
);
2598 case bitc::TYPE_CODE_POINTER
: { // POINTER: [pointee type] or
2599 // [pointee type, address space]
2601 return error("Invalid pointer record");
2602 unsigned AddressSpace
= 0;
2603 if (Record
.size() == 2)
2604 AddressSpace
= Record
[1];
2605 ResultTy
= getTypeByID(Record
[0]);
2607 !PointerType::isValidElementType(ResultTy
))
2608 return error("Invalid type");
2609 ContainedIDs
.push_back(Record
[0]);
2610 ResultTy
= PointerType::get(ResultTy
->getContext(), AddressSpace
);
2613 case bitc::TYPE_CODE_OPAQUE_POINTER
: { // OPAQUE_POINTER: [addrspace]
2614 if (Record
.size() != 1)
2615 return error("Invalid opaque pointer record");
2616 unsigned AddressSpace
= Record
[0];
2617 ResultTy
= PointerType::get(Context
, AddressSpace
);
2620 case bitc::TYPE_CODE_FUNCTION_OLD
: {
2621 // Deprecated, but still needed to read old bitcode files.
2622 // FUNCTION: [vararg, attrid, retty, paramty x N]
2623 if (Record
.size() < 3)
2624 return error("Invalid function record");
2625 SmallVector
<Type
*, 8> ArgTys
;
2626 for (unsigned i
= 3, e
= Record
.size(); i
!= e
; ++i
) {
2627 if (Type
*T
= getTypeByID(Record
[i
]))
2628 ArgTys
.push_back(T
);
2633 ResultTy
= getTypeByID(Record
[2]);
2634 if (!ResultTy
|| ArgTys
.size() < Record
.size()-3)
2635 return error("Invalid type");
2637 ContainedIDs
.append(Record
.begin() + 2, Record
.end());
2638 ResultTy
= FunctionType::get(ResultTy
, ArgTys
, Record
[0]);
2641 case bitc::TYPE_CODE_FUNCTION
: {
2642 // FUNCTION: [vararg, retty, paramty x N]
2643 if (Record
.size() < 2)
2644 return error("Invalid function record");
2645 SmallVector
<Type
*, 8> ArgTys
;
2646 for (unsigned i
= 2, e
= Record
.size(); i
!= e
; ++i
) {
2647 if (Type
*T
= getTypeByID(Record
[i
])) {
2648 if (!FunctionType::isValidArgumentType(T
))
2649 return error("Invalid function argument type");
2650 ArgTys
.push_back(T
);
2656 ResultTy
= getTypeByID(Record
[1]);
2657 if (!ResultTy
|| ArgTys
.size() < Record
.size()-2)
2658 return error("Invalid type");
2660 ContainedIDs
.append(Record
.begin() + 1, Record
.end());
2661 ResultTy
= FunctionType::get(ResultTy
, ArgTys
, Record
[0]);
2664 case bitc::TYPE_CODE_STRUCT_ANON
: { // STRUCT: [ispacked, eltty x N]
2666 return error("Invalid anon struct record");
2667 SmallVector
<Type
*, 8> EltTys
;
2668 for (unsigned i
= 1, e
= Record
.size(); i
!= e
; ++i
) {
2669 if (Type
*T
= getTypeByID(Record
[i
]))
2670 EltTys
.push_back(T
);
2674 if (EltTys
.size() != Record
.size()-1)
2675 return error("Invalid type");
2676 ContainedIDs
.append(Record
.begin() + 1, Record
.end());
2677 ResultTy
= StructType::get(Context
, EltTys
, Record
[0]);
2680 case bitc::TYPE_CODE_STRUCT_NAME
: // STRUCT_NAME: [strchr x N]
2681 if (convertToString(Record
, 0, TypeName
))
2682 return error("Invalid struct name record");
2685 case bitc::TYPE_CODE_STRUCT_NAMED
: { // STRUCT: [ispacked, eltty x N]
2687 return error("Invalid named struct record");
2689 if (NumRecords
>= TypeList
.size())
2690 return error("Invalid TYPE table");
2692 // Check to see if this was forward referenced, if so fill in the temp.
2693 StructType
*Res
= cast_or_null
<StructType
>(TypeList
[NumRecords
]);
2695 Res
->setName(TypeName
);
2696 TypeList
[NumRecords
] = nullptr;
2697 } else // Otherwise, create a new struct.
2698 Res
= createIdentifiedStructType(Context
, TypeName
);
2701 SmallVector
<Type
*, 8> EltTys
;
2702 for (unsigned i
= 1, e
= Record
.size(); i
!= e
; ++i
) {
2703 if (Type
*T
= getTypeByID(Record
[i
]))
2704 EltTys
.push_back(T
);
2708 if (EltTys
.size() != Record
.size()-1)
2709 return error("Invalid named struct record");
2710 if (auto E
= Res
->setBodyOrError(EltTys
, Record
[0]))
2712 ContainedIDs
.append(Record
.begin() + 1, Record
.end());
2716 case bitc::TYPE_CODE_OPAQUE
: { // OPAQUE: []
2717 if (Record
.size() != 1)
2718 return error("Invalid opaque type record");
2720 if (NumRecords
>= TypeList
.size())
2721 return error("Invalid TYPE table");
2723 // Check to see if this was forward referenced, if so fill in the temp.
2724 StructType
*Res
= cast_or_null
<StructType
>(TypeList
[NumRecords
]);
2726 Res
->setName(TypeName
);
2727 TypeList
[NumRecords
] = nullptr;
2728 } else // Otherwise, create a new struct with no body.
2729 Res
= createIdentifiedStructType(Context
, TypeName
);
2734 case bitc::TYPE_CODE_TARGET_TYPE
: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2735 if (Record
.size() < 1)
2736 return error("Invalid target extension type record");
2738 if (NumRecords
>= TypeList
.size())
2739 return error("Invalid TYPE table");
2741 if (Record
[0] >= Record
.size())
2742 return error("Too many type parameters");
2744 unsigned NumTys
= Record
[0];
2745 SmallVector
<Type
*, 4> TypeParams
;
2746 SmallVector
<unsigned, 8> IntParams
;
2747 for (unsigned i
= 0; i
< NumTys
; i
++) {
2748 if (Type
*T
= getTypeByID(Record
[i
+ 1]))
2749 TypeParams
.push_back(T
);
2751 return error("Invalid type");
2754 for (unsigned i
= NumTys
+ 1, e
= Record
.size(); i
< e
; i
++) {
2755 if (Record
[i
] > UINT_MAX
)
2756 return error("Integer parameter too large");
2757 IntParams
.push_back(Record
[i
]);
2760 TargetExtType::getOrError(Context
, TypeName
, TypeParams
, IntParams
);
2761 if (auto E
= TTy
.takeError())
2767 case bitc::TYPE_CODE_ARRAY
: // ARRAY: [numelts, eltty]
2768 if (Record
.size() < 2)
2769 return error("Invalid array type record");
2770 ResultTy
= getTypeByID(Record
[1]);
2771 if (!ResultTy
|| !ArrayType::isValidElementType(ResultTy
))
2772 return error("Invalid type");
2773 ContainedIDs
.push_back(Record
[1]);
2774 ResultTy
= ArrayType::get(ResultTy
, Record
[0]);
2776 case bitc::TYPE_CODE_VECTOR
: // VECTOR: [numelts, eltty] or
2777 // [numelts, eltty, scalable]
2778 if (Record
.size() < 2)
2779 return error("Invalid vector type record");
2781 return error("Invalid vector length");
2782 ResultTy
= getTypeByID(Record
[1]);
2783 if (!ResultTy
|| !VectorType::isValidElementType(ResultTy
))
2784 return error("Invalid type");
2785 bool Scalable
= Record
.size() > 2 ? Record
[2] : false;
2786 ContainedIDs
.push_back(Record
[1]);
2787 ResultTy
= VectorType::get(ResultTy
, Record
[0], Scalable
);
2791 if (NumRecords
>= TypeList
.size())
2792 return error("Invalid TYPE table");
2793 if (TypeList
[NumRecords
])
2795 "Invalid TYPE table: Only named structs can be forward referenced");
2796 assert(ResultTy
&& "Didn't read a type?");
2797 TypeList
[NumRecords
] = ResultTy
;
2798 if (!ContainedIDs
.empty())
2799 ContainedTypeIDs
[NumRecords
] = std::move(ContainedIDs
);
2804 Error
BitcodeReader::parseOperandBundleTags() {
2805 if (Error Err
= Stream
.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
))
2808 if (!BundleTags
.empty())
2809 return error("Invalid multiple blocks");
2811 SmallVector
<uint64_t, 64> Record
;
2814 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2816 return MaybeEntry
.takeError();
2817 BitstreamEntry Entry
= MaybeEntry
.get();
2819 switch (Entry
.Kind
) {
2820 case BitstreamEntry::SubBlock
: // Handled for us already.
2821 case BitstreamEntry::Error
:
2822 return error("Malformed block");
2823 case BitstreamEntry::EndBlock
:
2824 return Error::success();
2825 case BitstreamEntry::Record
:
2826 // The interesting case.
2830 // Tags are implicitly mapped to integers by their order.
2832 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2834 return MaybeRecord
.takeError();
2835 if (MaybeRecord
.get() != bitc::OPERAND_BUNDLE_TAG
)
2836 return error("Invalid operand bundle record");
2838 // OPERAND_BUNDLE_TAG: [strchr x N]
2839 BundleTags
.emplace_back();
2840 if (convertToString(Record
, 0, BundleTags
.back()))
2841 return error("Invalid operand bundle record");
2846 Error
BitcodeReader::parseSyncScopeNames() {
2847 if (Error Err
= Stream
.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID
))
2851 return error("Invalid multiple synchronization scope names blocks");
2853 SmallVector
<uint64_t, 64> Record
;
2855 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2857 return MaybeEntry
.takeError();
2858 BitstreamEntry Entry
= MaybeEntry
.get();
2860 switch (Entry
.Kind
) {
2861 case BitstreamEntry::SubBlock
: // Handled for us already.
2862 case BitstreamEntry::Error
:
2863 return error("Malformed block");
2864 case BitstreamEntry::EndBlock
:
2866 return error("Invalid empty synchronization scope names block");
2867 return Error::success();
2868 case BitstreamEntry::Record
:
2869 // The interesting case.
2873 // Synchronization scope names are implicitly mapped to synchronization
2874 // scope IDs by their order.
2876 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2878 return MaybeRecord
.takeError();
2879 if (MaybeRecord
.get() != bitc::SYNC_SCOPE_NAME
)
2880 return error("Invalid sync scope record");
2882 SmallString
<16> SSN
;
2883 if (convertToString(Record
, 0, SSN
))
2884 return error("Invalid sync scope record");
2886 SSIDs
.push_back(Context
.getOrInsertSyncScopeID(SSN
));
2891 /// Associate a value with its name from the given index in the provided record.
2892 Expected
<Value
*> BitcodeReader::recordValue(SmallVectorImpl
<uint64_t> &Record
,
2893 unsigned NameIndex
, Triple
&TT
) {
2894 SmallString
<128> ValueName
;
2895 if (convertToString(Record
, NameIndex
, ValueName
))
2896 return error("Invalid record");
2897 unsigned ValueID
= Record
[0];
2898 if (ValueID
>= ValueList
.size() || !ValueList
[ValueID
])
2899 return error("Invalid record");
2900 Value
*V
= ValueList
[ValueID
];
2902 StringRef
NameStr(ValueName
.data(), ValueName
.size());
2903 if (NameStr
.contains(0))
2904 return error("Invalid value name");
2905 V
->setName(NameStr
);
2906 auto *GO
= dyn_cast
<GlobalObject
>(V
);
2907 if (GO
&& ImplicitComdatObjects
.contains(GO
) && TT
.supportsCOMDAT())
2908 GO
->setComdat(TheModule
->getOrInsertComdat(V
->getName()));
2912 /// Helper to note and return the current location, and jump to the given
2914 static Expected
<uint64_t> jumpToValueSymbolTable(uint64_t Offset
,
2915 BitstreamCursor
&Stream
) {
2916 // Save the current parsing location so we can jump back at the end
2918 uint64_t CurrentBit
= Stream
.GetCurrentBitNo();
2919 if (Error JumpFailed
= Stream
.JumpToBit(Offset
* 32))
2920 return std::move(JumpFailed
);
2921 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advance();
2923 return MaybeEntry
.takeError();
2924 if (MaybeEntry
.get().Kind
!= BitstreamEntry::SubBlock
||
2925 MaybeEntry
.get().ID
!= bitc::VALUE_SYMTAB_BLOCK_ID
)
2926 return error("Expected value symbol table subblock");
2930 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta
,
2932 ArrayRef
<uint64_t> Record
) {
2933 // Note that we subtract 1 here because the offset is relative to one word
2934 // before the start of the identification or module block, which was
2935 // historically always the start of the regular bitcode header.
2936 uint64_t FuncWordOffset
= Record
[1] - 1;
2937 uint64_t FuncBitOffset
= FuncWordOffset
* 32;
2938 DeferredFunctionInfo
[F
] = FuncBitOffset
+ FuncBitcodeOffsetDelta
;
2939 // Set the LastFunctionBlockBit to point to the last function block.
2940 // Later when parsing is resumed after function materialization,
2941 // we can simply skip that last function block.
2942 if (FuncBitOffset
> LastFunctionBlockBit
)
2943 LastFunctionBlockBit
= FuncBitOffset
;
2946 /// Read a new-style GlobalValue symbol table.
2947 Error
BitcodeReader::parseGlobalValueSymbolTable() {
2948 unsigned FuncBitcodeOffsetDelta
=
2949 Stream
.getAbbrevIDWidth() + bitc::BlockIDWidth
;
2951 if (Error Err
= Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
2954 SmallVector
<uint64_t, 64> Record
;
2956 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
2958 return MaybeEntry
.takeError();
2959 BitstreamEntry Entry
= MaybeEntry
.get();
2961 switch (Entry
.Kind
) {
2962 case BitstreamEntry::SubBlock
:
2963 case BitstreamEntry::Error
:
2964 return error("Malformed block");
2965 case BitstreamEntry::EndBlock
:
2966 return Error::success();
2967 case BitstreamEntry::Record
:
2972 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2974 return MaybeRecord
.takeError();
2975 switch (MaybeRecord
.get()) {
2976 case bitc::VST_CODE_FNENTRY
: { // [valueid, offset]
2977 unsigned ValueID
= Record
[0];
2978 if (ValueID
>= ValueList
.size() || !ValueList
[ValueID
])
2979 return error("Invalid value reference in symbol table");
2980 setDeferredFunctionInfo(FuncBitcodeOffsetDelta
,
2981 cast
<Function
>(ValueList
[ValueID
]), Record
);
2988 /// Parse the value symbol table at either the current parsing location or
2989 /// at the given bit offset if provided.
2990 Error
BitcodeReader::parseValueSymbolTable(uint64_t Offset
) {
2991 uint64_t CurrentBit
;
2992 // Pass in the Offset to distinguish between calling for the module-level
2993 // VST (where we want to jump to the VST offset) and the function-level
2994 // VST (where we don't).
2996 Expected
<uint64_t> MaybeCurrentBit
= jumpToValueSymbolTable(Offset
, Stream
);
2997 if (!MaybeCurrentBit
)
2998 return MaybeCurrentBit
.takeError();
2999 CurrentBit
= MaybeCurrentBit
.get();
3000 // If this module uses a string table, read this as a module-level VST.
3002 if (Error Err
= parseGlobalValueSymbolTable())
3004 if (Error JumpFailed
= Stream
.JumpToBit(CurrentBit
))
3006 return Error::success();
3008 // Otherwise, the VST will be in a similar format to a function-level VST,
3009 // and will contain symbol names.
3012 // Compute the delta between the bitcode indices in the VST (the word offset
3013 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
3014 // expected by the lazy reader. The reader's EnterSubBlock expects to have
3015 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
3016 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
3017 // just before entering the VST subblock because: 1) the EnterSubBlock
3018 // changes the AbbrevID width; 2) the VST block is nested within the same
3019 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
3020 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
3021 // jump to the FUNCTION_BLOCK using this offset later, we don't want
3022 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
3023 unsigned FuncBitcodeOffsetDelta
=
3024 Stream
.getAbbrevIDWidth() + bitc::BlockIDWidth
;
3026 if (Error Err
= Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
3029 SmallVector
<uint64_t, 64> Record
;
3031 Triple
TT(TheModule
->getTargetTriple());
3033 // Read all the records for this value table.
3034 SmallString
<128> ValueName
;
3037 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
3039 return MaybeEntry
.takeError();
3040 BitstreamEntry Entry
= MaybeEntry
.get();
3042 switch (Entry
.Kind
) {
3043 case BitstreamEntry::SubBlock
: // Handled for us already.
3044 case BitstreamEntry::Error
:
3045 return error("Malformed block");
3046 case BitstreamEntry::EndBlock
:
3048 if (Error JumpFailed
= Stream
.JumpToBit(CurrentBit
))
3050 return Error::success();
3051 case BitstreamEntry::Record
:
3052 // The interesting case.
3058 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
3060 return MaybeRecord
.takeError();
3061 switch (MaybeRecord
.get()) {
3062 default: // Default behavior: unknown type.
3064 case bitc::VST_CODE_ENTRY
: { // VST_CODE_ENTRY: [valueid, namechar x N]
3065 Expected
<Value
*> ValOrErr
= recordValue(Record
, 1, TT
);
3066 if (Error Err
= ValOrErr
.takeError())
3071 case bitc::VST_CODE_FNENTRY
: {
3072 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
3073 Expected
<Value
*> ValOrErr
= recordValue(Record
, 2, TT
);
3074 if (Error Err
= ValOrErr
.takeError())
3076 Value
*V
= ValOrErr
.get();
3078 // Ignore function offsets emitted for aliases of functions in older
3079 // versions of LLVM.
3080 if (auto *F
= dyn_cast
<Function
>(V
))
3081 setDeferredFunctionInfo(FuncBitcodeOffsetDelta
, F
, Record
);
3084 case bitc::VST_CODE_BBENTRY
: {
3085 if (convertToString(Record
, 1, ValueName
))
3086 return error("Invalid bbentry record");
3087 BasicBlock
*BB
= getBasicBlock(Record
[0]);
3089 return error("Invalid bbentry record");
3091 BB
->setName(ValueName
.str());
3099 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
3101 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V
) {
3106 // There is no such thing as -0 with integers. "-0" really means MININT.
3110 /// Resolve all of the initializers for global values and aliases that we can.
3111 Error
BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3112 std::vector
<std::pair
<GlobalVariable
*, unsigned>> GlobalInitWorklist
;
3113 std::vector
<std::pair
<GlobalValue
*, unsigned>> IndirectSymbolInitWorklist
;
3114 std::vector
<FunctionOperandInfo
> FunctionOperandWorklist
;
3116 GlobalInitWorklist
.swap(GlobalInits
);
3117 IndirectSymbolInitWorklist
.swap(IndirectSymbolInits
);
3118 FunctionOperandWorklist
.swap(FunctionOperands
);
3120 while (!GlobalInitWorklist
.empty()) {
3121 unsigned ValID
= GlobalInitWorklist
.back().second
;
3122 if (ValID
>= ValueList
.size()) {
3123 // Not ready to resolve this yet, it requires something later in the file.
3124 GlobalInits
.push_back(GlobalInitWorklist
.back());
3126 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3128 return MaybeC
.takeError();
3129 GlobalInitWorklist
.back().first
->setInitializer(MaybeC
.get());
3131 GlobalInitWorklist
.pop_back();
3134 while (!IndirectSymbolInitWorklist
.empty()) {
3135 unsigned ValID
= IndirectSymbolInitWorklist
.back().second
;
3136 if (ValID
>= ValueList
.size()) {
3137 IndirectSymbolInits
.push_back(IndirectSymbolInitWorklist
.back());
3139 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3141 return MaybeC
.takeError();
3142 Constant
*C
= MaybeC
.get();
3143 GlobalValue
*GV
= IndirectSymbolInitWorklist
.back().first
;
3144 if (auto *GA
= dyn_cast
<GlobalAlias
>(GV
)) {
3145 if (C
->getType() != GV
->getType())
3146 return error("Alias and aliasee types don't match");
3148 } else if (auto *GI
= dyn_cast
<GlobalIFunc
>(GV
)) {
3151 return error("Expected an alias or an ifunc");
3154 IndirectSymbolInitWorklist
.pop_back();
3157 while (!FunctionOperandWorklist
.empty()) {
3158 FunctionOperandInfo
&Info
= FunctionOperandWorklist
.back();
3159 if (Info
.PersonalityFn
) {
3160 unsigned ValID
= Info
.PersonalityFn
- 1;
3161 if (ValID
< ValueList
.size()) {
3162 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3164 return MaybeC
.takeError();
3165 Info
.F
->setPersonalityFn(MaybeC
.get());
3166 Info
.PersonalityFn
= 0;
3170 unsigned ValID
= Info
.Prefix
- 1;
3171 if (ValID
< ValueList
.size()) {
3172 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3174 return MaybeC
.takeError();
3175 Info
.F
->setPrefixData(MaybeC
.get());
3179 if (Info
.Prologue
) {
3180 unsigned ValID
= Info
.Prologue
- 1;
3181 if (ValID
< ValueList
.size()) {
3182 Expected
<Constant
*> MaybeC
= getValueForInitializer(ValID
);
3184 return MaybeC
.takeError();
3185 Info
.F
->setPrologueData(MaybeC
.get());
3189 if (Info
.PersonalityFn
|| Info
.Prefix
|| Info
.Prologue
)
3190 FunctionOperands
.push_back(Info
);
3191 FunctionOperandWorklist
.pop_back();
3194 return Error::success();
3197 APInt
llvm::readWideAPInt(ArrayRef
<uint64_t> Vals
, unsigned TypeBits
) {
3198 SmallVector
<uint64_t, 8> Words(Vals
.size());
3199 transform(Vals
, Words
.begin(),
3200 BitcodeReader::decodeSignRotatedValue
);
3202 return APInt(TypeBits
, Words
);
3205 Error
BitcodeReader::parseConstants() {
3206 if (Error Err
= Stream
.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID
))
3209 SmallVector
<uint64_t, 64> Record
;
3211 // Read all the records for this value table.
3212 Type
*CurTy
= Type::getInt32Ty(Context
);
3213 unsigned Int32TyID
= getVirtualTypeID(CurTy
);
3214 unsigned CurTyID
= Int32TyID
;
3215 Type
*CurElemTy
= nullptr;
3216 unsigned NextCstNo
= ValueList
.size();
3219 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
3221 return MaybeEntry
.takeError();
3222 BitstreamEntry Entry
= MaybeEntry
.get();
3224 switch (Entry
.Kind
) {
3225 case BitstreamEntry::SubBlock
: // Handled for us already.
3226 case BitstreamEntry::Error
:
3227 return error("Malformed block");
3228 case BitstreamEntry::EndBlock
:
3229 if (NextCstNo
!= ValueList
.size())
3230 return error("Invalid constant reference");
3231 return Error::success();
3232 case BitstreamEntry::Record
:
3233 // The interesting case.
3239 Type
*VoidType
= Type::getVoidTy(Context
);
3241 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
3243 return MaybeBitCode
.takeError();
3244 switch (unsigned BitCode
= MaybeBitCode
.get()) {
3245 default: // Default behavior: unknown constant
3246 case bitc::CST_CODE_UNDEF
: // UNDEF
3247 V
= UndefValue::get(CurTy
);
3249 case bitc::CST_CODE_POISON
: // POISON
3250 V
= PoisonValue::get(CurTy
);
3252 case bitc::CST_CODE_SETTYPE
: // SETTYPE: [typeid]
3254 return error("Invalid settype record");
3255 if (Record
[0] >= TypeList
.size() || !TypeList
[Record
[0]])
3256 return error("Invalid settype record");
3257 if (TypeList
[Record
[0]] == VoidType
)
3258 return error("Invalid constant type");
3259 CurTyID
= Record
[0];
3260 CurTy
= TypeList
[CurTyID
];
3261 CurElemTy
= getPtrElementTypeByID(CurTyID
);
3262 continue; // Skip the ValueList manipulation.
3263 case bitc::CST_CODE_NULL
: // NULL
3264 if (CurTy
->isVoidTy() || CurTy
->isFunctionTy() || CurTy
->isLabelTy())
3265 return error("Invalid type for a constant null value");
3266 if (auto *TETy
= dyn_cast
<TargetExtType
>(CurTy
))
3267 if (!TETy
->hasProperty(TargetExtType::HasZeroInit
))
3268 return error("Invalid type for a constant null value");
3269 V
= Constant::getNullValue(CurTy
);
3271 case bitc::CST_CODE_INTEGER
: // INTEGER: [intval]
3272 if (!CurTy
->isIntOrIntVectorTy() || Record
.empty())
3273 return error("Invalid integer const record");
3274 V
= ConstantInt::get(CurTy
, decodeSignRotatedValue(Record
[0]));
3276 case bitc::CST_CODE_WIDE_INTEGER
: {// WIDE_INTEGER: [n x intval]
3277 if (!CurTy
->isIntOrIntVectorTy() || Record
.empty())
3278 return error("Invalid wide integer const record");
3280 auto *ScalarTy
= cast
<IntegerType
>(CurTy
->getScalarType());
3281 APInt VInt
= readWideAPInt(Record
, ScalarTy
->getBitWidth());
3282 V
= ConstantInt::get(CurTy
, VInt
);
3285 case bitc::CST_CODE_FLOAT
: { // FLOAT: [fpval]
3287 return error("Invalid float const record");
3289 auto *ScalarTy
= CurTy
->getScalarType();
3290 if (ScalarTy
->isHalfTy())
3291 V
= ConstantFP::get(CurTy
, APFloat(APFloat::IEEEhalf(),
3292 APInt(16, (uint16_t)Record
[0])));
3293 else if (ScalarTy
->isBFloatTy())
3294 V
= ConstantFP::get(
3295 CurTy
, APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record
[0])));
3296 else if (ScalarTy
->isFloatTy())
3297 V
= ConstantFP::get(CurTy
, APFloat(APFloat::IEEEsingle(),
3298 APInt(32, (uint32_t)Record
[0])));
3299 else if (ScalarTy
->isDoubleTy())
3300 V
= ConstantFP::get(
3301 CurTy
, APFloat(APFloat::IEEEdouble(), APInt(64, Record
[0])));
3302 else if (ScalarTy
->isX86_FP80Ty()) {
3303 // Bits are not stored the same way as a normal i80 APInt, compensate.
3304 uint64_t Rearrange
[2];
3305 Rearrange
[0] = (Record
[1] & 0xffffLL
) | (Record
[0] << 16);
3306 Rearrange
[1] = Record
[0] >> 48;
3307 V
= ConstantFP::get(
3308 CurTy
, APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange
)));
3309 } else if (ScalarTy
->isFP128Ty())
3310 V
= ConstantFP::get(CurTy
,
3311 APFloat(APFloat::IEEEquad(), APInt(128, Record
)));
3312 else if (ScalarTy
->isPPC_FP128Ty())
3313 V
= ConstantFP::get(
3314 CurTy
, APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record
)));
3316 V
= PoisonValue::get(CurTy
);
3320 case bitc::CST_CODE_AGGREGATE
: {// AGGREGATE: [n x value number]
3322 return error("Invalid aggregate record");
3324 unsigned Size
= Record
.size();
3325 SmallVector
<unsigned, 16> Elts
;
3326 for (unsigned i
= 0; i
!= Size
; ++i
)
3327 Elts
.push_back(Record
[i
]);
3329 if (isa
<StructType
>(CurTy
)) {
3330 V
= BitcodeConstant::create(
3331 Alloc
, CurTy
, BitcodeConstant::ConstantStructOpcode
, Elts
);
3332 } else if (isa
<ArrayType
>(CurTy
)) {
3333 V
= BitcodeConstant::create(Alloc
, CurTy
,
3334 BitcodeConstant::ConstantArrayOpcode
, Elts
);
3335 } else if (isa
<VectorType
>(CurTy
)) {
3336 V
= BitcodeConstant::create(
3337 Alloc
, CurTy
, BitcodeConstant::ConstantVectorOpcode
, Elts
);
3339 V
= PoisonValue::get(CurTy
);
3343 case bitc::CST_CODE_STRING
: // STRING: [values]
3344 case bitc::CST_CODE_CSTRING
: { // CSTRING: [values]
3346 return error("Invalid string record");
3348 SmallString
<16> Elts(Record
.begin(), Record
.end());
3349 V
= ConstantDataArray::getString(Context
, Elts
,
3350 BitCode
== bitc::CST_CODE_CSTRING
);
3353 case bitc::CST_CODE_DATA
: {// DATA: [n x value]
3355 return error("Invalid data record");
3358 if (auto *Array
= dyn_cast
<ArrayType
>(CurTy
))
3359 EltTy
= Array
->getElementType();
3361 EltTy
= cast
<VectorType
>(CurTy
)->getElementType();
3362 if (EltTy
->isIntegerTy(8)) {
3363 SmallVector
<uint8_t, 16> Elts(Record
.begin(), Record
.end());
3364 if (isa
<VectorType
>(CurTy
))
3365 V
= ConstantDataVector::get(Context
, Elts
);
3367 V
= ConstantDataArray::get(Context
, Elts
);
3368 } else if (EltTy
->isIntegerTy(16)) {
3369 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
3370 if (isa
<VectorType
>(CurTy
))
3371 V
= ConstantDataVector::get(Context
, Elts
);
3373 V
= ConstantDataArray::get(Context
, Elts
);
3374 } else if (EltTy
->isIntegerTy(32)) {
3375 SmallVector
<uint32_t, 16> Elts(Record
.begin(), Record
.end());
3376 if (isa
<VectorType
>(CurTy
))
3377 V
= ConstantDataVector::get(Context
, Elts
);
3379 V
= ConstantDataArray::get(Context
, Elts
);
3380 } else if (EltTy
->isIntegerTy(64)) {
3381 SmallVector
<uint64_t, 16> Elts(Record
.begin(), Record
.end());
3382 if (isa
<VectorType
>(CurTy
))
3383 V
= ConstantDataVector::get(Context
, Elts
);
3385 V
= ConstantDataArray::get(Context
, Elts
);
3386 } else if (EltTy
->isHalfTy()) {
3387 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
3388 if (isa
<VectorType
>(CurTy
))
3389 V
= ConstantDataVector::getFP(EltTy
, Elts
);
3391 V
= ConstantDataArray::getFP(EltTy
, Elts
);
3392 } else if (EltTy
->isBFloatTy()) {
3393 SmallVector
<uint16_t, 16> Elts(Record
.begin(), Record
.end());
3394 if (isa
<VectorType
>(CurTy
))
3395 V
= ConstantDataVector::getFP(EltTy
, Elts
);
3397 V
= ConstantDataArray::getFP(EltTy
, Elts
);
3398 } else if (EltTy
->isFloatTy()) {
3399 SmallVector
<uint32_t, 16> Elts(Record
.begin(), Record
.end());
3400 if (isa
<VectorType
>(CurTy
))
3401 V
= ConstantDataVector::getFP(EltTy
, Elts
);
3403 V
= ConstantDataArray::getFP(EltTy
, Elts
);
3404 } else if (EltTy
->isDoubleTy()) {
3405 SmallVector
<uint64_t, 16> Elts(Record
.begin(), Record
.end());
3406 if (isa
<VectorType
>(CurTy
))
3407 V
= ConstantDataVector::getFP(EltTy
, Elts
);
3409 V
= ConstantDataArray::getFP(EltTy
, Elts
);
3411 return error("Invalid type for value");
3415 case bitc::CST_CODE_CE_UNOP
: { // CE_UNOP: [opcode, opval]
3416 if (Record
.size() < 2)
3417 return error("Invalid unary op constexpr record");
3418 int Opc
= getDecodedUnaryOpcode(Record
[0], CurTy
);
3420 V
= PoisonValue::get(CurTy
); // Unknown unop.
3422 V
= BitcodeConstant::create(Alloc
, CurTy
, Opc
, (unsigned)Record
[1]);
3426 case bitc::CST_CODE_CE_BINOP
: { // CE_BINOP: [opcode, opval, opval]
3427 if (Record
.size() < 3)
3428 return error("Invalid binary op constexpr record");
3429 int Opc
= getDecodedBinaryOpcode(Record
[0], CurTy
);
3431 V
= PoisonValue::get(CurTy
); // Unknown binop.
3434 if (Record
.size() >= 4) {
3435 if (Opc
== Instruction::Add
||
3436 Opc
== Instruction::Sub
||
3437 Opc
== Instruction::Mul
||
3438 Opc
== Instruction::Shl
) {
3439 if (Record
[3] & (1 << bitc::OBO_NO_SIGNED_WRAP
))
3440 Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
3441 if (Record
[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP
))
3442 Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
3443 } else if (Opc
== Instruction::SDiv
||
3444 Opc
== Instruction::UDiv
||
3445 Opc
== Instruction::LShr
||
3446 Opc
== Instruction::AShr
) {
3447 if (Record
[3] & (1 << bitc::PEO_EXACT
))
3448 Flags
|= PossiblyExactOperator::IsExact
;
3451 V
= BitcodeConstant::create(Alloc
, CurTy
, {(uint8_t)Opc
, Flags
},
3452 {(unsigned)Record
[1], (unsigned)Record
[2]});
3456 case bitc::CST_CODE_CE_CAST
: { // CE_CAST: [opcode, opty, opval]
3457 if (Record
.size() < 3)
3458 return error("Invalid cast constexpr record");
3459 int Opc
= getDecodedCastOpcode(Record
[0]);
3461 V
= PoisonValue::get(CurTy
); // Unknown cast.
3463 unsigned OpTyID
= Record
[1];
3464 Type
*OpTy
= getTypeByID(OpTyID
);
3466 return error("Invalid cast constexpr record");
3467 V
= BitcodeConstant::create(Alloc
, CurTy
, Opc
, (unsigned)Record
[2]);
3471 case bitc::CST_CODE_CE_INBOUNDS_GEP
: // [ty, n x operands]
3472 case bitc::CST_CODE_CE_GEP_OLD
: // [ty, n x operands]
3473 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
: // [ty, flags, n x
3475 case bitc::CST_CODE_CE_GEP
: // [ty, flags, n x operands]
3476 case bitc::CST_CODE_CE_GEP_WITH_INRANGE
: { // [ty, flags, start, end, n x
3478 if (Record
.size() < 2)
3479 return error("Constant GEP record must have at least two elements");
3481 Type
*PointeeType
= nullptr;
3482 if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
||
3483 BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE
||
3484 BitCode
== bitc::CST_CODE_CE_GEP
|| Record
.size() % 2)
3485 PointeeType
= getTypeByID(Record
[OpNum
++]);
3488 std::optional
<ConstantRange
> InRange
;
3489 if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
) {
3490 uint64_t Op
= Record
[OpNum
++];
3491 Flags
= Op
& 1; // inbounds
3492 unsigned InRangeIndex
= Op
>> 1;
3493 // "Upgrade" inrange by dropping it. The feature is too niche to
3496 } else if (BitCode
== bitc::CST_CODE_CE_GEP_WITH_INRANGE
) {
3497 Flags
= Record
[OpNum
++];
3498 Expected
<ConstantRange
> MaybeInRange
=
3499 readBitWidthAndConstantRange(Record
, OpNum
);
3501 return MaybeInRange
.takeError();
3502 InRange
= MaybeInRange
.get();
3503 } else if (BitCode
== bitc::CST_CODE_CE_GEP
) {
3504 Flags
= Record
[OpNum
++];
3505 } else if (BitCode
== bitc::CST_CODE_CE_INBOUNDS_GEP
)
3506 Flags
= (1 << bitc::GEP_INBOUNDS
);
3508 SmallVector
<unsigned, 16> Elts
;
3509 unsigned BaseTypeID
= Record
[OpNum
];
3510 while (OpNum
!= Record
.size()) {
3511 unsigned ElTyID
= Record
[OpNum
++];
3512 Type
*ElTy
= getTypeByID(ElTyID
);
3514 return error("Invalid getelementptr constexpr record");
3515 Elts
.push_back(Record
[OpNum
++]);
3518 if (Elts
.size() < 1)
3519 return error("Invalid gep with no operands");
3521 Type
*BaseType
= getTypeByID(BaseTypeID
);
3522 if (isa
<VectorType
>(BaseType
)) {
3523 BaseTypeID
= getContainedTypeID(BaseTypeID
, 0);
3524 BaseType
= getTypeByID(BaseTypeID
);
3527 PointerType
*OrigPtrTy
= dyn_cast_or_null
<PointerType
>(BaseType
);
3529 return error("GEP base operand must be pointer or vector of pointer");
3532 PointeeType
= getPtrElementTypeByID(BaseTypeID
);
3534 return error("Missing element type for old-style constant GEP");
3537 V
= BitcodeConstant::create(
3539 {Instruction::GetElementPtr
, uint8_t(Flags
), PointeeType
, InRange
},
3543 case bitc::CST_CODE_CE_SELECT
: { // CE_SELECT: [opval#, opval#, opval#]
3544 if (Record
.size() < 3)
3545 return error("Invalid select constexpr record");
3547 V
= BitcodeConstant::create(
3548 Alloc
, CurTy
, Instruction::Select
,
3549 {(unsigned)Record
[0], (unsigned)Record
[1], (unsigned)Record
[2]});
3552 case bitc::CST_CODE_CE_EXTRACTELT
3553 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3554 if (Record
.size() < 3)
3555 return error("Invalid extractelement constexpr record");
3556 unsigned OpTyID
= Record
[0];
3558 dyn_cast_or_null
<VectorType
>(getTypeByID(OpTyID
));
3560 return error("Invalid extractelement constexpr record");
3562 if (Record
.size() == 4) {
3563 unsigned IdxTyID
= Record
[2];
3564 Type
*IdxTy
= getTypeByID(IdxTyID
);
3566 return error("Invalid extractelement constexpr record");
3567 IdxRecord
= Record
[3];
3569 // Deprecated, but still needed to read old bitcode files.
3570 IdxRecord
= Record
[2];
3572 V
= BitcodeConstant::create(Alloc
, CurTy
, Instruction::ExtractElement
,
3573 {(unsigned)Record
[1], IdxRecord
});
3576 case bitc::CST_CODE_CE_INSERTELT
3577 : { // CE_INSERTELT: [opval, opval, opty, opval]
3578 VectorType
*OpTy
= dyn_cast
<VectorType
>(CurTy
);
3579 if (Record
.size() < 3 || !OpTy
)
3580 return error("Invalid insertelement constexpr record");
3582 if (Record
.size() == 4) {
3583 unsigned IdxTyID
= Record
[2];
3584 Type
*IdxTy
= getTypeByID(IdxTyID
);
3586 return error("Invalid insertelement constexpr record");
3587 IdxRecord
= Record
[3];
3589 // Deprecated, but still needed to read old bitcode files.
3590 IdxRecord
= Record
[2];
3592 V
= BitcodeConstant::create(
3593 Alloc
, CurTy
, Instruction::InsertElement
,
3594 {(unsigned)Record
[0], (unsigned)Record
[1], IdxRecord
});
3597 case bitc::CST_CODE_CE_SHUFFLEVEC
: { // CE_SHUFFLEVEC: [opval, opval, opval]
3598 VectorType
*OpTy
= dyn_cast
<VectorType
>(CurTy
);
3599 if (Record
.size() < 3 || !OpTy
)
3600 return error("Invalid shufflevector constexpr record");
3601 V
= BitcodeConstant::create(
3602 Alloc
, CurTy
, Instruction::ShuffleVector
,
3603 {(unsigned)Record
[0], (unsigned)Record
[1], (unsigned)Record
[2]});
3606 case bitc::CST_CODE_CE_SHUFVEC_EX
: { // [opty, opval, opval, opval]
3607 VectorType
*RTy
= dyn_cast
<VectorType
>(CurTy
);
3609 dyn_cast_or_null
<VectorType
>(getTypeByID(Record
[0]));
3610 if (Record
.size() < 4 || !RTy
|| !OpTy
)
3611 return error("Invalid shufflevector constexpr record");
3612 V
= BitcodeConstant::create(
3613 Alloc
, CurTy
, Instruction::ShuffleVector
,
3614 {(unsigned)Record
[1], (unsigned)Record
[2], (unsigned)Record
[3]});
3617 case bitc::CST_CODE_CE_CMP
: { // CE_CMP: [opty, opval, opval, pred]
3618 if (Record
.size() < 4)
3619 return error("Invalid cmp constexpt record");
3620 unsigned OpTyID
= Record
[0];
3621 Type
*OpTy
= getTypeByID(OpTyID
);
3623 return error("Invalid cmp constexpr record");
3624 V
= BitcodeConstant::create(
3626 {(uint8_t)(OpTy
->isFPOrFPVectorTy() ? Instruction::FCmp
3627 : Instruction::ICmp
),
3628 (uint8_t)Record
[3]},
3629 {(unsigned)Record
[1], (unsigned)Record
[2]});
3632 // This maintains backward compatibility, pre-asm dialect keywords.
3633 // Deprecated, but still needed to read old bitcode files.
3634 case bitc::CST_CODE_INLINEASM_OLD
: {
3635 if (Record
.size() < 2)
3636 return error("Invalid inlineasm record");
3637 std::string AsmStr
, ConstrStr
;
3638 bool HasSideEffects
= Record
[0] & 1;
3639 bool IsAlignStack
= Record
[0] >> 1;
3640 unsigned AsmStrSize
= Record
[1];
3641 if (2+AsmStrSize
>= Record
.size())
3642 return error("Invalid inlineasm record");
3643 unsigned ConstStrSize
= Record
[2+AsmStrSize
];
3644 if (3+AsmStrSize
+ConstStrSize
> Record
.size())
3645 return error("Invalid inlineasm record");
3647 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
3648 AsmStr
+= (char)Record
[2+i
];
3649 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
3650 ConstrStr
+= (char)Record
[3+AsmStrSize
+i
];
3651 UpgradeInlineAsmString(&AsmStr
);
3653 return error("Missing element type for old-style inlineasm");
3654 V
= InlineAsm::get(cast
<FunctionType
>(CurElemTy
), AsmStr
, ConstrStr
,
3655 HasSideEffects
, IsAlignStack
);
3658 // This version adds support for the asm dialect keywords (e.g.,
3660 case bitc::CST_CODE_INLINEASM_OLD2
: {
3661 if (Record
.size() < 2)
3662 return error("Invalid inlineasm record");
3663 std::string AsmStr
, ConstrStr
;
3664 bool HasSideEffects
= Record
[0] & 1;
3665 bool IsAlignStack
= (Record
[0] >> 1) & 1;
3666 unsigned AsmDialect
= Record
[0] >> 2;
3667 unsigned AsmStrSize
= Record
[1];
3668 if (2+AsmStrSize
>= Record
.size())
3669 return error("Invalid inlineasm record");
3670 unsigned ConstStrSize
= Record
[2+AsmStrSize
];
3671 if (3+AsmStrSize
+ConstStrSize
> Record
.size())
3672 return error("Invalid inlineasm record");
3674 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
3675 AsmStr
+= (char)Record
[2+i
];
3676 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
3677 ConstrStr
+= (char)Record
[3+AsmStrSize
+i
];
3678 UpgradeInlineAsmString(&AsmStr
);
3680 return error("Missing element type for old-style inlineasm");
3681 V
= InlineAsm::get(cast
<FunctionType
>(CurElemTy
), AsmStr
, ConstrStr
,
3682 HasSideEffects
, IsAlignStack
,
3683 InlineAsm::AsmDialect(AsmDialect
));
3686 // This version adds support for the unwind keyword.
3687 case bitc::CST_CODE_INLINEASM_OLD3
: {
3688 if (Record
.size() < 2)
3689 return error("Invalid inlineasm record");
3691 std::string AsmStr
, ConstrStr
;
3692 bool HasSideEffects
= Record
[OpNum
] & 1;
3693 bool IsAlignStack
= (Record
[OpNum
] >> 1) & 1;
3694 unsigned AsmDialect
= (Record
[OpNum
] >> 2) & 1;
3695 bool CanThrow
= (Record
[OpNum
] >> 3) & 1;
3697 unsigned AsmStrSize
= Record
[OpNum
];
3699 if (OpNum
+ AsmStrSize
>= Record
.size())
3700 return error("Invalid inlineasm record");
3701 unsigned ConstStrSize
= Record
[OpNum
+ AsmStrSize
];
3702 if (OpNum
+ 1 + AsmStrSize
+ ConstStrSize
> Record
.size())
3703 return error("Invalid inlineasm record");
3705 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
3706 AsmStr
+= (char)Record
[OpNum
+ i
];
3708 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
3709 ConstrStr
+= (char)Record
[OpNum
+ AsmStrSize
+ i
];
3710 UpgradeInlineAsmString(&AsmStr
);
3712 return error("Missing element type for old-style inlineasm");
3713 V
= InlineAsm::get(cast
<FunctionType
>(CurElemTy
), AsmStr
, ConstrStr
,
3714 HasSideEffects
, IsAlignStack
,
3715 InlineAsm::AsmDialect(AsmDialect
), CanThrow
);
3718 // This version adds explicit function type.
3719 case bitc::CST_CODE_INLINEASM
: {
3720 if (Record
.size() < 3)
3721 return error("Invalid inlineasm record");
3723 auto *FnTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(Record
[OpNum
]));
3726 return error("Invalid inlineasm record");
3727 std::string AsmStr
, ConstrStr
;
3728 bool HasSideEffects
= Record
[OpNum
] & 1;
3729 bool IsAlignStack
= (Record
[OpNum
] >> 1) & 1;
3730 unsigned AsmDialect
= (Record
[OpNum
] >> 2) & 1;
3731 bool CanThrow
= (Record
[OpNum
] >> 3) & 1;
3733 unsigned AsmStrSize
= Record
[OpNum
];
3735 if (OpNum
+ AsmStrSize
>= Record
.size())
3736 return error("Invalid inlineasm record");
3737 unsigned ConstStrSize
= Record
[OpNum
+ AsmStrSize
];
3738 if (OpNum
+ 1 + AsmStrSize
+ ConstStrSize
> Record
.size())
3739 return error("Invalid inlineasm record");
3741 for (unsigned i
= 0; i
!= AsmStrSize
; ++i
)
3742 AsmStr
+= (char)Record
[OpNum
+ i
];
3744 for (unsigned i
= 0; i
!= ConstStrSize
; ++i
)
3745 ConstrStr
+= (char)Record
[OpNum
+ AsmStrSize
+ i
];
3746 UpgradeInlineAsmString(&AsmStr
);
3747 V
= InlineAsm::get(FnTy
, AsmStr
, ConstrStr
, HasSideEffects
, IsAlignStack
,
3748 InlineAsm::AsmDialect(AsmDialect
), CanThrow
);
3751 case bitc::CST_CODE_BLOCKADDRESS
:{
3752 if (Record
.size() < 3)
3753 return error("Invalid blockaddress record");
3754 unsigned FnTyID
= Record
[0];
3755 Type
*FnTy
= getTypeByID(FnTyID
);
3757 return error("Invalid blockaddress record");
3758 V
= BitcodeConstant::create(
3760 {BitcodeConstant::BlockAddressOpcode
, 0, (unsigned)Record
[2]},
3764 case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT
: {
3765 if (Record
.size() < 2)
3766 return error("Invalid dso_local record");
3767 unsigned GVTyID
= Record
[0];
3768 Type
*GVTy
= getTypeByID(GVTyID
);
3770 return error("Invalid dso_local record");
3771 V
= BitcodeConstant::create(
3772 Alloc
, CurTy
, BitcodeConstant::DSOLocalEquivalentOpcode
, Record
[1]);
3775 case bitc::CST_CODE_NO_CFI_VALUE
: {
3776 if (Record
.size() < 2)
3777 return error("Invalid no_cfi record");
3778 unsigned GVTyID
= Record
[0];
3779 Type
*GVTy
= getTypeByID(GVTyID
);
3781 return error("Invalid no_cfi record");
3782 V
= BitcodeConstant::create(Alloc
, CurTy
, BitcodeConstant::NoCFIOpcode
,
3786 case bitc::CST_CODE_PTRAUTH
: {
3787 if (Record
.size() < 4)
3788 return error("Invalid ptrauth record");
3789 // Ptr, Key, Disc, AddrDisc
3790 V
= BitcodeConstant::create(Alloc
, CurTy
,
3791 BitcodeConstant::ConstantPtrAuthOpcode
,
3792 {(unsigned)Record
[0], (unsigned)Record
[1],
3793 (unsigned)Record
[2], (unsigned)Record
[3]});
3798 assert(V
->getType() == getTypeByID(CurTyID
) && "Incorrect result type ID");
3799 if (Error Err
= ValueList
.assignValue(NextCstNo
, V
, CurTyID
))
3805 Error
BitcodeReader::parseUseLists() {
3806 if (Error Err
= Stream
.EnterSubBlock(bitc::USELIST_BLOCK_ID
))
3809 // Read all the records.
3810 SmallVector
<uint64_t, 64> Record
;
3813 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
3815 return MaybeEntry
.takeError();
3816 BitstreamEntry Entry
= MaybeEntry
.get();
3818 switch (Entry
.Kind
) {
3819 case BitstreamEntry::SubBlock
: // Handled for us already.
3820 case BitstreamEntry::Error
:
3821 return error("Malformed block");
3822 case BitstreamEntry::EndBlock
:
3823 return Error::success();
3824 case BitstreamEntry::Record
:
3825 // The interesting case.
3829 // Read a use list record.
3832 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
3834 return MaybeRecord
.takeError();
3835 switch (MaybeRecord
.get()) {
3836 default: // Default behavior: unknown type.
3838 case bitc::USELIST_CODE_BB
:
3841 case bitc::USELIST_CODE_DEFAULT
: {
3842 unsigned RecordLength
= Record
.size();
3843 if (RecordLength
< 3)
3844 // Records should have at least an ID and two indexes.
3845 return error("Invalid record");
3846 unsigned ID
= Record
.pop_back_val();
3850 assert(ID
< FunctionBBs
.size() && "Basic block not found");
3851 V
= FunctionBBs
[ID
];
3854 unsigned NumUses
= 0;
3855 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
3856 for (const Use
&U
: V
->materialized_uses()) {
3857 if (++NumUses
> Record
.size())
3859 Order
[&U
] = Record
[NumUses
- 1];
3861 if (Order
.size() != Record
.size() || NumUses
> Record
.size())
3862 // Mismatches can happen if the functions are being materialized lazily
3863 // (out-of-order), or a value has been upgraded.
3866 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
3867 return Order
.lookup(&L
) < Order
.lookup(&R
);
3875 /// When we see the block for metadata, remember where it is and then skip it.
3876 /// This lets us lazily deserialize the metadata.
3877 Error
BitcodeReader::rememberAndSkipMetadata() {
3878 // Save the current stream state.
3879 uint64_t CurBit
= Stream
.GetCurrentBitNo();
3880 DeferredMetadataInfo
.push_back(CurBit
);
3882 // Skip over the block for now.
3883 if (Error Err
= Stream
.SkipBlock())
3885 return Error::success();
3888 Error
BitcodeReader::materializeMetadata() {
3889 for (uint64_t BitPos
: DeferredMetadataInfo
) {
3890 // Move the bit stream to the saved position.
3891 if (Error JumpFailed
= Stream
.JumpToBit(BitPos
))
3893 if (Error Err
= MDLoader
->parseModuleMetadata())
3897 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3898 // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3900 if (!TheModule
->getNamedMetadata("llvm.linker.options")) {
3901 if (Metadata
*Val
= TheModule
->getModuleFlag("Linker Options")) {
3902 NamedMDNode
*LinkerOpts
=
3903 TheModule
->getOrInsertNamedMetadata("llvm.linker.options");
3904 for (const MDOperand
&MDOptions
: cast
<MDNode
>(Val
)->operands())
3905 LinkerOpts
->addOperand(cast
<MDNode
>(MDOptions
));
3909 DeferredMetadataInfo
.clear();
3910 return Error::success();
3913 void BitcodeReader::setStripDebugInfo() { StripDebugInfo
= true; }
3915 /// When we see the block for a function body, remember where it is and then
3916 /// skip it. This lets us lazily deserialize the functions.
3917 Error
BitcodeReader::rememberAndSkipFunctionBody() {
3918 // Get the function we are talking about.
3919 if (FunctionsWithBodies
.empty())
3920 return error("Insufficient function protos");
3922 Function
*Fn
= FunctionsWithBodies
.back();
3923 FunctionsWithBodies
.pop_back();
3925 // Save the current stream state.
3926 uint64_t CurBit
= Stream
.GetCurrentBitNo();
3928 (DeferredFunctionInfo
[Fn
] == 0 || DeferredFunctionInfo
[Fn
] == CurBit
) &&
3929 "Mismatch between VST and scanned function offsets");
3930 DeferredFunctionInfo
[Fn
] = CurBit
;
3932 // Skip over the function block for now.
3933 if (Error Err
= Stream
.SkipBlock())
3935 return Error::success();
3938 Error
BitcodeReader::globalCleanup() {
3939 // Patch the initializers for globals and aliases up.
3940 if (Error Err
= resolveGlobalAndIndirectSymbolInits())
3942 if (!GlobalInits
.empty() || !IndirectSymbolInits
.empty())
3943 return error("Malformed global initializer set");
3945 // Look for intrinsic functions which need to be upgraded at some point
3946 // and functions that need to have their function attributes upgraded.
3947 for (Function
&F
: *TheModule
) {
3948 MDLoader
->upgradeDebugIntrinsics(F
);
3950 // If PreserveInputDbgFormat=true, then we don't know whether we want
3951 // intrinsics or records, and we won't perform any conversions in either
3952 // case, so don't upgrade intrinsics to records.
3953 if (UpgradeIntrinsicFunction(
3954 &F
, NewFn
, PreserveInputDbgFormat
!= cl::boolOrDefault::BOU_TRUE
))
3955 UpgradedIntrinsics
[&F
] = NewFn
;
3956 // Look for functions that rely on old function attribute behavior.
3957 UpgradeFunctionAttributes(F
);
3960 // Look for global variables which need to be renamed.
3961 std::vector
<std::pair
<GlobalVariable
*, GlobalVariable
*>> UpgradedVariables
;
3962 for (GlobalVariable
&GV
: TheModule
->globals())
3963 if (GlobalVariable
*Upgraded
= UpgradeGlobalVariable(&GV
))
3964 UpgradedVariables
.emplace_back(&GV
, Upgraded
);
3965 for (auto &Pair
: UpgradedVariables
) {
3966 Pair
.first
->eraseFromParent();
3967 TheModule
->insertGlobalVariable(Pair
.second
);
3970 // Force deallocation of memory for these vectors to favor the client that
3971 // want lazy deserialization.
3972 std::vector
<std::pair
<GlobalVariable
*, unsigned>>().swap(GlobalInits
);
3973 std::vector
<std::pair
<GlobalValue
*, unsigned>>().swap(IndirectSymbolInits
);
3974 return Error::success();
3977 /// Support for lazy parsing of function bodies. This is required if we
3978 /// either have an old bitcode file without a VST forward declaration record,
3979 /// or if we have an anonymous function being materialized, since anonymous
3980 /// functions do not have a name and are therefore not in the VST.
3981 Error
BitcodeReader::rememberAndSkipFunctionBodies() {
3982 if (Error JumpFailed
= Stream
.JumpToBit(NextUnreadBit
))
3985 if (Stream
.AtEndOfStream())
3986 return error("Could not find function in stream");
3988 if (!SeenFirstFunctionBody
)
3989 return error("Trying to materialize functions before seeing function blocks");
3991 // An old bitcode file with the symbol table at the end would have
3992 // finished the parse greedily.
3993 assert(SeenValueSymbolTable
);
3995 SmallVector
<uint64_t, 64> Record
;
3998 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
4000 return MaybeEntry
.takeError();
4001 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
4003 switch (Entry
.Kind
) {
4005 return error("Expect SubBlock");
4006 case BitstreamEntry::SubBlock
:
4009 return error("Expect function block");
4010 case bitc::FUNCTION_BLOCK_ID
:
4011 if (Error Err
= rememberAndSkipFunctionBody())
4013 NextUnreadBit
= Stream
.GetCurrentBitNo();
4014 return Error::success();
4020 Error
BitcodeReaderBase::readBlockInfo() {
4021 Expected
<std::optional
<BitstreamBlockInfo
>> MaybeNewBlockInfo
=
4022 Stream
.ReadBlockInfoBlock();
4023 if (!MaybeNewBlockInfo
)
4024 return MaybeNewBlockInfo
.takeError();
4025 std::optional
<BitstreamBlockInfo
> NewBlockInfo
=
4026 std::move(MaybeNewBlockInfo
.get());
4028 return error("Malformed block");
4029 BlockInfo
= std::move(*NewBlockInfo
);
4030 return Error::success();
4033 Error
BitcodeReader::parseComdatRecord(ArrayRef
<uint64_t> Record
) {
4034 // v1: [selection_kind, name]
4035 // v2: [strtab_offset, strtab_size, selection_kind]
4037 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
4040 return error("Invalid record");
4041 Comdat::SelectionKind SK
= getDecodedComdatSelectionKind(Record
[0]);
4042 std::string OldFormatName
;
4044 if (Record
.size() < 2)
4045 return error("Invalid record");
4046 unsigned ComdatNameSize
= Record
[1];
4047 if (ComdatNameSize
> Record
.size() - 2)
4048 return error("Comdat name size too large");
4049 OldFormatName
.reserve(ComdatNameSize
);
4050 for (unsigned i
= 0; i
!= ComdatNameSize
; ++i
)
4051 OldFormatName
+= (char)Record
[2 + i
];
4052 Name
= OldFormatName
;
4054 Comdat
*C
= TheModule
->getOrInsertComdat(Name
);
4055 C
->setSelectionKind(SK
);
4056 ComdatList
.push_back(C
);
4057 return Error::success();
4060 static void inferDSOLocal(GlobalValue
*GV
) {
4061 // infer dso_local from linkage and visibility if it is not encoded.
4062 if (GV
->hasLocalLinkage() ||
4063 (!GV
->hasDefaultVisibility() && !GV
->hasExternalWeakLinkage()))
4064 GV
->setDSOLocal(true);
4067 GlobalValue::SanitizerMetadata
deserializeSanitizerMetadata(unsigned V
) {
4068 GlobalValue::SanitizerMetadata Meta
;
4070 Meta
.NoAddress
= true;
4072 Meta
.NoHWAddress
= true;
4076 Meta
.IsDynInit
= true;
4080 Error
BitcodeReader::parseGlobalVarRecord(ArrayRef
<uint64_t> Record
) {
4081 // v1: [pointer type, isconst, initid, linkage, alignment, section,
4082 // visibility, threadlocal, unnamed_addr, externally_initialized,
4083 // dllstorageclass, comdat, attributes, preemption specifier,
4084 // partition strtab offset, partition strtab size] (name in VST)
4085 // v2: [strtab_offset, strtab_size, v1]
4086 // v3: [v2, code_model]
4088 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
4090 if (Record
.size() < 6)
4091 return error("Invalid record");
4092 unsigned TyID
= Record
[0];
4093 Type
*Ty
= getTypeByID(TyID
);
4095 return error("Invalid record");
4096 bool isConstant
= Record
[1] & 1;
4097 bool explicitType
= Record
[1] & 2;
4098 unsigned AddressSpace
;
4100 AddressSpace
= Record
[1] >> 2;
4102 if (!Ty
->isPointerTy())
4103 return error("Invalid type for value");
4104 AddressSpace
= cast
<PointerType
>(Ty
)->getAddressSpace();
4105 TyID
= getContainedTypeID(TyID
);
4106 Ty
= getTypeByID(TyID
);
4108 return error("Missing element type for old-style global");
4111 uint64_t RawLinkage
= Record
[3];
4112 GlobalValue::LinkageTypes Linkage
= getDecodedLinkage(RawLinkage
);
4113 MaybeAlign Alignment
;
4114 if (Error Err
= parseAlignmentValue(Record
[4], Alignment
))
4116 std::string Section
;
4118 if (Record
[5] - 1 >= SectionTable
.size())
4119 return error("Invalid ID");
4120 Section
= SectionTable
[Record
[5] - 1];
4122 GlobalValue::VisibilityTypes Visibility
= GlobalValue::DefaultVisibility
;
4123 // Local linkage must have default visibility.
4124 // auto-upgrade `hidden` and `protected` for old bitcode.
4125 if (Record
.size() > 6 && !GlobalValue::isLocalLinkage(Linkage
))
4126 Visibility
= getDecodedVisibility(Record
[6]);
4128 GlobalVariable::ThreadLocalMode TLM
= GlobalVariable::NotThreadLocal
;
4129 if (Record
.size() > 7)
4130 TLM
= getDecodedThreadLocalMode(Record
[7]);
4132 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
4133 if (Record
.size() > 8)
4134 UnnamedAddr
= getDecodedUnnamedAddrType(Record
[8]);
4136 bool ExternallyInitialized
= false;
4137 if (Record
.size() > 9)
4138 ExternallyInitialized
= Record
[9];
4140 GlobalVariable
*NewGV
=
4141 new GlobalVariable(*TheModule
, Ty
, isConstant
, Linkage
, nullptr, Name
,
4142 nullptr, TLM
, AddressSpace
, ExternallyInitialized
);
4144 NewGV
->setAlignment(*Alignment
);
4145 if (!Section
.empty())
4146 NewGV
->setSection(Section
);
4147 NewGV
->setVisibility(Visibility
);
4148 NewGV
->setUnnamedAddr(UnnamedAddr
);
4150 if (Record
.size() > 10) {
4151 // A GlobalValue with local linkage cannot have a DLL storage class.
4152 if (!NewGV
->hasLocalLinkage()) {
4153 NewGV
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[10]));
4156 upgradeDLLImportExportLinkage(NewGV
, RawLinkage
);
4159 ValueList
.push_back(NewGV
, getVirtualTypeID(NewGV
->getType(), TyID
));
4161 // Remember which value to use for the global initializer.
4162 if (unsigned InitID
= Record
[2])
4163 GlobalInits
.push_back(std::make_pair(NewGV
, InitID
- 1));
4165 if (Record
.size() > 11) {
4166 if (unsigned ComdatID
= Record
[11]) {
4167 if (ComdatID
> ComdatList
.size())
4168 return error("Invalid global variable comdat ID");
4169 NewGV
->setComdat(ComdatList
[ComdatID
- 1]);
4171 } else if (hasImplicitComdat(RawLinkage
)) {
4172 ImplicitComdatObjects
.insert(NewGV
);
4175 if (Record
.size() > 12) {
4176 auto AS
= getAttributes(Record
[12]).getFnAttrs();
4177 NewGV
->setAttributes(AS
);
4180 if (Record
.size() > 13) {
4181 NewGV
->setDSOLocal(getDecodedDSOLocal(Record
[13]));
4183 inferDSOLocal(NewGV
);
4185 // Check whether we have enough values to read a partition name.
4186 if (Record
.size() > 15)
4187 NewGV
->setPartition(StringRef(Strtab
.data() + Record
[14], Record
[15]));
4189 if (Record
.size() > 16 && Record
[16]) {
4190 llvm::GlobalValue::SanitizerMetadata Meta
=
4191 deserializeSanitizerMetadata(Record
[16]);
4192 NewGV
->setSanitizerMetadata(Meta
);
4195 if (Record
.size() > 17 && Record
[17]) {
4196 if (auto CM
= getDecodedCodeModel(Record
[17]))
4197 NewGV
->setCodeModel(*CM
);
4199 return error("Invalid global variable code model");
4202 return Error::success();
4205 void BitcodeReader::callValueTypeCallback(Value
*F
, unsigned TypeID
) {
4206 if (ValueTypeCallback
) {
4207 (*ValueTypeCallback
)(
4208 F
, TypeID
, [this](unsigned I
) { return getTypeByID(I
); },
4209 [this](unsigned I
, unsigned J
) { return getContainedTypeID(I
, J
); });
4213 Error
BitcodeReader::parseFunctionRecord(ArrayRef
<uint64_t> Record
) {
4214 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
4215 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
4216 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
4217 // v2: [strtab_offset, strtab_size, v1]
4219 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
4221 if (Record
.size() < 8)
4222 return error("Invalid record");
4223 unsigned FTyID
= Record
[0];
4224 Type
*FTy
= getTypeByID(FTyID
);
4226 return error("Invalid record");
4227 if (isa
<PointerType
>(FTy
)) {
4228 FTyID
= getContainedTypeID(FTyID
, 0);
4229 FTy
= getTypeByID(FTyID
);
4231 return error("Missing element type for old-style function");
4234 if (!isa
<FunctionType
>(FTy
))
4235 return error("Invalid type for value");
4236 auto CC
= static_cast<CallingConv::ID
>(Record
[1]);
4237 if (CC
& ~CallingConv::MaxID
)
4238 return error("Invalid calling convention ID");
4240 unsigned AddrSpace
= TheModule
->getDataLayout().getProgramAddressSpace();
4241 if (Record
.size() > 16)
4242 AddrSpace
= Record
[16];
4245 Function::Create(cast
<FunctionType
>(FTy
), GlobalValue::ExternalLinkage
,
4246 AddrSpace
, Name
, TheModule
);
4248 assert(Func
->getFunctionType() == FTy
&&
4249 "Incorrect fully specified type provided for function");
4250 FunctionTypeIDs
[Func
] = FTyID
;
4252 Func
->setCallingConv(CC
);
4253 bool isProto
= Record
[2];
4254 uint64_t RawLinkage
= Record
[3];
4255 Func
->setLinkage(getDecodedLinkage(RawLinkage
));
4256 Func
->setAttributes(getAttributes(Record
[4]));
4257 callValueTypeCallback(Func
, FTyID
);
4259 // Upgrade any old-style byval or sret without a type by propagating the
4260 // argument's pointee type. There should be no opaque pointers where the byval
4261 // type is implicit.
4262 for (unsigned i
= 0; i
!= Func
->arg_size(); ++i
) {
4263 for (Attribute::AttrKind Kind
: {Attribute::ByVal
, Attribute::StructRet
,
4264 Attribute::InAlloca
}) {
4265 if (!Func
->hasParamAttribute(i
, Kind
))
4268 if (Func
->getParamAttribute(i
, Kind
).getValueAsType())
4271 Func
->removeParamAttr(i
, Kind
);
4273 unsigned ParamTypeID
= getContainedTypeID(FTyID
, i
+ 1);
4274 Type
*PtrEltTy
= getPtrElementTypeByID(ParamTypeID
);
4276 return error("Missing param element type for attribute upgrade");
4280 case Attribute::ByVal
:
4281 NewAttr
= Attribute::getWithByValType(Context
, PtrEltTy
);
4283 case Attribute::StructRet
:
4284 NewAttr
= Attribute::getWithStructRetType(Context
, PtrEltTy
);
4286 case Attribute::InAlloca
:
4287 NewAttr
= Attribute::getWithInAllocaType(Context
, PtrEltTy
);
4290 llvm_unreachable("not an upgraded type attribute");
4293 Func
->addParamAttr(i
, NewAttr
);
4297 if (Func
->getCallingConv() == CallingConv::X86_INTR
&&
4298 !Func
->arg_empty() && !Func
->hasParamAttribute(0, Attribute::ByVal
)) {
4299 unsigned ParamTypeID
= getContainedTypeID(FTyID
, 1);
4300 Type
*ByValTy
= getPtrElementTypeByID(ParamTypeID
);
4302 return error("Missing param element type for x86_intrcc upgrade");
4303 Attribute NewAttr
= Attribute::getWithByValType(Context
, ByValTy
);
4304 Func
->addParamAttr(0, NewAttr
);
4307 MaybeAlign Alignment
;
4308 if (Error Err
= parseAlignmentValue(Record
[5], Alignment
))
4311 Func
->setAlignment(*Alignment
);
4313 if (Record
[6] - 1 >= SectionTable
.size())
4314 return error("Invalid ID");
4315 Func
->setSection(SectionTable
[Record
[6] - 1]);
4317 // Local linkage must have default visibility.
4318 // auto-upgrade `hidden` and `protected` for old bitcode.
4319 if (!Func
->hasLocalLinkage())
4320 Func
->setVisibility(getDecodedVisibility(Record
[7]));
4321 if (Record
.size() > 8 && Record
[8]) {
4322 if (Record
[8] - 1 >= GCTable
.size())
4323 return error("Invalid ID");
4324 Func
->setGC(GCTable
[Record
[8] - 1]);
4326 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
4327 if (Record
.size() > 9)
4328 UnnamedAddr
= getDecodedUnnamedAddrType(Record
[9]);
4329 Func
->setUnnamedAddr(UnnamedAddr
);
4331 FunctionOperandInfo OperandInfo
= {Func
, 0, 0, 0};
4332 if (Record
.size() > 10)
4333 OperandInfo
.Prologue
= Record
[10];
4335 if (Record
.size() > 11) {
4336 // A GlobalValue with local linkage cannot have a DLL storage class.
4337 if (!Func
->hasLocalLinkage()) {
4338 Func
->setDLLStorageClass(getDecodedDLLStorageClass(Record
[11]));
4341 upgradeDLLImportExportLinkage(Func
, RawLinkage
);
4344 if (Record
.size() > 12) {
4345 if (unsigned ComdatID
= Record
[12]) {
4346 if (ComdatID
> ComdatList
.size())
4347 return error("Invalid function comdat ID");
4348 Func
->setComdat(ComdatList
[ComdatID
- 1]);
4350 } else if (hasImplicitComdat(RawLinkage
)) {
4351 ImplicitComdatObjects
.insert(Func
);
4354 if (Record
.size() > 13)
4355 OperandInfo
.Prefix
= Record
[13];
4357 if (Record
.size() > 14)
4358 OperandInfo
.PersonalityFn
= Record
[14];
4360 if (Record
.size() > 15) {
4361 Func
->setDSOLocal(getDecodedDSOLocal(Record
[15]));
4363 inferDSOLocal(Func
);
4365 // Record[16] is the address space number.
4367 // Check whether we have enough values to read a partition name. Also make
4368 // sure Strtab has enough values.
4369 if (Record
.size() > 18 && Strtab
.data() &&
4370 Record
[17] + Record
[18] <= Strtab
.size()) {
4371 Func
->setPartition(StringRef(Strtab
.data() + Record
[17], Record
[18]));
4374 ValueList
.push_back(Func
, getVirtualTypeID(Func
->getType(), FTyID
));
4376 if (OperandInfo
.PersonalityFn
|| OperandInfo
.Prefix
|| OperandInfo
.Prologue
)
4377 FunctionOperands
.push_back(OperandInfo
);
4379 // If this is a function with a body, remember the prototype we are
4380 // creating now, so that we can match up the body with them later.
4382 Func
->setIsMaterializable(true);
4383 FunctionsWithBodies
.push_back(Func
);
4384 DeferredFunctionInfo
[Func
] = 0;
4386 return Error::success();
4389 Error
BitcodeReader::parseGlobalIndirectSymbolRecord(
4390 unsigned BitCode
, ArrayRef
<uint64_t> Record
) {
4391 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
4392 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4393 // dllstorageclass, threadlocal, unnamed_addr,
4394 // preemption specifier] (name in VST)
4395 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
4396 // visibility, dllstorageclass, threadlocal, unnamed_addr,
4397 // preemption specifier] (name in VST)
4398 // v2: [strtab_offset, strtab_size, v1]
4400 std::tie(Name
, Record
) = readNameFromStrtab(Record
);
4402 bool NewRecord
= BitCode
!= bitc::MODULE_CODE_ALIAS_OLD
;
4403 if (Record
.size() < (3 + (unsigned)NewRecord
))
4404 return error("Invalid record");
4406 unsigned TypeID
= Record
[OpNum
++];
4407 Type
*Ty
= getTypeByID(TypeID
);
4409 return error("Invalid record");
4413 auto *PTy
= dyn_cast
<PointerType
>(Ty
);
4415 return error("Invalid type for value");
4416 AddrSpace
= PTy
->getAddressSpace();
4417 TypeID
= getContainedTypeID(TypeID
);
4418 Ty
= getTypeByID(TypeID
);
4420 return error("Missing element type for old-style indirect symbol");
4422 AddrSpace
= Record
[OpNum
++];
4425 auto Val
= Record
[OpNum
++];
4426 auto Linkage
= Record
[OpNum
++];
4428 if (BitCode
== bitc::MODULE_CODE_ALIAS
||
4429 BitCode
== bitc::MODULE_CODE_ALIAS_OLD
)
4430 NewGA
= GlobalAlias::create(Ty
, AddrSpace
, getDecodedLinkage(Linkage
), Name
,
4433 NewGA
= GlobalIFunc::create(Ty
, AddrSpace
, getDecodedLinkage(Linkage
), Name
,
4434 nullptr, TheModule
);
4436 // Local linkage must have default visibility.
4437 // auto-upgrade `hidden` and `protected` for old bitcode.
4438 if (OpNum
!= Record
.size()) {
4439 auto VisInd
= OpNum
++;
4440 if (!NewGA
->hasLocalLinkage())
4441 NewGA
->setVisibility(getDecodedVisibility(Record
[VisInd
]));
4443 if (BitCode
== bitc::MODULE_CODE_ALIAS
||
4444 BitCode
== bitc::MODULE_CODE_ALIAS_OLD
) {
4445 if (OpNum
!= Record
.size()) {
4446 auto S
= Record
[OpNum
++];
4447 // A GlobalValue with local linkage cannot have a DLL storage class.
4448 if (!NewGA
->hasLocalLinkage())
4449 NewGA
->setDLLStorageClass(getDecodedDLLStorageClass(S
));
4452 upgradeDLLImportExportLinkage(NewGA
, Linkage
);
4453 if (OpNum
!= Record
.size())
4454 NewGA
->setThreadLocalMode(getDecodedThreadLocalMode(Record
[OpNum
++]));
4455 if (OpNum
!= Record
.size())
4456 NewGA
->setUnnamedAddr(getDecodedUnnamedAddrType(Record
[OpNum
++]));
4458 if (OpNum
!= Record
.size())
4459 NewGA
->setDSOLocal(getDecodedDSOLocal(Record
[OpNum
++]));
4460 inferDSOLocal(NewGA
);
4462 // Check whether we have enough values to read a partition name.
4463 if (OpNum
+ 1 < Record
.size()) {
4464 // Check Strtab has enough values for the partition.
4465 if (Record
[OpNum
] + Record
[OpNum
+ 1] > Strtab
.size())
4466 return error("Malformed partition, too large.");
4467 NewGA
->setPartition(
4468 StringRef(Strtab
.data() + Record
[OpNum
], Record
[OpNum
+ 1]));
4471 ValueList
.push_back(NewGA
, getVirtualTypeID(NewGA
->getType(), TypeID
));
4472 IndirectSymbolInits
.push_back(std::make_pair(NewGA
, Val
));
4473 return Error::success();
4476 Error
BitcodeReader::parseModule(uint64_t ResumeBit
,
4477 bool ShouldLazyLoadMetadata
,
4478 ParserCallbacks Callbacks
) {
4479 // Load directly into RemoveDIs format if LoadBitcodeIntoNewDbgInfoFormat
4480 // has been set to true and we aren't attempting to preserve the existing
4481 // format in the bitcode (default action: load into the old debug format).
4482 if (PreserveInputDbgFormat
!= cl::boolOrDefault::BOU_TRUE
) {
4483 TheModule
->IsNewDbgInfoFormat
=
4484 UseNewDbgInfoFormat
&&
4485 LoadBitcodeIntoNewDbgInfoFormat
!= cl::boolOrDefault::BOU_FALSE
;
4488 this->ValueTypeCallback
= std::move(Callbacks
.ValueType
);
4490 if (Error JumpFailed
= Stream
.JumpToBit(ResumeBit
))
4492 } else if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
4495 SmallVector
<uint64_t, 64> Record
;
4497 // Parts of bitcode parsing depend on the datalayout. Make sure we
4498 // finalize the datalayout before we run any of that code.
4499 bool ResolvedDataLayout
= false;
4500 // In order to support importing modules with illegal data layout strings,
4501 // delay parsing the data layout string until after upgrades and overrides
4502 // have been applied, allowing to fix illegal data layout strings.
4503 // Initialize to the current module's layout string in case none is specified.
4504 std::string TentativeDataLayoutStr
= TheModule
->getDataLayoutStr();
4506 auto ResolveDataLayout
= [&]() -> Error
{
4507 if (ResolvedDataLayout
)
4508 return Error::success();
4510 // Datalayout and triple can't be parsed after this point.
4511 ResolvedDataLayout
= true;
4513 // Auto-upgrade the layout string
4514 TentativeDataLayoutStr
= llvm::UpgradeDataLayoutString(
4515 TentativeDataLayoutStr
, TheModule
->getTargetTriple());
4518 if (Callbacks
.DataLayout
) {
4519 if (auto LayoutOverride
= (*Callbacks
.DataLayout
)(
4520 TheModule
->getTargetTriple(), TentativeDataLayoutStr
))
4521 TentativeDataLayoutStr
= *LayoutOverride
;
4524 // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4525 Expected
<DataLayout
> MaybeDL
= DataLayout::parse(TentativeDataLayoutStr
);
4527 return MaybeDL
.takeError();
4529 TheModule
->setDataLayout(MaybeDL
.get());
4530 return Error::success();
4533 // Read all the records for this module.
4535 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
4537 return MaybeEntry
.takeError();
4538 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
4540 switch (Entry
.Kind
) {
4541 case BitstreamEntry::Error
:
4542 return error("Malformed block");
4543 case BitstreamEntry::EndBlock
:
4544 if (Error Err
= ResolveDataLayout())
4546 return globalCleanup();
4548 case BitstreamEntry::SubBlock
:
4550 default: // Skip unknown content.
4551 if (Error Err
= Stream
.SkipBlock())
4554 case bitc::BLOCKINFO_BLOCK_ID
:
4555 if (Error Err
= readBlockInfo())
4558 case bitc::PARAMATTR_BLOCK_ID
:
4559 if (Error Err
= parseAttributeBlock())
4562 case bitc::PARAMATTR_GROUP_BLOCK_ID
:
4563 if (Error Err
= parseAttributeGroupBlock())
4566 case bitc::TYPE_BLOCK_ID_NEW
:
4567 if (Error Err
= parseTypeTable())
4570 case bitc::VALUE_SYMTAB_BLOCK_ID
:
4571 if (!SeenValueSymbolTable
) {
4572 // Either this is an old form VST without function index and an
4573 // associated VST forward declaration record (which would have caused
4574 // the VST to be jumped to and parsed before it was encountered
4575 // normally in the stream), or there were no function blocks to
4576 // trigger an earlier parsing of the VST.
4577 assert(VSTOffset
== 0 || FunctionsWithBodies
.empty());
4578 if (Error Err
= parseValueSymbolTable())
4580 SeenValueSymbolTable
= true;
4582 // We must have had a VST forward declaration record, which caused
4583 // the parser to jump to and parse the VST earlier.
4584 assert(VSTOffset
> 0);
4585 if (Error Err
= Stream
.SkipBlock())
4589 case bitc::CONSTANTS_BLOCK_ID
:
4590 if (Error Err
= parseConstants())
4592 if (Error Err
= resolveGlobalAndIndirectSymbolInits())
4595 case bitc::METADATA_BLOCK_ID
:
4596 if (ShouldLazyLoadMetadata
) {
4597 if (Error Err
= rememberAndSkipMetadata())
4601 assert(DeferredMetadataInfo
.empty() && "Unexpected deferred metadata");
4602 if (Error Err
= MDLoader
->parseModuleMetadata())
4605 case bitc::METADATA_KIND_BLOCK_ID
:
4606 if (Error Err
= MDLoader
->parseMetadataKinds())
4609 case bitc::FUNCTION_BLOCK_ID
:
4610 if (Error Err
= ResolveDataLayout())
4613 // If this is the first function body we've seen, reverse the
4614 // FunctionsWithBodies list.
4615 if (!SeenFirstFunctionBody
) {
4616 std::reverse(FunctionsWithBodies
.begin(), FunctionsWithBodies
.end());
4617 if (Error Err
= globalCleanup())
4619 SeenFirstFunctionBody
= true;
4622 if (VSTOffset
> 0) {
4623 // If we have a VST forward declaration record, make sure we
4624 // parse the VST now if we haven't already. It is needed to
4625 // set up the DeferredFunctionInfo vector for lazy reading.
4626 if (!SeenValueSymbolTable
) {
4627 if (Error Err
= BitcodeReader::parseValueSymbolTable(VSTOffset
))
4629 SeenValueSymbolTable
= true;
4630 // Fall through so that we record the NextUnreadBit below.
4631 // This is necessary in case we have an anonymous function that
4632 // is later materialized. Since it will not have a VST entry we
4633 // need to fall back to the lazy parse to find its offset.
4635 // If we have a VST forward declaration record, but have already
4636 // parsed the VST (just above, when the first function body was
4637 // encountered here), then we are resuming the parse after
4638 // materializing functions. The ResumeBit points to the
4639 // start of the last function block recorded in the
4640 // DeferredFunctionInfo map. Skip it.
4641 if (Error Err
= Stream
.SkipBlock())
4647 // Support older bitcode files that did not have the function
4648 // index in the VST, nor a VST forward declaration record, as
4649 // well as anonymous functions that do not have VST entries.
4650 // Build the DeferredFunctionInfo vector on the fly.
4651 if (Error Err
= rememberAndSkipFunctionBody())
4654 // Suspend parsing when we reach the function bodies. Subsequent
4655 // materialization calls will resume it when necessary. If the bitcode
4656 // file is old, the symbol table will be at the end instead and will not
4657 // have been seen yet. In this case, just finish the parse now.
4658 if (SeenValueSymbolTable
) {
4659 NextUnreadBit
= Stream
.GetCurrentBitNo();
4660 // After the VST has been parsed, we need to make sure intrinsic name
4661 // are auto-upgraded.
4662 return globalCleanup();
4665 case bitc::USELIST_BLOCK_ID
:
4666 if (Error Err
= parseUseLists())
4669 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID
:
4670 if (Error Err
= parseOperandBundleTags())
4673 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID
:
4674 if (Error Err
= parseSyncScopeNames())
4680 case BitstreamEntry::Record
:
4681 // The interesting case.
4686 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
4688 return MaybeBitCode
.takeError();
4689 switch (unsigned BitCode
= MaybeBitCode
.get()) {
4690 default: break; // Default behavior, ignore unknown content.
4691 case bitc::MODULE_CODE_VERSION
: {
4692 Expected
<unsigned> VersionOrErr
= parseVersionRecord(Record
);
4694 return VersionOrErr
.takeError();
4695 UseRelativeIDs
= *VersionOrErr
>= 1;
4698 case bitc::MODULE_CODE_TRIPLE
: { // TRIPLE: [strchr x N]
4699 if (ResolvedDataLayout
)
4700 return error("target triple too late in module");
4702 if (convertToString(Record
, 0, S
))
4703 return error("Invalid record");
4704 TheModule
->setTargetTriple(S
);
4707 case bitc::MODULE_CODE_DATALAYOUT
: { // DATALAYOUT: [strchr x N]
4708 if (ResolvedDataLayout
)
4709 return error("datalayout too late in module");
4710 if (convertToString(Record
, 0, TentativeDataLayoutStr
))
4711 return error("Invalid record");
4714 case bitc::MODULE_CODE_ASM
: { // ASM: [strchr x N]
4716 if (convertToString(Record
, 0, S
))
4717 return error("Invalid record");
4718 TheModule
->setModuleInlineAsm(S
);
4721 case bitc::MODULE_CODE_DEPLIB
: { // DEPLIB: [strchr x N]
4722 // Deprecated, but still needed to read old bitcode files.
4724 if (convertToString(Record
, 0, S
))
4725 return error("Invalid record");
4729 case bitc::MODULE_CODE_SECTIONNAME
: { // SECTIONNAME: [strchr x N]
4731 if (convertToString(Record
, 0, S
))
4732 return error("Invalid record");
4733 SectionTable
.push_back(S
);
4736 case bitc::MODULE_CODE_GCNAME
: { // SECTIONNAME: [strchr x N]
4738 if (convertToString(Record
, 0, S
))
4739 return error("Invalid record");
4740 GCTable
.push_back(S
);
4743 case bitc::MODULE_CODE_COMDAT
:
4744 if (Error Err
= parseComdatRecord(Record
))
4747 // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4748 // written by ThinLinkBitcodeWriter. See
4749 // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4751 // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4752 case bitc::MODULE_CODE_GLOBALVAR
:
4753 if (Error Err
= parseGlobalVarRecord(Record
))
4756 case bitc::MODULE_CODE_FUNCTION
:
4757 if (Error Err
= ResolveDataLayout())
4759 if (Error Err
= parseFunctionRecord(Record
))
4762 case bitc::MODULE_CODE_IFUNC
:
4763 case bitc::MODULE_CODE_ALIAS
:
4764 case bitc::MODULE_CODE_ALIAS_OLD
:
4765 if (Error Err
= parseGlobalIndirectSymbolRecord(BitCode
, Record
))
4768 /// MODULE_CODE_VSTOFFSET: [offset]
4769 case bitc::MODULE_CODE_VSTOFFSET
:
4771 return error("Invalid record");
4772 // Note that we subtract 1 here because the offset is relative to one word
4773 // before the start of the identification or module block, which was
4774 // historically always the start of the regular bitcode header.
4775 VSTOffset
= Record
[0] - 1;
4777 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4778 case bitc::MODULE_CODE_SOURCE_FILENAME
:
4779 SmallString
<128> ValueName
;
4780 if (convertToString(Record
, 0, ValueName
))
4781 return error("Invalid record");
4782 TheModule
->setSourceFileName(ValueName
);
4787 this->ValueTypeCallback
= std::nullopt
;
4788 return Error::success();
4791 Error
BitcodeReader::parseBitcodeInto(Module
*M
, bool ShouldLazyLoadMetadata
,
4793 ParserCallbacks Callbacks
) {
4795 MetadataLoaderCallbacks MDCallbacks
;
4796 MDCallbacks
.GetTypeByID
= [&](unsigned ID
) { return getTypeByID(ID
); };
4797 MDCallbacks
.GetContainedTypeID
= [&](unsigned I
, unsigned J
) {
4798 return getContainedTypeID(I
, J
);
4800 MDCallbacks
.MDType
= Callbacks
.MDType
;
4801 MDLoader
= MetadataLoader(Stream
, *M
, ValueList
, IsImporting
, MDCallbacks
);
4802 return parseModule(0, ShouldLazyLoadMetadata
, Callbacks
);
4805 Error
BitcodeReader::typeCheckLoadStoreInst(Type
*ValType
, Type
*PtrType
) {
4806 if (!isa
<PointerType
>(PtrType
))
4807 return error("Load/Store operand is not a pointer type");
4808 if (!PointerType::isLoadableOrStorableType(ValType
))
4809 return error("Cannot load/store from pointer");
4810 return Error::success();
4813 Error
BitcodeReader::propagateAttributeTypes(CallBase
*CB
,
4814 ArrayRef
<unsigned> ArgTyIDs
) {
4815 AttributeList Attrs
= CB
->getAttributes();
4816 for (unsigned i
= 0; i
!= CB
->arg_size(); ++i
) {
4817 for (Attribute::AttrKind Kind
: {Attribute::ByVal
, Attribute::StructRet
,
4818 Attribute::InAlloca
}) {
4819 if (!Attrs
.hasParamAttr(i
, Kind
) ||
4820 Attrs
.getParamAttr(i
, Kind
).getValueAsType())
4823 Type
*PtrEltTy
= getPtrElementTypeByID(ArgTyIDs
[i
]);
4825 return error("Missing element type for typed attribute upgrade");
4829 case Attribute::ByVal
:
4830 NewAttr
= Attribute::getWithByValType(Context
, PtrEltTy
);
4832 case Attribute::StructRet
:
4833 NewAttr
= Attribute::getWithStructRetType(Context
, PtrEltTy
);
4835 case Attribute::InAlloca
:
4836 NewAttr
= Attribute::getWithInAllocaType(Context
, PtrEltTy
);
4839 llvm_unreachable("not an upgraded type attribute");
4842 Attrs
= Attrs
.addParamAttribute(Context
, i
, NewAttr
);
4846 if (CB
->isInlineAsm()) {
4847 const InlineAsm
*IA
= cast
<InlineAsm
>(CB
->getCalledOperand());
4849 for (const InlineAsm::ConstraintInfo
&CI
: IA
->ParseConstraints()) {
4853 if (CI
.isIndirect
&& !Attrs
.getParamElementType(ArgNo
)) {
4854 Type
*ElemTy
= getPtrElementTypeByID(ArgTyIDs
[ArgNo
]);
4856 return error("Missing element type for inline asm upgrade");
4857 Attrs
= Attrs
.addParamAttribute(
4859 Attribute::get(Context
, Attribute::ElementType
, ElemTy
));
4866 switch (CB
->getIntrinsicID()) {
4867 case Intrinsic::preserve_array_access_index
:
4868 case Intrinsic::preserve_struct_access_index
:
4869 case Intrinsic::aarch64_ldaxr
:
4870 case Intrinsic::aarch64_ldxr
:
4871 case Intrinsic::aarch64_stlxr
:
4872 case Intrinsic::aarch64_stxr
:
4873 case Intrinsic::arm_ldaex
:
4874 case Intrinsic::arm_ldrex
:
4875 case Intrinsic::arm_stlex
:
4876 case Intrinsic::arm_strex
: {
4878 switch (CB
->getIntrinsicID()) {
4879 case Intrinsic::aarch64_stlxr
:
4880 case Intrinsic::aarch64_stxr
:
4881 case Intrinsic::arm_stlex
:
4882 case Intrinsic::arm_strex
:
4889 if (!Attrs
.getParamElementType(ArgNo
)) {
4890 Type
*ElTy
= getPtrElementTypeByID(ArgTyIDs
[ArgNo
]);
4892 return error("Missing element type for elementtype upgrade");
4893 Attribute NewAttr
= Attribute::get(Context
, Attribute::ElementType
, ElTy
);
4894 Attrs
= Attrs
.addParamAttribute(Context
, ArgNo
, NewAttr
);
4902 CB
->setAttributes(Attrs
);
4903 return Error::success();
4906 /// Lazily parse the specified function body block.
4907 Error
BitcodeReader::parseFunctionBody(Function
*F
) {
4908 if (Error Err
= Stream
.EnterSubBlock(bitc::FUNCTION_BLOCK_ID
))
4911 // Unexpected unresolved metadata when parsing function.
4912 if (MDLoader
->hasFwdRefs())
4913 return error("Invalid function metadata: incoming forward references");
4915 InstructionList
.clear();
4916 unsigned ModuleValueListSize
= ValueList
.size();
4917 unsigned ModuleMDLoaderSize
= MDLoader
->size();
4919 // Add all the function arguments to the value table.
4921 unsigned FTyID
= FunctionTypeIDs
[F
];
4922 for (Argument
&I
: F
->args()) {
4923 unsigned ArgTyID
= getContainedTypeID(FTyID
, ArgNo
+ 1);
4924 assert(I
.getType() == getTypeByID(ArgTyID
) &&
4925 "Incorrect fully specified type for Function Argument");
4926 ValueList
.push_back(&I
, ArgTyID
);
4929 unsigned NextValueNo
= ValueList
.size();
4930 BasicBlock
*CurBB
= nullptr;
4931 unsigned CurBBNo
= 0;
4932 // Block into which constant expressions from phi nodes are materialized.
4933 BasicBlock
*PhiConstExprBB
= nullptr;
4934 // Edge blocks for phi nodes into which constant expressions have been
4936 SmallMapVector
<std::pair
<BasicBlock
*, BasicBlock
*>, BasicBlock
*, 4>
4940 auto getLastInstruction
= [&]() -> Instruction
* {
4941 if (CurBB
&& !CurBB
->empty())
4942 return &CurBB
->back();
4943 else if (CurBBNo
&& FunctionBBs
[CurBBNo
- 1] &&
4944 !FunctionBBs
[CurBBNo
- 1]->empty())
4945 return &FunctionBBs
[CurBBNo
- 1]->back();
4949 std::vector
<OperandBundleDef
> OperandBundles
;
4951 // Read all the records.
4952 SmallVector
<uint64_t, 64> Record
;
4955 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
4957 return MaybeEntry
.takeError();
4958 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
4960 switch (Entry
.Kind
) {
4961 case BitstreamEntry::Error
:
4962 return error("Malformed block");
4963 case BitstreamEntry::EndBlock
:
4964 goto OutOfRecordLoop
;
4966 case BitstreamEntry::SubBlock
:
4968 default: // Skip unknown content.
4969 if (Error Err
= Stream
.SkipBlock())
4972 case bitc::CONSTANTS_BLOCK_ID
:
4973 if (Error Err
= parseConstants())
4975 NextValueNo
= ValueList
.size();
4977 case bitc::VALUE_SYMTAB_BLOCK_ID
:
4978 if (Error Err
= parseValueSymbolTable())
4981 case bitc::METADATA_ATTACHMENT_ID
:
4982 if (Error Err
= MDLoader
->parseMetadataAttachment(*F
, InstructionList
))
4985 case bitc::METADATA_BLOCK_ID
:
4986 assert(DeferredMetadataInfo
.empty() &&
4987 "Must read all module-level metadata before function-level");
4988 if (Error Err
= MDLoader
->parseFunctionMetadata())
4991 case bitc::USELIST_BLOCK_ID
:
4992 if (Error Err
= parseUseLists())
4998 case BitstreamEntry::Record
:
4999 // The interesting case.
5005 Instruction
*I
= nullptr;
5006 unsigned ResTypeID
= InvalidTypeID
;
5007 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
5009 return MaybeBitCode
.takeError();
5010 switch (unsigned BitCode
= MaybeBitCode
.get()) {
5011 default: // Default behavior: reject
5012 return error("Invalid value");
5013 case bitc::FUNC_CODE_DECLAREBLOCKS
: { // DECLAREBLOCKS: [nblocks]
5014 if (Record
.empty() || Record
[0] == 0)
5015 return error("Invalid record");
5016 // Create all the basic blocks for the function.
5017 FunctionBBs
.resize(Record
[0]);
5019 // See if anything took the address of blocks in this function.
5020 auto BBFRI
= BasicBlockFwdRefs
.find(F
);
5021 if (BBFRI
== BasicBlockFwdRefs
.end()) {
5022 for (BasicBlock
*&BB
: FunctionBBs
)
5023 BB
= BasicBlock::Create(Context
, "", F
);
5025 auto &BBRefs
= BBFRI
->second
;
5026 // Check for invalid basic block references.
5027 if (BBRefs
.size() > FunctionBBs
.size())
5028 return error("Invalid ID");
5029 assert(!BBRefs
.empty() && "Unexpected empty array");
5030 assert(!BBRefs
.front() && "Invalid reference to entry block");
5031 for (unsigned I
= 0, E
= FunctionBBs
.size(), RE
= BBRefs
.size(); I
!= E
;
5033 if (I
< RE
&& BBRefs
[I
]) {
5034 BBRefs
[I
]->insertInto(F
);
5035 FunctionBBs
[I
] = BBRefs
[I
];
5037 FunctionBBs
[I
] = BasicBlock::Create(Context
, "", F
);
5040 // Erase from the table.
5041 BasicBlockFwdRefs
.erase(BBFRI
);
5044 CurBB
= FunctionBBs
[0];
5048 case bitc::FUNC_CODE_BLOCKADDR_USERS
: // BLOCKADDR_USERS: [vals...]
5049 // The record should not be emitted if it's an empty list.
5051 return error("Invalid record");
5052 // When we have the RARE case of a BlockAddress Constant that is not
5053 // scoped to the Function it refers to, we need to conservatively
5054 // materialize the referred to Function, regardless of whether or not
5055 // that Function will ultimately be linked, otherwise users of
5056 // BitcodeReader might start splicing out Function bodies such that we
5057 // might no longer be able to materialize the BlockAddress since the
5058 // BasicBlock (and entire body of the Function) the BlockAddress refers
5059 // to may have been moved. In the case that the user of BitcodeReader
5060 // decides ultimately not to link the Function body, materializing here
5061 // could be considered wasteful, but it's better than a deserialization
5062 // failure as described. This keeps BitcodeReader unaware of complex
5063 // linkage policy decisions such as those use by LTO, leaving those
5064 // decisions "one layer up."
5065 for (uint64_t ValID
: Record
)
5066 if (auto *F
= dyn_cast
<Function
>(ValueList
[ValID
]))
5067 BackwardRefFunctions
.push_back(F
);
5069 return error("Invalid record");
5073 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN
: // DEBUG_LOC_AGAIN
5074 // This record indicates that the last instruction is at the same
5075 // location as the previous instruction with a location.
5076 I
= getLastInstruction();
5079 return error("Invalid record");
5080 I
->setDebugLoc(LastLoc
);
5084 case bitc::FUNC_CODE_DEBUG_LOC
: { // DEBUG_LOC: [line, col, scope, ia]
5085 I
= getLastInstruction();
5086 if (!I
|| Record
.size() < 4)
5087 return error("Invalid record");
5089 unsigned Line
= Record
[0], Col
= Record
[1];
5090 unsigned ScopeID
= Record
[2], IAID
= Record
[3];
5091 bool isImplicitCode
= Record
.size() == 5 && Record
[4];
5093 MDNode
*Scope
= nullptr, *IA
= nullptr;
5095 Scope
= dyn_cast_or_null
<MDNode
>(
5096 MDLoader
->getMetadataFwdRefOrLoad(ScopeID
- 1));
5098 return error("Invalid record");
5101 IA
= dyn_cast_or_null
<MDNode
>(
5102 MDLoader
->getMetadataFwdRefOrLoad(IAID
- 1));
5104 return error("Invalid record");
5106 LastLoc
= DILocation::get(Scope
->getContext(), Line
, Col
, Scope
, IA
,
5108 I
->setDebugLoc(LastLoc
);
5112 case bitc::FUNC_CODE_INST_UNOP
: { // UNOP: [opval, ty, opcode]
5116 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
, TypeID
, CurBB
) ||
5117 OpNum
+1 > Record
.size())
5118 return error("Invalid record");
5120 int Opc
= getDecodedUnaryOpcode(Record
[OpNum
++], LHS
->getType());
5122 return error("Invalid record");
5123 I
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
5125 InstructionList
.push_back(I
);
5126 if (OpNum
< Record
.size()) {
5127 if (isa
<FPMathOperator
>(I
)) {
5128 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
5130 I
->setFastMathFlags(FMF
);
5135 case bitc::FUNC_CODE_INST_BINOP
: { // BINOP: [opval, ty, opval, opcode]
5139 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
, TypeID
, CurBB
) ||
5140 popValue(Record
, OpNum
, NextValueNo
, LHS
->getType(), TypeID
, RHS
,
5142 OpNum
+1 > Record
.size())
5143 return error("Invalid record");
5145 int Opc
= getDecodedBinaryOpcode(Record
[OpNum
++], LHS
->getType());
5147 return error("Invalid record");
5148 I
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
5150 InstructionList
.push_back(I
);
5151 if (OpNum
< Record
.size()) {
5152 if (Opc
== Instruction::Add
||
5153 Opc
== Instruction::Sub
||
5154 Opc
== Instruction::Mul
||
5155 Opc
== Instruction::Shl
) {
5156 if (Record
[OpNum
] & (1 << bitc::OBO_NO_SIGNED_WRAP
))
5157 cast
<BinaryOperator
>(I
)->setHasNoSignedWrap(true);
5158 if (Record
[OpNum
] & (1 << bitc::OBO_NO_UNSIGNED_WRAP
))
5159 cast
<BinaryOperator
>(I
)->setHasNoUnsignedWrap(true);
5160 } else if (Opc
== Instruction::SDiv
||
5161 Opc
== Instruction::UDiv
||
5162 Opc
== Instruction::LShr
||
5163 Opc
== Instruction::AShr
) {
5164 if (Record
[OpNum
] & (1 << bitc::PEO_EXACT
))
5165 cast
<BinaryOperator
>(I
)->setIsExact(true);
5166 } else if (Opc
== Instruction::Or
) {
5167 if (Record
[OpNum
] & (1 << bitc::PDI_DISJOINT
))
5168 cast
<PossiblyDisjointInst
>(I
)->setIsDisjoint(true);
5169 } else if (isa
<FPMathOperator
>(I
)) {
5170 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
5172 I
->setFastMathFlags(FMF
);
5177 case bitc::FUNC_CODE_INST_CAST
: { // CAST: [opval, opty, destty, castopc]
5181 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
) ||
5182 OpNum
+ 1 > Record
.size())
5183 return error("Invalid record");
5185 ResTypeID
= Record
[OpNum
++];
5186 Type
*ResTy
= getTypeByID(ResTypeID
);
5187 int Opc
= getDecodedCastOpcode(Record
[OpNum
++]);
5189 if (Opc
== -1 || !ResTy
)
5190 return error("Invalid record");
5191 Instruction
*Temp
= nullptr;
5192 if ((I
= UpgradeBitCastInst(Opc
, Op
, ResTy
, Temp
))) {
5194 InstructionList
.push_back(Temp
);
5195 assert(CurBB
&& "No current BB?");
5196 Temp
->insertInto(CurBB
, CurBB
->end());
5199 auto CastOp
= (Instruction::CastOps
)Opc
;
5200 if (!CastInst::castIsValid(CastOp
, Op
, ResTy
))
5201 return error("Invalid cast");
5202 I
= CastInst::Create(CastOp
, Op
, ResTy
);
5205 if (OpNum
< Record
.size()) {
5206 if (Opc
== Instruction::ZExt
|| Opc
== Instruction::UIToFP
) {
5207 if (Record
[OpNum
] & (1 << bitc::PNNI_NON_NEG
))
5208 cast
<PossiblyNonNegInst
>(I
)->setNonNeg(true);
5209 } else if (Opc
== Instruction::Trunc
) {
5210 if (Record
[OpNum
] & (1 << bitc::TIO_NO_UNSIGNED_WRAP
))
5211 cast
<TruncInst
>(I
)->setHasNoUnsignedWrap(true);
5212 if (Record
[OpNum
] & (1 << bitc::TIO_NO_SIGNED_WRAP
))
5213 cast
<TruncInst
>(I
)->setHasNoSignedWrap(true);
5215 if (isa
<FPMathOperator
>(I
)) {
5216 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
5218 I
->setFastMathFlags(FMF
);
5222 InstructionList
.push_back(I
);
5225 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD
:
5226 case bitc::FUNC_CODE_INST_GEP_OLD
:
5227 case bitc::FUNC_CODE_INST_GEP
: { // GEP: type, [n x operands]
5234 if (BitCode
== bitc::FUNC_CODE_INST_GEP
) {
5235 NW
= toGEPNoWrapFlags(Record
[OpNum
++]);
5236 TyID
= Record
[OpNum
++];
5237 Ty
= getTypeByID(TyID
);
5239 if (BitCode
== bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD
)
5240 NW
= GEPNoWrapFlags::inBounds();
5241 TyID
= InvalidTypeID
;
5246 unsigned BasePtrTypeID
;
5247 if (getValueTypePair(Record
, OpNum
, NextValueNo
, BasePtr
, BasePtrTypeID
,
5249 return error("Invalid record");
5252 TyID
= getContainedTypeID(BasePtrTypeID
);
5253 if (BasePtr
->getType()->isVectorTy())
5254 TyID
= getContainedTypeID(TyID
);
5255 Ty
= getTypeByID(TyID
);
5258 SmallVector
<Value
*, 16> GEPIdx
;
5259 while (OpNum
!= Record
.size()) {
5262 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
5263 return error("Invalid record");
5264 GEPIdx
.push_back(Op
);
5267 auto *GEP
= GetElementPtrInst::Create(Ty
, BasePtr
, GEPIdx
);
5271 if (cast
<GEPOperator
>(I
)->getNumIndices() != 0) {
5272 auto GTI
= std::next(gep_type_begin(I
));
5273 for (Value
*Idx
: drop_begin(cast
<GEPOperator
>(I
)->indices())) {
5274 unsigned SubType
= 0;
5275 if (GTI
.isStruct()) {
5277 Idx
->getType()->isVectorTy()
5278 ? cast
<ConstantInt
>(cast
<Constant
>(Idx
)->getSplatValue())
5279 : cast
<ConstantInt
>(Idx
);
5280 SubType
= IdxC
->getZExtValue();
5282 ResTypeID
= getContainedTypeID(ResTypeID
, SubType
);
5287 // At this point ResTypeID is the result element type. We need a pointer
5288 // or vector of pointer to it.
5289 ResTypeID
= getVirtualTypeID(I
->getType()->getScalarType(), ResTypeID
);
5290 if (I
->getType()->isVectorTy())
5291 ResTypeID
= getVirtualTypeID(I
->getType(), ResTypeID
);
5293 InstructionList
.push_back(I
);
5294 GEP
->setNoWrapFlags(NW
);
5298 case bitc::FUNC_CODE_INST_EXTRACTVAL
: {
5299 // EXTRACTVAL: [opty, opval, n x indices]
5303 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Agg
, AggTypeID
, CurBB
))
5304 return error("Invalid record");
5305 Type
*Ty
= Agg
->getType();
5307 unsigned RecSize
= Record
.size();
5308 if (OpNum
== RecSize
)
5309 return error("EXTRACTVAL: Invalid instruction with 0 indices");
5311 SmallVector
<unsigned, 4> EXTRACTVALIdx
;
5312 ResTypeID
= AggTypeID
;
5313 for (; OpNum
!= RecSize
; ++OpNum
) {
5314 bool IsArray
= Ty
->isArrayTy();
5315 bool IsStruct
= Ty
->isStructTy();
5316 uint64_t Index
= Record
[OpNum
];
5318 if (!IsStruct
&& !IsArray
)
5319 return error("EXTRACTVAL: Invalid type");
5320 if ((unsigned)Index
!= Index
)
5321 return error("Invalid value");
5322 if (IsStruct
&& Index
>= Ty
->getStructNumElements())
5323 return error("EXTRACTVAL: Invalid struct index");
5324 if (IsArray
&& Index
>= Ty
->getArrayNumElements())
5325 return error("EXTRACTVAL: Invalid array index");
5326 EXTRACTVALIdx
.push_back((unsigned)Index
);
5329 Ty
= Ty
->getStructElementType(Index
);
5330 ResTypeID
= getContainedTypeID(ResTypeID
, Index
);
5332 Ty
= Ty
->getArrayElementType();
5333 ResTypeID
= getContainedTypeID(ResTypeID
);
5337 I
= ExtractValueInst::Create(Agg
, EXTRACTVALIdx
);
5338 InstructionList
.push_back(I
);
5342 case bitc::FUNC_CODE_INST_INSERTVAL
: {
5343 // INSERTVAL: [opty, opval, opty, opval, n x indices]
5347 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Agg
, AggTypeID
, CurBB
))
5348 return error("Invalid record");
5351 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
, ValTypeID
, CurBB
))
5352 return error("Invalid record");
5354 unsigned RecSize
= Record
.size();
5355 if (OpNum
== RecSize
)
5356 return error("INSERTVAL: Invalid instruction with 0 indices");
5358 SmallVector
<unsigned, 4> INSERTVALIdx
;
5359 Type
*CurTy
= Agg
->getType();
5360 for (; OpNum
!= RecSize
; ++OpNum
) {
5361 bool IsArray
= CurTy
->isArrayTy();
5362 bool IsStruct
= CurTy
->isStructTy();
5363 uint64_t Index
= Record
[OpNum
];
5365 if (!IsStruct
&& !IsArray
)
5366 return error("INSERTVAL: Invalid type");
5367 if ((unsigned)Index
!= Index
)
5368 return error("Invalid value");
5369 if (IsStruct
&& Index
>= CurTy
->getStructNumElements())
5370 return error("INSERTVAL: Invalid struct index");
5371 if (IsArray
&& Index
>= CurTy
->getArrayNumElements())
5372 return error("INSERTVAL: Invalid array index");
5374 INSERTVALIdx
.push_back((unsigned)Index
);
5376 CurTy
= CurTy
->getStructElementType(Index
);
5378 CurTy
= CurTy
->getArrayElementType();
5381 if (CurTy
!= Val
->getType())
5382 return error("Inserted value type doesn't match aggregate type");
5384 I
= InsertValueInst::Create(Agg
, Val
, INSERTVALIdx
);
5385 ResTypeID
= AggTypeID
;
5386 InstructionList
.push_back(I
);
5390 case bitc::FUNC_CODE_INST_SELECT
: { // SELECT: [opval, ty, opval, opval]
5391 // obsolete form of select
5392 // handles select i1 ... in old bitcode
5394 Value
*TrueVal
, *FalseVal
, *Cond
;
5396 Type
*CondType
= Type::getInt1Ty(Context
);
5397 if (getValueTypePair(Record
, OpNum
, NextValueNo
, TrueVal
, TypeID
,
5399 popValue(Record
, OpNum
, NextValueNo
, TrueVal
->getType(), TypeID
,
5401 popValue(Record
, OpNum
, NextValueNo
, CondType
,
5402 getVirtualTypeID(CondType
), Cond
, CurBB
))
5403 return error("Invalid record");
5405 I
= SelectInst::Create(Cond
, TrueVal
, FalseVal
);
5407 InstructionList
.push_back(I
);
5411 case bitc::FUNC_CODE_INST_VSELECT
: {// VSELECT: [ty,opval,opval,predty,pred]
5412 // new form of select
5413 // handles select i1 or select [N x i1]
5415 Value
*TrueVal
, *FalseVal
, *Cond
;
5416 unsigned ValTypeID
, CondTypeID
;
5417 if (getValueTypePair(Record
, OpNum
, NextValueNo
, TrueVal
, ValTypeID
,
5419 popValue(Record
, OpNum
, NextValueNo
, TrueVal
->getType(), ValTypeID
,
5421 getValueTypePair(Record
, OpNum
, NextValueNo
, Cond
, CondTypeID
, CurBB
))
5422 return error("Invalid record");
5424 // select condition can be either i1 or [N x i1]
5425 if (VectorType
* vector_type
=
5426 dyn_cast
<VectorType
>(Cond
->getType())) {
5428 if (vector_type
->getElementType() != Type::getInt1Ty(Context
))
5429 return error("Invalid type for value");
5432 if (Cond
->getType() != Type::getInt1Ty(Context
))
5433 return error("Invalid type for value");
5436 I
= SelectInst::Create(Cond
, TrueVal
, FalseVal
);
5437 ResTypeID
= ValTypeID
;
5438 InstructionList
.push_back(I
);
5439 if (OpNum
< Record
.size() && isa
<FPMathOperator
>(I
)) {
5440 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[OpNum
]);
5442 I
->setFastMathFlags(FMF
);
5447 case bitc::FUNC_CODE_INST_EXTRACTELT
: { // EXTRACTELT: [opty, opval, opval]
5450 unsigned VecTypeID
, IdxTypeID
;
5451 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec
, VecTypeID
, CurBB
) ||
5452 getValueTypePair(Record
, OpNum
, NextValueNo
, Idx
, IdxTypeID
, CurBB
))
5453 return error("Invalid record");
5454 if (!Vec
->getType()->isVectorTy())
5455 return error("Invalid type for value");
5456 I
= ExtractElementInst::Create(Vec
, Idx
);
5457 ResTypeID
= getContainedTypeID(VecTypeID
);
5458 InstructionList
.push_back(I
);
5462 case bitc::FUNC_CODE_INST_INSERTELT
: { // INSERTELT: [ty, opval,opval,opval]
5464 Value
*Vec
, *Elt
, *Idx
;
5465 unsigned VecTypeID
, IdxTypeID
;
5466 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec
, VecTypeID
, CurBB
))
5467 return error("Invalid record");
5468 if (!Vec
->getType()->isVectorTy())
5469 return error("Invalid type for value");
5470 if (popValue(Record
, OpNum
, NextValueNo
,
5471 cast
<VectorType
>(Vec
->getType())->getElementType(),
5472 getContainedTypeID(VecTypeID
), Elt
, CurBB
) ||
5473 getValueTypePair(Record
, OpNum
, NextValueNo
, Idx
, IdxTypeID
, CurBB
))
5474 return error("Invalid record");
5475 I
= InsertElementInst::Create(Vec
, Elt
, Idx
);
5476 ResTypeID
= VecTypeID
;
5477 InstructionList
.push_back(I
);
5481 case bitc::FUNC_CODE_INST_SHUFFLEVEC
: {// SHUFFLEVEC: [opval,ty,opval,opval]
5483 Value
*Vec1
, *Vec2
, *Mask
;
5484 unsigned Vec1TypeID
;
5485 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Vec1
, Vec1TypeID
,
5487 popValue(Record
, OpNum
, NextValueNo
, Vec1
->getType(), Vec1TypeID
,
5489 return error("Invalid record");
5491 unsigned MaskTypeID
;
5492 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Mask
, MaskTypeID
, CurBB
))
5493 return error("Invalid record");
5494 if (!Vec1
->getType()->isVectorTy() || !Vec2
->getType()->isVectorTy())
5495 return error("Invalid type for value");
5497 I
= new ShuffleVectorInst(Vec1
, Vec2
, Mask
);
5499 getVirtualTypeID(I
->getType(), getContainedTypeID(Vec1TypeID
));
5500 InstructionList
.push_back(I
);
5504 case bitc::FUNC_CODE_INST_CMP
: // CMP: [opty, opval, opval, pred]
5505 // Old form of ICmp/FCmp returning bool
5506 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5507 // both legal on vectors but had different behaviour.
5508 case bitc::FUNC_CODE_INST_CMP2
: { // CMP2: [opty, opval, opval, pred]
5509 // FCmp/ICmp returning bool or vector of bool
5514 if (getValueTypePair(Record
, OpNum
, NextValueNo
, LHS
, LHSTypeID
, CurBB
) ||
5515 popValue(Record
, OpNum
, NextValueNo
, LHS
->getType(), LHSTypeID
, RHS
,
5517 return error("Invalid record");
5519 if (OpNum
>= Record
.size())
5521 "Invalid record: operand number exceeded available operands");
5523 CmpInst::Predicate PredVal
= CmpInst::Predicate(Record
[OpNum
]);
5524 bool IsFP
= LHS
->getType()->isFPOrFPVectorTy();
5526 if (IsFP
&& Record
.size() > OpNum
+1)
5527 FMF
= getDecodedFastMathFlags(Record
[++OpNum
]);
5530 if (!CmpInst::isFPPredicate(PredVal
))
5531 return error("Invalid fcmp predicate");
5532 I
= new FCmpInst(PredVal
, LHS
, RHS
);
5534 if (!CmpInst::isIntPredicate(PredVal
))
5535 return error("Invalid icmp predicate");
5536 I
= new ICmpInst(PredVal
, LHS
, RHS
);
5537 if (Record
.size() > OpNum
+ 1 &&
5538 (Record
[++OpNum
] & (1 << bitc::ICMP_SAME_SIGN
)))
5539 cast
<ICmpInst
>(I
)->setSameSign();
5542 if (OpNum
+ 1 != Record
.size())
5543 return error("Invalid record");
5545 ResTypeID
= getVirtualTypeID(I
->getType()->getScalarType());
5546 if (LHS
->getType()->isVectorTy())
5547 ResTypeID
= getVirtualTypeID(I
->getType(), ResTypeID
);
5550 I
->setFastMathFlags(FMF
);
5551 InstructionList
.push_back(I
);
5555 case bitc::FUNC_CODE_INST_RET
: // RET: [opty,opval<optional>]
5557 unsigned Size
= Record
.size();
5559 I
= ReturnInst::Create(Context
);
5560 InstructionList
.push_back(I
);
5565 Value
*Op
= nullptr;
5567 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
5568 return error("Invalid record");
5569 if (OpNum
!= Record
.size())
5570 return error("Invalid record");
5572 I
= ReturnInst::Create(Context
, Op
);
5573 InstructionList
.push_back(I
);
5576 case bitc::FUNC_CODE_INST_BR
: { // BR: [bb#, bb#, opval] or [bb#]
5577 if (Record
.size() != 1 && Record
.size() != 3)
5578 return error("Invalid record");
5579 BasicBlock
*TrueDest
= getBasicBlock(Record
[0]);
5581 return error("Invalid record");
5583 if (Record
.size() == 1) {
5584 I
= BranchInst::Create(TrueDest
);
5585 InstructionList
.push_back(I
);
5588 BasicBlock
*FalseDest
= getBasicBlock(Record
[1]);
5589 Type
*CondType
= Type::getInt1Ty(Context
);
5590 Value
*Cond
= getValue(Record
, 2, NextValueNo
, CondType
,
5591 getVirtualTypeID(CondType
), CurBB
);
5592 if (!FalseDest
|| !Cond
)
5593 return error("Invalid record");
5594 I
= BranchInst::Create(TrueDest
, FalseDest
, Cond
);
5595 InstructionList
.push_back(I
);
5599 case bitc::FUNC_CODE_INST_CLEANUPRET
: { // CLEANUPRET: [val] or [val,bb#]
5600 if (Record
.size() != 1 && Record
.size() != 2)
5601 return error("Invalid record");
5603 Type
*TokenTy
= Type::getTokenTy(Context
);
5604 Value
*CleanupPad
= getValue(Record
, Idx
++, NextValueNo
, TokenTy
,
5605 getVirtualTypeID(TokenTy
), CurBB
);
5607 return error("Invalid record");
5608 BasicBlock
*UnwindDest
= nullptr;
5609 if (Record
.size() == 2) {
5610 UnwindDest
= getBasicBlock(Record
[Idx
++]);
5612 return error("Invalid record");
5615 I
= CleanupReturnInst::Create(CleanupPad
, UnwindDest
);
5616 InstructionList
.push_back(I
);
5619 case bitc::FUNC_CODE_INST_CATCHRET
: { // CATCHRET: [val,bb#]
5620 if (Record
.size() != 2)
5621 return error("Invalid record");
5623 Type
*TokenTy
= Type::getTokenTy(Context
);
5624 Value
*CatchPad
= getValue(Record
, Idx
++, NextValueNo
, TokenTy
,
5625 getVirtualTypeID(TokenTy
), CurBB
);
5627 return error("Invalid record");
5628 BasicBlock
*BB
= getBasicBlock(Record
[Idx
++]);
5630 return error("Invalid record");
5632 I
= CatchReturnInst::Create(CatchPad
, BB
);
5633 InstructionList
.push_back(I
);
5636 case bitc::FUNC_CODE_INST_CATCHSWITCH
: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5637 // We must have, at minimum, the outer scope and the number of arguments.
5638 if (Record
.size() < 2)
5639 return error("Invalid record");
5643 Type
*TokenTy
= Type::getTokenTy(Context
);
5644 Value
*ParentPad
= getValue(Record
, Idx
++, NextValueNo
, TokenTy
,
5645 getVirtualTypeID(TokenTy
), CurBB
);
5647 return error("Invalid record");
5649 unsigned NumHandlers
= Record
[Idx
++];
5651 SmallVector
<BasicBlock
*, 2> Handlers
;
5652 for (unsigned Op
= 0; Op
!= NumHandlers
; ++Op
) {
5653 BasicBlock
*BB
= getBasicBlock(Record
[Idx
++]);
5655 return error("Invalid record");
5656 Handlers
.push_back(BB
);
5659 BasicBlock
*UnwindDest
= nullptr;
5660 if (Idx
+ 1 == Record
.size()) {
5661 UnwindDest
= getBasicBlock(Record
[Idx
++]);
5663 return error("Invalid record");
5666 if (Record
.size() != Idx
)
5667 return error("Invalid record");
5670 CatchSwitchInst::Create(ParentPad
, UnwindDest
, NumHandlers
);
5671 for (BasicBlock
*Handler
: Handlers
)
5672 CatchSwitch
->addHandler(Handler
);
5674 ResTypeID
= getVirtualTypeID(I
->getType());
5675 InstructionList
.push_back(I
);
5678 case bitc::FUNC_CODE_INST_CATCHPAD
:
5679 case bitc::FUNC_CODE_INST_CLEANUPPAD
: { // [tok,num,(ty,val)*]
5680 // We must have, at minimum, the outer scope and the number of arguments.
5681 if (Record
.size() < 2)
5682 return error("Invalid record");
5686 Type
*TokenTy
= Type::getTokenTy(Context
);
5687 Value
*ParentPad
= getValue(Record
, Idx
++, NextValueNo
, TokenTy
,
5688 getVirtualTypeID(TokenTy
), CurBB
);
5690 return error("Invald record");
5692 unsigned NumArgOperands
= Record
[Idx
++];
5694 SmallVector
<Value
*, 2> Args
;
5695 for (unsigned Op
= 0; Op
!= NumArgOperands
; ++Op
) {
5698 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
, ValTypeID
, nullptr))
5699 return error("Invalid record");
5700 Args
.push_back(Val
);
5703 if (Record
.size() != Idx
)
5704 return error("Invalid record");
5706 if (BitCode
== bitc::FUNC_CODE_INST_CLEANUPPAD
)
5707 I
= CleanupPadInst::Create(ParentPad
, Args
);
5709 I
= CatchPadInst::Create(ParentPad
, Args
);
5710 ResTypeID
= getVirtualTypeID(I
->getType());
5711 InstructionList
.push_back(I
);
5714 case bitc::FUNC_CODE_INST_SWITCH
: { // SWITCH: [opty, op0, op1, ...]
5716 if ((Record
[0] >> 16) == SWITCH_INST_MAGIC
) {
5717 // "New" SwitchInst format with case ranges. The changes to write this
5718 // format were reverted but we still recognize bitcode that uses it.
5719 // Hopefully someday we will have support for case ranges and can use
5720 // this format again.
5722 unsigned OpTyID
= Record
[1];
5723 Type
*OpTy
= getTypeByID(OpTyID
);
5724 unsigned ValueBitWidth
= cast
<IntegerType
>(OpTy
)->getBitWidth();
5726 Value
*Cond
= getValue(Record
, 2, NextValueNo
, OpTy
, OpTyID
, CurBB
);
5727 BasicBlock
*Default
= getBasicBlock(Record
[3]);
5728 if (!OpTy
|| !Cond
|| !Default
)
5729 return error("Invalid record");
5731 unsigned NumCases
= Record
[4];
5733 SwitchInst
*SI
= SwitchInst::Create(Cond
, Default
, NumCases
);
5734 InstructionList
.push_back(SI
);
5736 unsigned CurIdx
= 5;
5737 for (unsigned i
= 0; i
!= NumCases
; ++i
) {
5738 SmallVector
<ConstantInt
*, 1> CaseVals
;
5739 unsigned NumItems
= Record
[CurIdx
++];
5740 for (unsigned ci
= 0; ci
!= NumItems
; ++ci
) {
5741 bool isSingleNumber
= Record
[CurIdx
++];
5744 unsigned ActiveWords
= 1;
5745 if (ValueBitWidth
> 64)
5746 ActiveWords
= Record
[CurIdx
++];
5747 Low
= readWideAPInt(ArrayRef(&Record
[CurIdx
], ActiveWords
),
5749 CurIdx
+= ActiveWords
;
5751 if (!isSingleNumber
) {
5753 if (ValueBitWidth
> 64)
5754 ActiveWords
= Record
[CurIdx
++];
5755 APInt High
= readWideAPInt(ArrayRef(&Record
[CurIdx
], ActiveWords
),
5757 CurIdx
+= ActiveWords
;
5759 // FIXME: It is not clear whether values in the range should be
5760 // compared as signed or unsigned values. The partially
5761 // implemented changes that used this format in the past used
5762 // unsigned comparisons.
5763 for ( ; Low
.ule(High
); ++Low
)
5764 CaseVals
.push_back(ConstantInt::get(Context
, Low
));
5766 CaseVals
.push_back(ConstantInt::get(Context
, Low
));
5768 BasicBlock
*DestBB
= getBasicBlock(Record
[CurIdx
++]);
5769 for (ConstantInt
*Cst
: CaseVals
)
5770 SI
->addCase(Cst
, DestBB
);
5776 // Old SwitchInst format without case ranges.
5778 if (Record
.size() < 3 || (Record
.size() & 1) == 0)
5779 return error("Invalid record");
5780 unsigned OpTyID
= Record
[0];
5781 Type
*OpTy
= getTypeByID(OpTyID
);
5782 Value
*Cond
= getValue(Record
, 1, NextValueNo
, OpTy
, OpTyID
, CurBB
);
5783 BasicBlock
*Default
= getBasicBlock(Record
[2]);
5784 if (!OpTy
|| !Cond
|| !Default
)
5785 return error("Invalid record");
5786 unsigned NumCases
= (Record
.size()-3)/2;
5787 SwitchInst
*SI
= SwitchInst::Create(Cond
, Default
, NumCases
);
5788 InstructionList
.push_back(SI
);
5789 for (unsigned i
= 0, e
= NumCases
; i
!= e
; ++i
) {
5790 ConstantInt
*CaseVal
= dyn_cast_or_null
<ConstantInt
>(
5791 getFnValueByID(Record
[3+i
*2], OpTy
, OpTyID
, nullptr));
5792 BasicBlock
*DestBB
= getBasicBlock(Record
[1+3+i
*2]);
5793 if (!CaseVal
|| !DestBB
) {
5795 return error("Invalid record");
5797 SI
->addCase(CaseVal
, DestBB
);
5802 case bitc::FUNC_CODE_INST_INDIRECTBR
: { // INDIRECTBR: [opty, op0, op1, ...]
5803 if (Record
.size() < 2)
5804 return error("Invalid record");
5805 unsigned OpTyID
= Record
[0];
5806 Type
*OpTy
= getTypeByID(OpTyID
);
5807 Value
*Address
= getValue(Record
, 1, NextValueNo
, OpTy
, OpTyID
, CurBB
);
5808 if (!OpTy
|| !Address
)
5809 return error("Invalid record");
5810 unsigned NumDests
= Record
.size()-2;
5811 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, NumDests
);
5812 InstructionList
.push_back(IBI
);
5813 for (unsigned i
= 0, e
= NumDests
; i
!= e
; ++i
) {
5814 if (BasicBlock
*DestBB
= getBasicBlock(Record
[2+i
])) {
5815 IBI
->addDestination(DestBB
);
5818 return error("Invalid record");
5825 case bitc::FUNC_CODE_INST_INVOKE
: {
5826 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5827 if (Record
.size() < 4)
5828 return error("Invalid record");
5830 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
5831 unsigned CCInfo
= Record
[OpNum
++];
5832 BasicBlock
*NormalBB
= getBasicBlock(Record
[OpNum
++]);
5833 BasicBlock
*UnwindBB
= getBasicBlock(Record
[OpNum
++]);
5835 unsigned FTyID
= InvalidTypeID
;
5836 FunctionType
*FTy
= nullptr;
5837 if ((CCInfo
>> 13) & 1) {
5838 FTyID
= Record
[OpNum
++];
5839 FTy
= dyn_cast
<FunctionType
>(getTypeByID(FTyID
));
5841 return error("Explicit invoke type is not a function type");
5845 unsigned CalleeTypeID
;
5846 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
, CalleeTypeID
,
5848 return error("Invalid record");
5850 PointerType
*CalleeTy
= dyn_cast
<PointerType
>(Callee
->getType());
5852 return error("Callee is not a pointer");
5854 FTyID
= getContainedTypeID(CalleeTypeID
);
5855 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
5857 return error("Callee is not of pointer to function type");
5859 if (Record
.size() < FTy
->getNumParams() + OpNum
)
5860 return error("Insufficient operands to call");
5862 SmallVector
<Value
*, 16> Ops
;
5863 SmallVector
<unsigned, 16> ArgTyIDs
;
5864 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
5865 unsigned ArgTyID
= getContainedTypeID(FTyID
, i
+ 1);
5866 Ops
.push_back(getValue(Record
, OpNum
, NextValueNo
, FTy
->getParamType(i
),
5868 ArgTyIDs
.push_back(ArgTyID
);
5870 return error("Invalid record");
5873 if (!FTy
->isVarArg()) {
5874 if (Record
.size() != OpNum
)
5875 return error("Invalid record");
5877 // Read type/value pairs for varargs params.
5878 while (OpNum
!= Record
.size()) {
5881 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
5882 return error("Invalid record");
5884 ArgTyIDs
.push_back(OpTypeID
);
5888 // Upgrade the bundles if needed.
5889 if (!OperandBundles
.empty())
5890 UpgradeOperandBundles(OperandBundles
);
5892 I
= InvokeInst::Create(FTy
, Callee
, NormalBB
, UnwindBB
, Ops
,
5894 ResTypeID
= getContainedTypeID(FTyID
);
5895 OperandBundles
.clear();
5896 InstructionList
.push_back(I
);
5897 cast
<InvokeInst
>(I
)->setCallingConv(
5898 static_cast<CallingConv::ID
>(CallingConv::MaxID
& CCInfo
));
5899 cast
<InvokeInst
>(I
)->setAttributes(PAL
);
5900 if (Error Err
= propagateAttributeTypes(cast
<CallBase
>(I
), ArgTyIDs
)) {
5907 case bitc::FUNC_CODE_INST_RESUME
: { // RESUME: [opval]
5909 Value
*Val
= nullptr;
5911 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
, ValTypeID
, CurBB
))
5912 return error("Invalid record");
5913 I
= ResumeInst::Create(Val
);
5914 InstructionList
.push_back(I
);
5917 case bitc::FUNC_CODE_INST_CALLBR
: {
5918 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5920 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
5921 unsigned CCInfo
= Record
[OpNum
++];
5923 BasicBlock
*DefaultDest
= getBasicBlock(Record
[OpNum
++]);
5924 unsigned NumIndirectDests
= Record
[OpNum
++];
5925 SmallVector
<BasicBlock
*, 16> IndirectDests
;
5926 for (unsigned i
= 0, e
= NumIndirectDests
; i
!= e
; ++i
)
5927 IndirectDests
.push_back(getBasicBlock(Record
[OpNum
++]));
5929 unsigned FTyID
= InvalidTypeID
;
5930 FunctionType
*FTy
= nullptr;
5931 if ((CCInfo
>> bitc::CALL_EXPLICIT_TYPE
) & 1) {
5932 FTyID
= Record
[OpNum
++];
5933 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
5935 return error("Explicit call type is not a function type");
5939 unsigned CalleeTypeID
;
5940 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
, CalleeTypeID
,
5942 return error("Invalid record");
5944 PointerType
*OpTy
= dyn_cast
<PointerType
>(Callee
->getType());
5946 return error("Callee is not a pointer type");
5948 FTyID
= getContainedTypeID(CalleeTypeID
);
5949 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
5951 return error("Callee is not of pointer to function type");
5953 if (Record
.size() < FTy
->getNumParams() + OpNum
)
5954 return error("Insufficient operands to call");
5956 SmallVector
<Value
*, 16> Args
;
5957 SmallVector
<unsigned, 16> ArgTyIDs
;
5958 // Read the fixed params.
5959 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
5961 unsigned ArgTyID
= getContainedTypeID(FTyID
, i
+ 1);
5962 if (FTy
->getParamType(i
)->isLabelTy())
5963 Arg
= getBasicBlock(Record
[OpNum
]);
5965 Arg
= getValue(Record
, OpNum
, NextValueNo
, FTy
->getParamType(i
),
5968 return error("Invalid record");
5969 Args
.push_back(Arg
);
5970 ArgTyIDs
.push_back(ArgTyID
);
5973 // Read type/value pairs for varargs params.
5974 if (!FTy
->isVarArg()) {
5975 if (OpNum
!= Record
.size())
5976 return error("Invalid record");
5978 while (OpNum
!= Record
.size()) {
5981 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
5982 return error("Invalid record");
5984 ArgTyIDs
.push_back(OpTypeID
);
5988 // Upgrade the bundles if needed.
5989 if (!OperandBundles
.empty())
5990 UpgradeOperandBundles(OperandBundles
);
5992 if (auto *IA
= dyn_cast
<InlineAsm
>(Callee
)) {
5993 InlineAsm::ConstraintInfoVector ConstraintInfo
= IA
->ParseConstraints();
5994 auto IsLabelConstraint
= [](const InlineAsm::ConstraintInfo
&CI
) {
5995 return CI
.Type
== InlineAsm::isLabel
;
5997 if (none_of(ConstraintInfo
, IsLabelConstraint
)) {
5998 // Upgrade explicit blockaddress arguments to label constraints.
5999 // Verify that the last arguments are blockaddress arguments that
6000 // match the indirect destinations. Clang always generates callbr
6001 // in this form. We could support reordering with more effort.
6002 unsigned FirstBlockArg
= Args
.size() - IndirectDests
.size();
6003 for (unsigned ArgNo
= FirstBlockArg
; ArgNo
< Args
.size(); ++ArgNo
) {
6004 unsigned LabelNo
= ArgNo
- FirstBlockArg
;
6005 auto *BA
= dyn_cast
<BlockAddress
>(Args
[ArgNo
]);
6006 if (!BA
|| BA
->getFunction() != F
||
6007 LabelNo
> IndirectDests
.size() ||
6008 BA
->getBasicBlock() != IndirectDests
[LabelNo
])
6009 return error("callbr argument does not match indirect dest");
6012 // Remove blockaddress arguments.
6013 Args
.erase(Args
.begin() + FirstBlockArg
, Args
.end());
6014 ArgTyIDs
.erase(ArgTyIDs
.begin() + FirstBlockArg
, ArgTyIDs
.end());
6016 // Recreate the function type with less arguments.
6017 SmallVector
<Type
*> ArgTys
;
6018 for (Value
*Arg
: Args
)
6019 ArgTys
.push_back(Arg
->getType());
6021 FunctionType::get(FTy
->getReturnType(), ArgTys
, FTy
->isVarArg());
6023 // Update constraint string to use label constraints.
6024 std::string Constraints
= IA
->getConstraintString();
6027 for (const auto &CI
: ConstraintInfo
) {
6029 if (ArgNo
>= FirstBlockArg
)
6030 Constraints
.insert(Pos
, "!");
6034 // Go to next constraint in string.
6035 Pos
= Constraints
.find(',', Pos
);
6036 if (Pos
== std::string::npos
)
6041 Callee
= InlineAsm::get(FTy
, IA
->getAsmString(), Constraints
,
6042 IA
->hasSideEffects(), IA
->isAlignStack(),
6043 IA
->getDialect(), IA
->canThrow());
6047 I
= CallBrInst::Create(FTy
, Callee
, DefaultDest
, IndirectDests
, Args
,
6049 ResTypeID
= getContainedTypeID(FTyID
);
6050 OperandBundles
.clear();
6051 InstructionList
.push_back(I
);
6052 cast
<CallBrInst
>(I
)->setCallingConv(
6053 static_cast<CallingConv::ID
>((0x7ff & CCInfo
) >> bitc::CALL_CCONV
));
6054 cast
<CallBrInst
>(I
)->setAttributes(PAL
);
6055 if (Error Err
= propagateAttributeTypes(cast
<CallBase
>(I
), ArgTyIDs
)) {
6061 case bitc::FUNC_CODE_INST_UNREACHABLE
: // UNREACHABLE
6062 I
= new UnreachableInst(Context
);
6063 InstructionList
.push_back(I
);
6065 case bitc::FUNC_CODE_INST_PHI
: { // PHI: [ty, val0,bb0, ...]
6067 return error("Invalid phi record");
6068 // The first record specifies the type.
6069 unsigned TyID
= Record
[0];
6070 Type
*Ty
= getTypeByID(TyID
);
6072 return error("Invalid phi record");
6074 // Phi arguments are pairs of records of [value, basic block].
6075 // There is an optional final record for fast-math-flags if this phi has a
6076 // floating-point type.
6077 size_t NumArgs
= (Record
.size() - 1) / 2;
6078 PHINode
*PN
= PHINode::Create(Ty
, NumArgs
);
6079 if ((Record
.size() - 1) % 2 == 1 && !isa
<FPMathOperator
>(PN
)) {
6081 return error("Invalid phi record");
6083 InstructionList
.push_back(PN
);
6085 SmallDenseMap
<BasicBlock
*, Value
*> Args
;
6086 for (unsigned i
= 0; i
!= NumArgs
; i
++) {
6087 BasicBlock
*BB
= getBasicBlock(Record
[i
* 2 + 2]);
6090 return error("Invalid phi BB");
6093 // Phi nodes may contain the same predecessor multiple times, in which
6094 // case the incoming value must be identical. Directly reuse the already
6095 // seen value here, to avoid expanding a constant expression multiple
6097 auto It
= Args
.find(BB
);
6098 if (It
!= Args
.end()) {
6099 PN
->addIncoming(It
->second
, BB
);
6103 // If there already is a block for this edge (from a different phi),
6105 BasicBlock
*EdgeBB
= ConstExprEdgeBBs
.lookup({BB
, CurBB
});
6107 // Otherwise, use a temporary block (that we will discard if it
6108 // turns out to be unnecessary).
6109 if (!PhiConstExprBB
)
6110 PhiConstExprBB
= BasicBlock::Create(Context
, "phi.constexpr", F
);
6111 EdgeBB
= PhiConstExprBB
;
6114 // With the new function encoding, it is possible that operands have
6115 // negative IDs (for forward references). Use a signed VBR
6116 // representation to keep the encoding small.
6119 V
= getValueSigned(Record
, i
* 2 + 1, NextValueNo
, Ty
, TyID
, EdgeBB
);
6121 V
= getValue(Record
, i
* 2 + 1, NextValueNo
, Ty
, TyID
, EdgeBB
);
6124 PhiConstExprBB
->eraseFromParent();
6125 return error("Invalid phi record");
6128 if (EdgeBB
== PhiConstExprBB
&& !EdgeBB
->empty()) {
6129 ConstExprEdgeBBs
.insert({{BB
, CurBB
}, EdgeBB
});
6130 PhiConstExprBB
= nullptr;
6132 PN
->addIncoming(V
, BB
);
6133 Args
.insert({BB
, V
});
6138 // If there are an even number of records, the final record must be FMF.
6139 if (Record
.size() % 2 == 0) {
6140 assert(isa
<FPMathOperator
>(I
) && "Unexpected phi type");
6141 FastMathFlags FMF
= getDecodedFastMathFlags(Record
[Record
.size() - 1]);
6143 I
->setFastMathFlags(FMF
);
6149 case bitc::FUNC_CODE_INST_LANDINGPAD
:
6150 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD
: {
6151 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
6153 if (BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD
) {
6154 if (Record
.size() < 3)
6155 return error("Invalid record");
6157 assert(BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD_OLD
);
6158 if (Record
.size() < 4)
6159 return error("Invalid record");
6161 ResTypeID
= Record
[Idx
++];
6162 Type
*Ty
= getTypeByID(ResTypeID
);
6164 return error("Invalid record");
6165 if (BitCode
== bitc::FUNC_CODE_INST_LANDINGPAD_OLD
) {
6166 Value
*PersFn
= nullptr;
6167 unsigned PersFnTypeID
;
6168 if (getValueTypePair(Record
, Idx
, NextValueNo
, PersFn
, PersFnTypeID
,
6170 return error("Invalid record");
6172 if (!F
->hasPersonalityFn())
6173 F
->setPersonalityFn(cast
<Constant
>(PersFn
));
6174 else if (F
->getPersonalityFn() != cast
<Constant
>(PersFn
))
6175 return error("Personality function mismatch");
6178 bool IsCleanup
= !!Record
[Idx
++];
6179 unsigned NumClauses
= Record
[Idx
++];
6180 LandingPadInst
*LP
= LandingPadInst::Create(Ty
, NumClauses
);
6181 LP
->setCleanup(IsCleanup
);
6182 for (unsigned J
= 0; J
!= NumClauses
; ++J
) {
6183 LandingPadInst::ClauseType CT
=
6184 LandingPadInst::ClauseType(Record
[Idx
++]); (void)CT
;
6188 if (getValueTypePair(Record
, Idx
, NextValueNo
, Val
, ValTypeID
,
6191 return error("Invalid record");
6194 assert((CT
!= LandingPadInst::Catch
||
6195 !isa
<ArrayType
>(Val
->getType())) &&
6196 "Catch clause has a invalid type!");
6197 assert((CT
!= LandingPadInst::Filter
||
6198 isa
<ArrayType
>(Val
->getType())) &&
6199 "Filter clause has invalid type!");
6200 LP
->addClause(cast
<Constant
>(Val
));
6204 InstructionList
.push_back(I
);
6208 case bitc::FUNC_CODE_INST_ALLOCA
: { // ALLOCA: [instty, opty, op, align]
6209 if (Record
.size() != 4 && Record
.size() != 5)
6210 return error("Invalid record");
6211 using APV
= AllocaPackedValues
;
6212 const uint64_t Rec
= Record
[3];
6213 const bool InAlloca
= Bitfield::get
<APV::UsedWithInAlloca
>(Rec
);
6214 const bool SwiftError
= Bitfield::get
<APV::SwiftError
>(Rec
);
6215 unsigned TyID
= Record
[0];
6216 Type
*Ty
= getTypeByID(TyID
);
6217 if (!Bitfield::get
<APV::ExplicitType
>(Rec
)) {
6218 TyID
= getContainedTypeID(TyID
);
6219 Ty
= getTypeByID(TyID
);
6221 return error("Missing element type for old-style alloca");
6223 unsigned OpTyID
= Record
[1];
6224 Type
*OpTy
= getTypeByID(OpTyID
);
6225 Value
*Size
= getFnValueByID(Record
[2], OpTy
, OpTyID
, CurBB
);
6228 Bitfield::get
<APV::AlignLower
>(Rec
) |
6229 (Bitfield::get
<APV::AlignUpper
>(Rec
) << APV::AlignLower::Bits
);
6230 if (Error Err
= parseAlignmentValue(AlignExp
, Align
)) {
6234 return error("Invalid record");
6236 const DataLayout
&DL
= TheModule
->getDataLayout();
6237 unsigned AS
= Record
.size() == 5 ? Record
[4] : DL
.getAllocaAddrSpace();
6239 SmallPtrSet
<Type
*, 4> Visited
;
6240 if (!Align
&& !Ty
->isSized(&Visited
))
6241 return error("alloca of unsized type");
6243 Align
= DL
.getPrefTypeAlign(Ty
);
6245 if (!Size
->getType()->isIntegerTy())
6246 return error("alloca element count must have integer type");
6248 AllocaInst
*AI
= new AllocaInst(Ty
, AS
, Size
, *Align
);
6249 AI
->setUsedWithInAlloca(InAlloca
);
6250 AI
->setSwiftError(SwiftError
);
6252 ResTypeID
= getVirtualTypeID(AI
->getType(), TyID
);
6253 InstructionList
.push_back(I
);
6256 case bitc::FUNC_CODE_INST_LOAD
: { // LOAD: [opty, op, align, vol]
6260 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
) ||
6261 (OpNum
+ 2 != Record
.size() && OpNum
+ 3 != Record
.size()))
6262 return error("Invalid record");
6264 if (!isa
<PointerType
>(Op
->getType()))
6265 return error("Load operand is not a pointer type");
6268 if (OpNum
+ 3 == Record
.size()) {
6269 ResTypeID
= Record
[OpNum
++];
6270 Ty
= getTypeByID(ResTypeID
);
6272 ResTypeID
= getContainedTypeID(OpTypeID
);
6273 Ty
= getTypeByID(ResTypeID
);
6277 return error("Missing load type");
6279 if (Error Err
= typeCheckLoadStoreInst(Ty
, Op
->getType()))
6283 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
6285 SmallPtrSet
<Type
*, 4> Visited
;
6286 if (!Align
&& !Ty
->isSized(&Visited
))
6287 return error("load of unsized type");
6289 Align
= TheModule
->getDataLayout().getABITypeAlign(Ty
);
6290 I
= new LoadInst(Ty
, Op
, "", Record
[OpNum
+ 1], *Align
);
6291 InstructionList
.push_back(I
);
6294 case bitc::FUNC_CODE_INST_LOADATOMIC
: {
6295 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
6299 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
) ||
6300 (OpNum
+ 4 != Record
.size() && OpNum
+ 5 != Record
.size()))
6301 return error("Invalid record");
6303 if (!isa
<PointerType
>(Op
->getType()))
6304 return error("Load operand is not a pointer type");
6307 if (OpNum
+ 5 == Record
.size()) {
6308 ResTypeID
= Record
[OpNum
++];
6309 Ty
= getTypeByID(ResTypeID
);
6311 ResTypeID
= getContainedTypeID(OpTypeID
);
6312 Ty
= getTypeByID(ResTypeID
);
6316 return error("Missing atomic load type");
6318 if (Error Err
= typeCheckLoadStoreInst(Ty
, Op
->getType()))
6321 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
6322 if (Ordering
== AtomicOrdering::NotAtomic
||
6323 Ordering
== AtomicOrdering::Release
||
6324 Ordering
== AtomicOrdering::AcquireRelease
)
6325 return error("Invalid record");
6326 if (Ordering
!= AtomicOrdering::NotAtomic
&& Record
[OpNum
] == 0)
6327 return error("Invalid record");
6328 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
6331 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
6334 return error("Alignment missing from atomic load");
6335 I
= new LoadInst(Ty
, Op
, "", Record
[OpNum
+ 1], *Align
, Ordering
, SSID
);
6336 InstructionList
.push_back(I
);
6339 case bitc::FUNC_CODE_INST_STORE
:
6340 case bitc::FUNC_CODE_INST_STORE_OLD
: { // STORE2:[ptrty, ptr, val, align, vol]
6343 unsigned PtrTypeID
, ValTypeID
;
6344 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
))
6345 return error("Invalid record");
6347 if (BitCode
== bitc::FUNC_CODE_INST_STORE
) {
6348 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
, ValTypeID
, CurBB
))
6349 return error("Invalid record");
6351 ValTypeID
= getContainedTypeID(PtrTypeID
);
6352 if (popValue(Record
, OpNum
, NextValueNo
, getTypeByID(ValTypeID
),
6353 ValTypeID
, Val
, CurBB
))
6354 return error("Invalid record");
6357 if (OpNum
+ 2 != Record
.size())
6358 return error("Invalid record");
6360 if (Error Err
= typeCheckLoadStoreInst(Val
->getType(), Ptr
->getType()))
6363 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
6365 SmallPtrSet
<Type
*, 4> Visited
;
6366 if (!Align
&& !Val
->getType()->isSized(&Visited
))
6367 return error("store of unsized type");
6369 Align
= TheModule
->getDataLayout().getABITypeAlign(Val
->getType());
6370 I
= new StoreInst(Val
, Ptr
, Record
[OpNum
+ 1], *Align
);
6371 InstructionList
.push_back(I
);
6374 case bitc::FUNC_CODE_INST_STOREATOMIC
:
6375 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD
: {
6376 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
6379 unsigned PtrTypeID
, ValTypeID
;
6380 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
) ||
6381 !isa
<PointerType
>(Ptr
->getType()))
6382 return error("Invalid record");
6383 if (BitCode
== bitc::FUNC_CODE_INST_STOREATOMIC
) {
6384 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
, ValTypeID
, CurBB
))
6385 return error("Invalid record");
6387 ValTypeID
= getContainedTypeID(PtrTypeID
);
6388 if (popValue(Record
, OpNum
, NextValueNo
, getTypeByID(ValTypeID
),
6389 ValTypeID
, Val
, CurBB
))
6390 return error("Invalid record");
6393 if (OpNum
+ 4 != Record
.size())
6394 return error("Invalid record");
6396 if (Error Err
= typeCheckLoadStoreInst(Val
->getType(), Ptr
->getType()))
6398 AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
6399 if (Ordering
== AtomicOrdering::NotAtomic
||
6400 Ordering
== AtomicOrdering::Acquire
||
6401 Ordering
== AtomicOrdering::AcquireRelease
)
6402 return error("Invalid record");
6403 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
6404 if (Ordering
!= AtomicOrdering::NotAtomic
&& Record
[OpNum
] == 0)
6405 return error("Invalid record");
6408 if (Error Err
= parseAlignmentValue(Record
[OpNum
], Align
))
6411 return error("Alignment missing from atomic store");
6412 I
= new StoreInst(Val
, Ptr
, Record
[OpNum
+ 1], *Align
, Ordering
, SSID
);
6413 InstructionList
.push_back(I
);
6416 case bitc::FUNC_CODE_INST_CMPXCHG_OLD
: {
6417 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6418 // failure_ordering?, weak?]
6419 const size_t NumRecords
= Record
.size();
6421 Value
*Ptr
= nullptr;
6423 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
))
6424 return error("Invalid record");
6426 if (!isa
<PointerType
>(Ptr
->getType()))
6427 return error("Cmpxchg operand is not a pointer type");
6429 Value
*Cmp
= nullptr;
6430 unsigned CmpTypeID
= getContainedTypeID(PtrTypeID
);
6431 if (popValue(Record
, OpNum
, NextValueNo
, getTypeByID(CmpTypeID
),
6432 CmpTypeID
, Cmp
, CurBB
))
6433 return error("Invalid record");
6435 Value
*New
= nullptr;
6436 if (popValue(Record
, OpNum
, NextValueNo
, Cmp
->getType(), CmpTypeID
,
6438 NumRecords
< OpNum
+ 3 || NumRecords
> OpNum
+ 5)
6439 return error("Invalid record");
6441 const AtomicOrdering SuccessOrdering
=
6442 getDecodedOrdering(Record
[OpNum
+ 1]);
6443 if (SuccessOrdering
== AtomicOrdering::NotAtomic
||
6444 SuccessOrdering
== AtomicOrdering::Unordered
)
6445 return error("Invalid record");
6447 const SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 2]);
6449 if (Error Err
= typeCheckLoadStoreInst(Cmp
->getType(), Ptr
->getType()))
6452 const AtomicOrdering FailureOrdering
=
6454 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering
)
6455 : getDecodedOrdering(Record
[OpNum
+ 3]);
6457 if (FailureOrdering
== AtomicOrdering::NotAtomic
||
6458 FailureOrdering
== AtomicOrdering::Unordered
)
6459 return error("Invalid record");
6461 const Align
Alignment(
6462 TheModule
->getDataLayout().getTypeStoreSize(Cmp
->getType()));
6464 I
= new AtomicCmpXchgInst(Ptr
, Cmp
, New
, Alignment
, SuccessOrdering
,
6465 FailureOrdering
, SSID
);
6466 cast
<AtomicCmpXchgInst
>(I
)->setVolatile(Record
[OpNum
]);
6468 if (NumRecords
< 8) {
6469 // Before weak cmpxchgs existed, the instruction simply returned the
6470 // value loaded from memory, so bitcode files from that era will be
6471 // expecting the first component of a modern cmpxchg.
6472 I
->insertInto(CurBB
, CurBB
->end());
6473 I
= ExtractValueInst::Create(I
, 0);
6474 ResTypeID
= CmpTypeID
;
6476 cast
<AtomicCmpXchgInst
>(I
)->setWeak(Record
[OpNum
+ 4]);
6477 unsigned I1TypeID
= getVirtualTypeID(Type::getInt1Ty(Context
));
6478 ResTypeID
= getVirtualTypeID(I
->getType(), {CmpTypeID
, I1TypeID
});
6481 InstructionList
.push_back(I
);
6484 case bitc::FUNC_CODE_INST_CMPXCHG
: {
6485 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6486 // failure_ordering, weak, align?]
6487 const size_t NumRecords
= Record
.size();
6489 Value
*Ptr
= nullptr;
6491 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
))
6492 return error("Invalid record");
6494 if (!isa
<PointerType
>(Ptr
->getType()))
6495 return error("Cmpxchg operand is not a pointer type");
6497 Value
*Cmp
= nullptr;
6499 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Cmp
, CmpTypeID
, CurBB
))
6500 return error("Invalid record");
6502 Value
*Val
= nullptr;
6503 if (popValue(Record
, OpNum
, NextValueNo
, Cmp
->getType(), CmpTypeID
, Val
,
6505 return error("Invalid record");
6507 if (NumRecords
< OpNum
+ 3 || NumRecords
> OpNum
+ 6)
6508 return error("Invalid record");
6510 const bool IsVol
= Record
[OpNum
];
6512 const AtomicOrdering SuccessOrdering
=
6513 getDecodedOrdering(Record
[OpNum
+ 1]);
6514 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering
))
6515 return error("Invalid cmpxchg success ordering");
6517 const SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 2]);
6519 if (Error Err
= typeCheckLoadStoreInst(Cmp
->getType(), Ptr
->getType()))
6522 const AtomicOrdering FailureOrdering
=
6523 getDecodedOrdering(Record
[OpNum
+ 3]);
6524 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering
))
6525 return error("Invalid cmpxchg failure ordering");
6527 const bool IsWeak
= Record
[OpNum
+ 4];
6529 MaybeAlign Alignment
;
6531 if (NumRecords
== (OpNum
+ 6)) {
6532 if (Error Err
= parseAlignmentValue(Record
[OpNum
+ 5], Alignment
))
6537 Align(TheModule
->getDataLayout().getTypeStoreSize(Cmp
->getType()));
6539 I
= new AtomicCmpXchgInst(Ptr
, Cmp
, Val
, *Alignment
, SuccessOrdering
,
6540 FailureOrdering
, SSID
);
6541 cast
<AtomicCmpXchgInst
>(I
)->setVolatile(IsVol
);
6542 cast
<AtomicCmpXchgInst
>(I
)->setWeak(IsWeak
);
6544 unsigned I1TypeID
= getVirtualTypeID(Type::getInt1Ty(Context
));
6545 ResTypeID
= getVirtualTypeID(I
->getType(), {CmpTypeID
, I1TypeID
});
6547 InstructionList
.push_back(I
);
6550 case bitc::FUNC_CODE_INST_ATOMICRMW_OLD
:
6551 case bitc::FUNC_CODE_INST_ATOMICRMW
: {
6552 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6553 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6554 const size_t NumRecords
= Record
.size();
6557 Value
*Ptr
= nullptr;
6559 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Ptr
, PtrTypeID
, CurBB
))
6560 return error("Invalid record");
6562 if (!isa
<PointerType
>(Ptr
->getType()))
6563 return error("Invalid record");
6565 Value
*Val
= nullptr;
6566 unsigned ValTypeID
= InvalidTypeID
;
6567 if (BitCode
== bitc::FUNC_CODE_INST_ATOMICRMW_OLD
) {
6568 ValTypeID
= getContainedTypeID(PtrTypeID
);
6569 if (popValue(Record
, OpNum
, NextValueNo
,
6570 getTypeByID(ValTypeID
), ValTypeID
, Val
, CurBB
))
6571 return error("Invalid record");
6573 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Val
, ValTypeID
, CurBB
))
6574 return error("Invalid record");
6577 if (!(NumRecords
== (OpNum
+ 4) || NumRecords
== (OpNum
+ 5)))
6578 return error("Invalid record");
6580 const AtomicRMWInst::BinOp Operation
=
6581 getDecodedRMWOperation(Record
[OpNum
]);
6582 if (Operation
< AtomicRMWInst::FIRST_BINOP
||
6583 Operation
> AtomicRMWInst::LAST_BINOP
)
6584 return error("Invalid record");
6586 const bool IsVol
= Record
[OpNum
+ 1];
6588 const AtomicOrdering Ordering
= getDecodedOrdering(Record
[OpNum
+ 2]);
6589 if (Ordering
== AtomicOrdering::NotAtomic
||
6590 Ordering
== AtomicOrdering::Unordered
)
6591 return error("Invalid record");
6593 const SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[OpNum
+ 3]);
6595 MaybeAlign Alignment
;
6597 if (NumRecords
== (OpNum
+ 5)) {
6598 if (Error Err
= parseAlignmentValue(Record
[OpNum
+ 4], Alignment
))
6604 Align(TheModule
->getDataLayout().getTypeStoreSize(Val
->getType()));
6606 I
= new AtomicRMWInst(Operation
, Ptr
, Val
, *Alignment
, Ordering
, SSID
);
6607 ResTypeID
= ValTypeID
;
6608 cast
<AtomicRMWInst
>(I
)->setVolatile(IsVol
);
6610 InstructionList
.push_back(I
);
6613 case bitc::FUNC_CODE_INST_FENCE
: { // FENCE:[ordering, ssid]
6614 if (2 != Record
.size())
6615 return error("Invalid record");
6616 AtomicOrdering Ordering
= getDecodedOrdering(Record
[0]);
6617 if (Ordering
== AtomicOrdering::NotAtomic
||
6618 Ordering
== AtomicOrdering::Unordered
||
6619 Ordering
== AtomicOrdering::Monotonic
)
6620 return error("Invalid record");
6621 SyncScope::ID SSID
= getDecodedSyncScopeID(Record
[1]);
6622 I
= new FenceInst(Context
, Ordering
, SSID
);
6623 InstructionList
.push_back(I
);
6626 case bitc::FUNC_CODE_DEBUG_RECORD_LABEL
: {
6627 // DbgLabelRecords are placed after the Instructions that they are
6629 SeenDebugRecord
= true;
6630 Instruction
*Inst
= getLastInstruction();
6632 return error("Invalid dbg record: missing instruction");
6633 DILocation
*DIL
= cast
<DILocation
>(getFnMetadataByID(Record
[0]));
6634 DILabel
*Label
= cast
<DILabel
>(getFnMetadataByID(Record
[1]));
6635 Inst
->getParent()->insertDbgRecordBefore(
6636 new DbgLabelRecord(Label
, DebugLoc(DIL
)), Inst
->getIterator());
6637 continue; // This isn't an instruction.
6639 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
:
6640 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE
:
6641 case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE
:
6642 case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN
: {
6643 // DbgVariableRecords are placed after the Instructions that they are
6645 SeenDebugRecord
= true;
6646 Instruction
*Inst
= getLastInstruction();
6648 return error("Invalid dbg record: missing instruction");
6650 // First 3 fields are common to all kinds:
6651 // DILocation, DILocalVariable, DIExpression
6652 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
6653 // ..., LocationMetadata
6654 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
6656 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
6657 // ..., LocationMetadata
6658 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
6659 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
6661 // Common fields (0-2).
6662 DILocation
*DIL
= cast
<DILocation
>(getFnMetadataByID(Record
[Slot
++]));
6663 DILocalVariable
*Var
=
6664 cast
<DILocalVariable
>(getFnMetadataByID(Record
[Slot
++]));
6665 DIExpression
*Expr
=
6666 cast
<DIExpression
>(getFnMetadataByID(Record
[Slot
++]));
6668 // Union field (3: LocationMetadata | Value).
6669 Metadata
*RawLocation
= nullptr;
6670 if (BitCode
== bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
) {
6673 // We never expect to see a fwd reference value here because
6674 // use-before-defs are encoded with the standard non-abbrev record
6675 // type (they'd require encoding the type too, and they're rare). As a
6676 // result, getValueTypePair only ever increments Slot by one here (once
6677 // for the value, never twice for value and type).
6678 unsigned SlotBefore
= Slot
;
6679 if (getValueTypePair(Record
, Slot
, NextValueNo
, V
, TyID
, CurBB
))
6680 return error("Invalid dbg record: invalid value");
6682 assert((SlotBefore
== Slot
- 1) && "unexpected fwd ref");
6683 RawLocation
= ValueAsMetadata::get(V
);
6685 RawLocation
= getFnMetadataByID(Record
[Slot
++]);
6688 DbgVariableRecord
*DVR
= nullptr;
6690 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE
:
6691 case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
:
6692 DVR
= new DbgVariableRecord(RawLocation
, Var
, Expr
, DIL
,
6693 DbgVariableRecord::LocationType::Value
);
6695 case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE
:
6696 DVR
= new DbgVariableRecord(RawLocation
, Var
, Expr
, DIL
,
6697 DbgVariableRecord::LocationType::Declare
);
6699 case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN
: {
6700 DIAssignID
*ID
= cast
<DIAssignID
>(getFnMetadataByID(Record
[Slot
++]));
6701 DIExpression
*AddrExpr
=
6702 cast
<DIExpression
>(getFnMetadataByID(Record
[Slot
++]));
6703 Metadata
*Addr
= getFnMetadataByID(Record
[Slot
++]);
6704 DVR
= new DbgVariableRecord(RawLocation
, Var
, Expr
, ID
, Addr
, AddrExpr
,
6709 llvm_unreachable("Unknown DbgVariableRecord bitcode");
6711 Inst
->getParent()->insertDbgRecordBefore(DVR
, Inst
->getIterator());
6712 continue; // This isn't an instruction.
6714 case bitc::FUNC_CODE_INST_CALL
: {
6715 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6716 if (Record
.size() < 3)
6717 return error("Invalid record");
6720 AttributeList PAL
= getAttributes(Record
[OpNum
++]);
6721 unsigned CCInfo
= Record
[OpNum
++];
6724 if ((CCInfo
>> bitc::CALL_FMF
) & 1) {
6725 FMF
= getDecodedFastMathFlags(Record
[OpNum
++]);
6727 return error("Fast math flags indicator set for call with no FMF");
6730 unsigned FTyID
= InvalidTypeID
;
6731 FunctionType
*FTy
= nullptr;
6732 if ((CCInfo
>> bitc::CALL_EXPLICIT_TYPE
) & 1) {
6733 FTyID
= Record
[OpNum
++];
6734 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
6736 return error("Explicit call type is not a function type");
6740 unsigned CalleeTypeID
;
6741 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Callee
, CalleeTypeID
,
6743 return error("Invalid record");
6745 PointerType
*OpTy
= dyn_cast
<PointerType
>(Callee
->getType());
6747 return error("Callee is not a pointer type");
6749 FTyID
= getContainedTypeID(CalleeTypeID
);
6750 FTy
= dyn_cast_or_null
<FunctionType
>(getTypeByID(FTyID
));
6752 return error("Callee is not of pointer to function type");
6754 if (Record
.size() < FTy
->getNumParams() + OpNum
)
6755 return error("Insufficient operands to call");
6757 SmallVector
<Value
*, 16> Args
;
6758 SmallVector
<unsigned, 16> ArgTyIDs
;
6759 // Read the fixed params.
6760 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
, ++OpNum
) {
6761 unsigned ArgTyID
= getContainedTypeID(FTyID
, i
+ 1);
6762 if (FTy
->getParamType(i
)->isLabelTy())
6763 Args
.push_back(getBasicBlock(Record
[OpNum
]));
6765 Args
.push_back(getValue(Record
, OpNum
, NextValueNo
,
6766 FTy
->getParamType(i
), ArgTyID
, CurBB
));
6767 ArgTyIDs
.push_back(ArgTyID
);
6769 return error("Invalid record");
6772 // Read type/value pairs for varargs params.
6773 if (!FTy
->isVarArg()) {
6774 if (OpNum
!= Record
.size())
6775 return error("Invalid record");
6777 while (OpNum
!= Record
.size()) {
6780 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
6781 return error("Invalid record");
6783 ArgTyIDs
.push_back(OpTypeID
);
6787 // Upgrade the bundles if needed.
6788 if (!OperandBundles
.empty())
6789 UpgradeOperandBundles(OperandBundles
);
6791 I
= CallInst::Create(FTy
, Callee
, Args
, OperandBundles
);
6792 ResTypeID
= getContainedTypeID(FTyID
);
6793 OperandBundles
.clear();
6794 InstructionList
.push_back(I
);
6795 cast
<CallInst
>(I
)->setCallingConv(
6796 static_cast<CallingConv::ID
>((0x7ff & CCInfo
) >> bitc::CALL_CCONV
));
6797 CallInst::TailCallKind TCK
= CallInst::TCK_None
;
6798 if (CCInfo
& (1 << bitc::CALL_TAIL
))
6799 TCK
= CallInst::TCK_Tail
;
6800 if (CCInfo
& (1 << bitc::CALL_MUSTTAIL
))
6801 TCK
= CallInst::TCK_MustTail
;
6802 if (CCInfo
& (1 << bitc::CALL_NOTAIL
))
6803 TCK
= CallInst::TCK_NoTail
;
6804 cast
<CallInst
>(I
)->setTailCallKind(TCK
);
6805 cast
<CallInst
>(I
)->setAttributes(PAL
);
6806 if (isa
<DbgInfoIntrinsic
>(I
))
6807 SeenDebugIntrinsic
= true;
6808 if (Error Err
= propagateAttributeTypes(cast
<CallBase
>(I
), ArgTyIDs
)) {
6813 if (!isa
<FPMathOperator
>(I
))
6814 return error("Fast-math-flags specified for call without "
6815 "floating-point scalar or vector return type");
6816 I
->setFastMathFlags(FMF
);
6820 case bitc::FUNC_CODE_INST_VAARG
: { // VAARG: [valistty, valist, instty]
6821 if (Record
.size() < 3)
6822 return error("Invalid record");
6823 unsigned OpTyID
= Record
[0];
6824 Type
*OpTy
= getTypeByID(OpTyID
);
6825 Value
*Op
= getValue(Record
, 1, NextValueNo
, OpTy
, OpTyID
, CurBB
);
6826 ResTypeID
= Record
[2];
6827 Type
*ResTy
= getTypeByID(ResTypeID
);
6828 if (!OpTy
|| !Op
|| !ResTy
)
6829 return error("Invalid record");
6830 I
= new VAArgInst(Op
, ResTy
);
6831 InstructionList
.push_back(I
);
6835 case bitc::FUNC_CODE_OPERAND_BUNDLE
: {
6836 // A call or an invoke can be optionally prefixed with some variable
6837 // number of operand bundle blocks. These blocks are read into
6838 // OperandBundles and consumed at the next call or invoke instruction.
6840 if (Record
.empty() || Record
[0] >= BundleTags
.size())
6841 return error("Invalid record");
6843 std::vector
<Value
*> Inputs
;
6846 while (OpNum
!= Record
.size()) {
6848 if (getValueOrMetadata(Record
, OpNum
, NextValueNo
, Op
, CurBB
))
6849 return error("Invalid record");
6850 Inputs
.push_back(Op
);
6853 OperandBundles
.emplace_back(BundleTags
[Record
[0]], std::move(Inputs
));
6857 case bitc::FUNC_CODE_INST_FREEZE
: { // FREEZE: [opty,opval]
6859 Value
*Op
= nullptr;
6861 if (getValueTypePair(Record
, OpNum
, NextValueNo
, Op
, OpTypeID
, CurBB
))
6862 return error("Invalid record");
6863 if (OpNum
!= Record
.size())
6864 return error("Invalid record");
6866 I
= new FreezeInst(Op
);
6867 ResTypeID
= OpTypeID
;
6868 InstructionList
.push_back(I
);
6873 // Add instruction to end of current BB. If there is no current BB, reject
6877 return error("Invalid instruction with no BB");
6879 if (!OperandBundles
.empty()) {
6881 return error("Operand bundles found with no consumer");
6883 I
->insertInto(CurBB
, CurBB
->end());
6885 // If this was a terminator instruction, move to the next block.
6886 if (I
->isTerminator()) {
6888 CurBB
= CurBBNo
< FunctionBBs
.size() ? FunctionBBs
[CurBBNo
] : nullptr;
6891 // Non-void values get registered in the value table for future use.
6892 if (!I
->getType()->isVoidTy()) {
6893 assert(I
->getType() == getTypeByID(ResTypeID
) &&
6894 "Incorrect result type ID");
6895 if (Error Err
= ValueList
.assignValue(NextValueNo
++, I
, ResTypeID
))
6902 if (!OperandBundles
.empty())
6903 return error("Operand bundles found with no consumer");
6905 // Check the function list for unresolved values.
6906 if (Argument
*A
= dyn_cast
<Argument
>(ValueList
.back())) {
6907 if (!A
->getParent()) {
6908 // We found at least one unresolved value. Nuke them all to avoid leaks.
6909 for (unsigned i
= ModuleValueListSize
, e
= ValueList
.size(); i
!= e
; ++i
){
6910 if ((A
= dyn_cast_or_null
<Argument
>(ValueList
[i
])) && !A
->getParent()) {
6911 A
->replaceAllUsesWith(PoisonValue::get(A
->getType()));
6915 return error("Never resolved value found in function");
6919 // Unexpected unresolved metadata about to be dropped.
6920 if (MDLoader
->hasFwdRefs())
6921 return error("Invalid function metadata: outgoing forward refs");
6924 PhiConstExprBB
->eraseFromParent();
6926 for (const auto &Pair
: ConstExprEdgeBBs
) {
6927 BasicBlock
*From
= Pair
.first
.first
;
6928 BasicBlock
*To
= Pair
.first
.second
;
6929 BasicBlock
*EdgeBB
= Pair
.second
;
6930 BranchInst::Create(To
, EdgeBB
);
6931 From
->getTerminator()->replaceSuccessorWith(To
, EdgeBB
);
6932 To
->replacePhiUsesWith(From
, EdgeBB
);
6933 EdgeBB
->moveBefore(To
);
6936 // Trim the value list down to the size it was before we parsed this function.
6937 ValueList
.shrinkTo(ModuleValueListSize
);
6938 MDLoader
->shrinkTo(ModuleMDLoaderSize
);
6939 std::vector
<BasicBlock
*>().swap(FunctionBBs
);
6940 return Error::success();
6943 /// Find the function body in the bitcode stream
6944 Error
BitcodeReader::findFunctionInStream(
6946 DenseMap
<Function
*, uint64_t>::iterator DeferredFunctionInfoIterator
) {
6947 while (DeferredFunctionInfoIterator
->second
== 0) {
6948 // This is the fallback handling for the old format bitcode that
6949 // didn't contain the function index in the VST, or when we have
6950 // an anonymous function which would not have a VST entry.
6951 // Assert that we have one of those two cases.
6952 assert(VSTOffset
== 0 || !F
->hasName());
6953 // Parse the next body in the stream and set its position in the
6954 // DeferredFunctionInfo map.
6955 if (Error Err
= rememberAndSkipFunctionBodies())
6958 return Error::success();
6961 SyncScope::ID
BitcodeReader::getDecodedSyncScopeID(unsigned Val
) {
6962 if (Val
== SyncScope::SingleThread
|| Val
== SyncScope::System
)
6963 return SyncScope::ID(Val
);
6964 if (Val
>= SSIDs
.size())
6965 return SyncScope::System
; // Map unknown synchronization scopes to system.
6969 //===----------------------------------------------------------------------===//
6970 // GVMaterializer implementation
6971 //===----------------------------------------------------------------------===//
6973 Error
BitcodeReader::materialize(GlobalValue
*GV
) {
6974 Function
*F
= dyn_cast
<Function
>(GV
);
6975 // If it's not a function or is already material, ignore the request.
6976 if (!F
|| !F
->isMaterializable())
6977 return Error::success();
6979 DenseMap
<Function
*, uint64_t>::iterator DFII
= DeferredFunctionInfo
.find(F
);
6980 assert(DFII
!= DeferredFunctionInfo
.end() && "Deferred function not found!");
6981 // If its position is recorded as 0, its body is somewhere in the stream
6982 // but we haven't seen it yet.
6983 if (DFII
->second
== 0)
6984 if (Error Err
= findFunctionInStream(F
, DFII
))
6987 // Materialize metadata before parsing any function bodies.
6988 if (Error Err
= materializeMetadata())
6991 // Move the bit stream to the saved position of the deferred function body.
6992 if (Error JumpFailed
= Stream
.JumpToBit(DFII
->second
))
6995 // Regardless of the debug info format we want to end up in, we need
6996 // IsNewDbgInfoFormat=true to construct any debug records seen in the bitcode.
6997 F
->IsNewDbgInfoFormat
= true;
6999 if (Error Err
= parseFunctionBody(F
))
7001 F
->setIsMaterializable(false);
7003 // All parsed Functions should load into the debug info format dictated by the
7004 // Module, unless we're attempting to preserve the input debug info format.
7005 if (SeenDebugIntrinsic
&& SeenDebugRecord
)
7006 return error("Mixed debug intrinsics and debug records in bitcode module!");
7007 if (PreserveInputDbgFormat
== cl::boolOrDefault::BOU_TRUE
) {
7008 bool SeenAnyDebugInfo
= SeenDebugIntrinsic
|| SeenDebugRecord
;
7009 bool NewDbgInfoFormatDesired
=
7010 SeenAnyDebugInfo
? SeenDebugRecord
: F
->getParent()->IsNewDbgInfoFormat
;
7011 if (SeenAnyDebugInfo
) {
7012 UseNewDbgInfoFormat
= SeenDebugRecord
;
7013 WriteNewDbgInfoFormatToBitcode
= SeenDebugRecord
;
7014 WriteNewDbgInfoFormat
= SeenDebugRecord
;
7016 // If the module's debug info format doesn't match the observed input
7017 // format, then set its format now; we don't need to call the conversion
7018 // function because there must be no existing intrinsics to convert.
7019 // Otherwise, just set the format on this function now.
7020 if (NewDbgInfoFormatDesired
!= F
->getParent()->IsNewDbgInfoFormat
)
7021 F
->getParent()->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired
);
7023 F
->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired
);
7025 // If we aren't preserving formats, we use the Module flag to get our
7026 // desired format instead of reading flags, in case we are lazy-loading and
7027 // the format of the module has been changed since it was set by the flags.
7028 // We only need to convert debug info here if we have debug records but
7029 // desire the intrinsic format; everything else is a no-op or handled by the
7031 bool ModuleIsNewDbgInfoFormat
= F
->getParent()->IsNewDbgInfoFormat
;
7032 if (ModuleIsNewDbgInfoFormat
|| !SeenDebugRecord
)
7033 F
->setNewDbgInfoFormatFlag(ModuleIsNewDbgInfoFormat
);
7035 F
->setIsNewDbgInfoFormat(ModuleIsNewDbgInfoFormat
);
7041 // Upgrade any old intrinsic calls in the function.
7042 for (auto &I
: UpgradedIntrinsics
) {
7043 for (User
*U
: llvm::make_early_inc_range(I
.first
->materialized_users()))
7044 if (CallInst
*CI
= dyn_cast
<CallInst
>(U
))
7045 UpgradeIntrinsicCall(CI
, I
.second
);
7048 // Finish fn->subprogram upgrade for materialized functions.
7049 if (DISubprogram
*SP
= MDLoader
->lookupSubprogramForFunction(F
))
7050 F
->setSubprogram(SP
);
7052 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
7053 if (!MDLoader
->isStrippingTBAA()) {
7054 for (auto &I
: instructions(F
)) {
7055 MDNode
*TBAA
= I
.getMetadata(LLVMContext::MD_tbaa
);
7056 if (!TBAA
|| TBAAVerifyHelper
.visitTBAAMetadata(I
, TBAA
))
7058 MDLoader
->setStripTBAA(true);
7059 stripTBAA(F
->getParent());
7063 for (auto &I
: instructions(F
)) {
7064 // "Upgrade" older incorrect branch weights by dropping them.
7065 if (auto *MD
= I
.getMetadata(LLVMContext::MD_prof
)) {
7066 if (MD
->getOperand(0) != nullptr && isa
<MDString
>(MD
->getOperand(0))) {
7067 MDString
*MDS
= cast
<MDString
>(MD
->getOperand(0));
7068 StringRef ProfName
= MDS
->getString();
7069 // Check consistency of !prof branch_weights metadata.
7070 if (ProfName
!= "branch_weights")
7072 unsigned ExpectedNumOperands
= 0;
7073 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(&I
))
7074 ExpectedNumOperands
= BI
->getNumSuccessors();
7075 else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(&I
))
7076 ExpectedNumOperands
= SI
->getNumSuccessors();
7077 else if (isa
<CallInst
>(&I
))
7078 ExpectedNumOperands
= 1;
7079 else if (IndirectBrInst
*IBI
= dyn_cast
<IndirectBrInst
>(&I
))
7080 ExpectedNumOperands
= IBI
->getNumDestinations();
7081 else if (isa
<SelectInst
>(&I
))
7082 ExpectedNumOperands
= 2;
7084 continue; // ignore and continue.
7086 unsigned Offset
= getBranchWeightOffset(MD
);
7088 // If branch weight doesn't match, just strip branch weight.
7089 if (MD
->getNumOperands() != Offset
+ ExpectedNumOperands
)
7090 I
.setMetadata(LLVMContext::MD_prof
, nullptr);
7094 // Remove incompatible attributes on function calls.
7095 if (auto *CI
= dyn_cast
<CallBase
>(&I
)) {
7096 CI
->removeRetAttrs(AttributeFuncs::typeIncompatible(
7097 CI
->getFunctionType()->getReturnType(), CI
->getRetAttributes()));
7099 for (unsigned ArgNo
= 0; ArgNo
< CI
->arg_size(); ++ArgNo
)
7100 CI
->removeParamAttrs(ArgNo
, AttributeFuncs::typeIncompatible(
7101 CI
->getArgOperand(ArgNo
)->getType(),
7102 CI
->getParamAttributes(ArgNo
)));
7106 // Look for functions that rely on old function attribute behavior.
7107 UpgradeFunctionAttributes(*F
);
7109 // Bring in any functions that this function forward-referenced via
7111 return materializeForwardReferencedFunctions();
7114 Error
BitcodeReader::materializeModule() {
7115 if (Error Err
= materializeMetadata())
7118 // Promise to materialize all forward references.
7119 WillMaterializeAllForwardRefs
= true;
7121 // Iterate over the module, deserializing any functions that are still on
7123 for (Function
&F
: *TheModule
) {
7124 if (Error Err
= materialize(&F
))
7127 // At this point, if there are any function bodies, parse the rest of
7128 // the bits in the module past the last function block we have recorded
7129 // through either lazy scanning or the VST.
7130 if (LastFunctionBlockBit
|| NextUnreadBit
)
7131 if (Error Err
= parseModule(LastFunctionBlockBit
> NextUnreadBit
7132 ? LastFunctionBlockBit
7136 // Check that all block address forward references got resolved (as we
7138 if (!BasicBlockFwdRefs
.empty())
7139 return error("Never resolved function from blockaddress");
7141 // Upgrade any intrinsic calls that slipped through (should not happen!) and
7142 // delete the old functions to clean up. We can't do this unless the entire
7143 // module is materialized because there could always be another function body
7144 // with calls to the old function.
7145 for (auto &I
: UpgradedIntrinsics
) {
7146 for (auto *U
: I
.first
->users()) {
7147 if (CallInst
*CI
= dyn_cast
<CallInst
>(U
))
7148 UpgradeIntrinsicCall(CI
, I
.second
);
7150 if (!I
.first
->use_empty())
7151 I
.first
->replaceAllUsesWith(I
.second
);
7152 I
.first
->eraseFromParent();
7154 UpgradedIntrinsics
.clear();
7156 UpgradeDebugInfo(*TheModule
);
7158 UpgradeModuleFlags(*TheModule
);
7160 UpgradeNVVMAnnotations(*TheModule
);
7162 UpgradeARCRuntime(*TheModule
);
7164 return Error::success();
7167 std::vector
<StructType
*> BitcodeReader::getIdentifiedStructTypes() const {
7168 return IdentifiedStructTypes
;
7171 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7172 BitstreamCursor Cursor
, StringRef Strtab
, ModuleSummaryIndex
&TheIndex
,
7173 StringRef ModulePath
, std::function
<bool(GlobalValue::GUID
)> IsPrevailing
)
7174 : BitcodeReaderBase(std::move(Cursor
), Strtab
), TheIndex(TheIndex
),
7175 ModulePath(ModulePath
), IsPrevailing(IsPrevailing
) {}
7177 void ModuleSummaryIndexBitcodeReader::addThisModule() {
7178 TheIndex
.addModule(ModulePath
);
7181 ModuleSummaryIndex::ModuleInfo
*
7182 ModuleSummaryIndexBitcodeReader::getThisModule() {
7183 return TheIndex
.getModule(ModulePath
);
7186 template <bool AllowNullValueInfo
>
7187 std::pair
<ValueInfo
, GlobalValue::GUID
>
7188 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId
) {
7189 auto VGI
= ValueIdToValueInfoMap
[ValueId
];
7190 // We can have a null value info for memprof callsite info records in
7191 // distributed ThinLTO index files when the callee function summary is not
7192 // included in the index. The bitcode writer records 0 in that case,
7193 // and the caller of this helper will set AllowNullValueInfo to true.
7194 assert(AllowNullValueInfo
|| std::get
<0>(VGI
));
7198 void ModuleSummaryIndexBitcodeReader::setValueGUID(
7199 uint64_t ValueID
, StringRef ValueName
, GlobalValue::LinkageTypes Linkage
,
7200 StringRef SourceFileName
) {
7201 std::string GlobalId
=
7202 GlobalValue::getGlobalIdentifier(ValueName
, Linkage
, SourceFileName
);
7203 auto ValueGUID
= GlobalValue::getGUID(GlobalId
);
7204 auto OriginalNameID
= ValueGUID
;
7205 if (GlobalValue::isLocalLinkage(Linkage
))
7206 OriginalNameID
= GlobalValue::getGUID(ValueName
);
7207 if (PrintSummaryGUIDs
)
7208 dbgs() << "GUID " << ValueGUID
<< "(" << OriginalNameID
<< ") is "
7209 << ValueName
<< "\n";
7211 // UseStrtab is false for legacy summary formats and value names are
7212 // created on stack. In that case we save the name in a string saver in
7213 // the index so that the value name can be recorded.
7214 ValueIdToValueInfoMap
[ValueID
] = std::make_pair(
7215 TheIndex
.getOrInsertValueInfo(
7216 ValueGUID
, UseStrtab
? ValueName
: TheIndex
.saveString(ValueName
)),
7220 // Specialized value symbol table parser used when reading module index
7221 // blocks where we don't actually create global values. The parsed information
7222 // is saved in the bitcode reader for use when later parsing summaries.
7223 Error
ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7225 DenseMap
<unsigned, GlobalValue::LinkageTypes
> &ValueIdToLinkageMap
) {
7226 // With a strtab the VST is not required to parse the summary.
7228 return Error::success();
7230 assert(Offset
> 0 && "Expected non-zero VST offset");
7231 Expected
<uint64_t> MaybeCurrentBit
= jumpToValueSymbolTable(Offset
, Stream
);
7232 if (!MaybeCurrentBit
)
7233 return MaybeCurrentBit
.takeError();
7234 uint64_t CurrentBit
= MaybeCurrentBit
.get();
7236 if (Error Err
= Stream
.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID
))
7239 SmallVector
<uint64_t, 64> Record
;
7241 // Read all the records for this value table.
7242 SmallString
<128> ValueName
;
7245 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
7247 return MaybeEntry
.takeError();
7248 BitstreamEntry Entry
= MaybeEntry
.get();
7250 switch (Entry
.Kind
) {
7251 case BitstreamEntry::SubBlock
: // Handled for us already.
7252 case BitstreamEntry::Error
:
7253 return error("Malformed block");
7254 case BitstreamEntry::EndBlock
:
7255 // Done parsing VST, jump back to wherever we came from.
7256 if (Error JumpFailed
= Stream
.JumpToBit(CurrentBit
))
7258 return Error::success();
7259 case BitstreamEntry::Record
:
7260 // The interesting case.
7266 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
7268 return MaybeRecord
.takeError();
7269 switch (MaybeRecord
.get()) {
7270 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
7272 case bitc::VST_CODE_ENTRY
: { // VST_CODE_ENTRY: [valueid, namechar x N]
7273 if (convertToString(Record
, 1, ValueName
))
7274 return error("Invalid record");
7275 unsigned ValueID
= Record
[0];
7276 assert(!SourceFileName
.empty());
7277 auto VLI
= ValueIdToLinkageMap
.find(ValueID
);
7278 assert(VLI
!= ValueIdToLinkageMap
.end() &&
7279 "No linkage found for VST entry?");
7280 auto Linkage
= VLI
->second
;
7281 setValueGUID(ValueID
, ValueName
, Linkage
, SourceFileName
);
7285 case bitc::VST_CODE_FNENTRY
: {
7286 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
7287 if (convertToString(Record
, 2, ValueName
))
7288 return error("Invalid record");
7289 unsigned ValueID
= Record
[0];
7290 assert(!SourceFileName
.empty());
7291 auto VLI
= ValueIdToLinkageMap
.find(ValueID
);
7292 assert(VLI
!= ValueIdToLinkageMap
.end() &&
7293 "No linkage found for VST entry?");
7294 auto Linkage
= VLI
->second
;
7295 setValueGUID(ValueID
, ValueName
, Linkage
, SourceFileName
);
7299 case bitc::VST_CODE_COMBINED_ENTRY
: {
7300 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
7301 unsigned ValueID
= Record
[0];
7302 GlobalValue::GUID RefGUID
= Record
[1];
7303 // The "original name", which is the second value of the pair will be
7304 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
7305 ValueIdToValueInfoMap
[ValueID
] =
7306 std::make_pair(TheIndex
.getOrInsertValueInfo(RefGUID
), RefGUID
);
7313 // Parse just the blocks needed for building the index out of the module.
7314 // At the end of this routine the module Index is populated with a map
7315 // from global value id to GlobalValueSummary objects.
7316 Error
ModuleSummaryIndexBitcodeReader::parseModule() {
7317 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
7320 SmallVector
<uint64_t, 64> Record
;
7321 DenseMap
<unsigned, GlobalValue::LinkageTypes
> ValueIdToLinkageMap
;
7322 unsigned ValueId
= 0;
7324 // Read the index for this module.
7326 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
7328 return MaybeEntry
.takeError();
7329 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
7331 switch (Entry
.Kind
) {
7332 case BitstreamEntry::Error
:
7333 return error("Malformed block");
7334 case BitstreamEntry::EndBlock
:
7335 return Error::success();
7337 case BitstreamEntry::SubBlock
:
7339 default: // Skip unknown content.
7340 if (Error Err
= Stream
.SkipBlock())
7343 case bitc::BLOCKINFO_BLOCK_ID
:
7344 // Need to parse these to get abbrev ids (e.g. for VST)
7345 if (Error Err
= readBlockInfo())
7348 case bitc::VALUE_SYMTAB_BLOCK_ID
:
7349 // Should have been parsed earlier via VSTOffset, unless there
7350 // is no summary section.
7351 assert(((SeenValueSymbolTable
&& VSTOffset
> 0) ||
7352 !SeenGlobalValSummary
) &&
7353 "Expected early VST parse via VSTOffset record");
7354 if (Error Err
= Stream
.SkipBlock())
7357 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID
:
7358 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
:
7359 // Add the module if it is a per-module index (has a source file name).
7360 if (!SourceFileName
.empty())
7362 assert(!SeenValueSymbolTable
&&
7363 "Already read VST when parsing summary block?");
7364 // We might not have a VST if there were no values in the
7365 // summary. An empty summary block generated when we are
7366 // performing ThinLTO compiles so we don't later invoke
7367 // the regular LTO process on them.
7368 if (VSTOffset
> 0) {
7369 if (Error Err
= parseValueSymbolTable(VSTOffset
, ValueIdToLinkageMap
))
7371 SeenValueSymbolTable
= true;
7373 SeenGlobalValSummary
= true;
7374 if (Error Err
= parseEntireSummary(Entry
.ID
))
7377 case bitc::MODULE_STRTAB_BLOCK_ID
:
7378 if (Error Err
= parseModuleStringTable())
7384 case BitstreamEntry::Record
: {
7386 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
7388 return MaybeBitCode
.takeError();
7389 switch (MaybeBitCode
.get()) {
7391 break; // Default behavior, ignore unknown content.
7392 case bitc::MODULE_CODE_VERSION
: {
7393 if (Error Err
= parseVersionRecord(Record
).takeError())
7397 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
7398 case bitc::MODULE_CODE_SOURCE_FILENAME
: {
7399 SmallString
<128> ValueName
;
7400 if (convertToString(Record
, 0, ValueName
))
7401 return error("Invalid record");
7402 SourceFileName
= ValueName
.c_str();
7405 /// MODULE_CODE_HASH: [5*i32]
7406 case bitc::MODULE_CODE_HASH
: {
7407 if (Record
.size() != 5)
7408 return error("Invalid hash length " + Twine(Record
.size()).str());
7409 auto &Hash
= getThisModule()->second
;
7411 for (auto &Val
: Record
) {
7412 assert(!(Val
>> 32) && "Unexpected high bits set");
7417 /// MODULE_CODE_VSTOFFSET: [offset]
7418 case bitc::MODULE_CODE_VSTOFFSET
:
7420 return error("Invalid record");
7421 // Note that we subtract 1 here because the offset is relative to one
7422 // word before the start of the identification or module block, which
7423 // was historically always the start of the regular bitcode header.
7424 VSTOffset
= Record
[0] - 1;
7426 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
7427 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
7428 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
7429 // v2: [strtab offset, strtab size, v1]
7430 case bitc::MODULE_CODE_GLOBALVAR
:
7431 case bitc::MODULE_CODE_FUNCTION
:
7432 case bitc::MODULE_CODE_ALIAS
: {
7434 ArrayRef
<uint64_t> GVRecord
;
7435 std::tie(Name
, GVRecord
) = readNameFromStrtab(Record
);
7436 if (GVRecord
.size() <= 3)
7437 return error("Invalid record");
7438 uint64_t RawLinkage
= GVRecord
[3];
7439 GlobalValue::LinkageTypes Linkage
= getDecodedLinkage(RawLinkage
);
7441 ValueIdToLinkageMap
[ValueId
++] = Linkage
;
7445 setValueGUID(ValueId
++, Name
, Linkage
, SourceFileName
);
7455 SmallVector
<ValueInfo
, 0>
7456 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef
<uint64_t> Record
) {
7457 SmallVector
<ValueInfo
, 0> Ret
;
7458 Ret
.reserve(Record
.size());
7459 for (uint64_t RefValueId
: Record
)
7460 Ret
.push_back(std::get
<0>(getValueInfoFromValueId(RefValueId
)));
7464 SmallVector
<FunctionSummary::EdgeTy
, 0>
7465 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef
<uint64_t> Record
,
7466 bool IsOldProfileFormat
,
7467 bool HasProfile
, bool HasRelBF
) {
7468 SmallVector
<FunctionSummary::EdgeTy
, 0> Ret
;
7469 // In the case of new profile formats, there are two Record entries per
7470 // Edge. Otherwise, conservatively reserve up to Record.size.
7471 if (!IsOldProfileFormat
&& (HasProfile
|| HasRelBF
))
7472 Ret
.reserve(Record
.size() / 2);
7474 Ret
.reserve(Record
.size());
7476 for (unsigned I
= 0, E
= Record
.size(); I
!= E
; ++I
) {
7477 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
7478 bool HasTailCall
= false;
7480 ValueInfo Callee
= std::get
<0>(getValueInfoFromValueId(Record
[I
]));
7481 if (IsOldProfileFormat
) {
7482 I
+= 1; // Skip old callsitecount field
7484 I
+= 1; // Skip old profilecount field
7485 } else if (HasProfile
)
7486 std::tie(Hotness
, HasTailCall
) =
7487 getDecodedHotnessCallEdgeInfo(Record
[++I
]);
7489 getDecodedRelBFCallEdgeInfo(Record
[++I
], RelBF
, HasTailCall
);
7490 Ret
.push_back(FunctionSummary::EdgeTy
{
7491 Callee
, CalleeInfo(Hotness
, HasTailCall
, RelBF
)});
7497 parseWholeProgramDevirtResolutionByArg(ArrayRef
<uint64_t> Record
, size_t &Slot
,
7498 WholeProgramDevirtResolution
&Wpd
) {
7499 uint64_t ArgNum
= Record
[Slot
++];
7500 WholeProgramDevirtResolution::ByArg
&B
=
7501 Wpd
.ResByArg
[{Record
.begin() + Slot
, Record
.begin() + Slot
+ ArgNum
}];
7505 static_cast<WholeProgramDevirtResolution::ByArg::Kind
>(Record
[Slot
++]);
7506 B
.Info
= Record
[Slot
++];
7507 B
.Byte
= Record
[Slot
++];
7508 B
.Bit
= Record
[Slot
++];
7511 static void parseWholeProgramDevirtResolution(ArrayRef
<uint64_t> Record
,
7512 StringRef Strtab
, size_t &Slot
,
7513 TypeIdSummary
&TypeId
) {
7514 uint64_t Id
= Record
[Slot
++];
7515 WholeProgramDevirtResolution
&Wpd
= TypeId
.WPDRes
[Id
];
7517 Wpd
.TheKind
= static_cast<WholeProgramDevirtResolution::Kind
>(Record
[Slot
++]);
7518 Wpd
.SingleImplName
= {Strtab
.data() + Record
[Slot
],
7519 static_cast<size_t>(Record
[Slot
+ 1])};
7522 uint64_t ResByArgNum
= Record
[Slot
++];
7523 for (uint64_t I
= 0; I
!= ResByArgNum
; ++I
)
7524 parseWholeProgramDevirtResolutionByArg(Record
, Slot
, Wpd
);
7527 static void parseTypeIdSummaryRecord(ArrayRef
<uint64_t> Record
,
7529 ModuleSummaryIndex
&TheIndex
) {
7531 TypeIdSummary
&TypeId
= TheIndex
.getOrInsertTypeIdSummary(
7532 {Strtab
.data() + Record
[Slot
], static_cast<size_t>(Record
[Slot
+ 1])});
7535 TypeId
.TTRes
.TheKind
= static_cast<TypeTestResolution::Kind
>(Record
[Slot
++]);
7536 TypeId
.TTRes
.SizeM1BitWidth
= Record
[Slot
++];
7537 TypeId
.TTRes
.AlignLog2
= Record
[Slot
++];
7538 TypeId
.TTRes
.SizeM1
= Record
[Slot
++];
7539 TypeId
.TTRes
.BitMask
= Record
[Slot
++];
7540 TypeId
.TTRes
.InlineBits
= Record
[Slot
++];
7542 while (Slot
< Record
.size())
7543 parseWholeProgramDevirtResolution(Record
, Strtab
, Slot
, TypeId
);
7546 std::vector
<FunctionSummary::ParamAccess
>
7547 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef
<uint64_t> Record
) {
7548 auto ReadRange
= [&]() {
7549 APInt
Lower(FunctionSummary::ParamAccess::RangeWidth
,
7550 BitcodeReader::decodeSignRotatedValue(Record
.front()));
7551 Record
= Record
.drop_front();
7552 APInt
Upper(FunctionSummary::ParamAccess::RangeWidth
,
7553 BitcodeReader::decodeSignRotatedValue(Record
.front()));
7554 Record
= Record
.drop_front();
7555 ConstantRange Range
{Lower
, Upper
};
7556 assert(!Range
.isFullSet());
7557 assert(!Range
.isUpperSignWrapped());
7561 std::vector
<FunctionSummary::ParamAccess
> PendingParamAccesses
;
7562 while (!Record
.empty()) {
7563 PendingParamAccesses
.emplace_back();
7564 FunctionSummary::ParamAccess
&ParamAccess
= PendingParamAccesses
.back();
7565 ParamAccess
.ParamNo
= Record
.front();
7566 Record
= Record
.drop_front();
7567 ParamAccess
.Use
= ReadRange();
7568 ParamAccess
.Calls
.resize(Record
.front());
7569 Record
= Record
.drop_front();
7570 for (auto &Call
: ParamAccess
.Calls
) {
7571 Call
.ParamNo
= Record
.front();
7572 Record
= Record
.drop_front();
7573 Call
.Callee
= std::get
<0>(getValueInfoFromValueId(Record
.front()));
7574 Record
= Record
.drop_front();
7575 Call
.Offsets
= ReadRange();
7578 return PendingParamAccesses
;
7581 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7582 ArrayRef
<uint64_t> Record
, size_t &Slot
,
7583 TypeIdCompatibleVtableInfo
&TypeId
) {
7584 uint64_t Offset
= Record
[Slot
++];
7585 ValueInfo Callee
= std::get
<0>(getValueInfoFromValueId(Record
[Slot
++]));
7586 TypeId
.push_back({Offset
, Callee
});
7589 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7590 ArrayRef
<uint64_t> Record
) {
7592 TypeIdCompatibleVtableInfo
&TypeId
=
7593 TheIndex
.getOrInsertTypeIdCompatibleVtableSummary(
7594 {Strtab
.data() + Record
[Slot
],
7595 static_cast<size_t>(Record
[Slot
+ 1])});
7598 while (Slot
< Record
.size())
7599 parseTypeIdCompatibleVtableInfo(Record
, Slot
, TypeId
);
7602 SmallVector
<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7603 ArrayRef
<uint64_t> Record
, unsigned &I
) {
7604 SmallVector
<unsigned> StackIdList
;
7605 // For backwards compatibility with old format before radix tree was
7606 // used, simply see if we found a radix tree array record (and thus if
7607 // the RadixArray is non-empty).
7608 if (RadixArray
.empty()) {
7609 unsigned NumStackEntries
= Record
[I
++];
7610 assert(Record
.size() - I
>= NumStackEntries
);
7611 StackIdList
.reserve(NumStackEntries
);
7612 for (unsigned J
= 0; J
< NumStackEntries
; J
++) {
7613 assert(Record
[I
] < StackIds
.size());
7614 StackIdList
.push_back(
7615 TheIndex
.addOrGetStackIdIndex(StackIds
[Record
[I
++]]));
7618 unsigned RadixIndex
= Record
[I
++];
7619 // See the comments above CallStackRadixTreeBuilder in ProfileData/MemProf.h
7620 // for a detailed description of the radix tree array format. Briefly, the
7621 // first entry will be the number of frames, any negative values are the
7622 // negative of the offset of the next frame, and otherwise the frames are in
7623 // increasing linear order.
7624 assert(RadixIndex
< RadixArray
.size());
7625 unsigned NumStackIds
= RadixArray
[RadixIndex
++];
7626 StackIdList
.reserve(NumStackIds
);
7627 while (NumStackIds
--) {
7628 assert(RadixIndex
< RadixArray
.size());
7629 unsigned Elem
= RadixArray
[RadixIndex
];
7630 if (static_cast<std::make_signed_t
<unsigned>>(Elem
) < 0) {
7631 RadixIndex
= RadixIndex
- Elem
;
7632 assert(RadixIndex
< RadixArray
.size());
7633 Elem
= RadixArray
[RadixIndex
];
7634 // We shouldn't encounter a second offset in a row.
7635 assert(static_cast<std::make_signed_t
<unsigned>>(Elem
) >= 0);
7638 StackIdList
.push_back(TheIndex
.addOrGetStackIdIndex(StackIds
[Elem
]));
7644 static void setSpecialRefs(SmallVectorImpl
<ValueInfo
> &Refs
, unsigned ROCnt
,
7646 // Readonly and writeonly refs are in the end of the refs list.
7647 assert(ROCnt
+ WOCnt
<= Refs
.size());
7648 unsigned FirstWORef
= Refs
.size() - WOCnt
;
7649 unsigned RefNo
= FirstWORef
- ROCnt
;
7650 for (; RefNo
< FirstWORef
; ++RefNo
)
7651 Refs
[RefNo
].setReadOnly();
7652 for (; RefNo
< Refs
.size(); ++RefNo
)
7653 Refs
[RefNo
].setWriteOnly();
7656 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
7657 // objects in the index.
7658 Error
ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID
) {
7659 if (Error Err
= Stream
.EnterSubBlock(ID
))
7661 SmallVector
<uint64_t, 64> Record
;
7665 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
7667 return MaybeEntry
.takeError();
7668 BitstreamEntry Entry
= MaybeEntry
.get();
7670 if (Entry
.Kind
!= BitstreamEntry::Record
)
7671 return error("Invalid Summary Block: record for version expected");
7672 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
7674 return MaybeRecord
.takeError();
7675 if (MaybeRecord
.get() != bitc::FS_VERSION
)
7676 return error("Invalid Summary Block: version expected");
7678 const uint64_t Version
= Record
[0];
7679 const bool IsOldProfileFormat
= Version
== 1;
7680 if (Version
< 1 || Version
> ModuleSummaryIndex::BitcodeSummaryVersion
)
7681 return error("Invalid summary version " + Twine(Version
) +
7682 ". Version should be in the range [1-" +
7683 Twine(ModuleSummaryIndex::BitcodeSummaryVersion
) +
7687 // Keep around the last seen summary to be used when we see an optional
7688 // "OriginalName" attachement.
7689 GlobalValueSummary
*LastSeenSummary
= nullptr;
7690 GlobalValue::GUID LastSeenGUID
= 0;
7692 // We can expect to see any number of type ID information records before
7693 // each function summary records; these variables store the information
7694 // collected so far so that it can be used to create the summary object.
7695 std::vector
<GlobalValue::GUID
> PendingTypeTests
;
7696 std::vector
<FunctionSummary::VFuncId
> PendingTypeTestAssumeVCalls
,
7697 PendingTypeCheckedLoadVCalls
;
7698 std::vector
<FunctionSummary::ConstVCall
> PendingTypeTestAssumeConstVCalls
,
7699 PendingTypeCheckedLoadConstVCalls
;
7700 std::vector
<FunctionSummary::ParamAccess
> PendingParamAccesses
;
7702 std::vector
<CallsiteInfo
> PendingCallsites
;
7703 std::vector
<AllocInfo
> PendingAllocs
;
7704 std::vector
<uint64_t> PendingContextIds
;
7707 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
7709 return MaybeEntry
.takeError();
7710 BitstreamEntry Entry
= MaybeEntry
.get();
7712 switch (Entry
.Kind
) {
7713 case BitstreamEntry::SubBlock
: // Handled for us already.
7714 case BitstreamEntry::Error
:
7715 return error("Malformed block");
7716 case BitstreamEntry::EndBlock
:
7717 return Error::success();
7718 case BitstreamEntry::Record
:
7719 // The interesting case.
7723 // Read a record. The record format depends on whether this
7724 // is a per-module index or a combined index file. In the per-module
7725 // case the records contain the associated value's ID for correlation
7726 // with VST entries. In the combined index the correlation is done
7727 // via the bitcode offset of the summary records (which were saved
7728 // in the combined index VST entries). The records also contain
7729 // information used for ThinLTO renaming and importing.
7731 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
7733 return MaybeBitCode
.takeError();
7734 switch (unsigned BitCode
= MaybeBitCode
.get()) {
7735 default: // Default behavior: ignore.
7737 case bitc::FS_FLAGS
: { // [flags]
7738 TheIndex
.setFlags(Record
[0]);
7741 case bitc::FS_VALUE_GUID
: { // [valueid, refguid_upper32, refguid_lower32]
7742 uint64_t ValueID
= Record
[0];
7743 GlobalValue::GUID RefGUID
;
7744 if (Version
>= 11) {
7745 RefGUID
= Record
[1] << 32 | Record
[2];
7747 RefGUID
= Record
[1];
7749 ValueIdToValueInfoMap
[ValueID
] =
7750 std::make_pair(TheIndex
.getOrInsertValueInfo(RefGUID
), RefGUID
);
7753 // FS_PERMODULE is legacy and does not have support for the tail call flag.
7754 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7755 // numrefs x valueid, n x (valueid)]
7756 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7757 // numrefs x valueid,
7758 // n x (valueid, hotness+tailcall flags)]
7759 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7760 // numrefs x valueid,
7761 // n x (valueid, relblockfreq+tailcall)]
7762 case bitc::FS_PERMODULE
:
7763 case bitc::FS_PERMODULE_RELBF
:
7764 case bitc::FS_PERMODULE_PROFILE
: {
7765 unsigned ValueID
= Record
[0];
7766 uint64_t RawFlags
= Record
[1];
7767 unsigned InstCount
= Record
[2];
7768 uint64_t RawFunFlags
= 0;
7769 unsigned NumRefs
= Record
[3];
7770 unsigned NumRORefs
= 0, NumWORefs
= 0;
7771 int RefListStartIndex
= 4;
7773 RawFunFlags
= Record
[3];
7774 NumRefs
= Record
[4];
7775 RefListStartIndex
= 5;
7777 NumRORefs
= Record
[5];
7778 RefListStartIndex
= 6;
7780 NumWORefs
= Record
[6];
7781 RefListStartIndex
= 7;
7786 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7787 // The module path string ref set in the summary must be owned by the
7788 // index's module string table. Since we don't have a module path
7789 // string table section in the per-module index, we create a single
7790 // module path string table entry with an empty (0) ID to take
7792 int CallGraphEdgeStartIndex
= RefListStartIndex
+ NumRefs
;
7793 assert(Record
.size() >= RefListStartIndex
+ NumRefs
&&
7794 "Record size inconsistent with number of references");
7795 SmallVector
<ValueInfo
, 0> Refs
= makeRefList(
7796 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
7797 bool HasProfile
= (BitCode
== bitc::FS_PERMODULE_PROFILE
);
7798 bool HasRelBF
= (BitCode
== bitc::FS_PERMODULE_RELBF
);
7799 SmallVector
<FunctionSummary::EdgeTy
, 0> Calls
= makeCallList(
7800 ArrayRef
<uint64_t>(Record
).slice(CallGraphEdgeStartIndex
),
7801 IsOldProfileFormat
, HasProfile
, HasRelBF
);
7802 setSpecialRefs(Refs
, NumRORefs
, NumWORefs
);
7803 auto VIAndOriginalGUID
= getValueInfoFromValueId(ValueID
);
7804 // In order to save memory, only record the memprof summaries if this is
7805 // the prevailing copy of a symbol. The linker doesn't resolve local
7806 // linkage values so don't check whether those are prevailing.
7807 auto LT
= (GlobalValue::LinkageTypes
)Flags
.Linkage
;
7808 if (IsPrevailing
&& !GlobalValue::isLocalLinkage(LT
) &&
7809 !IsPrevailing(VIAndOriginalGUID
.first
.getGUID())) {
7810 PendingCallsites
.clear();
7811 PendingAllocs
.clear();
7813 auto FS
= std::make_unique
<FunctionSummary
>(
7814 Flags
, InstCount
, getDecodedFFlags(RawFunFlags
), std::move(Refs
),
7815 std::move(Calls
), std::move(PendingTypeTests
),
7816 std::move(PendingTypeTestAssumeVCalls
),
7817 std::move(PendingTypeCheckedLoadVCalls
),
7818 std::move(PendingTypeTestAssumeConstVCalls
),
7819 std::move(PendingTypeCheckedLoadConstVCalls
),
7820 std::move(PendingParamAccesses
), std::move(PendingCallsites
),
7821 std::move(PendingAllocs
));
7822 FS
->setModulePath(getThisModule()->first());
7823 FS
->setOriginalName(std::get
<1>(VIAndOriginalGUID
));
7824 TheIndex
.addGlobalValueSummary(std::get
<0>(VIAndOriginalGUID
),
7828 // FS_ALIAS: [valueid, flags, valueid]
7829 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7830 // they expect all aliasee summaries to be available.
7831 case bitc::FS_ALIAS
: {
7832 unsigned ValueID
= Record
[0];
7833 uint64_t RawFlags
= Record
[1];
7834 unsigned AliaseeID
= Record
[2];
7835 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7836 auto AS
= std::make_unique
<AliasSummary
>(Flags
);
7837 // The module path string ref set in the summary must be owned by the
7838 // index's module string table. Since we don't have a module path
7839 // string table section in the per-module index, we create a single
7840 // module path string table entry with an empty (0) ID to take
7842 AS
->setModulePath(getThisModule()->first());
7844 auto AliaseeVI
= std::get
<0>(getValueInfoFromValueId(AliaseeID
));
7845 auto AliaseeInModule
= TheIndex
.findSummaryInModule(AliaseeVI
, ModulePath
);
7846 if (!AliaseeInModule
)
7847 return error("Alias expects aliasee summary to be parsed");
7848 AS
->setAliasee(AliaseeVI
, AliaseeInModule
);
7850 auto GUID
= getValueInfoFromValueId(ValueID
);
7851 AS
->setOriginalName(std::get
<1>(GUID
));
7852 TheIndex
.addGlobalValueSummary(std::get
<0>(GUID
), std::move(AS
));
7855 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7856 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS
: {
7857 unsigned ValueID
= Record
[0];
7858 uint64_t RawFlags
= Record
[1];
7859 unsigned RefArrayStart
= 2;
7860 GlobalVarSummary::GVarFlags
GVF(/* ReadOnly */ false,
7861 /* WriteOnly */ false,
7862 /* Constant */ false,
7863 GlobalObject::VCallVisibilityPublic
);
7864 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7866 GVF
= getDecodedGVarFlags(Record
[2]);
7869 SmallVector
<ValueInfo
, 0> Refs
=
7870 makeRefList(ArrayRef
<uint64_t>(Record
).slice(RefArrayStart
));
7872 std::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
7873 FS
->setModulePath(getThisModule()->first());
7874 auto GUID
= getValueInfoFromValueId(ValueID
);
7875 FS
->setOriginalName(std::get
<1>(GUID
));
7876 TheIndex
.addGlobalValueSummary(std::get
<0>(GUID
), std::move(FS
));
7879 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7880 // numrefs, numrefs x valueid,
7881 // n x (valueid, offset)]
7882 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
: {
7883 unsigned ValueID
= Record
[0];
7884 uint64_t RawFlags
= Record
[1];
7885 GlobalVarSummary::GVarFlags GVF
= getDecodedGVarFlags(Record
[2]);
7886 unsigned NumRefs
= Record
[3];
7887 unsigned RefListStartIndex
= 4;
7888 unsigned VTableListStartIndex
= RefListStartIndex
+ NumRefs
;
7889 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7890 SmallVector
<ValueInfo
, 0> Refs
= makeRefList(
7891 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
7892 VTableFuncList VTableFuncs
;
7893 for (unsigned I
= VTableListStartIndex
, E
= Record
.size(); I
!= E
; ++I
) {
7894 ValueInfo Callee
= std::get
<0>(getValueInfoFromValueId(Record
[I
]));
7895 uint64_t Offset
= Record
[++I
];
7896 VTableFuncs
.push_back({Callee
, Offset
});
7899 std::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
7900 VS
->setModulePath(getThisModule()->first());
7901 VS
->setVTableFuncs(VTableFuncs
);
7902 auto GUID
= getValueInfoFromValueId(ValueID
);
7903 VS
->setOriginalName(std::get
<1>(GUID
));
7904 TheIndex
.addGlobalValueSummary(std::get
<0>(GUID
), std::move(VS
));
7907 // FS_COMBINED is legacy and does not have support for the tail call flag.
7908 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
7909 // numrefs x valueid, n x (valueid)]
7910 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7911 // numrefs x valueid,
7912 // n x (valueid, hotness+tailcall flags)]
7913 case bitc::FS_COMBINED
:
7914 case bitc::FS_COMBINED_PROFILE
: {
7915 unsigned ValueID
= Record
[0];
7916 uint64_t ModuleId
= Record
[1];
7917 uint64_t RawFlags
= Record
[2];
7918 unsigned InstCount
= Record
[3];
7919 uint64_t RawFunFlags
= 0;
7920 unsigned NumRefs
= Record
[4];
7921 unsigned NumRORefs
= 0, NumWORefs
= 0;
7922 int RefListStartIndex
= 5;
7925 RawFunFlags
= Record
[4];
7926 RefListStartIndex
= 6;
7927 size_t NumRefsIndex
= 5;
7929 unsigned NumRORefsOffset
= 1;
7930 RefListStartIndex
= 7;
7933 RefListStartIndex
= 8;
7935 RefListStartIndex
= 9;
7936 NumWORefs
= Record
[8];
7937 NumRORefsOffset
= 2;
7940 NumRORefs
= Record
[RefListStartIndex
- NumRORefsOffset
];
7942 NumRefs
= Record
[NumRefsIndex
];
7945 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7946 int CallGraphEdgeStartIndex
= RefListStartIndex
+ NumRefs
;
7947 assert(Record
.size() >= RefListStartIndex
+ NumRefs
&&
7948 "Record size inconsistent with number of references");
7949 SmallVector
<ValueInfo
, 0> Refs
= makeRefList(
7950 ArrayRef
<uint64_t>(Record
).slice(RefListStartIndex
, NumRefs
));
7951 bool HasProfile
= (BitCode
== bitc::FS_COMBINED_PROFILE
);
7952 SmallVector
<FunctionSummary::EdgeTy
, 0> Edges
= makeCallList(
7953 ArrayRef
<uint64_t>(Record
).slice(CallGraphEdgeStartIndex
),
7954 IsOldProfileFormat
, HasProfile
, false);
7955 ValueInfo VI
= std::get
<0>(getValueInfoFromValueId(ValueID
));
7956 setSpecialRefs(Refs
, NumRORefs
, NumWORefs
);
7957 auto FS
= std::make_unique
<FunctionSummary
>(
7958 Flags
, InstCount
, getDecodedFFlags(RawFunFlags
), std::move(Refs
),
7959 std::move(Edges
), std::move(PendingTypeTests
),
7960 std::move(PendingTypeTestAssumeVCalls
),
7961 std::move(PendingTypeCheckedLoadVCalls
),
7962 std::move(PendingTypeTestAssumeConstVCalls
),
7963 std::move(PendingTypeCheckedLoadConstVCalls
),
7964 std::move(PendingParamAccesses
), std::move(PendingCallsites
),
7965 std::move(PendingAllocs
));
7966 LastSeenSummary
= FS
.get();
7967 LastSeenGUID
= VI
.getGUID();
7968 FS
->setModulePath(ModuleIdMap
[ModuleId
]);
7969 TheIndex
.addGlobalValueSummary(VI
, std::move(FS
));
7972 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
7973 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
7974 // they expect all aliasee summaries to be available.
7975 case bitc::FS_COMBINED_ALIAS
: {
7976 unsigned ValueID
= Record
[0];
7977 uint64_t ModuleId
= Record
[1];
7978 uint64_t RawFlags
= Record
[2];
7979 unsigned AliaseeValueId
= Record
[3];
7980 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
7981 auto AS
= std::make_unique
<AliasSummary
>(Flags
);
7982 LastSeenSummary
= AS
.get();
7983 AS
->setModulePath(ModuleIdMap
[ModuleId
]);
7985 auto AliaseeVI
= std::get
<0>(getValueInfoFromValueId(AliaseeValueId
));
7986 auto AliaseeInModule
= TheIndex
.findSummaryInModule(AliaseeVI
, AS
->modulePath());
7987 AS
->setAliasee(AliaseeVI
, AliaseeInModule
);
7989 ValueInfo VI
= std::get
<0>(getValueInfoFromValueId(ValueID
));
7990 LastSeenGUID
= VI
.getGUID();
7991 TheIndex
.addGlobalValueSummary(VI
, std::move(AS
));
7994 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
7995 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS
: {
7996 unsigned ValueID
= Record
[0];
7997 uint64_t ModuleId
= Record
[1];
7998 uint64_t RawFlags
= Record
[2];
7999 unsigned RefArrayStart
= 3;
8000 GlobalVarSummary::GVarFlags
GVF(/* ReadOnly */ false,
8001 /* WriteOnly */ false,
8002 /* Constant */ false,
8003 GlobalObject::VCallVisibilityPublic
);
8004 auto Flags
= getDecodedGVSummaryFlags(RawFlags
, Version
);
8006 GVF
= getDecodedGVarFlags(Record
[3]);
8009 SmallVector
<ValueInfo
, 0> Refs
=
8010 makeRefList(ArrayRef
<uint64_t>(Record
).slice(RefArrayStart
));
8012 std::make_unique
<GlobalVarSummary
>(Flags
, GVF
, std::move(Refs
));
8013 LastSeenSummary
= FS
.get();
8014 FS
->setModulePath(ModuleIdMap
[ModuleId
]);
8015 ValueInfo VI
= std::get
<0>(getValueInfoFromValueId(ValueID
));
8016 LastSeenGUID
= VI
.getGUID();
8017 TheIndex
.addGlobalValueSummary(VI
, std::move(FS
));
8020 // FS_COMBINED_ORIGINAL_NAME: [original_name]
8021 case bitc::FS_COMBINED_ORIGINAL_NAME
: {
8022 uint64_t OriginalName
= Record
[0];
8023 if (!LastSeenSummary
)
8024 return error("Name attachment that does not follow a combined record");
8025 LastSeenSummary
->setOriginalName(OriginalName
);
8026 TheIndex
.addOriginalName(LastSeenGUID
, OriginalName
);
8027 // Reset the LastSeenSummary
8028 LastSeenSummary
= nullptr;
8032 case bitc::FS_TYPE_TESTS
:
8033 assert(PendingTypeTests
.empty());
8034 llvm::append_range(PendingTypeTests
, Record
);
8037 case bitc::FS_TYPE_TEST_ASSUME_VCALLS
:
8038 assert(PendingTypeTestAssumeVCalls
.empty());
8039 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
8040 PendingTypeTestAssumeVCalls
.push_back({Record
[I
], Record
[I
+1]});
8043 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS
:
8044 assert(PendingTypeCheckedLoadVCalls
.empty());
8045 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
8046 PendingTypeCheckedLoadVCalls
.push_back({Record
[I
], Record
[I
+1]});
8049 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL
:
8050 PendingTypeTestAssumeConstVCalls
.push_back(
8051 {{Record
[0], Record
[1]}, {Record
.begin() + 2, Record
.end()}});
8054 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL
:
8055 PendingTypeCheckedLoadConstVCalls
.push_back(
8056 {{Record
[0], Record
[1]}, {Record
.begin() + 2, Record
.end()}});
8059 case bitc::FS_CFI_FUNCTION_DEFS
: {
8060 std::set
<std::string
, std::less
<>> &CfiFunctionDefs
=
8061 TheIndex
.cfiFunctionDefs();
8062 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
8063 CfiFunctionDefs
.insert(
8064 {Strtab
.data() + Record
[I
], static_cast<size_t>(Record
[I
+ 1])});
8068 case bitc::FS_CFI_FUNCTION_DECLS
: {
8069 std::set
<std::string
, std::less
<>> &CfiFunctionDecls
=
8070 TheIndex
.cfiFunctionDecls();
8071 for (unsigned I
= 0; I
!= Record
.size(); I
+= 2)
8072 CfiFunctionDecls
.insert(
8073 {Strtab
.data() + Record
[I
], static_cast<size_t>(Record
[I
+ 1])});
8077 case bitc::FS_TYPE_ID
:
8078 parseTypeIdSummaryRecord(Record
, Strtab
, TheIndex
);
8081 case bitc::FS_TYPE_ID_METADATA
:
8082 parseTypeIdCompatibleVtableSummaryRecord(Record
);
8085 case bitc::FS_BLOCK_COUNT
:
8086 TheIndex
.addBlockCount(Record
[0]);
8089 case bitc::FS_PARAM_ACCESS
: {
8090 PendingParamAccesses
= parseParamAccesses(Record
);
8094 case bitc::FS_STACK_IDS
: { // [n x stackid]
8095 // Save stack ids in the reader to consult when adding stack ids from the
8096 // lists in the stack node and alloc node entries.
8097 if (Version
<= 11) {
8098 StackIds
= ArrayRef
<uint64_t>(Record
);
8101 // This is an array of 32-bit fixed-width values, holding each 64-bit
8102 // context id as a pair of adjacent (most significant first) 32-bit words.
8103 assert(Record
.size() % 2 == 0);
8104 StackIds
.reserve(Record
.size() / 2);
8105 for (auto R
= Record
.begin(); R
!= Record
.end(); R
+= 2)
8106 StackIds
.push_back(*R
<< 32 | *(R
+ 1));
8110 case bitc::FS_CONTEXT_RADIX_TREE_ARRAY
: { // [n x entry]
8111 RadixArray
= ArrayRef
<uint64_t>(Record
);
8115 case bitc::FS_PERMODULE_CALLSITE_INFO
: {
8116 unsigned ValueID
= Record
[0];
8117 SmallVector
<unsigned> StackIdList
;
8118 for (auto R
= Record
.begin() + 1; R
!= Record
.end(); R
++) {
8119 assert(*R
< StackIds
.size());
8120 StackIdList
.push_back(TheIndex
.addOrGetStackIdIndex(StackIds
[*R
]));
8122 ValueInfo VI
= std::get
<0>(getValueInfoFromValueId(ValueID
));
8123 PendingCallsites
.push_back(CallsiteInfo({VI
, std::move(StackIdList
)}));
8127 case bitc::FS_COMBINED_CALLSITE_INFO
: {
8128 auto RecordIter
= Record
.begin();
8129 unsigned ValueID
= *RecordIter
++;
8130 unsigned NumStackIds
= *RecordIter
++;
8131 unsigned NumVersions
= *RecordIter
++;
8132 assert(Record
.size() == 3 + NumStackIds
+ NumVersions
);
8133 SmallVector
<unsigned> StackIdList
;
8134 for (unsigned J
= 0; J
< NumStackIds
; J
++) {
8135 assert(*RecordIter
< StackIds
.size());
8136 StackIdList
.push_back(
8137 TheIndex
.addOrGetStackIdIndex(StackIds
[*RecordIter
++]));
8139 SmallVector
<unsigned> Versions
;
8140 for (unsigned J
= 0; J
< NumVersions
; J
++)
8141 Versions
.push_back(*RecordIter
++);
8142 ValueInfo VI
= std::get
<0>(
8143 getValueInfoFromValueId
</*AllowNullValueInfo*/ true>(ValueID
));
8144 PendingCallsites
.push_back(
8145 CallsiteInfo({VI
, std::move(Versions
), std::move(StackIdList
)}));
8149 case bitc::FS_ALLOC_CONTEXT_IDS
: {
8150 // This is an array of 32-bit fixed-width values, holding each 64-bit
8151 // context id as a pair of adjacent (most significant first) 32-bit words.
8152 assert(Record
.size() % 2 == 0);
8153 PendingContextIds
.reserve(Record
.size() / 2);
8154 for (auto R
= Record
.begin(); R
!= Record
.end(); R
+= 2)
8155 PendingContextIds
.push_back(*R
<< 32 | *(R
+ 1));
8159 case bitc::FS_PERMODULE_ALLOC_INFO
: {
8161 std::vector
<MIBInfo
> MIBs
;
8162 unsigned NumMIBs
= 0;
8164 NumMIBs
= Record
[I
++];
8165 unsigned MIBsRead
= 0;
8166 while ((Version
>= 10 && MIBsRead
++ < NumMIBs
) ||
8167 (Version
< 10 && I
< Record
.size())) {
8168 assert(Record
.size() - I
>= 2);
8169 AllocationType AllocType
= (AllocationType
)Record
[I
++];
8170 auto StackIdList
= parseAllocInfoContext(Record
, I
);
8171 MIBs
.push_back(MIBInfo(AllocType
, std::move(StackIdList
)));
8173 // We either have nothing left or at least NumMIBs context size info
8174 // indices left (for the total sizes included when reporting of hinted
8175 // bytes is enabled).
8176 assert(I
== Record
.size() || Record
.size() - I
>= NumMIBs
);
8177 std::vector
<std::vector
<ContextTotalSize
>> AllContextSizes
;
8178 if (I
< Record
.size()) {
8179 assert(!PendingContextIds
.empty() &&
8180 "Missing context ids for alloc sizes");
8181 unsigned ContextIdIndex
= 0;
8183 // The sizes are a linearized array of sizes, where for each MIB there
8184 // is 1 or more sizes (due to context trimming, each MIB in the metadata
8185 // and summarized here can correspond to more than one original context
8186 // from the profile).
8187 while (MIBsRead
++ < NumMIBs
) {
8188 // First read the number of contexts recorded for this MIB.
8189 unsigned NumContextSizeInfoEntries
= Record
[I
++];
8190 assert(Record
.size() - I
>= NumContextSizeInfoEntries
);
8191 std::vector
<ContextTotalSize
> ContextSizes
;
8192 ContextSizes
.reserve(NumContextSizeInfoEntries
);
8193 for (unsigned J
= 0; J
< NumContextSizeInfoEntries
; J
++) {
8194 assert(ContextIdIndex
< PendingContextIds
.size());
8195 // PendingContextIds read from the preceding FS_ALLOC_CONTEXT_IDS
8196 // should be in the same order as the total sizes.
8197 ContextSizes
.push_back(
8198 {PendingContextIds
[ContextIdIndex
++], Record
[I
++]});
8200 AllContextSizes
.push_back(std::move(ContextSizes
));
8202 PendingContextIds
.clear();
8204 PendingAllocs
.push_back(AllocInfo(std::move(MIBs
)));
8205 if (!AllContextSizes
.empty()) {
8206 assert(PendingAllocs
.back().MIBs
.size() == AllContextSizes
.size());
8207 PendingAllocs
.back().ContextSizeInfos
= std::move(AllContextSizes
);
8212 case bitc::FS_COMBINED_ALLOC_INFO
: {
8214 std::vector
<MIBInfo
> MIBs
;
8215 unsigned NumMIBs
= Record
[I
++];
8216 unsigned NumVersions
= Record
[I
++];
8217 unsigned MIBsRead
= 0;
8218 while (MIBsRead
++ < NumMIBs
) {
8219 assert(Record
.size() - I
>= 2);
8220 AllocationType AllocType
= (AllocationType
)Record
[I
++];
8221 auto StackIdList
= parseAllocInfoContext(Record
, I
);
8222 MIBs
.push_back(MIBInfo(AllocType
, std::move(StackIdList
)));
8224 assert(Record
.size() - I
>= NumVersions
);
8225 SmallVector
<uint8_t> Versions
;
8226 for (unsigned J
= 0; J
< NumVersions
; J
++)
8227 Versions
.push_back(Record
[I
++]);
8228 assert(I
== Record
.size());
8229 PendingAllocs
.push_back(AllocInfo(std::move(Versions
), std::move(MIBs
)));
8234 llvm_unreachable("Exit infinite loop");
8237 // Parse the module string table block into the Index.
8238 // This populates the ModulePathStringTable map in the index.
8239 Error
ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8240 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID
))
8243 SmallVector
<uint64_t, 64> Record
;
8245 SmallString
<128> ModulePath
;
8246 ModuleSummaryIndex::ModuleInfo
*LastSeenModule
= nullptr;
8249 Expected
<BitstreamEntry
> MaybeEntry
= Stream
.advanceSkippingSubblocks();
8251 return MaybeEntry
.takeError();
8252 BitstreamEntry Entry
= MaybeEntry
.get();
8254 switch (Entry
.Kind
) {
8255 case BitstreamEntry::SubBlock
: // Handled for us already.
8256 case BitstreamEntry::Error
:
8257 return error("Malformed block");
8258 case BitstreamEntry::EndBlock
:
8259 return Error::success();
8260 case BitstreamEntry::Record
:
8261 // The interesting case.
8266 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
8268 return MaybeRecord
.takeError();
8269 switch (MaybeRecord
.get()) {
8270 default: // Default behavior: ignore.
8272 case bitc::MST_CODE_ENTRY
: {
8273 // MST_ENTRY: [modid, namechar x N]
8274 uint64_t ModuleId
= Record
[0];
8276 if (convertToString(Record
, 1, ModulePath
))
8277 return error("Invalid record");
8279 LastSeenModule
= TheIndex
.addModule(ModulePath
);
8280 ModuleIdMap
[ModuleId
] = LastSeenModule
->first();
8285 /// MST_CODE_HASH: [5*i32]
8286 case bitc::MST_CODE_HASH
: {
8287 if (Record
.size() != 5)
8288 return error("Invalid hash length " + Twine(Record
.size()).str());
8289 if (!LastSeenModule
)
8290 return error("Invalid hash that does not follow a module path");
8292 for (auto &Val
: Record
) {
8293 assert(!(Val
>> 32) && "Unexpected high bits set");
8294 LastSeenModule
->second
[Pos
++] = Val
;
8296 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
8297 LastSeenModule
= nullptr;
8302 llvm_unreachable("Exit infinite loop");
8307 // FIXME: This class is only here to support the transition to llvm::Error. It
8308 // will be removed once this transition is complete. Clients should prefer to
8309 // deal with the Error value directly, rather than converting to error_code.
8310 class BitcodeErrorCategoryType
: public std::error_category
{
8311 const char *name() const noexcept override
{
8312 return "llvm.bitcode";
8315 std::string
message(int IE
) const override
{
8316 BitcodeError E
= static_cast<BitcodeError
>(IE
);
8318 case BitcodeError::CorruptedBitcode
:
8319 return "Corrupted bitcode";
8321 llvm_unreachable("Unknown error type!");
8325 } // end anonymous namespace
8327 const std::error_category
&llvm::BitcodeErrorCategory() {
8328 static BitcodeErrorCategoryType ErrorCategory
;
8329 return ErrorCategory
;
8332 static Expected
<StringRef
> readBlobInRecord(BitstreamCursor
&Stream
,
8333 unsigned Block
, unsigned RecordID
) {
8334 if (Error Err
= Stream
.EnterSubBlock(Block
))
8335 return std::move(Err
);
8339 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
8341 return MaybeEntry
.takeError();
8342 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
8344 switch (Entry
.Kind
) {
8345 case BitstreamEntry::EndBlock
:
8348 case BitstreamEntry::Error
:
8349 return error("Malformed block");
8351 case BitstreamEntry::SubBlock
:
8352 if (Error Err
= Stream
.SkipBlock())
8353 return std::move(Err
);
8356 case BitstreamEntry::Record
:
8358 SmallVector
<uint64_t, 1> Record
;
8359 Expected
<unsigned> MaybeRecord
=
8360 Stream
.readRecord(Entry
.ID
, Record
, &Blob
);
8362 return MaybeRecord
.takeError();
8363 if (MaybeRecord
.get() == RecordID
)
8370 //===----------------------------------------------------------------------===//
8371 // External interface
8372 //===----------------------------------------------------------------------===//
8374 Expected
<std::vector
<BitcodeModule
>>
8375 llvm::getBitcodeModuleList(MemoryBufferRef Buffer
) {
8376 auto FOrErr
= getBitcodeFileContents(Buffer
);
8378 return FOrErr
.takeError();
8379 return std::move(FOrErr
->Mods
);
8382 Expected
<BitcodeFileContents
>
8383 llvm::getBitcodeFileContents(MemoryBufferRef Buffer
) {
8384 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
8386 return StreamOrErr
.takeError();
8387 BitstreamCursor
&Stream
= *StreamOrErr
;
8389 BitcodeFileContents F
;
8391 uint64_t BCBegin
= Stream
.getCurrentByteNo();
8393 // We may be consuming bitcode from a client that leaves garbage at the end
8394 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
8395 // the end that there cannot possibly be another module, stop looking.
8396 if (BCBegin
+ 8 >= Stream
.getBitcodeBytes().size())
8399 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
8401 return MaybeEntry
.takeError();
8402 llvm::BitstreamEntry Entry
= MaybeEntry
.get();
8404 switch (Entry
.Kind
) {
8405 case BitstreamEntry::EndBlock
:
8406 case BitstreamEntry::Error
:
8407 return error("Malformed block");
8409 case BitstreamEntry::SubBlock
: {
8410 uint64_t IdentificationBit
= -1ull;
8411 if (Entry
.ID
== bitc::IDENTIFICATION_BLOCK_ID
) {
8412 IdentificationBit
= Stream
.GetCurrentBitNo() - BCBegin
* 8;
8413 if (Error Err
= Stream
.SkipBlock())
8414 return std::move(Err
);
8417 Expected
<llvm::BitstreamEntry
> MaybeEntry
= Stream
.advance();
8419 return MaybeEntry
.takeError();
8420 Entry
= MaybeEntry
.get();
8423 if (Entry
.Kind
!= BitstreamEntry::SubBlock
||
8424 Entry
.ID
!= bitc::MODULE_BLOCK_ID
)
8425 return error("Malformed block");
8428 if (Entry
.ID
== bitc::MODULE_BLOCK_ID
) {
8429 uint64_t ModuleBit
= Stream
.GetCurrentBitNo() - BCBegin
* 8;
8430 if (Error Err
= Stream
.SkipBlock())
8431 return std::move(Err
);
8433 F
.Mods
.push_back({Stream
.getBitcodeBytes().slice(
8434 BCBegin
, Stream
.getCurrentByteNo() - BCBegin
),
8435 Buffer
.getBufferIdentifier(), IdentificationBit
,
8440 if (Entry
.ID
== bitc::STRTAB_BLOCK_ID
) {
8441 Expected
<StringRef
> Strtab
=
8442 readBlobInRecord(Stream
, bitc::STRTAB_BLOCK_ID
, bitc::STRTAB_BLOB
);
8444 return Strtab
.takeError();
8445 // This string table is used by every preceding bitcode module that does
8446 // not have its own string table. A bitcode file may have multiple
8447 // string tables if it was created by binary concatenation, for example
8448 // with "llvm-cat -b".
8449 for (BitcodeModule
&I
: llvm::reverse(F
.Mods
)) {
8450 if (!I
.Strtab
.empty())
8454 // Similarly, the string table is used by every preceding symbol table;
8455 // normally there will be just one unless the bitcode file was created
8456 // by binary concatenation.
8457 if (!F
.Symtab
.empty() && F
.StrtabForSymtab
.empty())
8458 F
.StrtabForSymtab
= *Strtab
;
8462 if (Entry
.ID
== bitc::SYMTAB_BLOCK_ID
) {
8463 Expected
<StringRef
> SymtabOrErr
=
8464 readBlobInRecord(Stream
, bitc::SYMTAB_BLOCK_ID
, bitc::SYMTAB_BLOB
);
8466 return SymtabOrErr
.takeError();
8468 // We can expect the bitcode file to have multiple symbol tables if it
8469 // was created by binary concatenation. In that case we silently
8470 // ignore any subsequent symbol tables, which is fine because this is a
8471 // low level function. The client is expected to notice that the number
8472 // of modules in the symbol table does not match the number of modules
8473 // in the input file and regenerate the symbol table.
8474 if (F
.Symtab
.empty())
8475 F
.Symtab
= *SymtabOrErr
;
8479 if (Error Err
= Stream
.SkipBlock())
8480 return std::move(Err
);
8483 case BitstreamEntry::Record
:
8484 if (Error E
= Stream
.skipRecord(Entry
.ID
).takeError())
8485 return std::move(E
);
8491 /// Get a lazy one-at-time loading module from bitcode.
8493 /// This isn't always used in a lazy context. In particular, it's also used by
8494 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
8495 /// in forward-referenced functions from block address references.
8497 /// \param[in] MaterializeAll Set to \c true if we should materialize
8499 Expected
<std::unique_ptr
<Module
>>
8500 BitcodeModule::getModuleImpl(LLVMContext
&Context
, bool MaterializeAll
,
8501 bool ShouldLazyLoadMetadata
, bool IsImporting
,
8502 ParserCallbacks Callbacks
) {
8503 BitstreamCursor
Stream(Buffer
);
8505 std::string ProducerIdentification
;
8506 if (IdentificationBit
!= -1ull) {
8507 if (Error JumpFailed
= Stream
.JumpToBit(IdentificationBit
))
8508 return std::move(JumpFailed
);
8510 readIdentificationBlock(Stream
).moveInto(ProducerIdentification
))
8511 return std::move(E
);
8514 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
8515 return std::move(JumpFailed
);
8516 auto *R
= new BitcodeReader(std::move(Stream
), Strtab
, ProducerIdentification
,
8519 std::unique_ptr
<Module
> M
=
8520 std::make_unique
<Module
>(ModuleIdentifier
, Context
);
8521 M
->setMaterializer(R
);
8523 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8524 if (Error Err
= R
->parseBitcodeInto(M
.get(), ShouldLazyLoadMetadata
,
8525 IsImporting
, Callbacks
))
8526 return std::move(Err
);
8528 if (MaterializeAll
) {
8529 // Read in the entire module, and destroy the BitcodeReader.
8530 if (Error Err
= M
->materializeAll())
8531 return std::move(Err
);
8533 // Resolve forward references from blockaddresses.
8534 if (Error Err
= R
->materializeForwardReferencedFunctions())
8535 return std::move(Err
);
8538 return std::move(M
);
8541 Expected
<std::unique_ptr
<Module
>>
8542 BitcodeModule::getLazyModule(LLVMContext
&Context
, bool ShouldLazyLoadMetadata
,
8543 bool IsImporting
, ParserCallbacks Callbacks
) {
8544 return getModuleImpl(Context
, false, ShouldLazyLoadMetadata
, IsImporting
,
8548 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
8549 // We don't use ModuleIdentifier here because the client may need to control the
8550 // module path used in the combined summary (e.g. when reading summaries for
8551 // regular LTO modules).
8552 Error
BitcodeModule::readSummary(
8553 ModuleSummaryIndex
&CombinedIndex
, StringRef ModulePath
,
8554 std::function
<bool(GlobalValue::GUID
)> IsPrevailing
) {
8555 BitstreamCursor
Stream(Buffer
);
8556 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
8559 ModuleSummaryIndexBitcodeReader
R(std::move(Stream
), Strtab
, CombinedIndex
,
8560 ModulePath
, IsPrevailing
);
8561 return R
.parseModule();
8564 // Parse the specified bitcode buffer, returning the function info index.
8565 Expected
<std::unique_ptr
<ModuleSummaryIndex
>> BitcodeModule::getSummary() {
8566 BitstreamCursor
Stream(Buffer
);
8567 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
8568 return std::move(JumpFailed
);
8570 auto Index
= std::make_unique
<ModuleSummaryIndex
>(/*HaveGVs=*/false);
8571 ModuleSummaryIndexBitcodeReader
R(std::move(Stream
), Strtab
, *Index
,
8572 ModuleIdentifier
, 0);
8574 if (Error Err
= R
.parseModule())
8575 return std::move(Err
);
8577 return std::move(Index
);
8580 static Expected
<std::pair
<bool, bool>>
8581 getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor
&Stream
,
8583 BitcodeLTOInfo
<OInfo
) {
8584 if (Error Err
= Stream
.EnterSubBlock(ID
))
8585 return std::move(Err
);
8586 SmallVector
<uint64_t, 64> Record
;
8589 BitstreamEntry Entry
;
8590 std::pair
<bool, bool> Result
= {false,false};
8591 if (Error E
= Stream
.advanceSkippingSubblocks().moveInto(Entry
))
8592 return std::move(E
);
8594 switch (Entry
.Kind
) {
8595 case BitstreamEntry::SubBlock
: // Handled for us already.
8596 case BitstreamEntry::Error
:
8597 return error("Malformed block");
8598 case BitstreamEntry::EndBlock
: {
8599 // If no flags record found, set both flags to false.
8602 case BitstreamEntry::Record
:
8603 // The interesting case.
8607 // Look for the FS_FLAGS record.
8609 Expected
<unsigned> MaybeBitCode
= Stream
.readRecord(Entry
.ID
, Record
);
8611 return MaybeBitCode
.takeError();
8612 switch (MaybeBitCode
.get()) {
8613 default: // Default behavior: ignore.
8615 case bitc::FS_FLAGS
: { // [flags]
8616 uint64_t Flags
= Record
[0];
8618 assert(Flags
<= 0x2ff && "Unexpected bits in flag");
8620 bool EnableSplitLTOUnit
= Flags
& 0x8;
8621 bool UnifiedLTO
= Flags
& 0x200;
8622 Result
= {EnableSplitLTOUnit
, UnifiedLTO
};
8628 llvm_unreachable("Exit infinite loop");
8631 // Check if the given bitcode buffer contains a global value summary block.
8632 Expected
<BitcodeLTOInfo
> BitcodeModule::getLTOInfo() {
8633 BitstreamCursor
Stream(Buffer
);
8634 if (Error JumpFailed
= Stream
.JumpToBit(ModuleBit
))
8635 return std::move(JumpFailed
);
8637 if (Error Err
= Stream
.EnterSubBlock(bitc::MODULE_BLOCK_ID
))
8638 return std::move(Err
);
8641 llvm::BitstreamEntry Entry
;
8642 if (Error E
= Stream
.advance().moveInto(Entry
))
8643 return std::move(E
);
8645 switch (Entry
.Kind
) {
8646 case BitstreamEntry::Error
:
8647 return error("Malformed block");
8648 case BitstreamEntry::EndBlock
:
8649 return BitcodeLTOInfo
{/*IsThinLTO=*/false, /*HasSummary=*/false,
8650 /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8652 case BitstreamEntry::SubBlock
:
8653 if (Entry
.ID
== bitc::GLOBALVAL_SUMMARY_BLOCK_ID
) {
8654 BitcodeLTOInfo LTOInfo
;
8655 Expected
<std::pair
<bool, bool>> Flags
=
8656 getEnableSplitLTOUnitAndUnifiedFlag(Stream
, Entry
.ID
, LTOInfo
);
8658 return Flags
.takeError();
8659 std::tie(LTOInfo
.EnableSplitLTOUnit
, LTOInfo
.UnifiedLTO
) = Flags
.get();
8660 LTOInfo
.IsThinLTO
= true;
8661 LTOInfo
.HasSummary
= true;
8665 if (Entry
.ID
== bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
) {
8666 BitcodeLTOInfo LTOInfo
;
8667 Expected
<std::pair
<bool, bool>> Flags
=
8668 getEnableSplitLTOUnitAndUnifiedFlag(Stream
, Entry
.ID
, LTOInfo
);
8670 return Flags
.takeError();
8671 std::tie(LTOInfo
.EnableSplitLTOUnit
, LTOInfo
.UnifiedLTO
) = Flags
.get();
8672 LTOInfo
.IsThinLTO
= false;
8673 LTOInfo
.HasSummary
= true;
8677 // Ignore other sub-blocks.
8678 if (Error Err
= Stream
.SkipBlock())
8679 return std::move(Err
);
8682 case BitstreamEntry::Record
:
8683 if (Expected
<unsigned> StreamFailed
= Stream
.skipRecord(Entry
.ID
))
8686 return StreamFailed
.takeError();
8691 static Expected
<BitcodeModule
> getSingleModule(MemoryBufferRef Buffer
) {
8692 Expected
<std::vector
<BitcodeModule
>> MsOrErr
= getBitcodeModuleList(Buffer
);
8694 return MsOrErr
.takeError();
8696 if (MsOrErr
->size() != 1)
8697 return error("Expected a single module");
8699 return (*MsOrErr
)[0];
8702 Expected
<std::unique_ptr
<Module
>>
8703 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer
, LLVMContext
&Context
,
8704 bool ShouldLazyLoadMetadata
, bool IsImporting
,
8705 ParserCallbacks Callbacks
) {
8706 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8708 return BM
.takeError();
8710 return BM
->getLazyModule(Context
, ShouldLazyLoadMetadata
, IsImporting
,
8714 Expected
<std::unique_ptr
<Module
>> llvm::getOwningLazyBitcodeModule(
8715 std::unique_ptr
<MemoryBuffer
> &&Buffer
, LLVMContext
&Context
,
8716 bool ShouldLazyLoadMetadata
, bool IsImporting
, ParserCallbacks Callbacks
) {
8717 auto MOrErr
= getLazyBitcodeModule(*Buffer
, Context
, ShouldLazyLoadMetadata
,
8718 IsImporting
, Callbacks
);
8720 (*MOrErr
)->setOwnedMemoryBuffer(std::move(Buffer
));
8724 Expected
<std::unique_ptr
<Module
>>
8725 BitcodeModule::parseModule(LLVMContext
&Context
, ParserCallbacks Callbacks
) {
8726 return getModuleImpl(Context
, true, false, false, Callbacks
);
8727 // TODO: Restore the use-lists to the in-memory state when the bitcode was
8728 // written. We must defer until the Module has been fully materialized.
8731 Expected
<std::unique_ptr
<Module
>>
8732 llvm::parseBitcodeFile(MemoryBufferRef Buffer
, LLVMContext
&Context
,
8733 ParserCallbacks Callbacks
) {
8734 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8736 return BM
.takeError();
8738 return BM
->parseModule(Context
, Callbacks
);
8741 Expected
<std::string
> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer
) {
8742 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
8744 return StreamOrErr
.takeError();
8746 return readTriple(*StreamOrErr
);
8749 Expected
<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer
) {
8750 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
8752 return StreamOrErr
.takeError();
8754 return hasObjCCategory(*StreamOrErr
);
8757 Expected
<std::string
> llvm::getBitcodeProducerString(MemoryBufferRef Buffer
) {
8758 Expected
<BitstreamCursor
> StreamOrErr
= initStream(Buffer
);
8760 return StreamOrErr
.takeError();
8762 return readIdentificationCode(*StreamOrErr
);
8765 Error
llvm::readModuleSummaryIndex(MemoryBufferRef Buffer
,
8766 ModuleSummaryIndex
&CombinedIndex
) {
8767 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8769 return BM
.takeError();
8771 return BM
->readSummary(CombinedIndex
, BM
->getModuleIdentifier());
8774 Expected
<std::unique_ptr
<ModuleSummaryIndex
>>
8775 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer
) {
8776 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8778 return BM
.takeError();
8780 return BM
->getSummary();
8783 Expected
<BitcodeLTOInfo
> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer
) {
8784 Expected
<BitcodeModule
> BM
= getSingleModule(Buffer
);
8786 return BM
.takeError();
8788 return BM
->getLTOInfo();
8791 Expected
<std::unique_ptr
<ModuleSummaryIndex
>>
8792 llvm::getModuleSummaryIndexForFile(StringRef Path
,
8793 bool IgnoreEmptyThinLTOIndexFile
) {
8794 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> FileOrErr
=
8795 MemoryBuffer::getFileOrSTDIN(Path
);
8797 return errorCodeToError(FileOrErr
.getError());
8798 if (IgnoreEmptyThinLTOIndexFile
&& !(*FileOrErr
)->getBufferSize())
8800 return getModuleSummaryIndex(**FileOrErr
);