LLVM 21.0.0git
BitcodeReader.cpp
Go to the documentation of this file.
1//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
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"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
24#include "llvm/Config/llvm-config.h"
25#include "llvm/IR/Argument.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/AutoUpgrade.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/CallingConv.h"
31#include "llvm/IR/Comdat.h"
32#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/DebugInfo.h"
38#include "llvm/IR/DebugLoc.h"
40#include "llvm/IR/Function.h"
43#include "llvm/IR/GlobalAlias.h"
44#include "llvm/IR/GlobalIFunc.h"
46#include "llvm/IR/GlobalValue.h"
48#include "llvm/IR/InlineAsm.h"
50#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.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"
60#include "llvm/IR/Operator.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Value.h"
64#include "llvm/IR/Verifier.h"
69#include "llvm/Support/Debug.h"
70#include "llvm/Support/Error.h"
75#include "llvm/Support/ModRef.h"
78#include <algorithm>
79#include <cassert>
80#include <cstddef>
81#include <cstdint>
82#include <deque>
83#include <map>
84#include <memory>
85#include <optional>
86#include <set>
87#include <string>
88#include <system_error>
89#include <tuple>
90#include <utility>
91#include <vector>
92
93using namespace llvm;
94
96 "print-summary-global-ids", cl::init(false), cl::Hidden,
98 "Print the global id for each value when reading the module summary"));
99
101 "expand-constant-exprs", cl::Hidden,
102 cl::desc(
103 "Expand constant expressions to instructions for testing purposes"));
104
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.
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)"));
117
118namespace {
119
120enum {
121 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
122};
123
124} // end anonymous namespace
125
126static Error error(const Twine &Message) {
127 return make_error<StringError>(
128 Message, make_error_code(BitcodeError::CorruptedBitcode));
129}
130
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)) {
137 if (Res.get() != C)
138 return createStringError(std::errc::illegal_byte_sequence,
139 "file doesn't start with bitcode header");
140 } else
141 return Res.takeError();
142 for (unsigned C : {0x0, 0xC, 0xE, 0xD})
143 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
144 if (Res.get() != C)
145 return createStringError(std::errc::illegal_byte_sequence,
146 "file doesn't start with bitcode header");
147 } else
148 return Res.takeError();
149 return Error::success();
150}
151
153 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
154 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
155
156 if (Buffer.getBufferSize() & 3)
157 return error("Invalid bitcode signature");
158
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");
164
165 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
166 if (Error Err = hasInvalidBitcodeHeader(Stream))
167 return std::move(Err);
168
169 return std::move(Stream);
170}
171
172/// Convert a string from a record into an std::string, return true on failure.
173template <typename StrTy>
175 StrTy &Result) {
176 if (Idx > Record.size())
177 return true;
178
179 Result.append(Record.begin() + Idx, Record.end());
180 return false;
181}
182
183// Strip all the TBAA attachment for the module.
184static void stripTBAA(Module *M) {
185 for (auto &F : *M) {
186 if (F.isMaterializable())
187 continue;
188 for (auto &I : instructions(F))
189 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
190 }
191}
192
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.
197 return std::move(Err);
198
199 // Read all the records.
201
202 std::string ProducerIdentification;
203
204 while (true) {
205 BitstreamEntry Entry;
206 if (Error E = Stream.advance().moveInto(Entry))
207 return std::move(E);
208
209 switch (Entry.Kind) {
210 default:
212 return error("Malformed block");
214 return ProducerIdentification;
216 // The interesting case.
217 break;
218 }
219
220 // Read a record.
221 Record.clear();
222 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
223 if (!MaybeBitCode)
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);
230 break;
231 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
232 unsigned epoch = (unsigned)Record[0];
233 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
234 return error(
235 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
236 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
237 }
238 }
239 }
240 }
241}
242
244 // We expect a number of well-defined blocks, though we don't necessarily
245 // need to understand them all.
246 while (true) {
247 if (Stream.AtEndOfStream())
248 return "";
249
250 BitstreamEntry Entry;
251 if (Error E = Stream.advance().moveInto(Entry))
252 return std::move(E);
253
254 switch (Entry.Kind) {
257 return error("Malformed block");
258
260 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
261 return readIdentificationBlock(Stream);
262
263 // Ignore other sub-blocks.
264 if (Error Err = Stream.SkipBlock())
265 return std::move(Err);
266 continue;
268 if (Error E = Stream.skipRecord(Entry.ID).takeError())
269 return std::move(E);
270 continue;
271 }
272 }
273}
274
276 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
277 return std::move(Err);
278
280 // Read all the records for this module.
281
282 while (true) {
284 if (!MaybeEntry)
285 return MaybeEntry.takeError();
286 BitstreamEntry Entry = MaybeEntry.get();
287
288 switch (Entry.Kind) {
289 case BitstreamEntry::SubBlock: // Handled for us already.
291 return error("Malformed block");
293 return false;
295 // The interesting case.
296 break;
297 }
298
299 // Read a record.
300 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
301 if (!MaybeRecord)
302 return MaybeRecord.takeError();
303 switch (MaybeRecord.get()) {
304 default:
305 break; // Default behavior, ignore unknown content.
306 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
307 std::string S;
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)
314 return true;
315 break;
316 }
317 }
318 Record.clear();
319 }
320 llvm_unreachable("Exit infinite loop");
321}
322
324 // We expect a number of well-defined blocks, though we don't necessarily
325 // need to understand them all.
326 while (true) {
327 BitstreamEntry Entry;
328 if (Error E = Stream.advance().moveInto(Entry))
329 return std::move(E);
330
331 switch (Entry.Kind) {
333 return error("Malformed block");
335 return false;
336
338 if (Entry.ID == bitc::MODULE_BLOCK_ID)
339 return hasObjCCategoryInModule(Stream);
340
341 // Ignore other sub-blocks.
342 if (Error Err = Stream.SkipBlock())
343 return std::move(Err);
344 continue;
345
347 if (Error E = Stream.skipRecord(Entry.ID).takeError())
348 return std::move(E);
349 continue;
350 }
351 }
352}
353
355 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
356 return std::move(Err);
357
359
360 std::string Triple;
361
362 // Read all the records for this module.
363 while (true) {
365 if (!MaybeEntry)
366 return MaybeEntry.takeError();
367 BitstreamEntry Entry = MaybeEntry.get();
368
369 switch (Entry.Kind) {
370 case BitstreamEntry::SubBlock: // Handled for us already.
372 return error("Malformed block");
374 return Triple;
376 // The interesting case.
377 break;
378 }
379
380 // Read a record.
381 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
382 if (!MaybeRecord)
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]
387 std::string S;
388 if (convertToString(Record, 0, S))
389 return error("Invalid triple record");
390 Triple = S;
391 break;
392 }
393 }
394 Record.clear();
395 }
396 llvm_unreachable("Exit infinite loop");
397}
398
400 // We expect a number of well-defined blocks, though we don't necessarily
401 // need to understand them all.
402 while (true) {
403 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
404 if (!MaybeEntry)
405 return MaybeEntry.takeError();
406 BitstreamEntry Entry = MaybeEntry.get();
407
408 switch (Entry.Kind) {
410 return error("Malformed block");
412 return "";
413
415 if (Entry.ID == bitc::MODULE_BLOCK_ID)
416 return readModuleTriple(Stream);
417
418 // Ignore other sub-blocks.
419 if (Error Err = Stream.SkipBlock())
420 return std::move(Err);
421 continue;
422
424 if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
425 continue;
426 else
427 return Skipped.takeError();
428 }
429 }
430}
431
432namespace {
433
434class BitcodeReaderBase {
435protected:
436 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
437 : Stream(std::move(Stream)), Strtab(Strtab) {
438 this->Stream.setBlockInfo(&BlockInfo);
439 }
440
441 BitstreamBlockInfo BlockInfo;
442 BitstreamCursor Stream;
443 StringRef Strtab;
444
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;
448
449 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
450
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);
456
457 Error readBlockInfo();
458
459 // Contains an arbitrary and optional string identifying the bitcode producer
460 std::string ProducerIdentification;
461
462 Error error(const Twine &Message);
463};
464
465} // end anonymous namespace
466
467Error 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);
473}
474
476BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
477 if (Record.empty())
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;
484}
485
486std::pair<StringRef, ArrayRef<uint64_t>>
487BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
488 if (!UseStrtab)
489 return {"", Record};
490 // Invalid reference. Let the caller complain about the record being empty.
491 if (Record[0] + Record[1] > Strtab.size())
492 return {"", {}};
493 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
494}
495
496namespace {
497
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.
504class BitcodeConstant final : public Value,
505 TrailingObjects<BitcodeConstant, unsigned> {
506 friend TrailingObjects;
507
508 // Value subclass ID: Pick largest possible value to avoid any clashes.
509 static constexpr uint8_t SubclassID = 255;
510
511public:
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;
525
526 // Separate struct to make passing different number of parameters to
527 // BitcodeConstant::create() more convenient.
528 struct ExtraInfo {
529 uint8_t Opcode;
531 unsigned BlockAddressBB = 0;
532 Type *SrcElemTy = nullptr;
533 std::optional<ConstantRange> InRange;
534
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)) {}
539
540 ExtraInfo(uint8_t Opcode, uint8_t Flags, unsigned BlockAddressBB)
541 : Opcode(Opcode), Flags(Flags), BlockAddressBB(BlockAddressBB) {}
542 };
543
544 uint8_t Opcode;
546 unsigned NumOperands;
547 unsigned BlockAddressBB;
548 Type *SrcElemTy; // GEP source element type.
549 std::optional<ConstantRange> InRange; // GEP inrange attribute.
550
551private:
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>());
558 }
559
560 BitcodeConstant &operator=(const BitcodeConstant &) = delete;
561
562public:
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);
569 }
570
571 static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
572
573 ArrayRef<unsigned> getOperandIDs() const {
574 return ArrayRef(getTrailingObjects<unsigned>(), NumOperands);
575 }
576
577 std::optional<ConstantRange> getInRange() const {
578 assert(Opcode == Instruction::GetElementPtr);
579 return InRange;
580 }
581
582 const char *getOpcodeName() const {
583 return Instruction::getOpcodeName(Opcode);
584 }
585};
586
587class 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;
596
597 std::vector<std::string> SectionTable;
598 std::vector<std::string> GCTable;
599
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.
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.
617 BitcodeReaderValueList ValueList;
618 std::optional<MetadataLoader> MDLoader;
619 std::vector<Comdat *> ComdatList;
620 DenseSet<GlobalObject *> ImplicitComdatObjects;
621 SmallVector<Instruction *, 64> InstructionList;
622
623 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
624 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
625
626 struct FunctionOperandInfo {
627 Function *F;
628 unsigned PersonalityFn;
629 unsigned Prefix;
630 unsigned Prologue;
631 };
632 std::vector<FunctionOperandInfo> FunctionOperands;
633
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;
637
638 /// The set of attribute groups.
639 std::map<unsigned, AttributeList> MAttributeGroups;
640
641 /// While parsing a function body, this is a list of the basic blocks for the
642 /// function.
643 std::vector<BasicBlock*> FunctionBBs;
644
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;
648
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;
653
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;
658
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;
662
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;
667
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.
672 std::deque<Function *> BasicBlockFwdRefQueue;
673
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;
680
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;
688
689 /// True if all functions will be materialized, negating the need to process
690 /// (e.g.) blockaddress forward references.
691 bool WillMaterializeAllForwardRefs = false;
692
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;
697
698 bool StripDebugInfo = false;
699 TBAAVerifier TBAAVerifyHelper;
700
701 std::vector<std::string> BundleTags;
703
704 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
705
706public:
707 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
708 StringRef ProducerIdentification, LLVMContext &Context);
709
710 Error materializeForwardReferencedFunctions();
711
712 Error materialize(GlobalValue *GV) override;
713 Error materializeModule() override;
714 std::vector<StructType *> getIdentifiedStructTypes() const override;
715
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 = {});
720
722
723 /// Materialize any deferred Metadata block.
724 Error materializeMetadata() override;
725
726 void setStripDebugInfo() override;
727
728private:
729 std::vector<StructType *> IdentifiedStructTypes;
730 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
731 StructType *createIdentifiedStructType(LLVMContext &Context);
732
733 static constexpr unsigned InvalidTypeID = ~0u;
734
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 = {});
739
740 void callValueTypeCallback(Value *F, unsigned TypeID);
741 Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
742 Expected<Constant *> getValueForInitializer(unsigned ID);
743
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);
749 }
750
751 Metadata *getFnMetadataByID(unsigned ID) {
752 return MDLoader->getMetadataFwdRefOrLoad(ID);
753 }
754
755 BasicBlock *getBasicBlock(unsigned ID) const {
756 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
757 return FunctionBBs[ID];
758 }
759
760 AttributeList getAttributes(unsigned i) const {
761 if (i-1 < MAttributes.size())
762 return MAttributes[i-1];
763 return AttributeList();
764 }
765
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
768 /// failure.
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.
775 if (UseRelativeIDs)
776 ValNo = InstNum - ValNo;
777 if (ValNo < InstNum) {
778 // If this is not a forward reference, just return the value we already
779 // have.
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;
785 }
786 if (Slot == Record.size())
787 return true;
788
789 TypeID = (unsigned)Record[Slot++];
790 ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID,
791 ConstExprInsertBB);
792 return ResVal == nullptr;
793 }
794
795 bool getValueOrMetadata(const SmallVectorImpl<uint64_t> &Record,
796 unsigned &Slot, unsigned InstNum, Value *&ResVal,
797 BasicBlock *ConstExprInsertBB) {
798 if (Slot == Record.size())
799 return true;
800 unsigned ValID = Record[Slot++];
801 if (ValID != static_cast<unsigned>(bitc::OB_METADATA)) {
802 unsigned TypeId;
803 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
804 ConstExprInsertBB);
805 }
806 if (Slot == Record.size())
807 return true;
808 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
809 ResVal = MetadataAsValue::get(Context, getFnMetadataByID(ValNo));
810 return false;
811 }
812
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))
820 return true;
821 // All values currently take a single record slot.
822 ++Slot;
823 return false;
824 }
825
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;
832 }
833
834 /// Version of getValue that returns ResVal directly, or 0 if there is an
835 /// error.
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.
842 if (UseRelativeIDs)
843 ValNo = InstNum - ValNo;
844 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
845 }
846
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.
854 if (UseRelativeIDs)
855 ValNo = InstNum - ValNo;
856 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
857 }
858
860 unsigned &OpNum,
861 unsigned BitWidth) {
862 if (Record.size() - OpNum < 2)
863 return error("Too few records for range");
864 if (BitWidth > 64) {
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");
869 APInt Lower =
870 readWideAPInt(ArrayRef(&Record[OpNum], LowerActiveWords), BitWidth);
871 OpNum += LowerActiveWords;
872 APInt Upper =
873 readWideAPInt(ArrayRef(&Record[OpNum], UpperActiveWords), BitWidth);
874 OpNum += UpperActiveWords;
875 return ConstantRange(Lower, Upper);
876 } else {
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));
881 }
882 }
883
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);
890 }
891
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);
896
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 = {});
904
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,
910
911 Error parseAttributeBlock();
912 Error parseAttributeGroupBlock();
913 Error parseTypeTable();
914 Error parseTypeTableBody();
915 Error parseOperandBundleTags();
916 Error parseSyncScopeNames();
917
919 unsigned NameIndex, Triple &TT);
920 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
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(
935 Function *F,
936 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
937
938 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
939};
940
941/// Class to manage reading and parsing function summary index bitcode
942/// files/sections.
943class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
944 /// The module index built during parsing.
945 ModuleSummaryIndex &TheIndex;
946
947 /// Indicates whether we have encountered a global value summary section
948 /// yet during parsing.
949 bool SeenGlobalValSummary = false;
950
951 /// Indicates whether we have already parsed the VST, used for error checking.
952 bool SeenValueSymbolTable = false;
953
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;
957
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.
967 ValueIdToValueInfoMap;
968
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
972 /// summary records.
974
975 /// Original source file name recorded in a bitcode record.
976 std::string SourceFileName;
977
978 /// The string identifier given to this module by the client, normally the
979 /// path to the bitcode file.
980 StringRef ModulePath;
981
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;
985
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;
989
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;
993
994public:
995 ModuleSummaryIndexBitcodeReader(
996 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
997 StringRef ModulePath,
998 std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
999
1001
1002private:
1003 void setValueGUID(uint64_t ValueID, StringRef ValueName,
1005 StringRef SourceFileName);
1006 Error parseValueSymbolTable(
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,
1018 std::vector<FunctionSummary::ParamAccess>
1019 parseParamAccesses(ArrayRef<uint64_t> Record);
1020 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1021 unsigned &I);
1022
1023 template <bool AllowNullValueInfo = false>
1024 std::pair<ValueInfo, GlobalValue::GUID>
1025 getValueInfoFromValueId(unsigned ValueId);
1026
1027 void addThisModule();
1028 ModuleSummaryIndex::ModuleInfo *getThisModule();
1029};
1030
1031} // end anonymous namespace
1032
1034 Error Err) {
1035 if (Err) {
1036 std::error_code EC;
1037 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
1038 EC = EIB.convertToErrorCode();
1039 Ctx.emitError(EIB.message());
1040 });
1041 return EC;
1042 }
1043 return std::error_code();
1044}
1045
1046BitcodeReader::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);
1053 }) {
1054 this->ProducerIdentification = std::string(ProducerIdentification);
1055}
1056
1057Error BitcodeReader::materializeForwardReferencedFunctions() {
1058 if (WillMaterializeAllForwardRefs)
1059 return Error::success();
1060
1061 // Prevent recursion.
1062 WillMaterializeAllForwardRefs = true;
1063
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.
1070 continue;
1071
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");
1078
1079 // Try to materialize F.
1080 if (Error Err = materialize(F))
1081 return Err;
1082 }
1083 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
1084
1085 for (Function *F : BackwardRefFunctions)
1086 if (Error Err = materialize(F))
1087 return Err;
1088 BackwardRefFunctions.clear();
1089
1090 // Reset state.
1091 WillMaterializeAllForwardRefs = false;
1092 return Error::success();
1093}
1094
1095//===----------------------------------------------------------------------===//
1096// Helper functions to implement forward reference resolution, etc.
1097//===----------------------------------------------------------------------===//
1098
1099static bool hasImplicitComdat(size_t Val) {
1100 switch (Val) {
1101 default:
1102 return false;
1103 case 1: // Old WeakAnyLinkage
1104 case 4: // Old LinkOnceAnyLinkage
1105 case 10: // Old WeakODRLinkage
1106 case 11: // Old LinkOnceODRLinkage
1107 return true;
1108 }
1109}
1110
1112 switch (Val) {
1113 default: // Map unknown/new linkages to external
1114 case 0:
1116 case 2:
1118 case 3:
1120 case 5:
1121 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
1122 case 6:
1123 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
1124 case 7:
1126 case 8:
1128 case 9:
1130 case 12:
1132 case 13:
1133 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
1134 case 14:
1135 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
1136 case 15:
1137 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
1138 case 1: // Old value with implicit comdat.
1139 case 16:
1141 case 10: // Old value with implicit comdat.
1142 case 17:
1144 case 4: // Old value with implicit comdat.
1145 case 18:
1147 case 11: // Old value with implicit comdat.
1148 case 19:
1150 }
1151}
1152
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;
1165 return Flags;
1166}
1167
1168// Decode the flags for GlobalValue in the summary. The bits for each attribute:
1169//
1170// linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1171// visibility: [8, 10).
1173 uint64_t Version) {
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
1184 // values as live.
1185 bool Live = (RawFlags & 0x2) || Version < 3;
1186 bool Local = (RawFlags & 0x4);
1187 bool AutoHide = (RawFlags & 0x8);
1188
1189 return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
1190 Live, Local, AutoHide, IK);
1191}
1192
1193// Decode the flags for GlobalVariable in the summary
1196 (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
1197 (RawFlags & 0x4) ? true : false,
1198 (GlobalObject::VCallVisibility)(RawFlags >> 3));
1199}
1200
1201static std::pair<CalleeInfo::HotnessType, bool>
1203 CalleeInfo::HotnessType Hotness =
1204 static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits
1205 bool HasTailCall = (RawFlags & 0x8); // 1 bit
1206 return {Hotness, HasTailCall};
1207}
1208
1209static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF,
1210 bool &HasTailCall) {
1211 static constexpr uint64_t RelBlockFreqMask =
1213 RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits
1214 HasTailCall = (RawFlags & (1 << CalleeInfo::RelBlockFreqBits)); // 1 bit
1215}
1216
1218 switch (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;
1223 }
1224}
1225
1228 switch (Val) {
1229 default: // Map unknown values to default.
1230 case 0: return GlobalValue::DefaultStorageClass;
1233 }
1234}
1235
1236static bool getDecodedDSOLocal(unsigned Val) {
1237 switch(Val) {
1238 default: // Map unknown values to preemptable.
1239 case 0: return false;
1240 case 1: return true;
1241 }
1242}
1243
1244static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) {
1245 switch (Val) {
1246 case 1:
1247 return CodeModel::Tiny;
1248 case 2:
1249 return CodeModel::Small;
1250 case 3:
1251 return CodeModel::Kernel;
1252 case 4:
1253 return CodeModel::Medium;
1254 case 5:
1255 return CodeModel::Large;
1256 }
1257
1258 return {};
1259}
1260
1262 switch (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;
1269 }
1270}
1271
1273 switch (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;
1278 }
1279}
1280
1281static int getDecodedCastOpcode(unsigned Val) {
1282 switch (Val) {
1283 default: return -1;
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;
1297 }
1298}
1299
1300static 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())
1304 return -1;
1305
1306 switch (Val) {
1307 default:
1308 return -1;
1309 case bitc::UNOP_FNEG:
1310 return IsFP ? Instruction::FNeg : -1;
1311 }
1312}
1313
1314static 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())
1318 return -1;
1319
1320 switch (Val) {
1321 default:
1322 return -1;
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;
1349 }
1350}
1351
1353 switch (Val) {
1354 default: return AtomicRMWInst::BAD_BINOP;
1356 case bitc::RMW_ADD: return AtomicRMWInst::Add;
1357 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1358 case bitc::RMW_AND: return AtomicRMWInst::And;
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;
1376 case bitc::RMW_USUB_SAT:
1378 }
1379}
1380
1382 switch (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;
1391 }
1392}
1393
1395 switch (Val) {
1396 default: // Map unknown selection kinds to any.
1398 return Comdat::Any;
1400 return Comdat::ExactMatch;
1402 return Comdat::Largest;
1404 return Comdat::NoDeduplicate;
1406 return Comdat::SameSize;
1407 }
1408}
1409
1411 FastMathFlags FMF;
1412 if (0 != (Val & bitc::UnsafeAlgebra))
1413 FMF.setFast();
1414 if (0 != (Val & bitc::AllowReassoc))
1415 FMF.setAllowReassoc();
1416 if (0 != (Val & bitc::NoNaNs))
1417 FMF.setNoNaNs();
1418 if (0 != (Val & bitc::NoInfs))
1419 FMF.setNoInfs();
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();
1428 return FMF;
1429}
1430
1431static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1432 // A GlobalValue with local linkage cannot have a DLL storage class.
1433 if (GV->hasLocalLinkage())
1434 return;
1435 switch (Val) {
1438 }
1439}
1440
1441Type *BitcodeReader::getTypeByID(unsigned ID) {
1442 // The type table size is always specified correctly.
1443 if (ID >= TypeList.size())
1444 return nullptr;
1445
1446 if (Type *Ty = TypeList[ID])
1447 return Ty;
1448
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);
1452}
1453
1454unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
1455 auto It = ContainedTypeIDs.find(ID);
1456 if (It == ContainedTypeIDs.end())
1457 return InvalidTypeID;
1458
1459 if (Idx >= It->second.size())
1460 return InvalidTypeID;
1461
1462 return It->second[Idx];
1463}
1464
1465Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
1466 if (ID >= TypeList.size())
1467 return nullptr;
1468
1469 Type *Ty = TypeList[ID];
1470 if (!Ty->isPointerTy())
1471 return nullptr;
1472
1473 return getTypeByID(getContainedTypeID(ID, 0));
1474}
1475
1476unsigned 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");
1489 return It->second;
1490 }
1491
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});
1497 return TypeID;
1498}
1499
1501 GEPNoWrapFlags NW;
1502 if (Flags & (1 << bitc::GEP_INBOUNDS))
1504 if (Flags & (1 << bitc::GEP_NUSW))
1506 if (Flags & (1 << bitc::GEP_NUW))
1508 return NW;
1509}
1510
1511static bool isConstExprSupported(const BitcodeConstant *BC) {
1512 uint8_t Opcode = BC->Opcode;
1513
1514 // These are not real constant expressions, always consider them supported.
1515 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1516 return true;
1517
1518 // If -expand-constant-exprs is set, we want to consider all expressions
1519 // as unsupported.
1521 return false;
1522
1523 if (Instruction::isBinaryOp(Opcode))
1524 return ConstantExpr::isSupportedBinOp(Opcode);
1525
1526 if (Instruction::isCast(Opcode))
1527 return ConstantExpr::isSupportedCastOp(Opcode);
1528
1529 if (Opcode == Instruction::GetElementPtr)
1530 return ConstantExpr::isSupportedGetElementPtr(BC->SrcElemTy);
1531
1532 switch (Opcode) {
1533 case Instruction::FNeg:
1534 case Instruction::Select:
1535 case Instruction::ICmp:
1536 case Instruction::FCmp:
1537 return false;
1538 default:
1539 return true;
1540 }
1541}
1542
1543Expected<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];
1549
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();
1558 continue;
1559 }
1560
1561 if (ValID >= ValueList.size() || !ValueList[ValID])
1562 return error("Invalid value ID");
1563
1564 Value *V = ValueList[ValID];
1565 auto *BC = dyn_cast<BitcodeConstant>(V);
1566 if (!BC) {
1567 MaterializedValues.insert({ValID, V});
1568 Worklist.pop_back();
1569 continue;
1570 }
1571
1572 // Iterate in reverse, so values will get popped from the worklist in
1573 // expected order.
1575 for (unsigned OpID : reverse(BC->getOperandIDs())) {
1576 auto It = MaterializedValues.find(OpID);
1577 if (It != MaterializedValues.end())
1578 Ops.push_back(It->second);
1579 else
1580 Worklist.push_back(OpID);
1581 }
1582
1583 // Some expressions have not been resolved yet, handle them first and then
1584 // revisit this one.
1585 if (Ops.size() != BC->getOperandIDs().size())
1586 continue;
1587 std::reverse(Ops.begin(), Ops.end());
1588
1589 SmallVector<Constant *> ConstOps;
1590 for (Value *Op : Ops)
1591 if (auto *C = dyn_cast<Constant>(Op))
1592 ConstOps.push_back(C);
1593
1594 // Materialize as constant expression if possible.
1595 if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) {
1596 Constant *C;
1597 if (Instruction::isCast(BC->Opcode)) {
1598 C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType());
1599 if (!C)
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);
1603 } else {
1604 switch (BC->Opcode) {
1605 case BitcodeConstant::ConstantPtrAuthOpcode: {
1606 auto *Key = dyn_cast<ConstantInt>(ConstOps[1]);
1607 if (!Key)
1608 return error("ptrauth key operand must be ConstantInt");
1609
1610 auto *Disc = dyn_cast<ConstantInt>(ConstOps[2]);
1611 if (!Disc)
1612 return error("ptrauth disc operand must be ConstantInt");
1613
1614 C = ConstantPtrAuth::get(ConstOps[0], Key, Disc, ConstOps[3]);
1615 break;
1616 }
1617 case BitcodeConstant::NoCFIOpcode: {
1618 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1619 if (!GV)
1620 return error("no_cfi operand must be GlobalValue");
1621 C = NoCFIValue::get(GV);
1622 break;
1623 }
1624 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1625 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1626 if (!GV)
1627 return error("dso_local operand must be GlobalValue");
1629 break;
1630 }
1631 case BitcodeConstant::BlockAddressOpcode: {
1632 Function *Fn = dyn_cast<Function>(ConstOps[0]);
1633 if (!Fn)
1634 return error("blockaddress operand must be a function");
1635
1636 // If the function is already parsed we can insert the block address
1637 // right away.
1638 BasicBlock *BB;
1639 unsigned BBID = BC->BlockAddressBB;
1640 if (!BBID)
1641 // Invalid reference to entry block.
1642 return error("Invalid ID");
1643 if (!Fn->empty()) {
1644 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1645 for (size_t I = 0, E = BBID; I != E; ++I) {
1646 if (BBI == BBE)
1647 return error("Invalid ID");
1648 ++BBI;
1649 }
1650 BB = &*BBI;
1651 } else {
1652 // Otherwise insert a placeholder and remember it so it can be
1653 // inserted when the function is parsed.
1654 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1655 if (FwdBBs.empty())
1656 BasicBlockFwdRefQueue.push_back(Fn);
1657 if (FwdBBs.size() < BBID + 1)
1658 FwdBBs.resize(BBID + 1);
1659 if (!FwdBBs[BBID])
1660 FwdBBs[BBID] = BasicBlock::Create(Context);
1661 BB = FwdBBs[BBID];
1662 }
1663 C = BlockAddress::get(Fn, BB);
1664 break;
1665 }
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");
1670
1671 for (const auto [Ty, Op] : zip(ST->elements(), ConstOps))
1672 if (Op->getType() != Ty)
1673 return error("Incorrect type in struct initializer");
1674
1675 C = ConstantStruct::get(ST, ConstOps);
1676 break;
1677 }
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");
1682
1683 for (Constant *Op : ConstOps)
1684 if (Op->getType() != AT->getElementType())
1685 return error("Incorrect type in array initializer");
1686
1687 C = ConstantArray::get(AT, ConstOps);
1688 break;
1689 }
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");
1694
1695 for (Constant *Op : ConstOps)
1696 if (Op->getType() != VT->getElementType())
1697 return error("Incorrect type in vector initializer");
1698
1699 C = ConstantVector::get(ConstOps);
1700 break;
1701 }
1702 case Instruction::GetElementPtr:
1704 BC->SrcElemTy, ConstOps[0], ArrayRef(ConstOps).drop_front(),
1705 toGEPNoWrapFlags(BC->Flags), BC->getInRange());
1706 break;
1707 case Instruction::ExtractElement:
1708 C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]);
1709 break;
1710 case Instruction::InsertElement:
1711 C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1],
1712 ConstOps[2]);
1713 break;
1714 case Instruction::ShuffleVector: {
1716 ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask);
1717 C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask);
1718 break;
1719 }
1720 default:
1721 llvm_unreachable("Unhandled bitcode constant");
1722 }
1723 }
1724
1725 // Cache resolved constant.
1726 ValueList.replaceValueWithoutRAUW(ValID, C);
1727 MaterializedValues.insert({ValID, C});
1728 Worklist.pop_back();
1729 continue;
1730 }
1731
1732 if (!InsertBB)
1733 return error(Twine("Value referenced by initializer is an unsupported "
1734 "constant expression of type ") +
1735 BC->getOpcodeName());
1736
1737 // Materialize as instructions if necessary.
1738 Instruction *I;
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)) {
1750 I->setHasNoSignedWrap();
1752 I->setHasNoUnsignedWrap();
1753 }
1754 if (isa<PossiblyExactOperator>(I) &&
1755 (BC->Flags & PossiblyExactOperator::IsExact))
1756 I->setIsExact();
1757 } else {
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",
1765 InsertBB);
1766 }
1767 I = cast<Instruction>(V);
1768 break;
1769 }
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);
1777 break;
1778 }
1779 case Instruction::ICmp:
1780 case Instruction::FCmp:
1782 (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1],
1783 "constexpr", InsertBB);
1784 break;
1785 case Instruction::GetElementPtr:
1786 I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0],
1787 ArrayRef(Ops).drop_front(), "constexpr",
1788 InsertBB);
1789 cast<GetElementPtrInst>(I)->setNoWrapFlags(toGEPNoWrapFlags(BC->Flags));
1790 break;
1791 case Instruction::Select:
1792 I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB);
1793 break;
1794 case Instruction::ExtractElement:
1795 I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB);
1796 break;
1797 case Instruction::InsertElement:
1798 I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr",
1799 InsertBB);
1800 break;
1801 case Instruction::ShuffleVector:
1802 I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
1803 InsertBB);
1804 break;
1805 default:
1806 llvm_unreachable("Unhandled bitcode constant");
1807 }
1808 }
1809
1810 MaterializedValues.insert({ValID, I});
1811 Worklist.pop_back();
1812 }
1813
1814 return MaterializedValues[StartValID];
1815}
1816
1817Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
1818 Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr);
1819 if (!MaybeV)
1820 return MaybeV.takeError();
1821
1822 // Result must be Constant if InsertBB is nullptr.
1823 return cast<Constant>(MaybeV.get());
1824}
1825
1826StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1827 StringRef Name) {
1828 auto *Ret = StructType::create(Context, Name);
1829 IdentifiedStructTypes.push_back(Ret);
1830 return Ret;
1831}
1832
1833StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1834 auto *Ret = StructType::create(Context);
1835 IdentifiedStructTypes.push_back(Ret);
1836 return Ret;
1837}
1838
1839//===----------------------------------------------------------------------===//
1840// Functions for parsing blocks from the bitcode file
1841//===----------------------------------------------------------------------===//
1842
1844 switch (Val) {
1848 llvm_unreachable("Synthetic enumerators which should never get here");
1849
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:
1906 return 1ULL << 60;
1907 case Attribute::ImmArg:
1908 return 1ULL << 61;
1909 case Attribute::WillReturn:
1910 return 1ULL << 62;
1911 case Attribute::NoFree:
1912 return 1ULL << 63;
1913 default:
1914 // Other attributes are not supported in the raw format,
1915 // as we ran out of space.
1916 return 0;
1917 }
1918 llvm_unreachable("Unsupported attribute type");
1919}
1920
1922 if (!Val) return;
1923
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.
1933 else
1934 B.addAttribute(I);
1935 }
1936 }
1937}
1938
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'.
1943 uint64_t EncodedAttrs,
1944 uint64_t AttrIdx) {
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.");
1950
1951 if (Alignment)
1952 B.addAlignmentAttr(Alignment);
1953
1954 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1955 (EncodedAttrs & 0xffff);
1956
1957 if (AttrIdx == AttributeList::FunctionIndex) {
1958 // Upgrade old memory attributes.
1960 if (Attrs & (1ULL << 9)) {
1961 // ReadNone
1962 Attrs &= ~(1ULL << 9);
1963 ME &= MemoryEffects::none();
1964 }
1965 if (Attrs & (1ULL << 10)) {
1966 // ReadOnly
1967 Attrs &= ~(1ULL << 10);
1969 }
1970 if (Attrs & (1ULL << 49)) {
1971 // InaccessibleMemOnly
1972 Attrs &= ~(1ULL << 49);
1974 }
1975 if (Attrs & (1ULL << 50)) {
1976 // InaccessibleMemOrArgMemOnly
1977 Attrs &= ~(1ULL << 50);
1979 }
1980 if (Attrs & (1ULL << 53)) {
1981 // WriteOnly
1982 Attrs &= ~(1ULL << 53);
1984 }
1985 if (ME != MemoryEffects::unknown())
1986 B.addMemoryAttr(ME);
1987 }
1988
1989 // Upgrade nocapture to captures(none).
1990 if (Attrs & (1ULL << 21)) {
1991 Attrs &= ~(1ULL << 21);
1992 B.addCapturesAttr(CaptureInfo::none());
1993 }
1994
1995 addRawAttributeValue(B, Attrs);
1996}
1997
1998Error BitcodeReader::parseAttributeBlock() {
1999 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
2000 return Err;
2001
2002 if (!MAttributes.empty())
2003 return error("Invalid multiple blocks");
2004
2006
2008
2009 // Read all the records.
2010 while (true) {
2011 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2012 if (!MaybeEntry)
2013 return MaybeEntry.takeError();
2014 BitstreamEntry Entry = MaybeEntry.get();
2015
2016 switch (Entry.Kind) {
2017 case BitstreamEntry::SubBlock: // Handled for us already.
2019 return error("Malformed block");
2021 return Error::success();
2023 // The interesting case.
2024 break;
2025 }
2026
2027 // Read a record.
2028 Record.clear();
2029 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2030 if (!MaybeRecord)
2031 return MaybeRecord.takeError();
2032 switch (MaybeRecord.get()) {
2033 default: // Default behavior: ignore.
2034 break;
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");
2039
2040 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
2041 AttrBuilder B(Context);
2043 Attrs.push_back(AttributeList::get(Context, Record[i], B));
2044 }
2045
2046 MAttributes.push_back(AttributeList::get(Context, Attrs));
2047 Attrs.clear();
2048 break;
2049 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
2050 for (uint64_t Val : Record)
2051 Attrs.push_back(MAttributeGroups[Val]);
2052
2053 MAttributes.push_back(AttributeList::get(Context, Attrs));
2054 Attrs.clear();
2055 break;
2056 }
2057 }
2058}
2059
2060// Returns Attribute::None on unrecognized codes.
2062 switch (Code) {
2063 default:
2064 return Attribute::None;
2066 return Attribute::Alignment;
2068 return Attribute::AlwaysInline;
2070 return Attribute::Builtin;
2072 return Attribute::ByVal;
2074 return Attribute::InAlloca;
2076 return Attribute::Cold;
2078 return Attribute::Convergent;
2080 return Attribute::DisableSanitizerInstrumentation;
2082 return Attribute::ElementType;
2084 return Attribute::FnRetThunkExtern;
2086 return Attribute::InlineHint;
2088 return Attribute::InReg;
2090 return Attribute::JumpTable;
2092 return Attribute::Memory;
2094 return Attribute::NoFPClass;
2096 return Attribute::MinSize;
2098 return Attribute::Naked;
2100 return Attribute::Nest;
2102 return Attribute::NoAlias;
2104 return Attribute::NoBuiltin;
2106 return Attribute::NoCallback;
2108 return Attribute::NoDivergenceSource;
2110 return Attribute::NoDuplicate;
2112 return Attribute::NoFree;
2114 return Attribute::NoImplicitFloat;
2116 return Attribute::NoInline;
2118 return Attribute::NoRecurse;
2120 return Attribute::NoMerge;
2122 return Attribute::NonLazyBind;
2124 return Attribute::NonNull;
2126 return Attribute::Dereferenceable;
2128 return Attribute::DereferenceableOrNull;
2130 return Attribute::AllocAlign;
2132 return Attribute::AllocKind;
2134 return Attribute::AllocSize;
2136 return Attribute::AllocatedPointer;
2138 return Attribute::NoRedZone;
2140 return Attribute::NoReturn;
2142 return Attribute::NoSync;
2144 return Attribute::NoCfCheck;
2146 return Attribute::NoProfile;
2148 return Attribute::SkipProfile;
2150 return Attribute::NoUnwind;
2152 return Attribute::NoSanitizeBounds;
2154 return Attribute::NoSanitizeCoverage;
2156 return Attribute::NullPointerIsValid;
2158 return Attribute::OptimizeForDebugging;
2160 return Attribute::OptForFuzzing;
2162 return Attribute::OptimizeForSize;
2164 return Attribute::OptimizeNone;
2166 return Attribute::ReadNone;
2168 return Attribute::ReadOnly;
2170 return Attribute::Returned;
2172 return Attribute::ReturnsTwice;
2174 return Attribute::SExt;
2176 return Attribute::Speculatable;
2178 return Attribute::StackAlignment;
2180 return Attribute::StackProtect;
2182 return Attribute::StackProtectReq;
2184 return Attribute::StackProtectStrong;
2186 return Attribute::SafeStack;
2188 return Attribute::ShadowCallStack;
2190 return Attribute::StrictFP;
2192 return Attribute::StructRet;
2194 return Attribute::SanitizeAddress;
2196 return Attribute::SanitizeHWAddress;
2198 return Attribute::SanitizeThread;
2200 return Attribute::SanitizeType;
2202 return Attribute::SanitizeMemory;
2204 return Attribute::SanitizeNumericalStability;
2206 return Attribute::SanitizeRealtime;
2208 return Attribute::SanitizeRealtimeBlocking;
2210 return Attribute::SpeculativeLoadHardening;
2212 return Attribute::SwiftError;
2214 return Attribute::SwiftSelf;
2216 return Attribute::SwiftAsync;
2218 return Attribute::UWTable;
2220 return Attribute::VScaleRange;
2222 return Attribute::WillReturn;
2224 return Attribute::WriteOnly;
2226 return Attribute::ZExt;
2228 return Attribute::ImmArg;
2230 return Attribute::SanitizeMemTag;
2232 return Attribute::Preallocated;
2234 return Attribute::NoUndef;
2236 return Attribute::ByRef;
2238 return Attribute::MustProgress;
2240 return Attribute::Hot;
2242 return Attribute::PresplitCoroutine;
2244 return Attribute::Writable;
2246 return Attribute::CoroDestroyOnlyWhenComplete;
2248 return Attribute::DeadOnUnwind;
2250 return Attribute::Range;
2252 return Attribute::Initializes;
2254 return Attribute::CoroElideSafe;
2256 return Attribute::NoExt;
2258 return Attribute::Captures;
2259 }
2260}
2261
2262Error 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.
2267 return error("Invalid alignment value");
2268 Alignment = decodeMaybeAlign(Exponent);
2269 return Error::success();
2270}
2271
2272Error 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();
2277}
2278
2279static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
2280 switch (EncodedKind) {
2282 ME &= MemoryEffects::none();
2283 return true;
2286 return true;
2289 return true;
2292 return true;
2295 return true;
2298 return true;
2299 default:
2300 return false;
2301 }
2302}
2303
2304Error BitcodeReader::parseAttributeGroupBlock() {
2305 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
2306 return Err;
2307
2308 if (!MAttributeGroups.empty())
2309 return error("Invalid multiple blocks");
2310
2312
2313 // Read all the records.
2314 while (true) {
2315 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2316 if (!MaybeEntry)
2317 return MaybeEntry.takeError();
2318 BitstreamEntry Entry = MaybeEntry.get();
2319
2320 switch (Entry.Kind) {
2321 case BitstreamEntry::SubBlock: // Handled for us already.
2323 return error("Malformed block");
2325 return Error::success();
2327 // The interesting case.
2328 break;
2329 }
2330
2331 // Read a record.
2332 Record.clear();
2333 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2334 if (!MaybeRecord)
2335 return MaybeRecord.takeError();
2336 switch (MaybeRecord.get()) {
2337 default: // Default behavior: ignore.
2338 break;
2339 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
2340 if (Record.size() < 3)
2341 return error("Invalid grp record");
2342
2343 uint64_t GrpID = Record[0];
2344 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
2345
2346 AttrBuilder B(Context);
2348 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2349 if (Record[i] == 0) { // Enum attribute
2351 uint64_t EncodedKind = Record[++i];
2353 upgradeOldMemoryAttribute(ME, EncodedKind))
2354 continue;
2355
2356 if (EncodedKind == bitc::ATTR_KIND_NO_CAPTURE) {
2357 B.addCapturesAttr(CaptureInfo::none());
2358 continue;
2359 }
2360
2361 if (Error Err = parseAttrKind(EncodedKind, &Kind))
2362 return Err;
2363
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);
2377 else
2378 return error("Not an enum attribute");
2379 } else if (Record[i] == 1) { // Integer attribute
2381 if (Error Err = parseAttrKind(Record[++i], &Kind))
2382 return Err;
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)
2406 B.addNoFPClassAttr(
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;
2412
2413 while (Record[i] != 0 && i != e)
2414 KindStr += Record[i++];
2415 assert(Record[i] == 0 && "Kind string not null terminated");
2416
2417 if (HasValue) {
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");
2423 }
2424
2425 B.addAttribute(KindStr.str(), ValStr.str());
2426 } else if (Record[i] == 5 || Record[i] == 6) {
2427 bool HasType = Record[i] == 6;
2429 if (Error Err = parseAttrKind(Record[++i], &Kind))
2430 return Err;
2431 if (!Attribute::isTypeAttrKind(Kind))
2432 return error("Not a type attribute");
2433
2434 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
2435 } else if (Record[i] == 7) {
2437
2438 i++;
2439 if (Error Err = parseAttrKind(Record[i++], &Kind))
2440 return Err;
2442 return error("Not a ConstantRange attribute");
2443
2444 Expected<ConstantRange> MaybeCR =
2445 readBitWidthAndConstantRange(Record, i);
2446 if (!MaybeCR)
2447 return MaybeCR.takeError();
2448 i--;
2449
2450 B.addConstantRangeAttr(Kind, MaybeCR.get());
2451 } else if (Record[i] == 8) {
2453
2454 i++;
2455 if (Error Err = parseAttrKind(Record[i++], &Kind))
2456 return Err;
2458 return error("Not a constant range list attribute");
2459
2461 if (i + 2 > e)
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);
2468 if (!MaybeCR)
2469 return MaybeCR.takeError();
2470 Val.push_back(MaybeCR.get());
2471 }
2472 i--;
2473
2475 return error("Invalid (unordered or overlapping) range list");
2476 B.addConstantRangeListAttr(Kind, Val);
2477 } else {
2478 return error("Invalid attribute group entry");
2479 }
2480 }
2481
2482 if (ME != MemoryEffects::unknown())
2483 B.addMemoryAttr(ME);
2484
2486 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
2487 break;
2488 }
2489 }
2490 }
2491}
2492
2493Error BitcodeReader::parseTypeTable() {
2494 if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
2495 return Err;
2496
2497 return parseTypeTableBody();
2498}
2499
2500Error BitcodeReader::parseTypeTableBody() {
2501 if (!TypeList.empty())
2502 return error("Invalid multiple blocks");
2503
2505 unsigned NumRecords = 0;
2506
2508
2509 // Read all the records for this type table.
2510 while (true) {
2511 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2512 if (!MaybeEntry)
2513 return MaybeEntry.takeError();
2514 BitstreamEntry Entry = MaybeEntry.get();
2515
2516 switch (Entry.Kind) {
2517 case BitstreamEntry::SubBlock: // Handled for us already.
2519 return error("Malformed block");
2521 if (NumRecords != TypeList.size())
2522 return error("Malformed block");
2523 return Error::success();
2525 // The interesting case.
2526 break;
2527 }
2528
2529 // Read a record.
2530 Record.clear();
2531 Type *ResultTy = nullptr;
2532 SmallVector<unsigned> ContainedIDs;
2533 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2534 if (!MaybeRecord)
2535 return MaybeRecord.takeError();
2536 switch (MaybeRecord.get()) {
2537 default:
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.
2542 if (Record.empty())
2543 return error("Invalid numentry record");
2544 TypeList.resize(Record[0]);
2545 continue;
2546 case bitc::TYPE_CODE_VOID: // VOID
2547 ResultTy = Type::getVoidTy(Context);
2548 break;
2549 case bitc::TYPE_CODE_HALF: // HALF
2550 ResultTy = Type::getHalfTy(Context);
2551 break;
2552 case bitc::TYPE_CODE_BFLOAT: // BFLOAT
2553 ResultTy = Type::getBFloatTy(Context);
2554 break;
2555 case bitc::TYPE_CODE_FLOAT: // FLOAT
2556 ResultTy = Type::getFloatTy(Context);
2557 break;
2558 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
2559 ResultTy = Type::getDoubleTy(Context);
2560 break;
2561 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
2562 ResultTy = Type::getX86_FP80Ty(Context);
2563 break;
2564 case bitc::TYPE_CODE_FP128: // FP128
2565 ResultTy = Type::getFP128Ty(Context);
2566 break;
2567 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
2568 ResultTy = Type::getPPC_FP128Ty(Context);
2569 break;
2570 case bitc::TYPE_CODE_LABEL: // LABEL
2571 ResultTy = Type::getLabelTy(Context);
2572 break;
2573 case bitc::TYPE_CODE_METADATA: // METADATA
2574 ResultTy = Type::getMetadataTy(Context);
2575 break;
2576 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
2577 // Deprecated: decodes as <1 x i64>
2578 ResultTy =
2580 break;
2581 case bitc::TYPE_CODE_X86_AMX: // X86_AMX
2582 ResultTy = Type::getX86_AMXTy(Context);
2583 break;
2584 case bitc::TYPE_CODE_TOKEN: // TOKEN
2585 ResultTy = Type::getTokenTy(Context);
2586 break;
2587 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2588 if (Record.empty())
2589 return error("Invalid integer record");
2590
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);
2596 break;
2597 }
2598 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
2599 // [pointee type, address space]
2600 if (Record.empty())
2601 return error("Invalid pointer record");
2602 unsigned AddressSpace = 0;
2603 if (Record.size() == 2)
2604 AddressSpace = Record[1];
2605 ResultTy = getTypeByID(Record[0]);
2606 if (!ResultTy ||
2607 !PointerType::isValidElementType(ResultTy))
2608 return error("Invalid type");
2609 ContainedIDs.push_back(Record[0]);
2610 ResultTy = PointerType::get(ResultTy->getContext(), AddressSpace);
2611 break;
2612 }
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);
2618 break;
2619 }
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);
2629 else
2630 break;
2631 }
2632
2633 ResultTy = getTypeByID(Record[2]);
2634 if (!ResultTy || ArgTys.size() < Record.size()-3)
2635 return error("Invalid type");
2636
2637 ContainedIDs.append(Record.begin() + 2, Record.end());
2638 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2639 break;
2640 }
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);
2651 }
2652 else
2653 break;
2654 }
2655
2656 ResultTy = getTypeByID(Record[1]);
2657 if (!ResultTy || ArgTys.size() < Record.size()-2)
2658 return error("Invalid type");
2659
2660 ContainedIDs.append(Record.begin() + 1, Record.end());
2661 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2662 break;
2663 }
2664 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
2665 if (Record.empty())
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);
2671 else
2672 break;
2673 }
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]);
2678 break;
2679 }
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");
2683 continue;
2684
2685 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2686 if (Record.empty())
2687 return error("Invalid named struct record");
2688
2689 if (NumRecords >= TypeList.size())
2690 return error("Invalid TYPE table");
2691
2692 // Check to see if this was forward referenced, if so fill in the temp.
2693 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2694 if (Res) {
2695 Res->setName(TypeName);
2696 TypeList[NumRecords] = nullptr;
2697 } else // Otherwise, create a new struct.
2698 Res = createIdentifiedStructType(Context, TypeName);
2699 TypeName.clear();
2700
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);
2705 else
2706 break;
2707 }
2708 if (EltTys.size() != Record.size()-1)
2709 return error("Invalid named struct record");
2710 if (auto E = Res->setBodyOrError(EltTys, Record[0]))
2711 return E;
2712 ContainedIDs.append(Record.begin() + 1, Record.end());
2713 ResultTy = Res;
2714 break;
2715 }
2716 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
2717 if (Record.size() != 1)
2718 return error("Invalid opaque type record");
2719
2720 if (NumRecords >= TypeList.size())
2721 return error("Invalid TYPE table");
2722
2723 // Check to see if this was forward referenced, if so fill in the temp.
2724 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2725 if (Res) {
2726 Res->setName(TypeName);
2727 TypeList[NumRecords] = nullptr;
2728 } else // Otherwise, create a new struct with no body.
2729 Res = createIdentifiedStructType(Context, TypeName);
2730 TypeName.clear();
2731 ResultTy = Res;
2732 break;
2733 }
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");
2737
2738 if (NumRecords >= TypeList.size())
2739 return error("Invalid TYPE table");
2740
2741 if (Record[0] >= Record.size())
2742 return error("Too many type parameters");
2743
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);
2750 else
2751 return error("Invalid type");
2752 }
2753
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]);
2758 }
2759 auto TTy =
2760 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
2761 if (auto E = TTy.takeError())
2762 return E;
2763 ResultTy = *TTy;
2764 TypeName.clear();
2765 break;
2766 }
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]);
2775 break;
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");
2780 if (Record[0] == 0)
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);
2788 break;
2789 }
2790
2791 if (NumRecords >= TypeList.size())
2792 return error("Invalid TYPE table");
2793 if (TypeList[NumRecords])
2794 return error(
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);
2800 ++NumRecords;
2801 }
2802}
2803
2804Error BitcodeReader::parseOperandBundleTags() {
2805 if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
2806 return Err;
2807
2808 if (!BundleTags.empty())
2809 return error("Invalid multiple blocks");
2810
2812
2813 while (true) {
2814 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2815 if (!MaybeEntry)
2816 return MaybeEntry.takeError();
2817 BitstreamEntry Entry = MaybeEntry.get();
2818
2819 switch (Entry.Kind) {
2820 case BitstreamEntry::SubBlock: // Handled for us already.
2822 return error("Malformed block");
2824 return Error::success();
2826 // The interesting case.
2827 break;
2828 }
2829
2830 // Tags are implicitly mapped to integers by their order.
2831
2832 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2833 if (!MaybeRecord)
2834 return MaybeRecord.takeError();
2835 if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
2836 return error("Invalid operand bundle record");
2837
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");
2842 Record.clear();
2843 }
2844}
2845
2846Error BitcodeReader::parseSyncScopeNames() {
2847 if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2848 return Err;
2849
2850 if (!SSIDs.empty())
2851 return error("Invalid multiple synchronization scope names blocks");
2852
2854 while (true) {
2855 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2856 if (!MaybeEntry)
2857 return MaybeEntry.takeError();
2858 BitstreamEntry Entry = MaybeEntry.get();
2859
2860 switch (Entry.Kind) {
2861 case BitstreamEntry::SubBlock: // Handled for us already.
2863 return error("Malformed block");
2865 if (SSIDs.empty())
2866 return error("Invalid empty synchronization scope names block");
2867 return Error::success();
2869 // The interesting case.
2870 break;
2871 }
2872
2873 // Synchronization scope names are implicitly mapped to synchronization
2874 // scope IDs by their order.
2875
2876 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2877 if (!MaybeRecord)
2878 return MaybeRecord.takeError();
2879 if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2880 return error("Invalid sync scope record");
2881
2882 SmallString<16> SSN;
2883 if (convertToString(Record, 0, SSN))
2884 return error("Invalid sync scope record");
2885
2886 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2887 Record.clear();
2888 }
2889}
2890
2891/// Associate a value with its name from the given index in the provided record.
2892Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2893 unsigned NameIndex, Triple &TT) {
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];
2901
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()));
2909 return V;
2910}
2911
2912/// Helper to note and return the current location, and jump to the given
2913/// offset.
2915 BitstreamCursor &Stream) {
2916 // Save the current parsing location so we can jump back at the end
2917 // of the VST read.
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();
2922 if (!MaybeEntry)
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");
2927 return CurrentBit;
2928}
2929
2930void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2931 Function *F,
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;
2944}
2945
2946/// Read a new-style GlobalValue symbol table.
2947Error BitcodeReader::parseGlobalValueSymbolTable() {
2948 unsigned FuncBitcodeOffsetDelta =
2949 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2950
2951 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2952 return Err;
2953
2955 while (true) {
2956 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2957 if (!MaybeEntry)
2958 return MaybeEntry.takeError();
2959 BitstreamEntry Entry = MaybeEntry.get();
2960
2961 switch (Entry.Kind) {
2964 return error("Malformed block");
2966 return Error::success();
2968 break;
2969 }
2970
2971 Record.clear();
2972 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2973 if (!MaybeRecord)
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);
2982 break;
2983 }
2984 }
2985 }
2986}
2987
2988/// Parse the value symbol table at either the current parsing location or
2989/// at the given bit offset if provided.
2990Error 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).
2995 if (Offset > 0) {
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.
3001 if (UseStrtab) {
3002 if (Error Err = parseGlobalValueSymbolTable())
3003 return Err;
3004 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
3005 return JumpFailed;
3006 return Error::success();
3007 }
3008 // Otherwise, the VST will be in a similar format to a function-level VST,
3009 // and will contain symbol names.
3010 }
3011
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;
3025
3026 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
3027 return Err;
3028
3030
3031 Triple TT(TheModule->getTargetTriple());
3032
3033 // Read all the records for this value table.
3035
3036 while (true) {
3037 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3038 if (!MaybeEntry)
3039 return MaybeEntry.takeError();
3040 BitstreamEntry Entry = MaybeEntry.get();
3041
3042 switch (Entry.Kind) {
3043 case BitstreamEntry::SubBlock: // Handled for us already.
3045 return error("Malformed block");
3047 if (Offset > 0)
3048 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
3049 return JumpFailed;
3050 return Error::success();
3052 // The interesting case.
3053 break;
3054 }
3055
3056 // Read a record.
3057 Record.clear();
3058 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3059 if (!MaybeRecord)
3060 return MaybeRecord.takeError();
3061 switch (MaybeRecord.get()) {
3062 default: // Default behavior: unknown type.
3063 break;
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())
3067 return Err;
3068 ValOrErr.get();
3069 break;
3070 }
3072 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
3073 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3074 if (Error Err = ValOrErr.takeError())
3075 return Err;
3076 Value *V = ValOrErr.get();
3077
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);
3082 break;
3083 }
3086 return error("Invalid bbentry record");
3087 BasicBlock *BB = getBasicBlock(Record[0]);
3088 if (!BB)
3089 return error("Invalid bbentry record");
3090
3091 BB->setName(ValueName.str());
3092 ValueName.clear();
3093 break;
3094 }
3095 }
3096 }
3097}
3098
3099/// Decode a signed value stored with the sign bit in the LSB for dense VBR
3100/// encoding.
3101uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3102 if ((V & 1) == 0)
3103 return V >> 1;
3104 if (V != 1)
3105 return -(V >> 1);
3106 // There is no such thing as -0 with integers. "-0" really means MININT.
3107 return 1ULL << 63;
3108}
3109
3110/// Resolve all of the initializers for global values and aliases that we can.
3111Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3112 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3113 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3114 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3115
3116 GlobalInitWorklist.swap(GlobalInits);
3117 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3118 FunctionOperandWorklist.swap(FunctionOperands);
3119
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());
3125 } else {
3126 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3127 if (!MaybeC)
3128 return MaybeC.takeError();
3129 GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
3130 }
3131 GlobalInitWorklist.pop_back();
3132 }
3133
3134 while (!IndirectSymbolInitWorklist.empty()) {
3135 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3136 if (ValID >= ValueList.size()) {
3137 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3138 } else {
3139 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3140 if (!MaybeC)
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");
3147 GA->setAliasee(C);
3148 } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
3149 GI->setResolver(C);
3150 } else {
3151 return error("Expected an alias or an ifunc");
3152 }
3153 }
3154 IndirectSymbolInitWorklist.pop_back();
3155 }
3156
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);
3163 if (!MaybeC)
3164 return MaybeC.takeError();
3165 Info.F->setPersonalityFn(MaybeC.get());
3166 Info.PersonalityFn = 0;
3167 }
3168 }
3169 if (Info.Prefix) {
3170 unsigned ValID = Info.Prefix - 1;
3171 if (ValID < ValueList.size()) {
3172 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3173 if (!MaybeC)
3174 return MaybeC.takeError();
3175 Info.F->setPrefixData(MaybeC.get());
3176 Info.Prefix = 0;
3177 }
3178 }
3179 if (Info.Prologue) {
3180 unsigned ValID = Info.Prologue - 1;
3181 if (ValID < ValueList.size()) {
3182 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3183 if (!MaybeC)
3184 return MaybeC.takeError();
3185 Info.F->setPrologueData(MaybeC.get());
3186 Info.Prologue = 0;
3187 }
3188 }
3189 if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
3190 FunctionOperands.push_back(Info);
3191 FunctionOperandWorklist.pop_back();
3192 }
3193
3194 return Error::success();
3195}
3196
3198 SmallVector<uint64_t, 8> Words(Vals.size());
3199 transform(Vals, Words.begin(),
3200 BitcodeReader::decodeSignRotatedValue);
3201
3202 return APInt(TypeBits, Words);
3203}
3204
3205Error BitcodeReader::parseConstants() {
3206 if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
3207 return Err;
3208
3210
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();
3217
3218 while (true) {
3219 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3220 if (!MaybeEntry)
3221 return MaybeEntry.takeError();
3222 BitstreamEntry Entry = MaybeEntry.get();
3223
3224 switch (Entry.Kind) {
3225 case BitstreamEntry::SubBlock: // Handled for us already.
3227 return error("Malformed block");
3229 if (NextCstNo != ValueList.size())
3230 return error("Invalid constant reference");
3231 return Error::success();
3233 // The interesting case.
3234 break;
3235 }
3236
3237 // Read a record.
3238 Record.clear();
3239 Type *VoidType = Type::getVoidTy(Context);
3240 Value *V = nullptr;
3241 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3242 if (!MaybeBitCode)
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);
3248 break;
3249 case bitc::CST_CODE_POISON: // POISON
3250 V = PoisonValue::get(CurTy);
3251 break;
3252 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
3253 if (Record.empty())
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);
3270 break;
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]));
3275 break;
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");
3279
3280 auto *ScalarTy = cast<IntegerType>(CurTy->getScalarType());
3281 APInt VInt = readWideAPInt(Record, ScalarTy->getBitWidth());
3282 V = ConstantInt::get(CurTy, VInt);
3283 break;
3284 }
3285 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
3286 if (Record.empty())
3287 return error("Invalid float const record");
3288
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)));
3315 else
3316 V = PoisonValue::get(CurTy);
3317 break;
3318 }
3319
3320 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3321 if (Record.empty())
3322 return error("Invalid aggregate record");
3323
3324 unsigned Size = Record.size();
3326 for (unsigned i = 0; i != Size; ++i)
3327 Elts.push_back(Record[i]);
3328
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);
3338 } else {
3339 V = PoisonValue::get(CurTy);
3340 }
3341 break;
3342 }
3343 case bitc::CST_CODE_STRING: // STRING: [values]
3344 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3345 if (Record.empty())
3346 return error("Invalid string record");
3347
3348 SmallString<16> Elts(Record.begin(), Record.end());
3349 V = ConstantDataArray::getString(Context, Elts,
3350 BitCode == bitc::CST_CODE_CSTRING);
3351 break;
3352 }
3353 case bitc::CST_CODE_DATA: {// DATA: [n x value]
3354 if (Record.empty())
3355 return error("Invalid data record");
3356
3357 Type *EltTy;
3358 if (auto *Array = dyn_cast<ArrayType>(CurTy))
3359 EltTy = Array->getElementType();
3360 else
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);
3366 else
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);
3372 else
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);
3378 else
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);
3384 else
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);
3390 else
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);
3396 else
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);
3402 else
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);
3408 else
3409 V = ConstantDataArray::getFP(EltTy, Elts);
3410 } else {
3411 return error("Invalid type for value");
3412 }
3413 break;
3414 }
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);
3419 if (Opc < 0) {
3420 V = PoisonValue::get(CurTy); // Unknown unop.
3421 } else {
3422 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
3423 }
3424 break;
3425 }
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);
3430 if (Opc < 0) {
3431 V = PoisonValue::get(CurTy); // Unknown binop.
3432 } else {
3433 uint8_t Flags = 0;
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))
3441 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
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))
3449 }
3450 }
3451 V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
3452 {(unsigned)Record[1], (unsigned)Record[2]});
3453 }
3454 break;
3455 }
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]);
3460 if (Opc < 0) {
3461 V = PoisonValue::get(CurTy); // Unknown cast.
3462 } else {
3463 unsigned OpTyID = Record[1];
3464 Type *OpTy = getTypeByID(OpTyID);
3465 if (!OpTy)
3466 return error("Invalid cast constexpr record");
3467 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
3468 }
3469 break;
3470 }
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
3474 // operands]
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
3477 // operands]
3478 if (Record.size() < 2)
3479 return error("Constant GEP record must have at least two elements");
3480 unsigned OpNum = 0;
3481 Type *PointeeType = nullptr;
3484 BitCode == bitc::CST_CODE_CE_GEP || Record.size() % 2)
3485 PointeeType = getTypeByID(Record[OpNum++]);
3486
3487 uint64_t Flags = 0;
3488 std::optional<ConstantRange> InRange;
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
3494 // bother.
3495 (void)InRangeIndex;
3496 } else if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE) {
3497 Flags = Record[OpNum++];
3498 Expected<ConstantRange> MaybeInRange =
3499 readBitWidthAndConstantRange(Record, OpNum);
3500 if (!MaybeInRange)
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);
3507
3509 unsigned BaseTypeID = Record[OpNum];
3510 while (OpNum != Record.size()) {
3511 unsigned ElTyID = Record[OpNum++];
3512 Type *ElTy = getTypeByID(ElTyID);
3513 if (!ElTy)
3514 return error("Invalid getelementptr constexpr record");
3515 Elts.push_back(Record[OpNum++]);
3516 }
3517
3518 if (Elts.size() < 1)
3519 return error("Invalid gep with no operands");
3520
3521 Type *BaseType = getTypeByID(BaseTypeID);
3522 if (isa<VectorType>(BaseType)) {
3523 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3524 BaseType = getTypeByID(BaseTypeID);
3525 }
3526
3527 PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
3528 if (!OrigPtrTy)
3529 return error("GEP base operand must be pointer or vector of pointer");
3530
3531 if (!PointeeType) {
3532 PointeeType = getPtrElementTypeByID(BaseTypeID);
3533 if (!PointeeType)
3534 return error("Missing element type for old-style constant GEP");
3535 }
3536
3537 V = BitcodeConstant::create(
3538 Alloc, CurTy,
3539 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType, InRange},
3540 Elts);
3541 break;
3542 }
3543 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
3544 if (Record.size() < 3)
3545 return error("Invalid select constexpr record");
3546
3547 V = BitcodeConstant::create(
3548 Alloc, CurTy, Instruction::Select,
3549 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3550 break;
3551 }
3553 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3554 if (Record.size() < 3)
3555 return error("Invalid extractelement constexpr record");
3556 unsigned OpTyID = Record[0];
3557 VectorType *OpTy =
3558 dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
3559 if (!OpTy)
3560 return error("Invalid extractelement constexpr record");
3561 unsigned IdxRecord;
3562 if (Record.size() == 4) {
3563 unsigned IdxTyID = Record[2];
3564 Type *IdxTy = getTypeByID(IdxTyID);
3565 if (!IdxTy)
3566 return error("Invalid extractelement constexpr record");
3567 IdxRecord = Record[3];
3568 } else {
3569 // Deprecated, but still needed to read old bitcode files.
3570 IdxRecord = Record[2];
3571 }
3572 V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
3573 {(unsigned)Record[1], IdxRecord});
3574 break;
3575 }
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");
3581 unsigned IdxRecord;
3582 if (Record.size() == 4) {
3583 unsigned IdxTyID = Record[2];
3584 Type *IdxTy = getTypeByID(IdxTyID);
3585 if (!IdxTy)
3586 return error("Invalid insertelement constexpr record");
3587 IdxRecord = Record[3];
3588 } else {
3589 // Deprecated, but still needed to read old bitcode files.
3590 IdxRecord = Record[2];
3591 }
3592 V = BitcodeConstant::create(
3593 Alloc, CurTy, Instruction::InsertElement,
3594 {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
3595 break;
3596 }
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]});
3604 break;
3605 }
3606 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3607 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3608 VectorType *OpTy =
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]});
3615 break;
3616 }
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);
3622 if (!OpTy)
3623 return error("Invalid cmp constexpr record");
3624 V = BitcodeConstant::create(
3625 Alloc, CurTy,
3626 {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
3627 : Instruction::ICmp),
3628 (uint8_t)Record[3]},
3629 {(unsigned)Record[1], (unsigned)Record[2]});
3630 break;
3631 }
3632 // This maintains backward compatibility, pre-asm dialect keywords.
3633 // Deprecated, but still needed to read old bitcode files.
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");
3646
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);
3652 if (!CurElemTy)
3653 return error("Missing element type for old-style inlineasm");
3654 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3655 HasSideEffects, IsAlignStack);
3656 break;
3657 }
3658 // This version adds support for the asm dialect keywords (e.g.,
3659 // inteldialect).
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");
3673
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);
3679 if (!CurElemTy)
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));
3684 break;
3685 }
3686 // This version adds support for the unwind keyword.
3688 if (Record.size() < 2)
3689 return error("Invalid inlineasm record");
3690 unsigned OpNum = 0;
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;
3696 ++OpNum;
3697 unsigned AsmStrSize = Record[OpNum];
3698 ++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");
3704
3705 for (unsigned i = 0; i != AsmStrSize; ++i)
3706 AsmStr += (char)Record[OpNum + i];
3707 ++OpNum;
3708 for (unsigned i = 0; i != ConstStrSize; ++i)
3709 ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3710 UpgradeInlineAsmString(&AsmStr);
3711 if (!CurElemTy)
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);
3716 break;
3717 }
3718 // This version adds explicit function type.
3720 if (Record.size() < 3)
3721 return error("Invalid inlineasm record");
3722 unsigned OpNum = 0;
3723 auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
3724 ++OpNum;
3725 if (!FnTy)
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;
3732 ++OpNum;
3733 unsigned AsmStrSize = Record[OpNum];
3734 ++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");
3740
3741 for (unsigned i = 0; i != AsmStrSize; ++i)
3742 AsmStr += (char)Record[OpNum + i];
3743 ++OpNum;
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);
3749 break;
3750 }
3752 if (Record.size() < 3)
3753 return error("Invalid blockaddress record");
3754 unsigned FnTyID = Record[0];
3755 Type *FnTy = getTypeByID(FnTyID);
3756 if (!FnTy)
3757 return error("Invalid blockaddress record");
3758 V = BitcodeConstant::create(
3759 Alloc, CurTy,
3760 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3761 Record[1]);
3762 break;
3763 }
3765 if (Record.size() < 2)
3766 return error("Invalid dso_local record");
3767 unsigned GVTyID = Record[0];
3768 Type *GVTy = getTypeByID(GVTyID);
3769 if (!GVTy)
3770 return error("Invalid dso_local record");
3771 V = BitcodeConstant::create(
3772 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3773 break;
3774 }
3776 if (Record.size() < 2)
3777 return error("Invalid no_cfi record");
3778 unsigned GVTyID = Record[0];
3779 Type *GVTy = getTypeByID(GVTyID);
3780 if (!GVTy)
3781 return error("Invalid no_cfi record");
3782 V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3783 Record[1]);
3784 break;
3785 }
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]});
3794 break;
3795 }
3796 }
3797
3798 assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
3799 if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
3800 return Err;
3801 ++NextCstNo;
3802 }
3803}
3804
3805Error BitcodeReader::parseUseLists() {
3806 if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3807 return Err;
3808
3809 // Read all the records.
3811
3812 while (true) {
3813 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3814 if (!MaybeEntry)
3815 return MaybeEntry.takeError();
3816 BitstreamEntry Entry = MaybeEntry.get();
3817
3818 switch (Entry.Kind) {
3819 case BitstreamEntry::SubBlock: // Handled for us already.
3821 return error("Malformed block");
3823 return Error::success();
3825 // The interesting case.
3826 break;
3827 }
3828
3829 // Read a use list record.
3830 Record.clear();
3831 bool IsBB = false;
3832 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3833 if (!MaybeRecord)
3834 return MaybeRecord.takeError();
3835 switch (MaybeRecord.get()) {
3836 default: // Default behavior: unknown type.
3837 break;
3839 IsBB = true;
3840 [[fallthrough]];
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();
3847
3848 Value *V;
3849 if (IsBB) {
3850 assert(ID < FunctionBBs.size() && "Basic block not found");
3851 V = FunctionBBs[ID];
3852 } else
3853 V = ValueList[ID];
3854 unsigned NumUses = 0;
3856 for (const Use &U : V->materialized_uses()) {
3857 if (++NumUses > Record.size())
3858 break;
3859 Order[&U] = Record[NumUses - 1];
3860 }
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.
3864 break;
3865
3866 V->sortUseList([&](const Use &L, const Use &R) {
3867 return Order.lookup(&L) < Order.lookup(&R);
3868 });
3869 break;
3870 }
3871 }
3872 }
3873}
3874
3875/// When we see the block for metadata, remember where it is and then skip it.
3876/// This lets us lazily deserialize the metadata.
3877Error BitcodeReader::rememberAndSkipMetadata() {
3878 // Save the current stream state.
3879 uint64_t CurBit = Stream.GetCurrentBitNo();
3880 DeferredMetadataInfo.push_back(CurBit);
3881
3882 // Skip over the block for now.
3883 if (Error Err = Stream.SkipBlock())
3884 return Err;
3885 return Error::success();
3886}
3887
3888Error BitcodeReader::materializeMetadata() {
3889 for (uint64_t BitPos : DeferredMetadataInfo) {
3890 // Move the bit stream to the saved position.
3891 if (Error JumpFailed = Stream.JumpToBit(BitPos))
3892 return JumpFailed;
3893 if (Error Err = MDLoader->parseModuleMetadata())
3894 return Err;
3895 }
3896
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
3899 // multiple times.
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));
3906 }
3907 }
3908
3909 DeferredMetadataInfo.clear();
3910 return Error::success();
3911}
3912
3913void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3914
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.
3917Error BitcodeReader::rememberAndSkipFunctionBody() {
3918 // Get the function we are talking about.
3919 if (FunctionsWithBodies.empty())
3920 return error("Insufficient function protos");
3921
3922 Function *Fn = FunctionsWithBodies.back();
3923 FunctionsWithBodies.pop_back();
3924
3925 // Save the current stream state.
3926 uint64_t CurBit = Stream.GetCurrentBitNo();
3927 assert(
3928 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3929 "Mismatch between VST and scanned function offsets");
3930 DeferredFunctionInfo[Fn] = CurBit;
3931
3932 // Skip over the function block for now.
3933 if (Error Err = Stream.SkipBlock())
3934 return Err;
3935 return Error::success();
3936}
3937
3938Error BitcodeReader::globalCleanup() {
3939 // Patch the initializers for globals and aliases up.
3940 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3941 return Err;
3942 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3943 return error("Malformed global initializer set");
3944
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);
3949 Function *NewFn;
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.
3954 &F, NewFn, PreserveInputDbgFormat != cl::boolOrDefault::BOU_TRUE))
3955 UpgradedIntrinsics[&F] = NewFn;
3956 // Look for functions that rely on old function attribute behavior.
3958 }
3959
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);
3968 }
3969
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();
3975}
3976
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.
3981Error BitcodeReader::rememberAndSkipFunctionBodies() {
3982 if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3983 return JumpFailed;
3984
3985 if (Stream.AtEndOfStream())
3986 return error("Could not find function in stream");
3987
3988 if (!SeenFirstFunctionBody)
3989 return error("Trying to materialize functions before seeing function blocks");
3990
3991 // An old bitcode file with the symbol table at the end would have
3992 // finished the parse greedily.
3993 assert(SeenValueSymbolTable);
3994
3996
3997 while (true) {
3998 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3999 if (!MaybeEntry)
4000 return MaybeEntry.takeError();
4001 llvm::BitstreamEntry Entry = MaybeEntry.get();
4002
4003 switch (Entry.Kind) {
4004 default:
4005 return error("Expect SubBlock");
4007 switch (Entry.ID) {
4008 default:
4009 return error("Expect function block");
4011 if (Error Err = rememberAndSkipFunctionBody())
4012 return Err;
4013 NextUnreadBit = Stream.GetCurrentBitNo();
4014 return Error::success();
4015 }
4016 }
4017 }
4018}
4019
4020Error BitcodeReaderBase::readBlockInfo() {
4022 Stream.ReadBlockInfoBlock();
4023 if (!MaybeNewBlockInfo)
4024 return MaybeNewBlockInfo.takeError();
4025 std::optional<BitstreamBlockInfo> NewBlockInfo =
4026 std::move(MaybeNewBlockInfo.get());
4027 if (!NewBlockInfo)
4028 return error("Malformed block");
4029 BlockInfo = std::move(*NewBlockInfo);
4030 return Error::success();
4031}
4032
4033Error 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);
4038
4039 if (Record.empty())
4040 return error("Invalid record");
4042 std::string OldFormatName;
4043 if (!UseStrtab) {
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;
4053 }
4054 Comdat *C = TheModule->getOrInsertComdat(Name);
4055 C->setSelectionKind(SK);
4056 ComdatList.push_back(C);
4057 return Error::success();
4058}
4059
4060static void inferDSOLocal(GlobalValue *GV) {
4061 // infer dso_local from linkage and visibility if it is not encoded.
4062 if (GV->hasLocalLinkage() ||
4064 GV->setDSOLocal(true);
4065}
4066
4069 if (V & (1 << 0))
4070 Meta.NoAddress = true;
4071 if (V & (1 << 1))
4072 Meta.NoHWAddress = true;
4073 if (V & (1 << 2))
4074 Meta.Memtag = true;
4075 if (V & (1 << 3))
4076 Meta.IsDynInit = true;
4077 return Meta;
4078}
4079
4080Error 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);
4089
4090 if (Record.size() < 6)
4091 return error("Invalid record");
4092 unsigned TyID = Record[0];
4093 Type *Ty = getTypeByID(TyID);
4094 if (!Ty)
4095 return error("Invalid record");
4096 bool isConstant = Record[1] & 1;
4097 bool explicitType = Record[1] & 2;
4098 unsigned AddressSpace;
4099 if (explicitType) {
4100 AddressSpace = Record[1] >> 2;
4101 } else {
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);
4107 if (!Ty)
4108 return error("Missing element type for old-style global");
4109 }
4110
4111 uint64_t RawLinkage = Record[3];
4113 MaybeAlign Alignment;
4114 if (Error Err = parseAlignmentValue(Record[4], Alignment))
4115 return Err;
4116 std::string Section;
4117 if (Record[5]) {
4118 if (Record[5] - 1 >= SectionTable.size())
4119 return error("Invalid ID");
4120 Section = SectionTable[Record[5] - 1];
4121 }
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]);
4127
4128 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4129 if (Record.size() > 7)
4131
4132 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4133 if (Record.size() > 8)
4134 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
4135
4136 bool ExternallyInitialized = false;
4137 if (Record.size() > 9)
4138 ExternallyInitialized = Record[9];
4139
4140 GlobalVariable *NewGV =
4141 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
4142 nullptr, TLM, AddressSpace, ExternallyInitialized);
4143 if (Alignment)
4144 NewGV->setAlignment(*Alignment);
4145 if (!Section.empty())
4146 NewGV->setSection(Section);
4147 NewGV->setVisibility(Visibility);
4148 NewGV->setUnnamedAddr(UnnamedAddr);
4149
4150 if (Record.size() > 10) {
4151 // A GlobalValue with local linkage cannot have a DLL storage class.
4152 if (!NewGV->hasLocalLinkage()) {
4154 }
4155 } else {
4156 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
4157 }
4158
4159 ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
4160
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));
4164
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]);
4170 }
4171 } else if (hasImplicitComdat(RawLinkage)) {
4172 ImplicitComdatObjects.insert(NewGV);
4173 }
4174
4175 if (Record.size() > 12) {
4176 auto AS = getAttributes(Record[12]).getFnAttrs();
4177 NewGV->setAttributes(AS);
4178 }
4179
4180 if (Record.size() > 13) {
4182 }
4183 inferDSOLocal(NewGV);
4184
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]));
4188
4189 if (Record.size() > 16 && Record[16]) {
4192 NewGV->setSanitizerMetadata(Meta);
4193 }
4194
4195 if (Record.size() > 17 && Record[17]) {
4196 if (auto CM = getDecodedCodeModel(Record[17]))
4197 NewGV->setCodeModel(*CM);
4198 else
4199 return error("Invalid global variable code model");
4200 }
4201
4202 return Error::success();
4203}
4204
4205void 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); });
4210 }
4211}
4212
4213Error 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);
4220
4221 if (Record.size() < 8)
4222 return error("Invalid record");
4223 unsigned FTyID = Record[0];
4224 Type *FTy = getTypeByID(FTyID);
4225 if (!FTy)
4226 return error("Invalid record");
4227 if (isa<PointerType>(FTy)) {
4228 FTyID = getContainedTypeID(FTyID, 0);
4229 FTy = getTypeByID(FTyID);
4230 if (!FTy)
4231 return error("Missing element type for old-style function");
4232 }
4233
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");
4239
4240 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4241 if (Record.size() > 16)
4242 AddrSpace = Record[16];
4243
4244 Function *Func =
4245 Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
4246 AddrSpace, Name, TheModule);
4247
4248 assert(Func->getFunctionType() == FTy &&
4249 "Incorrect fully specified type provided for function");
4250 FunctionTypeIDs[Func] = FTyID;
4251
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);
4258
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))
4266 continue;
4267
4268 if (Func->getParamAttribute(i, Kind).getValueAsType())
4269 continue;
4270
4271 Func->removeParamAttr(i, Kind);
4272
4273 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4274 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4275 if (!PtrEltTy)
4276 return error("Missing param element type for attribute upgrade");
4277
4278 Attribute NewAttr;
4279 switch (Kind) {
4280 case Attribute::ByVal:
4281 NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4282 break;
4283 case Attribute::StructRet:
4284 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4285 break;
4286 case Attribute::InAlloca:
4287 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4288 break;
4289 default:
4290 llvm_unreachable("not an upgraded type attribute");
4291 }
4292
4293 Func->addParamAttr(i, NewAttr);
4294 }
4295 }
4296
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);
4301 if (!ByValTy)
4302 return error("Missing param element type for x86_intrcc upgrade");
4303 Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
4304 Func->addParamAttr(0, NewAttr);
4305 }
4306
4307 MaybeAlign Alignment;
4308 if (Error Err = parseAlignmentValue(Record[5], Alignment))
4309 return Err;
4310 if (Alignment)
4311 Func->setAlignment(*Alignment);
4312 if (Record[6]) {
4313 if (Record[6] - 1 >= SectionTable.size())
4314 return error("Invalid ID");
4315 Func->setSection(SectionTable[Record[6] - 1]);
4316 }
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]);
4325 }
4326 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4327 if (Record.size() > 9)
4328 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
4329 Func->setUnnamedAddr(UnnamedAddr);
4330
4331 FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
4332 if (Record.size() > 10)
4333 OperandInfo.Prologue = Record[10];
4334
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]));
4339 }
4340 } else {
4341 upgradeDLLImportExportLinkage(Func, RawLinkage);
4342 }
4343
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]);
4349 }
4350 } else if (hasImplicitComdat(RawLinkage)) {
4351 ImplicitComdatObjects.insert(Func);
4352 }
4353
4354 if (Record.size() > 13)
4355 OperandInfo.Prefix = Record[13];
4356
4357 if (Record.size() > 14)
4358 OperandInfo.PersonalityFn = Record[14];
4359
4360 if (Record.size() > 15) {
4361 Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
4362 }
4363 inferDSOLocal(Func);
4364
4365 // Record[16] is the address space number.
4366
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]));
4372 }
4373
4374 ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
4375
4376 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4377 FunctionOperands.push_back(OperandInfo);
4378
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.
4381 if (!isProto) {
4382 Func->setIsMaterializable(true);
4383 FunctionsWithBodies.push_back(Func);
4384 DeferredFunctionInfo[Func] = 0;
4385 }
4386 return Error::success();
4387}
4388
4389Error 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);
4401
4402 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
4403 if (Record.size() < (3 + (unsigned)NewRecord))
4404 return error("Invalid record");
4405 unsigned OpNum = 0;
4406 unsigned TypeID = Record[OpNum++];
4407 Type *Ty = getTypeByID(TypeID);
4408 if (!Ty)
4409 return error("Invalid record");
4410
4411 unsigned AddrSpace;
4412 if (!NewRecord) {
4413 auto *PTy = dyn_cast<PointerType>(Ty);
4414 if (!PTy)
4415 return error("Invalid type for value");
4416 AddrSpace = PTy->getAddressSpace();
4417 TypeID = getContainedTypeID(TypeID);
4418 Ty = getTypeByID(TypeID);
4419 if (!Ty)
4420 return error("Missing element type for old-style indirect symbol");
4421 } else {
4422 AddrSpace = Record[OpNum++];
4423 }
4424
4425 auto Val = Record[OpNum++];
4426 auto Linkage = Record[OpNum++];
4427 GlobalValue *NewGA;
4428 if (BitCode == bitc::MODULE_CODE_ALIAS ||
4429 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4430 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4431 TheModule);
4432 else
4433 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4434 nullptr, TheModule);
4435
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]));
4442 }
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())
4450 }
4451 else
4452 upgradeDLLImportExportLinkage(NewGA, Linkage);
4453 if (OpNum != Record.size())
4455 if (OpNum != Record.size())
4457 }
4458 if (OpNum != Record.size())
4459 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
4460 inferDSOLocal(NewGA);
4461
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]));
4469 }
4470
4471 ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
4472 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4473 return Error::success();
4474}
4475
4476Error 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 =
4485 LoadBitcodeIntoNewDbgInfoFormat != cl::boolOrDefault::BOU_FALSE;
4486 }
4487
4488 this->ValueTypeCallback = std::move(Callbacks.ValueType);
4489 if (ResumeBit) {
4490 if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
4491 return JumpFailed;
4492 } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4493 return Err;
4494
4496
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();
4505
4506 auto ResolveDataLayout = [&]() -> Error {
4507 if (ResolvedDataLayout)
4508 return Error::success();
4509
4510 // Datalayout and triple can't be parsed after this point.
4511 ResolvedDataLayout = true;
4512
4513 // Auto-upgrade the layout string
4514 TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4515 TentativeDataLayoutStr, TheModule->getTargetTriple());
4516
4517 // Apply override
4518 if (Callbacks.DataLayout) {
4519 if (auto LayoutOverride = (*Callbacks.DataLayout)(
4520 TheModule->getTargetTriple(), TentativeDataLayoutStr))
4521 TentativeDataLayoutStr = *LayoutOverride;
4522 }
4523
4524 // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4525 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
4526 if (!MaybeDL)
4527 return MaybeDL.takeError();
4528
4529 TheModule->setDataLayout(MaybeDL.get());
4530 return Error::success();
4531 };
4532
4533 // Read all the records for this module.
4534 while (true) {
4535 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4536 if (!MaybeEntry)
4537 return MaybeEntry.takeError();
4538 llvm::BitstreamEntry Entry = MaybeEntry.get();
4539
4540 switch (Entry.Kind) {
4542 return error("Malformed block");
4544 if (Error Err = ResolveDataLayout())
4545 return Err;
4546 return globalCleanup();
4547
4549 switch (Entry.ID) {
4550 default: // Skip unknown content.
4551 if (Error Err = Stream.SkipBlock())
4552 return Err;
4553 break;
4555 if (Error Err = readBlockInfo())
4556 return Err;
4557 break;
4559 if (Error Err = parseAttributeBlock())
4560 return Err;
4561 break;
4563 if (Error Err = parseAttributeGroupBlock())
4564 return Err;
4565 break;
4567 if (Error Err = parseTypeTable())
4568 return Err;
4569 break;
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())
4579 return Err;
4580 SeenValueSymbolTable = true;
4581 } else {
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())
4586 return Err;
4587 }
4588 break;
4590 if (Error Err = parseConstants())
4591 return Err;
4592 if (Error Err = resolveGlobalAndIndirectSymbolInits())
4593 return Err;
4594 break;
4596 if (ShouldLazyLoadMetadata) {
4597 if (Error Err = rememberAndSkipMetadata())
4598 return Err;
4599 break;
4600 }
4601 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
4602 if (Error Err = MDLoader->parseModuleMetadata())
4603 return Err;
4604 break;
4606 if (Error Err = MDLoader->parseMetadataKinds())
4607 return Err;
4608 break;
4610 if (Error Err = ResolveDataLayout())
4611 return Err;
4612
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())
4618 return Err;
4619 SeenFirstFunctionBody = true;
4620 }
4621
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))
4628 return Err;
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.
4634 } else {
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())
4642 return Err;
4643 continue;
4644 }
4645 }
4646
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())
4652 return Err;
4653
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();
4663 }
4664 break;
4666 if (Error Err = parseUseLists())
4667 return Err;
4668 break;
4670 if (Error Err = parseOperandBundleTags())
4671 return Err;
4672 break;
4674 if (Error Err = parseSyncScopeNames())
4675 return Err;
4676 break;
4677 }
4678 continue;
4679
4681 // The interesting case.
4682 break;
4683 }
4684
4685 // Read a record.
4686 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4687 if (!MaybeBitCode)
4688 return MaybeBitCode.takeError();
4689 switch (unsigned BitCode = MaybeBitCode.get()) {
4690 default: break; // Default behavior, ignore unknown content.
4692 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4693 if (!VersionOrErr)
4694 return VersionOrErr.takeError();
4695 UseRelativeIDs = *VersionOrErr >= 1;
4696 break;
4697 }
4698 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
4699 if (ResolvedDataLayout)
4700 return error("target triple too late in module");
4701 std::string S;
4702 if (convertToString(Record, 0, S))
4703 return error("Invalid record");
4704 TheModule->setTargetTriple(S);
4705 break;
4706 }
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");
4712 break;
4713 }
4714 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
4715 std::string S;
4716 if (convertToString(Record, 0, S))
4717 return error("Invalid record");
4718 TheModule->setModuleInlineAsm(S);
4719 break;
4720 }
4721 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
4722 // Deprecated, but still needed to read old bitcode files.
4723 std::string S;
4724 if (convertToString(Record, 0, S))
4725 return error("Invalid record");
4726 // Ignore value.
4727 break;
4728 }
4729 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4730 std::string S;
4731 if (convertToString(Record, 0, S))
4732 return error("Invalid record");
4733 SectionTable.push_back(S);
4734 break;
4735 }
4736 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
4737 std::string S;
4738 if (convertToString(Record, 0, S))
4739 return error("Invalid record");
4740 GCTable.push_back(S);
4741 break;
4742 }
4744 if (Error Err = parseComdatRecord(Record))
4745 return Err;
4746 break;
4747 // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4748 // written by ThinLinkBitcodeWriter. See
4749 // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4750 // record
4751 // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4753 if (Error Err = parseGlobalVarRecord(Record))
4754 return Err;
4755 break;
4757 if (Error Err = ResolveDataLayout())
4758 return Err;
4759 if (Error Err = parseFunctionRecord(Record))
4760 return Err;
4761 break;
4765 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4766 return Err;
4767 break;
4768 /// MODULE_CODE_VSTOFFSET: [offset]
4770 if (Record.empty())
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;
4776 break;
4777 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4781 return error("Invalid record");
4782 TheModule->setSourceFileName(ValueName);
4783 break;
4784 }
4785 Record.clear();
4786 }
4787 this->ValueTypeCallback = std::nullopt;
4788 return Error::success();
4789}
4790
4791Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
4792 bool IsImporting,
4793 ParserCallbacks Callbacks) {
4794 TheModule = M;
4795 MetadataLoaderCallbacks MDCallbacks;
4796 MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4797 MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4798 return getContainedTypeID(I, J);
4799 };
4800 MDCallbacks.MDType = Callbacks.MDType;
4801 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4802 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4803}
4804
4805Error 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();
4811}
4812
4813Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4814 ArrayRef<unsigned> ArgTyIDs) {
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())
4821 continue;
4822
4823 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4824 if (!PtrEltTy)
4825 return error("Missing element type for typed attribute upgrade");
4826
4827 Attribute NewAttr;
4828 switch (Kind) {
4829 case Attribute::ByVal:
4830 NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4831 break;
4832 case Attribute::StructRet:
4833 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4834 break;
4835 case Attribute::InAlloca:
4836 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4837 break;
4838 default:
4839 llvm_unreachable("not an upgraded type attribute");
4840 }
4841
4842 Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4843 }
4844 }
4845
4846 if (CB->isInlineAsm()) {
4847 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
4848 unsigned ArgNo = 0;
4849 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4850 if (!CI.hasArg())
4851 continue;
4852
4853 if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
4854 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4855 if (!ElemTy)
4856 return error("Missing element type for inline asm upgrade");
4857 Attrs = Attrs.addParamAttribute(
4858 Context, ArgNo,
4859 Attribute::get(Context, Attribute::ElementType, ElemTy));
4860 }
4861
4862 ArgNo++;
4863 }
4864 }
4865
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: {
4877 unsigned ArgNo;
4878 switch (CB->getIntrinsicID()) {
4879 case Intrinsic::aarch64_stlxr:
4880 case Intrinsic::aarch64_stxr:
4881 case Intrinsic::arm_stlex:
4882 case Intrinsic::arm_strex:
4883 ArgNo = 1;
4884 break;
4885 default:
4886 ArgNo = 0;
4887 break;
4888 }
4889 if (!Attrs.getParamElementType(ArgNo)) {
4890 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4891 if (!ElTy)
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);
4895 }
4896 break;
4897 }
4898 default:
4899 break;
4900 }
4901
4902 CB->setAttributes(Attrs);
4903 return Error::success();
4904}
4905
4906/// Lazily parse the specified function body block.
4907Error BitcodeReader::parseFunctionBody(Function *F) {
4908 if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4909 return Err;
4910
4911 // Unexpected unresolved metadata when parsing function.
4912 if (MDLoader->hasFwdRefs())
4913 return error("Invalid function metadata: incoming forward references");
4914
4915 InstructionList.clear();
4916 unsigned ModuleValueListSize = ValueList.size();
4917 unsigned ModuleMDLoaderSize = MDLoader->size();
4918
4919 // Add all the function arguments to the value table.
4920 unsigned ArgNo = 0;
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);
4927 ++ArgNo;
4928 }
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
4935 // expanded.
4937 ConstExprEdgeBBs;
4938
4939 DebugLoc LastLoc;
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();
4946 return nullptr;
4947 };
4948
4949 std::vector<OperandBundleDef> OperandBundles;
4950
4951 // Read all the records.
4953
4954 while (true) {
4955 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4956 if (!MaybeEntry)
4957 return MaybeEntry.takeError();
4958 llvm::BitstreamEntry Entry = MaybeEntry.get();
4959
4960 switch (Entry.Kind) {
4962 return error("Malformed block");
4964 goto OutOfRecordLoop;
4965
4967 switch (Entry.ID) {
4968 default: // Skip unknown content.
4969 if (Error Err = Stream.SkipBlock())
4970 return Err;
4971 break;
4973 if (Error Err = parseConstants())
4974 return Err;
4975 NextValueNo = ValueList.size();
4976 break;
4978 if (Error Err = parseValueSymbolTable())
4979 return Err;
4980 break;
4982 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4983 return Err;
4984 break;
4986 assert(DeferredMetadataInfo.empty() &&
4987 "Must read all module-level metadata before function-level");
4988 if (Error Err = MDLoader->parseFunctionMetadata())
4989 return Err;
4990 break;
4992 if (Error Err = parseUseLists())
4993 return Err;
4994 break;
4995 }
4996 continue;
4997
4999 // The interesting case.
5000 break;
5001 }
5002
5003 // Read a record.
5004 Record.clear();
5005 Instruction *I = nullptr;
5006 unsigned ResTypeID = InvalidTypeID;
5007 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5008 if (!MaybeBitCode)
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]);
5018
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);
5024 } else {
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;
5032 ++I)
5033 if (I < RE && BBRefs[I]) {
5034 BBRefs[I]->insertInto(F);
5035 FunctionBBs[I] = BBRefs[I];
5036 } else {
5037 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
5038 }
5039
5040 // Erase from the table.
5041 BasicBlockFwdRefs.erase(BBFRI);
5042 }
5043
5044 CurBB = FunctionBBs[0];
5045 continue;
5046 }
5047
5048 case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
5049 // The record should not be emitted if it's an empty list.
5050 if (Record.empty())
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);
5068 else
5069 return error("Invalid record");
5070
5071 continue;
5072
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();
5077
5078 if (!I)
5079 return error("Invalid record");
5080 I->setDebugLoc(LastLoc);
5081 I = nullptr;
5082 continue;
5083
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");
5088
5089 unsigned Line = Record[0], Col = Record[1];
5090 unsigned ScopeID = Record[2], IAID = Record[3];
5091 bool isImplicitCode = Record.size() == 5 && Record[4];
5092
5093 MDNode *Scope = nullptr, *IA = nullptr;
5094 if (ScopeID) {
5095 Scope = dyn_cast_or_null<MDNode>(
5096 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5097 if (!Scope)
5098 return error("Invalid record");
5099 }
5100 if (IAID) {
5101 IA = dyn_cast_or_null<MDNode>(
5102 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5103 if (!IA)
5104 return error("Invalid record");
5105 }
5106 LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
5107 isImplicitCode);
5108 I->setDebugLoc(LastLoc);
5109 I = nullptr;
5110 continue;
5111 }
5112 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
5113 unsigned OpNum = 0;
5114 Value *LHS;
5115 unsigned TypeID;
5116 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
5117 OpNum+1 > Record.size())
5118 return error("Invalid record");
5119
5120 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
5121 if (Opc == -1)
5122 return error("Invalid record");
5124 ResTypeID = TypeID;
5125 InstructionList.push_back(I);
5126 if (OpNum < Record.size()) {
5127 if (isa<FPMathOperator>(I)) {
5129 if (FMF.any())
5130 I->setFastMathFlags(FMF);
5131 }
5132 }
5133 break;
5134 }
5135 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
5136 unsigned OpNum = 0;
5137 Value *LHS, *RHS;
5138 unsigned TypeID;
5139 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
5140 popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
5141 CurBB) ||
5142 OpNum+1 > Record.size())
5143 return error("Invalid record");
5144
5145 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
5146 if (Opc == -1)
5147 return error("Invalid record");
5149 ResTypeID = TypeID;
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)) {
5171 if (FMF.any())
5172 I->setFastMathFlags(FMF);
5173 }
5174 }
5175 break;
5176 }
5177 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
5178 unsigned OpNum = 0;
5179 Value *Op;
5180 unsigned OpTypeID;
5181 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
5182 OpNum + 1 > Record.size())
5183 return error("Invalid record");
5184
5185 ResTypeID = Record[OpNum++];
5186 Type *ResTy = getTypeByID(ResTypeID);
5187 int Opc = getDecodedCastOpcode(Record[OpNum++]);
5188
5189 if (Opc == -1 || !ResTy)
5190 return error("Invalid record");
5191 Instruction *Temp = nullptr;
5192 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
5193 if (Temp) {
5194 InstructionList.push_back(Temp);
5195 assert(CurBB && "No current BB?");
5196 Temp->insertInto(CurBB, CurBB->end());
5197 }
5198 } else {
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);
5203 }
5204
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);
5214 }
5215 if (isa<FPMathOperator>(I)) {
5217 if (FMF.any())
5218 I->setFastMathFlags(FMF);
5219 }
5220 }
5221
5222 InstructionList.push_back(I);
5223 break;
5224 }
5227 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
5228 unsigned OpNum = 0;
5229
5230 unsigned TyID;
5231 Type *Ty;
5232 GEPNoWrapFlags NW;
5233
5234 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
5235 NW = toGEPNoWrapFlags(Record[OpNum++]);
5236 TyID = Record[OpNum++];
5237 Ty = getTypeByID(TyID);
5238 } else {
5241 TyID = InvalidTypeID;
5242 Ty = nullptr;
5243 }
5244
5245 Value *BasePtr;
5246 unsigned BasePtrTypeID;
5247 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5248 CurBB))
5249 return error("Invalid record");
5250
5251 if (!Ty) {
5252 TyID = getContainedTypeID(BasePtrTypeID);
5253 if (BasePtr->getType()->isVectorTy())
5254 TyID = getContainedTypeID(TyID);
5255 Ty = getTypeByID(TyID);
5256 }
5257
5259 while (OpNum != Record.size()) {
5260 Value *Op;
5261 unsigned OpTypeID;
5262 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5263 return error("Invalid record");
5264 GEPIdx.push_back(Op);
5265 }
5266
5267 auto *GEP = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
5268 I = GEP;
5269
5270 ResTypeID = TyID;
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()) {
5276 ConstantInt *IdxC =
5277 Idx->getType()->isVectorTy()
5278 ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
5279 : cast<ConstantInt>(Idx);
5280 SubType = IdxC->getZExtValue();
5281 }
5282 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5283 ++GTI;
5284 }
5285 }
5286
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);
5292
5293 InstructionList.push_back(I);
5294 GEP->setNoWrapFlags(NW);
5295 break;
5296 }
5297
5299 // EXTRACTVAL: [opty, opval, n x indices]
5300 unsigned OpNum = 0;
5301 Value *Agg;
5302 unsigned AggTypeID;
5303 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5304 return error("Invalid record");
5305 Type *Ty = Agg->getType();
5306
5307 unsigned RecSize = Record.size();
5308 if (OpNum == RecSize)
5309 return error("EXTRACTVAL: Invalid instruction with 0 indices");
5310
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];
5317
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);
5327
5328 if (IsStruct) {
5329 Ty = Ty->getStructElementType(Index);
5330 ResTypeID = getContainedTypeID(ResTypeID, Index);
5331 } else {
5332 Ty = Ty->getArrayElementType();
5333 ResTypeID = getContainedTypeID(ResTypeID);
5334 }
5335 }
5336
5337 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
5338 InstructionList.push_back(I);
5339 break;
5340 }
5341
5343 // INSERTVAL: [opty, opval, opty, opval, n x indices]
5344 unsigned OpNum = 0;
5345 Value *Agg;
5346 unsigned AggTypeID;
5347 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5348 return error("Invalid record");
5349 Value *Val;
5350 unsigned ValTypeID;
5351 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5352 return error("Invalid record");
5353
5354 unsigned RecSize = Record.size();
5355 if (OpNum == RecSize)
5356 return error("INSERTVAL: Invalid instruction with 0 indices");
5357
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];
5364
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");
5373
5374 INSERTVALIdx.push_back((unsigned)Index);
5375 if (IsStruct)
5376 CurTy = CurTy->getStructElementType(Index);
5377 else
5378 CurTy = CurTy->getArrayElementType();
5379 }
5380
5381 if (CurTy != Val->getType())
5382 return error("Inserted value type doesn't match aggregate type");
5383
5384 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
5385 ResTypeID = AggTypeID;
5386 InstructionList.push_back(I);
5387 break;
5388 }
5389
5390 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
5391 // obsolete form of select
5392 // handles select i1 ... in old bitcode
5393 unsigned OpNum = 0;
5395 unsigned TypeID;
5396 Type *CondType = Type::getInt1Ty(Context);
5397 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
5398 CurBB) ||
5399 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
5400 FalseVal, CurBB) ||
5401 popValue(Record, OpNum, NextValueNo, CondType,
5402 getVirtualTypeID(CondType), Cond, CurBB))
5403 return error("Invalid record");
5404
5405 I = SelectInst::Create(Cond, TrueVal, FalseVal);
5406 ResTypeID = TypeID;
5407 InstructionList.push_back(I);
5408 break;
5409 }
5410
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]
5414 unsigned OpNum = 0;
5416 unsigned ValTypeID, CondTypeID;
5417 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5418 CurBB) ||
5419 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
5420 FalseVal, CurBB) ||
5421 getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
5422 return error("Invalid record");
5423
5424 // select condition can be either i1 or [N x i1]
5425 if (VectorType* vector_type =
5426 dyn_cast<VectorType>(Cond->getType())) {
5427 // expect <n x i1>
5428 if (vector_type->getElementType() != Type::getInt1Ty(Context))
5429 return error("Invalid type for value");
5430 } else {
5431 // expect i1
5432 if (Cond->getType() != Type::getInt1Ty(Context))
5433 return error("Invalid type for value");
5434 }
5435
5436 I = SelectInst::Create(Cond, TrueVal, FalseVal);
5437 ResTypeID = ValTypeID;
5438 InstructionList.push_back(I);
5439 if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
5441 if (FMF.any())
5442 I->setFastMathFlags(FMF);
5443 }
5444 break;
5445 }
5446
5447 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
5448 unsigned OpNum = 0;
5449 Value *Vec, *Idx;
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");
5457 ResTypeID = getContainedTypeID(VecTypeID);
5458 InstructionList.push_back(I);
5459 break;
5460 }
5461
5462 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
5463 unsigned OpNum = 0;
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);
5478 break;
5479 }
5480
5481 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5482 unsigned OpNum = 0;
5483 Value *Vec1, *Vec2, *Mask;
5484 unsigned Vec1TypeID;
5485 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5486 CurBB) ||
5487 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
5488 Vec2, CurBB))
5489 return error("Invalid record");
5490
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");
5496
5497 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
5498 ResTypeID =
5499 getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
5500 InstructionList.push_back(I);
5501 break;
5502 }
5503
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
5510
5511 unsigned OpNum = 0;
5512 Value *LHS, *RHS;
5513 unsigned LHSTypeID;
5514 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5515 popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
5516 CurBB))
5517 return error("Invalid record");
5518
5519 if (OpNum >= Record.size())
5520 return error(
5521 "Invalid record: operand number exceeded available operands");
5522
5524 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5525 FastMathFlags FMF;
5526 if (IsFP && Record.size() > OpNum+1)
5527 FMF = getDecodedFastMathFlags(Record[++OpNum]);
5528
5529 if (IsFP) {
5530 if (!CmpInst::isFPPredicate(PredVal))
5531 return error("Invalid fcmp predicate");
5532 I = new FCmpInst(PredVal, LHS, RHS);
5533 } else {
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();
5540 }
5541
5542 if (OpNum + 1 != Record.size())
5543 return error("Invalid record");
5544
5545 ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
5546 if (LHS->getType()->isVectorTy())
5547 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5548
5549 if (FMF.any())
5550 I->setFastMathFlags(FMF);
5551 InstructionList.push_back(I);
5552 break;
5553 }
5554
5555 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5556 {
5557 unsigned Size = Record.size();
5558 if (Size == 0) {
5559 I = ReturnInst::Create(Context);
5560 InstructionList.push_back(I);
5561 break;
5562 }
5563
5564 unsigned OpNum = 0;
5565 Value *Op = nullptr;
5566 unsigned OpTypeID;
5567 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5568 return error("Invalid record");
5569 if (OpNum != Record.size())
5570 return error("Invalid record");
5571
5572 I = ReturnInst::Create(Context, Op);
5573 InstructionList.push_back(I);
5574 break;
5575 }
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]);
5580 if (!TrueDest)
5581 return error("Invalid record");
5582
5583 if (Record.size() == 1) {
5584 I = BranchInst::Create(TrueDest);
5585 InstructionList.push_back(I);
5586 }
5587 else {
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);
5596 }
5597 break;
5598 }
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");
5602 unsigned Idx = 0;
5603 Type *TokenTy = Type::getTokenTy(Context);
5604 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5605 getVirtualTypeID(TokenTy), CurBB);
5606 if (!CleanupPad)
5607 return error("Invalid record");
5608 BasicBlock *UnwindDest = nullptr;
5609 if (Record.size() == 2) {
5610 UnwindDest = getBasicBlock(Record[Idx++]);
5611 if (!UnwindDest)
5612 return error("Invalid record");
5613 }
5614
5615 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5616 InstructionList.push_back(I);
5617 break;
5618 }
5619 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5620 if (Record.size() != 2)
5621 return error("Invalid record");
5622 unsigned Idx = 0;
5623 Type *TokenTy = Type::getTokenTy(Context);
5624 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5625 getVirtualTypeID(TokenTy), CurBB);
5626 if (!CatchPad)
5627 return error("Invalid record");
5628 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5629 if (!BB)
5630 return error("Invalid record");
5631
5632 I = CatchReturnInst::Create(CatchPad, BB);
5633 InstructionList.push_back(I);
5634 break;
5635 }
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");
5640
5641 unsigned Idx = 0;
5642
5643 Type *TokenTy = Type::getTokenTy(Context);
5644 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5645 getVirtualTypeID(TokenTy), CurBB);
5646 if (!ParentPad)
5647 return error("Invalid record");
5648
5649 unsigned NumHandlers = Record[Idx++];
5650
5652 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5653 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5654 if (!BB)
5655 return error("Invalid record");
5656 Handlers.push_back(BB);
5657 }
5658
5659 BasicBlock *UnwindDest = nullptr;
5660 if (Idx + 1 == Record.size()) {
5661 UnwindDest = getBasicBlock(Record[Idx++]);
5662 if (!UnwindDest)
5663 return error("Invalid record");
5664 }
5665
5666 if (Record.size() != Idx)
5667 return error("Invalid record");
5668
5669 auto *CatchSwitch =
5670 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5671 for (BasicBlock *Handler : Handlers)
5672 CatchSwitch->addHandler(Handler);
5673 I = CatchSwitch;
5674 ResTypeID = getVirtualTypeID(I->getType());
5675 InstructionList.push_back(I);
5676 break;
5677 }
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");
5683
5684 unsigned Idx = 0;
5685
5686 Type *TokenTy = Type::getTokenTy(Context);
5687 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5688 getVirtualTypeID(TokenTy), CurBB);
5689 if (!ParentPad)
5690 return error("Invald record");
5691
5692 unsigned NumArgOperands = Record[Idx++];
5693
5695 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5696 Value *Val;
5697 unsigned ValTypeID;
5698 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
5699 return error("Invalid record");
5700 Args.push_back(Val);
5701 }
5702
5703 if (Record.size() != Idx)
5704 return error("Invalid record");
5705
5706 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5707 I = CleanupPadInst::Create(ParentPad, Args);
5708 else
5709 I = CatchPadInst::Create(ParentPad, Args);
5710 ResTypeID = getVirtualTypeID(I->getType());
5711 InstructionList.push_back(I);
5712 break;
5713 }
5714 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5715 // Check magic
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.
5721
5722 unsigned OpTyID = Record[1];
5723 Type *OpTy = getTypeByID(OpTyID);
5724 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5725
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");
5730
5731 unsigned NumCases = Record[4];
5732
5734 InstructionList.push_back(SI);
5735
5736 unsigned CurIdx = 5;
5737 for (unsigned i = 0; i != NumCases; ++i) {
5739 unsigned NumItems = Record[CurIdx++];
5740 for (unsigned ci = 0; ci != NumItems; ++ci) {
5741 bool isSingleNumber = Record[CurIdx++];
5742
5743 APInt Low;
5744 unsigned ActiveWords = 1;
5745 if (ValueBitWidth > 64)
5746 ActiveWords = Record[CurIdx++];
5747 Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5748 ValueBitWidth);
5749 CurIdx += ActiveWords;
5750
5751 if (!isSingleNumber) {
5752 ActiveWords = 1;
5753 if (ValueBitWidth > 64)
5754 ActiveWords = Record[CurIdx++];
5755 APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5756 ValueBitWidth);
5757 CurIdx += ActiveWords;
5758
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));
5765 } else
5766 CaseVals.push_back(ConstantInt::get(Context, Low));
5767 }
5768 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5769 for (ConstantInt *Cst : CaseVals)
5770 SI->addCase(Cst, DestBB);
5771 }
5772 I = SI;
5773 break;
5774 }
5775
5776 // Old SwitchInst format without case ranges.
5777
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;
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) {
5794 delete SI;
5795 return error("Invalid record");
5796 }
5797 SI->addCase(CaseVal, DestBB);
5798 }
5799 I = SI;
5800 break;
5801 }
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);
5816 } else {
5817 delete IBI;
5818 return error("Invalid record");
5819 }
5820 }
5821 I = IBI;
5822 break;
5823 }
5824
5826 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5827 if (Record.size() < 4)
5828 return error("Invalid record");
5829 unsigned OpNum = 0;
5830 AttributeList PAL = getAttributes(Record[OpNum++]);
5831 unsigned CCInfo = Record[OpNum++];
5832 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5833 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5834
5835 unsigned FTyID = InvalidTypeID;
5836 FunctionType *FTy = nullptr;
5837 if ((CCInfo >> 13) & 1) {
5838 FTyID = Record[OpNum++];
5839 FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5840 if (!FTy)
5841 return error("Explicit invoke type is not a function type");
5842 }
5843
5844 Value *Callee;
5845 unsigned CalleeTypeID;
5846 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5847 CurBB))
5848 return error("Invalid record");
5849
5850 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5851 if (!CalleeTy)
5852 return error("Callee is not a pointer");
5853 if (!FTy) {
5854 FTyID = getContainedTypeID(CalleeTypeID);
5855 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5856 if (!FTy)
5857 return error("Callee is not of pointer to function type");
5858 }
5859 if (Record.size() < FTy->getNumParams() + OpNum)
5860 return error("Insufficient operands to call");
5861
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),
5867 ArgTyID, CurBB));
5868 ArgTyIDs.push_back(ArgTyID);
5869 if (!Ops.back())
5870 return error("Invalid record");
5871 }
5872
5873 if (!FTy->isVarArg()) {
5874 if (Record.size() != OpNum)
5875 return error("Invalid record");
5876 } else {
5877 // Read type/value pairs for varargs params.
5878 while (OpNum != Record.size()) {
5879 Value *Op;
5880 unsigned OpTypeID;
5881 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5882 return error("Invalid record");
5883 Ops.push_back(Op);
5884 ArgTyIDs.push_back(OpTypeID);
5885 }
5886 }
5887
5888 // Upgrade the bundles if needed.
5889 if (!OperandBundles.empty())
5890 UpgradeOperandBundles(OperandBundles);
5891
5892 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
5893 OperandBundles);
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)) {
5901 I->deleteValue();
5902 return Err;
5903 }
5904
5905 break;
5906 }
5907 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5908 unsigned Idx = 0;
5909 Value *Val = nullptr;
5910 unsigned ValTypeID;
5911 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5912 return error("Invalid record");
5913 I = ResumeInst::Create(Val);
5914 InstructionList.push_back(I);
5915 break;
5916 }
5918 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5919 unsigned OpNum = 0;
5920 AttributeList PAL = getAttributes(Record[OpNum++]);
5921 unsigned CCInfo = Record[OpNum++];
5922
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++]));
5928
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));
5934 if (!FTy)
5935 return error("Explicit call type is not a function type");
5936 }
5937
5938 Value *Callee;
5939 unsigned CalleeTypeID;
5940 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5941 CurBB))
5942 return error("Invalid record");
5943
5944 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5945 if (!OpTy)
5946 return error("Callee is not a pointer type");
5947 if (!FTy) {
5948 FTyID = getContainedTypeID(CalleeTypeID);
5949 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5950 if (!FTy)
5951 return error("Callee is not of pointer to function type");
5952 }
5953 if (Record.size() < FTy->getNumParams() + OpNum)
5954 return error("Insufficient operands to call");
5955
5958 // Read the fixed params.
5959 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5960 Value *Arg;
5961 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5962 if (FTy->getParamType(i)->isLabelTy())
5963 Arg = getBasicBlock(Record[OpNum]);
5964 else
5965 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5966 ArgTyID, CurBB);
5967 if (!Arg)
5968 return error("Invalid record");
5969 Args.push_back(Arg);
5970 ArgTyIDs.push_back(ArgTyID);
5971 }
5972
5973 // Read type/value pairs for varargs params.
5974 if (!FTy->isVarArg()) {
5975 if (OpNum != Record.size())
5976 return error("Invalid record");
5977 } else {
5978 while (OpNum != Record.size()) {
5979 Value *Op;
5980 unsigned OpTypeID;
5981 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5982 return error("Invalid record");
5983 Args.push_back(Op);
5984 ArgTyIDs.push_back(OpTypeID);
5985 }
5986 }
5987
5988 // Upgrade the bundles if needed.
5989 if (!OperandBundles.empty())
5990 UpgradeOperandBundles(OperandBundles);
5991
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;
5996 };
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");
6010 }
6011
6012 // Remove blockaddress arguments.
6013 Args.erase(Args.begin() + FirstBlockArg, Args.end());
6014 ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
6015
6016 // Recreate the function type with less arguments.
6017 SmallVector<Type *> ArgTys;
6018 for (Value *Arg : Args)
6019 ArgTys.push_back(Arg->getType());
6020 FTy =
6021 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6022
6023 // Update constraint string to use label constraints.
6024 std::string Constraints = IA->getConstraintString();
6025 unsigned ArgNo = 0;
6026 size_t Pos = 0;
6027 for (const auto &CI : ConstraintInfo) {
6028 if (CI.hasArg()) {
6029 if (ArgNo >= FirstBlockArg)
6030 Constraints.insert(Pos, "!");
6031 ++ArgNo;
6032 }
6033
6034 // Go to next constraint in string.
6035 Pos = Constraints.find(',', Pos);
6036 if (Pos == std::string::npos)
6037 break;
6038 ++Pos;
6039 }
6040
6041 Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
6042 IA->hasSideEffects(), IA->isAlignStack(),
6043 IA->getDialect(), IA->canThrow());
6044 }
6045 }
6046
6047 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
6048 OperandBundles);
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)) {
6056 I->deleteValue();
6057 return Err;
6058 }
6059 break;
6060 }
6061 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
6062 I = new UnreachableInst(Context);
6063 InstructionList.push_back(I);
6064 break;
6065 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
6066 if (Record.empty())
6067 return error("Invalid phi record");
6068 // The first record specifies the type.
6069 unsigned TyID = Record[0];
6070 Type *Ty = getTypeByID(TyID);
6071 if (!Ty)
6072 return error("Invalid phi record");
6073
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)) {
6080 PN->deleteValue();
6081 return error("Invalid phi record");
6082 }
6083 InstructionList.push_back(PN);
6084
6086 for (unsigned i = 0; i != NumArgs; i++) {
6087 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6088 if (!BB) {
6089 PN->deleteValue();
6090 return error("Invalid phi BB");
6091 }
6092
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
6096 // times.
6097 auto It = Args.find(BB);
6098 if (It != Args.end()) {
6099 PN->addIncoming(It->second, BB);
6100 continue;
6101 }
6102
6103 // If there already is a block for this edge (from a different phi),
6104 // use it.
6105 BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
6106 if (!EdgeBB) {
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;
6112 }
6113
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.
6117 Value *V;
6118 if (UseRelativeIDs)
6119 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6120 else
6121 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6122 if (!V) {
6123 PN->deleteValue();
6124 PhiConstExprBB->eraseFromParent();
6125 return error("Invalid phi record");
6126 }
6127
6128 if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
6129 ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
6130 PhiConstExprBB = nullptr;
6131 }
6132 PN->addIncoming(V, BB);
6133 Args.insert({BB, V});
6134 }
6135 I = PN;
6136 ResTypeID = TyID;
6137
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");
6142 if (FMF.any())
6143 I->setFastMathFlags(FMF);
6144 }
6145
6146 break;
6147 }
6148
6151 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
6152 unsigned Idx = 0;
6153 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
6154 if (Record.size() < 3)
6155 return error("Invalid record");
6156 } else {
6158 if (Record.size() < 4)
6159 return error("Invalid record");
6160 }
6161 ResTypeID = Record[Idx++];
6162 Type *Ty = getTypeByID(ResTypeID);
6163 if (!Ty)
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,
6169 nullptr))
6170 return error("Invalid record");
6171
6172 if (!F->hasPersonalityFn())
6173 F->setPersonalityFn(cast<Constant>(PersFn));
6174 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
6175 return error("Personality function mismatch");
6176 }
6177
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) {
6185 Value *Val;
6186 unsigned ValTypeID;
6187
6188 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6189 nullptr)) {
6190 delete LP;
6191 return error("Invalid record");
6192 }
6193
6195 !isa<ArrayType>(Val->getType())) &&
6196 "Catch clause has a invalid type!");
6198 isa<ArrayType>(Val->getType())) &&
6199 "Filter clause has invalid type!");
6200 LP->addClause(cast<Constant>(Val));
6201 }
6202
6203 I = LP;
6204 InstructionList.push_back(I);
6205 break;
6206 }
6207
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);
6220 if (!Ty)
6221 return error("Missing element type for old-style alloca");
6222 }
6223 unsigned OpTyID = Record[1];
6224 Type *OpTy = getTypeByID(OpTyID);
6225 Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6227 uint64_t AlignExp =
6228 Bitfield::get<APV::AlignLower>(Rec) |
6229 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
6230 if (Error Err = parseAlignmentValue(AlignExp, Align)) {
6231 return Err;
6232 }
6233 if (!Ty || !Size)
6234 return error("Invalid record");
6235
6236 const DataLayout &DL = TheModule->getDataLayout();
6237 unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
6238
6239 SmallPtrSet<Type *, 4> Visited;
6240 if (!Align && !Ty->isSized(&Visited))
6241 return error("alloca of unsized type");
6242 if (!Align)
6243 Align = DL.getPrefTypeAlign(Ty);
6244
6245 if (!Size->getType()->isIntegerTy())
6246 return error("alloca element count must have integer type");
6247
6248 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
6249 AI->setUsedWithInAlloca(InAlloca);
6250 AI->setSwiftError(SwiftError);
6251 I = AI;
6252 ResTypeID = getVirtualTypeID(AI->getType(), TyID);
6253 InstructionList.push_back(I);
6254 break;
6255 }
6256 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
6257 unsigned OpNum = 0;
6258 Value *Op;
6259 unsigned OpTypeID;
6260 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6261 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
6262 return error("Invalid record");
6263
6264 if (!isa<PointerType>(Op->getType()))
6265 return error("Load operand is not a pointer type");
6266
6267 Type *Ty = nullptr;
6268 if (OpNum + 3 == Record.size()) {
6269 ResTypeID = Record[OpNum++];
6270 Ty = getTypeByID(ResTypeID);
6271 } else {
6272 ResTypeID = getContainedTypeID(OpTypeID);
6273 Ty = getTypeByID(ResTypeID);
6274 }
6275
6276 if (!Ty)
6277 return error("Missing load type");
6278
6279 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6280 return Err;
6281
6283 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6284 return Err;
6285 SmallPtrSet<Type *, 4> Visited;
6286 if (!Align && !Ty->isSized(&Visited))
6287 return error("load of unsized type");
6288 if (!Align)
6289 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6290 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
6291 InstructionList.push_back(I);
6292 break;
6293 }
6295 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
6296 unsigned OpNum = 0;
6297 Value *Op;
6298 unsigned OpTypeID;
6299 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6300 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
6301 return error("Invalid record");
6302
6303 if (!isa<PointerType>(Op->getType()))
6304 return error("Load operand is not a pointer type");
6305
6306 Type *Ty = nullptr;
6307 if (OpNum + 5 == Record.size()) {
6308 ResTypeID = Record[OpNum++];
6309 Ty = getTypeByID(ResTypeID);
6310 } else {
6311 ResTypeID = getContainedTypeID(OpTypeID);
6312 Ty = getTypeByID(ResTypeID);
6313 }
6314
6315 if (!Ty)
6316 return error("Missing atomic load type");
6317
6318 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6319 return Err;
6320
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]);
6329
6331 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6332 return Err;
6333 if (!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);
6337 break;
6338 }
6340 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
6341 unsigned OpNum = 0;
6342 Value *Val, *Ptr;
6343 unsigned PtrTypeID, ValTypeID;
6344 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6345 return error("Invalid record");
6346
6347 if (BitCode == bitc::FUNC_CODE_INST_STORE) {
6348 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6349 return error("Invalid record");
6350 } else {
6351 ValTypeID = getContainedTypeID(PtrTypeID);
6352 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6353 ValTypeID, Val, CurBB))
6354 return error("Invalid record");
6355 }
6356
6357 if (OpNum + 2 != Record.size())
6358 return error("Invalid record");
6359
6360 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6361 return Err;
6363 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6364 return Err;
6365 SmallPtrSet<Type *, 4> Visited;
6366 if (!Align && !Val->getType()->isSized(&Visited))
6367 return error("store of unsized type");
6368 if (!Align)
6369 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
6370 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6371 InstructionList.push_back(I);
6372 break;
6373 }
6376 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
6377 unsigned OpNum = 0;
6378 Value *Val, *Ptr;
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");
6386 } else {
6387 ValTypeID = getContainedTypeID(PtrTypeID);
6388 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6389 ValTypeID, Val, CurBB))
6390 return error("Invalid record");
6391 }
6392
6393 if (OpNum + 4 != Record.size())
6394 return error("Invalid record");
6395
6396 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6397 return Err;
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");
6406
6408 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6409 return Err;
6410 if (!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);
6414 break;
6415 }
6417 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6418 // failure_ordering?, weak?]
6419 const size_t NumRecords = Record.size();
6420 unsigned OpNum = 0;
6421 Value *Ptr = nullptr;
6422 unsigned PtrTypeID;
6423 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6424 return error("Invalid record");
6425
6426 if (!isa<PointerType>(Ptr->getType()))
6427 return error("Cmpxchg operand is not a pointer type");
6428
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");
6434
6435 Value *New = nullptr;
6436 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
6437 New, CurBB) ||
6438 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6439 return error("Invalid record");
6440
6441 const AtomicOrdering SuccessOrdering =
6442 getDecodedOrdering(Record[OpNum + 1]);
6443 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6444 SuccessOrdering == AtomicOrdering::Unordered)
6445 return error("Invalid record");
6446
6447 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6448
6449 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6450 return Err;
6451
6452 const AtomicOrdering FailureOrdering =
6453 NumRecords < 7
6455 : getDecodedOrdering(Record[OpNum + 3]);
6456
6457 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6458 FailureOrdering == AtomicOrdering::Unordered)
6459 return error("Invalid record");
6460
6461 const Align Alignment(
6462 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6463
6464 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6465 FailureOrdering, SSID);
6466 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
6467
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());
6474 ResTypeID = CmpTypeID;
6475 } else {
6476 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
6477 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6478 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6479 }
6480
6481 InstructionList.push_back(I);
6482 break;
6483 }
6485 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6486 // failure_ordering, weak, align?]
6487 const size_t NumRecords = Record.size();
6488 unsigned OpNum = 0;
6489 Value *Ptr = nullptr;
6490 unsigned PtrTypeID;
6491 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6492 return error("Invalid record");
6493
6494 if (!isa<PointerType>(Ptr->getType()))
6495 return error("Cmpxchg operand is not a pointer type");
6496
6497 Value *Cmp = nullptr;
6498 unsigned CmpTypeID;
6499 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6500 return error("Invalid record");
6501
6502 Value *Val = nullptr;
6503 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
6504 CurBB))
6505 return error("Invalid record");
6506
6507 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6508 return error("Invalid record");
6509
6510 const bool IsVol = Record[OpNum];
6511
6512 const AtomicOrdering SuccessOrdering =
6513 getDecodedOrdering(Record[OpNum + 1]);
6514 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6515 return error("Invalid cmpxchg success ordering");
6516
6517 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6518
6519 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6520 return Err;
6521
6522 const AtomicOrdering FailureOrdering =
6523 getDecodedOrdering(Record[OpNum + 3]);
6524 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6525 return error("Invalid cmpxchg failure ordering");
6526
6527 const bool IsWeak = Record[OpNum + 4];
6528
6529 MaybeAlign Alignment;
6530
6531 if (NumRecords == (OpNum + 6)) {
6532 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6533 return Err;
6534 }
6535 if (!Alignment)
6536 Alignment =
6537 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6538
6539 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6540 FailureOrdering, SSID);
6541 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6542 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6543
6544 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6545 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6546
6547 InstructionList.push_back(I);
6548 break;
6549 }
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();
6555 unsigned OpNum = 0;
6556
6557 Value *Ptr = nullptr;
6558 unsigned PtrTypeID;
6559 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6560 return error("Invalid record");
6561
6562 if (!isa<PointerType>(Ptr->getType()))
6563 return error("Invalid record");
6564
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");
6572 } else {
6573 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6574 return error("Invalid record");
6575 }
6576
6577 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6578 return error("Invalid record");
6579
6584 return error("Invalid record");
6585
6586 const bool IsVol = Record[OpNum + 1];
6587
6589 if (Ordering == AtomicOrdering::NotAtomic ||
6590 Ordering == AtomicOrdering::Unordered)
6591 return error("Invalid record");
6592
6593 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6594
6595 MaybeAlign Alignment;
6596
6597 if (NumRecords == (OpNum + 5)) {
6598 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6599 return Err;
6600 }
6601
6602 if (!Alignment)
6603 Alignment =
6604 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6605
6606 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
6607 ResTypeID = ValTypeID;
6608 cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6609
6610 InstructionList.push_back(I);
6611 break;
6612 }
6613 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
6614 if (2 != Record.size())
6615 return error("Invalid record");
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);
6624 break;
6625 }
6627 // DbgLabelRecords are placed after the Instructions that they are
6628 // attached to.
6629 SeenDebugRecord = true;
6630 Instruction *Inst = getLastInstruction();
6631 if (!Inst)
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.
6638 }
6643 // DbgVariableRecords are placed after the Instructions that they are
6644 // attached to.
6645 SeenDebugRecord = true;
6646 Instruction *Inst = getLastInstruction();
6647 if (!Inst)
6648 return error("Invalid dbg record: missing instruction");
6649
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)
6655 // ..., Value
6656 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
6657 // ..., LocationMetadata
6658 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
6659 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
6660 unsigned Slot = 0;
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++]));
6667
6668 // Union field (3: LocationMetadata | Value).
6669 Metadata *RawLocation = nullptr;
6671 Value *V = nullptr;
6672 unsigned TyID = 0;
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");
6681 (void)SlotBefore;
6682 assert((SlotBefore == Slot - 1) && "unexpected fwd ref");
6683 RawLocation = ValueAsMetadata::get(V);
6684 } else {
6685 RawLocation = getFnMetadataByID(Record[Slot++]);
6686 }
6687
6688 DbgVariableRecord *DVR = nullptr;
6689 switch (BitCode) {
6692 DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6693 DbgVariableRecord::LocationType::Value);
6694 break;
6696 DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6697 DbgVariableRecord::LocationType::Declare);
6698 break;
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,
6705 DIL);
6706 break;
6707 }
6708 default:
6709 llvm_unreachable("Unknown DbgVariableRecord bitcode");
6710 }
6711 Inst->getParent()->insertDbgRecordBefore(DVR, Inst->getIterator());
6712 continue; // This isn't an instruction.
6713 }
6715 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6716 if (Record.size() < 3)
6717 return error("Invalid record");
6718
6719 unsigned OpNum = 0;
6720 AttributeList PAL = getAttributes(Record[OpNum++]);
6721 unsigned CCInfo = Record[OpNum++];
6722
6723 FastMathFlags FMF;
6724 if ((CCInfo >> bitc::CALL_FMF) & 1) {
6725 FMF = getDecodedFastMathFlags(Record[OpNum++]);
6726 if (!FMF.any())
6727 return error("Fast math flags indicator set for call with no FMF");
6728 }
6729
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));
6735 if (!FTy)
6736 return error("Explicit call type is not a function type");
6737 }
6738
6739 Value *Callee;
6740 unsigned CalleeTypeID;
6741 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6742 CurBB))
6743 return error("Invalid record");
6744
6745 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
6746 if (!OpTy)
6747 return error("Callee is not a pointer type");
6748 if (!FTy) {
6749 FTyID = getContainedTypeID(CalleeTypeID);
6750 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6751 if (!FTy)
6752 return error("Callee is not of pointer to function type");
6753 }
6754 if (Record.size() < FTy->getNumParams() + OpNum)
6755 return error("Insufficient operands to call");
6756
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]));
6764 else
6765 Args.push_back(getValue(Record, OpNum, NextValueNo,
6766 FTy->getParamType(i), ArgTyID, CurBB));
6767 ArgTyIDs.push_back(ArgTyID);
6768 if (!Args.back())
6769 return error("Invalid record");
6770 }
6771
6772 // Read type/value pairs for varargs params.
6773 if (!FTy->isVarArg()) {
6774 if (OpNum != Record.size())
6775 return error("Invalid record");
6776 } else {
6777 while (OpNum != Record.size()) {
6778 Value *Op;
6779 unsigned OpTypeID;
6780 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6781 return error("Invalid record");
6782 Args.push_back(Op);
6783 ArgTyIDs.push_back(OpTypeID);
6784 }
6785 }
6786
6787 // Upgrade the bundles if needed.
6788 if (!OperandBundles.empty())
6789 UpgradeOperandBundles(OperandBundles);
6790
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));
6798 if (CCInfo & (1 << bitc::CALL_TAIL))
6799 TCK = CallInst::TCK_Tail;
6800 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
6802 if (CCInfo & (1 << bitc::CALL_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)) {
6809 I->deleteValue();
6810 return Err;
6811 }
6812 if (FMF.any()) {
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);
6817 }
6818 break;
6819 }
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);
6832 break;
6833 }
6834
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.
6839
6840 if (Record.empty() || Record[0] >= BundleTags.size())
6841 return error("Invalid record");
6842
6843 std::vector<Value *> Inputs;
6844
6845 unsigned OpNum = 1;
6846 while (OpNum != Record.size()) {
6847 Value *Op;
6848 if (getValueOrMetadata(Record, OpNum, NextValueNo, Op, CurBB))
6849 return error("Invalid record");
6850 Inputs.push_back(Op);
6851 }
6852
6853 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6854 continue;
6855 }
6856
6857 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6858 unsigned OpNum = 0;
6859 Value *Op = nullptr;
6860 unsigned OpTypeID;
6861 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6862 return error("Invalid record");
6863 if (OpNum != Record.size())
6864 return error("Invalid record");
6865
6866 I = new FreezeInst(Op);
6867 ResTypeID = OpTypeID;
6868 InstructionList.push_back(I);
6869 break;
6870 }
6871 }
6872
6873 // Add instruction to end of current BB. If there is no current BB, reject
6874 // this file.
6875 if (!CurBB) {
6876 I->deleteValue();
6877 return error("Invalid instruction with no BB");
6878 }
6879 if (!OperandBundles.empty()) {
6880 I->deleteValue();
6881 return error("Operand bundles found with no consumer");
6882 }
6883 I->insertInto(CurBB, CurBB->end());
6884
6885 // If this was a terminator instruction, move to the next block.
6886 if (I->isTerminator()) {
6887 ++CurBBNo;
6888 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
6889 }
6890
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))
6896 return Err;
6897 }
6898 }
6899
6900OutOfRecordLoop:
6901
6902 if (!OperandBundles.empty())
6903 return error("Operand bundles found with no consumer");
6904
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()));
6912 delete A;
6913 }
6914 }
6915 return error("Never resolved value found in function");
6916 }
6917 }
6918
6919 // Unexpected unresolved metadata about to be dropped.
6920 if (MDLoader->hasFwdRefs())
6921 return error("Invalid function metadata: outgoing forward refs");
6922
6923 if (PhiConstExprBB)
6924 PhiConstExprBB->eraseFromParent();
6925
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);
6934 }
6935
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();
6941}
6942
6943/// Find the function body in the bitcode stream
6944Error BitcodeReader::findFunctionInStream(
6945 Function *F,
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())
6956 return Err;
6957 }
6958 return Error::success();
6959}
6960
6961SyncScope::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.
6966 return SSIDs[Val];
6967}
6968
6969//===----------------------------------------------------------------------===//
6970// GVMaterializer implementation
6971//===----------------------------------------------------------------------===//
6972
6973Error 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();
6978
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))
6985 return Err;
6986
6987 // Materialize metadata before parsing any function bodies.
6988 if (Error Err = materializeMetadata())
6989 return Err;
6990
6991 // Move the bit stream to the saved position of the deferred function body.
6992 if (Error JumpFailed = Stream.JumpToBit(DFII->second))
6993 return JumpFailed;
6994
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;
6998
6999 if (Error Err = parseFunctionBody(F))
7000 return Err;
7001 F->setIsMaterializable(false);
7002
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;
7015 }
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);
7022 else
7023 F->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired);
7024 } else {
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
7030 // autoupgrader.
7031 bool ModuleIsNewDbgInfoFormat = F->getParent()->IsNewDbgInfoFormat;
7032 if (ModuleIsNewDbgInfoFormat || !SeenDebugRecord)
7033 F->setNewDbgInfoFormatFlag(ModuleIsNewDbgInfoFormat);
7034 else
7035 F->setIsNewDbgInfoFormat(ModuleIsNewDbgInfoFormat);
7036 }
7037
7038 if (StripDebugInfo)
7039 stripDebugInfo(*F);
7040
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);
7046 }
7047
7048 // Finish fn->subprogram upgrade for materialized functions.
7049 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
7050 F->setSubprogram(SP);
7051
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))
7057 continue;
7058 MDLoader->setStripTBAA(true);
7059 stripTBAA(F->getParent());
7060 }
7061 }
7062
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")
7071 continue;
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;
7083 else
7084 continue; // ignore and continue.
7085
7086 unsigned Offset = getBranchWeightOffset(MD);
7087
7088 // If branch weight doesn't match, just strip branch weight.
7089 if (MD->getNumOperands() != Offset + ExpectedNumOperands)
7090 I.setMetadata(LLVMContext::MD_prof, nullptr);
7091 }
7092 }
7093
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()));
7098
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)));
7103 }
7104 }
7105
7106 // Look for functions that rely on old function attribute behavior.
7108
7109 // Bring in any functions that this function forward-referenced via
7110 // blockaddresses.
7111 return materializeForwardReferencedFunctions();
7112}
7113
7114Error BitcodeReader::materializeModule() {
7115 if (Error Err = materializeMetadata())
7116 return Err;
7117
7118 // Promise to materialize all forward references.
7119 WillMaterializeAllForwardRefs = true;
7120
7121 // Iterate over the module, deserializing any functions that are still on
7122 // disk.
7123 for (Function &F : *TheModule) {
7124 if (Error Err = materialize(&F))
7125 return Err;
7126 }
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
7133 : NextUnreadBit))
7134 return Err;
7135
7136 // Check that all block address forward references got resolved (as we
7137 // promised above).
7138 if (!BasicBlockFwdRefs.empty())
7139 return error("Never resolved function from blockaddress");
7140
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);
7149 }
7150 if (!I.first->use_empty())
7151 I.first->replaceAllUsesWith(I.second);
7152 I.first->eraseFromParent();
7153 }
7154 UpgradedIntrinsics.clear();
7155
7156 UpgradeDebugInfo(*TheModule);
7157
7158 UpgradeModuleFlags(*TheModule);
7159
7160 UpgradeARCRuntime(*TheModule);
7161
7162 return Error::success();
7163}
7164
7165std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
7166 return IdentifiedStructTypes;
7167}
7168
7169ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7170 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7171 StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
7172 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
7173 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7174
7175void ModuleSummaryIndexBitcodeReader::addThisModule() {
7176 TheIndex.addModule(ModulePath);
7177}
7178
7180ModuleSummaryIndexBitcodeReader::getThisModule() {
7181 return TheIndex.getModule(ModulePath);
7182}
7183
7184template <bool AllowNullValueInfo>
7185std::pair<ValueInfo, GlobalValue::GUID>
7186ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
7187 auto VGI = ValueIdToValueInfoMap[ValueId];
7188 // We can have a null value info for memprof callsite info records in
7189 // distributed ThinLTO index files when the callee function summary is not
7190 // included in the index. The bitcode writer records 0 in that case,
7191 // and the caller of this helper will set AllowNullValueInfo to true.
7192 assert(AllowNullValueInfo || std::get<0>(VGI));
7193 return VGI;
7194}
7195
7196void ModuleSummaryIndexBitcodeReader::setValueGUID(
7198 StringRef SourceFileName) {
7199 std::string GlobalId =
7200 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
7201 auto ValueGUID = GlobalValue::getGUID(GlobalId);
7202 auto OriginalNameID = ValueGUID;
7203 if (GlobalValue::isLocalLinkage(Linkage))
7204 OriginalNameID = GlobalValue::getGUID(ValueName);
7206 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
7207 << ValueName << "\n";
7208
7209 // UseStrtab is false for legacy summary formats and value names are
7210 // created on stack. In that case we save the name in a string saver in
7211 // the index so that the value name can be recorded.
7212 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7213 TheIndex.getOrInsertValueInfo(
7214 ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
7215 OriginalNameID);
7216}
7217
7218// Specialized value symbol table parser used when reading module index
7219// blocks where we don't actually create global values. The parsed information
7220// is saved in the bitcode reader for use when later parsing summaries.
7221Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7223 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7224 // With a strtab the VST is not required to parse the summary.
7225 if (UseStrtab)
7226 return Error::success();
7227
7228 assert(Offset > 0 && "Expected non-zero VST offset");
7229 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
7230 if (!MaybeCurrentBit)
7231 return MaybeCurrentBit.takeError();
7232 uint64_t CurrentBit = MaybeCurrentBit.get();
7233
7234 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
7235 return Err;
7236
7238
7239 // Read all the records for this value table.
7241
7242 while (true) {
7243 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7244 if (!MaybeEntry)
7245 return MaybeEntry.takeError();
7246 BitstreamEntry Entry = MaybeEntry.get();
7247
7248 switch (Entry.Kind) {
7249 case BitstreamEntry::SubBlock: // Handled for us already.
7251 return error("Malformed block");
7253 // Done parsing VST, jump back to wherever we came from.
7254 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
7255 return JumpFailed;
7256 return Error::success();
7258 // The interesting case.
7259 break;
7260 }
7261
7262 // Read a record.
7263 Record.clear();
7264 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7265 if (!MaybeRecord)
7266 return MaybeRecord.takeError();
7267 switch (MaybeRecord.get()) {
7268 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
7269 break;
7270 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
7272 return error("Invalid record");
7273 unsigned ValueID = Record[0];
7274 assert(!SourceFileName.empty());
7275 auto VLI = ValueIdToLinkageMap.find(ValueID);
7276 assert(VLI != ValueIdToLinkageMap.end() &&
7277 "No linkage found for VST entry?");
7278 auto Linkage = VLI->second;
7279 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7280 ValueName.clear();
7281 break;
7282 }
7284 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
7286 return error("Invalid record");
7287 unsigned ValueID = Record[0];
7288 assert(!SourceFileName.empty());
7289 auto VLI = ValueIdToLinkageMap.find(ValueID);
7290 assert(VLI != ValueIdToLinkageMap.end() &&
7291 "No linkage found for VST entry?");
7292 auto Linkage = VLI->second;
7293 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7294 ValueName.clear();
7295 break;
7296 }
7298 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
7299 unsigned ValueID = Record[0];
7300 GlobalValue::GUID RefGUID = Record[1];
7301 // The "original name", which is the second value of the pair will be
7302 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
7303 ValueIdToValueInfoMap[ValueID] =
7304 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
7305 break;
7306 }
7307 }
7308 }
7309}
7310
7311// Parse just the blocks needed for building the index out of the module.
7312// At the end of this routine the module Index is populated with a map
7313// from global value id to GlobalValueSummary objects.
7314Error ModuleSummaryIndexBitcodeReader::parseModule() {
7315 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
7316 return Err;
7317
7320 unsigned ValueId = 0;
7321
7322 // Read the index for this module.
7323 while (true) {
7324 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7325 if (!MaybeEntry)
7326 return MaybeEntry.takeError();
7327 llvm::BitstreamEntry Entry = MaybeEntry.get();
7328
7329 switch (Entry.Kind) {
7331 return error("Malformed block");
7333 return Error::success();
7334
7336 switch (Entry.ID) {
7337 default: // Skip unknown content.
7338 if (Error Err = Stream.SkipBlock())
7339 return Err;
7340 break;
7342 // Need to parse these to get abbrev ids (e.g. for VST)
7343 if (Error Err = readBlockInfo())
7344 return Err;
7345 break;
7347 // Should have been parsed earlier via VSTOffset, unless there
7348 // is no summary section.
7349 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7350 !SeenGlobalValSummary) &&
7351 "Expected early VST parse via VSTOffset record");
7352 if (Error Err = Stream.SkipBlock())
7353 return Err;
7354 break;
7357 // Add the module if it is a per-module index (has a source file name).
7358 if (!SourceFileName.empty())
7359 addThisModule();
7360 assert(!SeenValueSymbolTable &&
7361 "Already read VST when parsing summary block?");
7362 // We might not have a VST if there were no values in the
7363 // summary. An empty summary block generated when we are
7364 // performing ThinLTO compiles so we don't later invoke
7365 // the regular LTO process on them.
7366 if (VSTOffset > 0) {
7367 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7368 return Err;
7369 SeenValueSymbolTable = true;
7370 }
7371 SeenGlobalValSummary = true;
7372 if (Error Err = parseEntireSummary(Entry.ID))
7373 return Err;
7374 break;
7376 if (Error Err = parseModuleStringTable())
7377 return Err;
7378 break;
7379 }
7380 continue;
7381
7383 Record.clear();
7384 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7385 if (!MaybeBitCode)
7386 return MaybeBitCode.takeError();
7387 switch (MaybeBitCode.get()) {
7388 default:
7389 break; // Default behavior, ignore unknown content.
7391 if (Error Err = parseVersionRecord(Record).takeError())
7392 return Err;
7393 break;
7394 }
7395 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
7399 return error("Invalid record");
7400 SourceFileName = ValueName.c_str();
7401 break;
7402 }
7403 /// MODULE_CODE_HASH: [5*i32]
7405 if (Record.size() != 5)
7406 return error("Invalid hash length " + Twine(Record.size()).str());
7407 auto &Hash = getThisModule()->second;
7408 int Pos = 0;
7409 for (auto &Val : Record) {
7410 assert(!(Val >> 32) && "Unexpected high bits set");
7411 Hash[Pos++] = Val;
7412 }
7413 break;
7414 }
7415 /// MODULE_CODE_VSTOFFSET: [offset]
7417 if (Record.empty())
7418 return error("Invalid record");
7419 // Note that we subtract 1 here because the offset is relative to one
7420 // word before the start of the identification or module block, which
7421 // was historically always the start of the regular bitcode header.
7422 VSTOffset = Record[0] - 1;
7423 break;
7424 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
7425 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
7426 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
7427 // v2: [strtab offset, strtab size, v1]
7432 ArrayRef<uint64_t> GVRecord;
7433 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7434 if (GVRecord.size() <= 3)
7435 return error("Invalid record");
7436 uint64_t RawLinkage = GVRecord[3];
7438 if (!UseStrtab) {
7439 ValueIdToLinkageMap[ValueId++] = Linkage;
7440 break;
7441 }
7442
7443 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
7444 break;
7445 }
7446 }
7447 }
7448 continue;
7449 }
7450 }
7451}
7452
7454ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7456 Ret.reserve(Record.size());
7457 for (uint64_t RefValueId : Record)
7458 Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7459 return Ret;
7460}
7461
7463ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7464 bool IsOldProfileFormat,
7465 bool HasProfile, bool HasRelBF) {
7467 // In the case of new profile formats, there are two Record entries per
7468 // Edge. Otherwise, conservatively reserve up to Record.size.
7469 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7470 Ret.reserve(Record.size() / 2);
7471 else
7472 Ret.reserve(Record.size());
7473
7474 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
7475 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7476 bool HasTailCall = false;
7477 uint64_t RelBF = 0;
7478 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7479 if (IsOldProfileFormat) {
7480 I += 1; // Skip old callsitecount field
7481 if (HasProfile)
7482 I += 1; // Skip old profilecount field
7483 } else if (HasProfile)
7484 std::tie(Hotness, HasTailCall) =
7486 else if (HasRelBF)
7487 getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
7488 Ret.push_back(FunctionSummary::EdgeTy{
7489 Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
7490 }
7491 return Ret;
7492}
7493
7494static void
7497 uint64_t ArgNum = Record[Slot++];
7499 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
7500 Slot += ArgNum;
7501
7502 B.TheKind =
7504 B.Info = Record[Slot++];
7505 B.Byte = Record[Slot++];
7506 B.Bit = Record[Slot++];
7507}
7508
7510 StringRef Strtab, size_t &Slot,
7511 TypeIdSummary &TypeId) {
7512 uint64_t Id = Record[Slot++];
7513 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
7514
7515 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
7516 Wpd.SingleImplName = {Strtab.data() + Record[Slot],
7517 static_cast<size_t>(Record[Slot + 1])};
7518 Slot += 2;
7519
7520 uint64_t ResByArgNum = Record[Slot++];
7521 for (uint64_t I = 0; I != ResByArgNum; ++I)
7523}
7524
7526 StringRef Strtab,
7527 ModuleSummaryIndex &TheIndex) {
7528 size_t Slot = 0;
7529 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
7530 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
7531 Slot += 2;
7532
7533 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
7534 TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
7535 TypeId.TTRes.AlignLog2 = Record[Slot++];
7536 TypeId.TTRes.SizeM1 = Record[Slot++];
7537 TypeId.TTRes.BitMask = Record[Slot++];
7538 TypeId.TTRes.InlineBits = Record[Slot++];
7539
7540 while (Slot < Record.size())
7541 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
7542}
7543
7544std::vector<FunctionSummary::ParamAccess>
7545ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7546 auto ReadRange = [&]() {
7548 BitcodeReader::decodeSignRotatedValue(Record.front()));
7549 Record = Record.drop_front();
7551 BitcodeReader::decodeSignRotatedValue(Record.front()));
7552 Record = Record.drop_front();
7556 return Range;
7557 };
7558
7559 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7560 while (!Record.empty()) {
7561 PendingParamAccesses.emplace_back();
7562 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7563 ParamAccess.ParamNo = Record.front();
7564 Record = Record.drop_front();
7565 ParamAccess.Use = ReadRange();
7566 ParamAccess.Calls.resize(Record.front());
7567 Record = Record.drop_front();
7568 for (auto &Call : ParamAccess.Calls) {
7569 Call.ParamNo = Record.front();
7570 Record = Record.drop_front();
7571 Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front()));
7572 Record = Record.drop_front();
7573 Call.Offsets = ReadRange();
7574 }
7575 }
7576 return PendingParamAccesses;
7577}
7578
7579void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7580 ArrayRef<uint64_t> Record, size_t &Slot,
7583 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7584 TypeId.push_back({Offset, Callee});
7585}
7586
7587void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7589 size_t Slot = 0;
7592 {Strtab.data() + Record[Slot],
7593 static_cast<size_t>(Record[Slot + 1])});
7594 Slot += 2;
7595
7596 while (Slot < Record.size())
7597 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7598}
7599
7600SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7601 ArrayRef<uint64_t> Record, unsigned &I) {
7602 SmallVector<unsigned> StackIdList;
7603 // For backwards compatibility with old format before radix tree was
7604 // used, simply see if we found a radix tree array record (and thus if
7605 // the RadixArray is non-empty).
7606 if (RadixArray.empty()) {
7607 unsigned NumStackEntries = Record[I++];
7608 assert(Record.size() - I >= NumStackEntries);
7609 StackIdList.reserve(NumStackEntries);
7610 for (unsigned J = 0; J < NumStackEntries; J++) {
7611 assert(Record[I] < StackIds.size());
7612 StackIdList.push_back(
7613 TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7614 }
7615 } else {
7616 unsigned RadixIndex = Record[I++];
7617 // See the comments above CallStackRadixTreeBuilder in ProfileData/MemProf.h
7618 // for a detailed description of the radix tree array format. Briefly, the
7619 // first entry will be the number of frames, any negative values are the
7620 // negative of the offset of the next frame, and otherwise the frames are in
7621 // increasing linear order.
7622 assert(RadixIndex < RadixArray.size());
7623 unsigned NumStackIds = RadixArray[RadixIndex++];
7624 StackIdList.reserve(NumStackIds);
7625 while (NumStackIds--) {
7626 assert(RadixIndex < RadixArray.size());
7627 unsigned Elem = RadixArray[RadixIndex];
7628 if (static_cast<std::make_signed_t<unsigned>>(Elem) < 0) {
7629 RadixIndex = RadixIndex - Elem;
7630 assert(RadixIndex < RadixArray.size());
7631 Elem = RadixArray[RadixIndex];
7632 // We shouldn't encounter a second offset in a row.
7633 assert(static_cast<std::make_signed_t<unsigned>>(Elem) >= 0);
7634 }
7635 RadixIndex++;
7636 StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[Elem]));
7637 }
7638 }
7639 return StackIdList;
7640}
7641
7642static void setSpecialRefs(SmallVectorImpl<ValueInfo> &Refs, unsigned ROCnt,
7643 unsigned WOCnt) {
7644 // Readonly and writeonly refs are in the end of the refs list.
7645 assert(ROCnt + WOCnt <= Refs.size());
7646 unsigned FirstWORef = Refs.size() - WOCnt;
7647 unsigned RefNo = FirstWORef - ROCnt;
7648 for (; RefNo < FirstWORef; ++RefNo)
7649 Refs[RefNo].setReadOnly();
7650 for (; RefNo < Refs.size(); ++RefNo)
7651 Refs[RefNo].setWriteOnly();
7652}
7653
7654// Eagerly parse the entire summary block. This populates the GlobalValueSummary
7655// objects in the index.
7656Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
7657 if (Error Err = Stream.EnterSubBlock(ID))
7658 return Err;
7660
7661 // Parse version
7662 {
7663 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7664 if (!MaybeEntry)
7665 return MaybeEntry.takeError();
7666 BitstreamEntry Entry = MaybeEntry.get();
7667
7668 if (Entry.Kind != BitstreamEntry::Record)
7669 return error("Invalid Summary Block: record for version expected");
7670 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7671 if (!MaybeRecord)
7672 return MaybeRecord.takeError();
7673 if (MaybeRecord.get() != bitc::FS_VERSION)
7674 return error("Invalid Summary Block: version expected");
7675 }
7676 const uint64_t Version = Record[0];
7677 const bool IsOldProfileFormat = Version == 1;
7678 if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
7679 return error("Invalid summary version " + Twine(Version) +
7680 ". Version should be in the range [1-" +
7682 "].");
7683 Record.clear();
7684
7685 // Keep around the last seen summary to be used when we see an optional
7686 // "OriginalName" attachement.
7687 GlobalValueSummary *LastSeenSummary = nullptr;
7688 GlobalValue::GUID LastSeenGUID = 0;
7689
7690 // We can expect to see any number of type ID information records before
7691 // each function summary records; these variables store the information
7692 // collected so far so that it can be used to create the summary object.
7693 std::vector<GlobalValue::GUID> PendingTypeTests;
7694 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7695 PendingTypeCheckedLoadVCalls;
7696 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7697 PendingTypeCheckedLoadConstVCalls;
7698 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7699
7700 std::vector<CallsiteInfo> PendingCallsites;
7701 std::vector<AllocInfo> PendingAllocs;
7702 std::vector<uint64_t> PendingContextIds;
7703
7704 while (true) {
7705 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7706 if (!MaybeEntry)
7707 return MaybeEntry.takeError();
7708 BitstreamEntry Entry = MaybeEntry.get();
7709
7710 switch (Entry.Kind) {
7711 case BitstreamEntry::SubBlock: // Handled for us already.
7713 return error("Malformed block");
7715 return Error::success();
7717 // The interesting case.
7718 break;
7719 }
7720
7721 // Read a record. The record format depends on whether this
7722 // is a per-module index or a combined index file. In the per-module
7723 // case the records contain the associated value's ID for correlation
7724 // with VST entries. In the combined index the correlation is done
7725 // via the bitcode offset of the summary records (which were saved
7726 // in the combined index VST entries). The records also contain
7727 // information used for ThinLTO renaming and importing.
7728 Record.clear();
7729 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7730 if (!MaybeBitCode)
7731 return MaybeBitCode.takeError();
7732 switch (unsigned BitCode = MaybeBitCode.get()) {
7733 default: // Default behavior: ignore.
7734 break;
7735 case bitc::FS_FLAGS: { // [flags]
7736 TheIndex.setFlags(Record[0]);
7737 break;
7738 }
7739 case bitc::FS_VALUE_GUID: { // [valueid, refguid_upper32, refguid_lower32]
7740 uint64_t ValueID = Record[0];
7741 GlobalValue::GUID RefGUID;
7742 if (Version >= 11) {
7743 RefGUID = Record[1] << 32 | Record[2];
7744 } else {
7745 RefGUID = Record[1];
7746 }
7747 ValueIdToValueInfoMap[ValueID] =
7748 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
7749 break;
7750 }
7751 // FS_PERMODULE is legacy and does not have support for the tail call flag.
7752 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7753 // numrefs x valueid, n x (valueid)]
7754 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7755 // numrefs x valueid,
7756 // n x (valueid, hotness+tailcall flags)]
7757 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7758 // numrefs x valueid,
7759 // n x (valueid, relblockfreq+tailcall)]
7760 case bitc::FS_PERMODULE:
7763 unsigned ValueID = Record[0];
7764 uint64_t RawFlags = Record[1];
7765 unsigned InstCount = Record[2];
7766 uint64_t RawFunFlags = 0;
7767 unsigned NumRefs = Record[3];
7768 unsigned NumRORefs = 0, NumWORefs = 0;
7769 int RefListStartIndex = 4;
7770 if (Version >= 4) {
7771 RawFunFlags = Record[3];
7772 NumRefs = Record[4];
7773 RefListStartIndex = 5;
7774 if (Version >= 5) {
7775 NumRORefs = Record[5];
7776 RefListStartIndex = 6;
7777 if (Version >= 7) {
7778 NumWORefs = Record[6];
7779 RefListStartIndex = 7;
7780 }
7781 }
7782 }
7783
7784 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7785 // The module path string ref set in the summary must be owned by the
7786 // index's module string table. Since we don't have a module path
7787 // string table section in the per-module index, we create a single
7788 // module path string table entry with an empty (0) ID to take
7789 // ownership.
7790 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7791 assert(Record.size() >= RefListStartIndex + NumRefs &&
7792 "Record size inconsistent with number of references");
7793 SmallVector<ValueInfo, 0> Refs = makeRefList(
7794 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7795 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
7796 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
7797 SmallVector<FunctionSummary::EdgeTy, 0> Calls = makeCallList(
7798 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7799 IsOldProfileFormat, HasProfile, HasRelBF);
7800 setSpecialRefs(Refs, NumRORefs, NumWORefs);
7801 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7802 // In order to save memory, only record the memprof summaries if this is
7803 // the prevailing copy of a symbol. The linker doesn't resolve local
7804 // linkage values so don't check whether those are prevailing.
7805 auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7806 if (IsPrevailing && !GlobalValue::isLocalLinkage(LT) &&
7807 !IsPrevailing(VIAndOriginalGUID.first.getGUID())) {
7808 PendingCallsites.clear();
7809 PendingAllocs.clear();
7810 }
7811 auto FS = std::make_unique<FunctionSummary>(
7812 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
7813 std::move(Calls), std::move(PendingTypeTests),
7814 std::move(PendingTypeTestAssumeVCalls),
7815 std::move(PendingTypeCheckedLoadVCalls),
7816 std::move(PendingTypeTestAssumeConstVCalls),
7817 std::move(PendingTypeCheckedLoadConstVCalls),
7818 std::move(PendingParamAccesses), std::move(PendingCallsites),
7819 std::move(PendingAllocs));
7820 FS->setModulePath(getThisModule()->first());
7821 FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7822 TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
7823 std::move(FS));
7824 break;
7825 }
7826 // FS_ALIAS: [valueid, flags, valueid]
7827 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7828 // they expect all aliasee summaries to be available.
7829 case bitc::FS_ALIAS: {
7830 unsigned ValueID = Record[0];
7831 uint64_t RawFlags = Record[1];
7832 unsigned AliaseeID = Record[2];
7833 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7834 auto AS = std::make_unique<AliasSummary>(Flags);
7835 // The module path string ref set in the summary must be owned by the
7836 // index's module string table. Since we don't have a module path
7837 // string table section in the per-module index, we create a single
7838 // module path string table entry with an empty (0) ID to take
7839 // ownership.
7840 AS->setModulePath(getThisModule()->first());
7841
7842 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7843 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
7844 if (!AliaseeInModule)
7845 return error("Alias expects aliasee summary to be parsed");
7846 AS->setAliasee(AliaseeVI, AliaseeInModule);
7847
7848 auto GUID = getValueInfoFromValueId(ValueID);
7849 AS->setOriginalName(std::get<1>(GUID));
7850 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
7851 break;
7852 }
7853 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7855 unsigned ValueID = Record[0];
7856 uint64_t RawFlags = Record[1];
7857 unsigned RefArrayStart = 2;
7858 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7859 /* WriteOnly */ false,
7860 /* Constant */ false,
7862 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7863 if (Version >= 5) {
7864 GVF = getDecodedGVarFlags(Record[2]);
7865 RefArrayStart = 3;
7866 }
7868 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7869 auto FS =
7870 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7871 FS->setModulePath(getThisModule()->first());
7872 auto GUID = getValueInfoFromValueId(ValueID);
7873 FS->setOriginalName(std::get<1>(GUID));
7874 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
7875 break;
7876 }
7877 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7878 // numrefs, numrefs x valueid,
7879 // n x (valueid, offset)]
7881 unsigned ValueID = Record[0];
7882 uint64_t RawFlags = Record[1];
7884 unsigned NumRefs = Record[3];
7885 unsigned RefListStartIndex = 4;
7886 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7887 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7888 SmallVector<ValueInfo, 0> Refs = makeRefList(
7889 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7890 VTableFuncList VTableFuncs;
7891 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7892 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7893 uint64_t Offset = Record[++I];
7894 VTableFuncs.push_back({Callee, Offset});
7895 }
7896 auto VS =
7897 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7898 VS->setModulePath(getThisModule()->first());
7899 VS->setVTableFuncs(VTableFuncs);
7900 auto GUID = getValueInfoFromValueId(ValueID);
7901 VS->setOriginalName(std::get<1>(GUID));
7902 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
7903 break;
7904 }
7905 // FS_COMBINED is legacy and does not have support for the tail call flag.
7906 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
7907 // numrefs x valueid, n x (valueid)]
7908 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7909 // numrefs x valueid,
7910 // n x (valueid, hotness+tailcall flags)]
7911 case bitc::FS_COMBINED:
7913 unsigned ValueID = Record[0];
7914 uint64_t ModuleId = Record[1];
7915 uint64_t RawFlags = Record[2];
7916 unsigned InstCount = Record[3];
7917 uint64_t RawFunFlags = 0;
7918 unsigned NumRefs = Record[4];
7919 unsigned NumRORefs = 0, NumWORefs = 0;
7920 int RefListStartIndex = 5;
7921
7922 if (Version >= 4) {
7923 RawFunFlags = Record[4];
7924 RefListStartIndex = 6;
7925 size_t NumRefsIndex = 5;
7926 if (Version >= 5) {
7927 unsigned NumRORefsOffset = 1;
7928 RefListStartIndex = 7;
7929 if (Version >= 6) {
7930 NumRefsIndex = 6;
7931 RefListStartIndex = 8;
7932 if (Version >= 7) {
7933 RefListStartIndex = 9;
7934 NumWORefs = Record[8];
7935 NumRORefsOffset = 2;
7936 }
7937 }
7938 NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
7939 }
7940 NumRefs = Record[NumRefsIndex];
7941 }
7942
7943 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7944 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7945 assert(Record.size() >= RefListStartIndex + NumRefs &&
7946 "Record size inconsistent with number of references");
7947 SmallVector<ValueInfo, 0> Refs = makeRefList(
7948 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7949 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
7950 SmallVector<FunctionSummary::EdgeTy, 0> Edges = makeCallList(
7951 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7952 IsOldProfileFormat, HasProfile, false);
7953 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7954 setSpecialRefs(Refs, NumRORefs, NumWORefs);
7955 auto FS = std::make_unique<FunctionSummary>(
7956 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
7957 std::move(Edges), std::move(PendingTypeTests),
7958 std::move(PendingTypeTestAssumeVCalls),
7959 std::move(PendingTypeCheckedLoadVCalls),
7960 std::move(PendingTypeTestAssumeConstVCalls),
7961 std::move(PendingTypeCheckedLoadConstVCalls),
7962 std::move(PendingParamAccesses), std::move(PendingCallsites),
7963 std::move(PendingAllocs));
7964 LastSeenSummary = FS.get();
7965 LastSeenGUID = VI.getGUID();
7966 FS->setModulePath(ModuleIdMap[ModuleId]);
7967 TheIndex.addGlobalValueSummary(VI, std::move(FS));
7968 break;
7969 }
7970 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
7971 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
7972 // they expect all aliasee summaries to be available.
7974 unsigned ValueID = Record[0];
7975 uint64_t ModuleId = Record[1];
7976 uint64_t RawFlags = Record[2];
7977 unsigned AliaseeValueId = Record[3];
7978 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7979 auto AS = std::make_unique<AliasSummary>(Flags);
7980 LastSeenSummary = AS.get();
7981 AS->setModulePath(ModuleIdMap[ModuleId]);
7982
7983 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
7984 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
7985 AS->setAliasee(AliaseeVI, AliaseeInModule);
7986
7987 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7988 LastSeenGUID = VI.getGUID();
7989 TheIndex.addGlobalValueSummary(VI, std::move(AS));
7990 break;
7991 }
7992 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
7994 unsigned ValueID = Record[0];
7995 uint64_t ModuleId = Record[1];
7996 uint64_t RawFlags = Record[2];
7997 unsigned RefArrayStart = 3;
7998 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7999 /* WriteOnly */ false,
8000 /* Constant */ false,
8002 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
8003 if (Version >= 5) {
8004 GVF = getDecodedGVarFlags(Record[3]);
8005 RefArrayStart = 4;
8006 }
8008 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8009 auto FS =
8010 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8011 LastSeenSummary = FS.get();
8012 FS->setModulePath(ModuleIdMap[ModuleId]);
8013 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8014 LastSeenGUID = VI.getGUID();
8015 TheIndex.addGlobalValueSummary(VI, std::move(FS));
8016 break;
8017 }
8018 // FS_COMBINED_ORIGINAL_NAME: [original_name]
8020 uint64_t OriginalName = Record[0];
8021 if (!LastSeenSummary)
8022 return error("Name attachment that does not follow a combined record");
8023 LastSeenSummary->setOriginalName(OriginalName);
8024 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
8025 // Reset the LastSeenSummary
8026 LastSeenSummary = nullptr;
8027 LastSeenGUID = 0;
8028 break;
8029 }
8031 assert(PendingTypeTests.empty());
8032 llvm::append_range(PendingTypeTests, Record);
8033 break;
8034
8036 assert(PendingTypeTestAssumeVCalls.empty());
8037 for (unsigned I = 0; I != Record.size(); I += 2)
8038 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8039 break;
8040
8042 assert(PendingTypeCheckedLoadVCalls.empty());
8043 for (unsigned I = 0; I != Record.size(); I += 2)
8044 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8045 break;
8046
8048 PendingTypeTestAssumeConstVCalls.push_back(
8049 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
8050 break;
8051
8053 PendingTypeCheckedLoadConstVCalls.push_back(
8054 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
8055 break;
8056
8058 std::set<std::string, std::less<>> &CfiFunctionDefs =
8059 TheIndex.cfiFunctionDefs();
8060 for (unsigned I = 0; I != Record.size(); I += 2)
8061 CfiFunctionDefs.insert(
8062 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
8063 break;
8064 }
8065
8067 std::set<std::string, std::less<>> &CfiFunctionDecls =
8068 TheIndex.cfiFunctionDecls();
8069 for (unsigned I = 0; I != Record.size(); I += 2)
8070 CfiFunctionDecls.insert(
8071 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
8072 break;
8073 }
8074
8075 case bitc::FS_TYPE_ID:
8076 parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
8077 break;
8078
8080 parseTypeIdCompatibleVtableSummaryRecord(Record);
8081 break;
8082
8084 TheIndex.addBlockCount(Record[0]);
8085 break;
8086
8087 case bitc::FS_PARAM_ACCESS: {
8088 PendingParamAccesses = parseParamAccesses(Record);
8089 break;
8090 }
8091
8092 case bitc::FS_STACK_IDS: { // [n x stackid]
8093 // Save stack ids in the reader to consult when adding stack ids from the
8094 // lists in the stack node and alloc node entries.
8095 if (Version <= 11) {
8096 StackIds = ArrayRef<uint64_t>(Record);
8097 break;
8098 }
8099 // This is an array of 32-bit fixed-width values, holding each 64-bit
8100 // context id as a pair of adjacent (most significant first) 32-bit words.
8101 assert(Record.size() % 2 == 0);
8102 StackIds.reserve(Record.size() / 2);
8103 for (auto R = Record.begin(); R != Record.end(); R += 2)
8104 StackIds.push_back(*R << 32 | *(R + 1));
8105 break;
8106 }
8107
8108 case bitc::FS_CONTEXT_RADIX_TREE_ARRAY: { // [n x entry]
8109 RadixArray = ArrayRef<uint64_t>(Record);
8110 break;
8111 }
8112
8114 unsigned ValueID = Record[0];
8115 SmallVector<unsigned> StackIdList;
8116 for (auto R = Record.begin() + 1; R != Record.end(); R++) {
8117 assert(*R < StackIds.size());
8118 StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R]));
8119 }
8120 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8121 PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
8122 break;
8123 }
8124
8126 auto RecordIter = Record.begin();
8127 unsigned ValueID = *RecordIter++;
8128 unsigned NumStackIds = *RecordIter++;
8129 unsigned NumVersions = *RecordIter++;
8130 assert(Record.size() == 3 + NumStackIds + NumVersions);
8131 SmallVector<unsigned> StackIdList;
8132 for (unsigned J = 0; J < NumStackIds; J++) {
8133 assert(*RecordIter < StackIds.size());
8134 StackIdList.push_back(
8135 TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
8136 }
8137 SmallVector<unsigned> Versions;
8138 for (unsigned J = 0; J < NumVersions; J++)
8139 Versions.push_back(*RecordIter++);
8140 ValueInfo VI = std::get<0>(
8141 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8142 PendingCallsites.push_back(
8143 CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
8144 break;
8145 }
8146
8148 // This is an array of 32-bit fixed-width values, holding each 64-bit
8149 // context id as a pair of adjacent (most significant first) 32-bit words.
8150 assert(Record.size() % 2 == 0);
8151 PendingContextIds.reserve(Record.size() / 2);
8152 for (auto R = Record.begin(); R != Record.end(); R += 2)
8153 PendingContextIds.push_back(*R << 32 | *(R + 1));
8154 break;
8155 }
8156
8158 unsigned I = 0;
8159 std::vector<MIBInfo> MIBs;
8160 unsigned NumMIBs = 0;
8161 if (Version >= 10)
8162 NumMIBs = Record[I++];
8163 unsigned MIBsRead = 0;
8164 while ((Version >= 10 && MIBsRead++ < NumMIBs) ||
8165 (Version < 10 && I < Record.size())) {
8166 assert(Record.size() - I >= 2);
8168 auto StackIdList = parseAllocInfoContext(Record, I);
8169 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8170 }
8171 // We either have nothing left or at least NumMIBs context size info
8172 // indices left (for the total sizes included when reporting of hinted
8173 // bytes is enabled).
8174 assert(I == Record.size() || Record.size() - I >= NumMIBs);
8175 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8176 if (I < Record.size()) {
8177 assert(!PendingContextIds.empty() &&
8178 "Missing context ids for alloc sizes");
8179 unsigned ContextIdIndex = 0;
8180 MIBsRead = 0;
8181 // The sizes are a linearized array of sizes, where for each MIB there
8182 // is 1 or more sizes (due to context trimming, each MIB in the metadata
8183 // and summarized here can correspond to more than one original context
8184 // from the profile).
8185 while (MIBsRead++ < NumMIBs) {
8186 // First read the number of contexts recorded for this MIB.
8187 unsigned NumContextSizeInfoEntries = Record[I++];
8188 assert(Record.size() - I >= NumContextSizeInfoEntries);
8189 std::vector<ContextTotalSize> ContextSizes;
8190 ContextSizes.reserve(NumContextSizeInfoEntries);
8191 for (unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8192 assert(ContextIdIndex < PendingContextIds.size());
8193 // PendingContextIds read from the preceding FS_ALLOC_CONTEXT_IDS
8194 // should be in the same order as the total sizes.
8195 ContextSizes.push_back(
8196 {PendingContextIds[ContextIdIndex++], Record[I++]});
8197 }
8198 AllContextSizes.push_back(std::move(ContextSizes));
8199 }
8200 PendingContextIds.clear();
8201 }
8202 PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
8203 if (!AllContextSizes.empty()) {
8204 assert(PendingAllocs.back().MIBs.size() == AllContextSizes.size());
8205 PendingAllocs.back().ContextSizeInfos = std::move(AllContextSizes);
8206 }
8207 break;
8208 }
8209
8211 unsigned I = 0;
8212 std::vector<MIBInfo> MIBs;
8213 unsigned NumMIBs = Record[I++];
8214 unsigned NumVersions = Record[I++];
8215 unsigned MIBsRead = 0;
8216 while (MIBsRead++ < NumMIBs) {
8217 assert(Record.size() - I >= 2);
8219 auto StackIdList = parseAllocInfoContext(Record, I);
8220 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8221 }
8222 assert(Record.size() - I >= NumVersions);
8223 SmallVector<uint8_t> Versions;
8224 for (unsigned J = 0; J < NumVersions; J++)
8225 Versions.push_back(Record[I++]);
8226 assert(I == Record.size());
8227 PendingAllocs.push_back(AllocInfo(std::move(Versions), std::move(MIBs)));
8228 break;
8229 }
8230 }
8231 }
8232 llvm_unreachable("Exit infinite loop");
8233}
8234
8235// Parse the module string table block into the Index.
8236// This populates the ModulePathStringTable map in the index.
8237Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8238 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
8239 return Err;
8240
8242
8243 SmallString<128> ModulePath;
8244 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
8245
8246 while (true) {
8247 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
8248 if (!MaybeEntry)
8249 return MaybeEntry.takeError();
8250 BitstreamEntry Entry = MaybeEntry.get();
8251
8252 switch (Entry.Kind) {
8253 case BitstreamEntry::SubBlock: // Handled for us already.
8255 return error("Malformed block");
8257 return Error::success();
8259 // The interesting case.
8260 break;
8261 }
8262
8263 Record.clear();
8264 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
8265 if (!MaybeRecord)
8266 return MaybeRecord.takeError();
8267 switch (MaybeRecord.get()) {
8268 default: // Default behavior: ignore.
8269 break;
8270 case bitc::MST_CODE_ENTRY: {
8271 // MST_ENTRY: [modid, namechar x N]
8272 uint64_t ModuleId = Record[0];
8273
8274 if (convertToString(Record, 1, ModulePath))
8275 return error("Invalid record");
8276
8277 LastSeenModule = TheIndex.addModule(ModulePath);
8278 ModuleIdMap[ModuleId] = LastSeenModule->first();
8279
8280 ModulePath.clear();
8281 break;
8282 }
8283 /// MST_CODE_HASH: [5*i32]
8284 case bitc::MST_CODE_HASH: {
8285 if (Record.size() != 5)
8286 return error("Invalid hash length " + Twine(Record.size()).str());
8287 if (!LastSeenModule)
8288 return error("Invalid hash that does not follow a module path");
8289 int Pos = 0;
8290 for (auto &Val : Record) {
8291 assert(!(Val >> 32) && "Unexpected high bits set");
8292 LastSeenModule->second[Pos++] = Val;
8293 }
8294 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
8295 LastSeenModule = nullptr;
8296 break;
8297 }
8298 }
8299 }
8300 llvm_unreachable("Exit infinite loop");
8301}
8302
8303namespace {
8304
8305// FIXME: This class is only here to support the transition to llvm::Error. It
8306// will be removed once this transition is complete. Clients should prefer to
8307// deal with the Error value directly, rather than converting to error_code.
8308class BitcodeErrorCategoryType : public std::error_category {
8309 const char *name() const noexcept override {
8310 return "llvm.bitcode";
8311 }
8312
8313 std::string message(int IE) const override {
8314 BitcodeError E = static_cast<BitcodeError>(IE);
8315 switch (E) {
8316 case BitcodeError::CorruptedBitcode:
8317 return "Corrupted bitcode";
8318 }
8319 llvm_unreachable("Unknown error type!");
8320 }
8321};
8322
8323} // end anonymous namespace
8324
8325const std::error_category &llvm::BitcodeErrorCategory() {
8326 static BitcodeErrorCategoryType ErrorCategory;
8327 return ErrorCategory;
8328}
8329
8331 unsigned Block, unsigned RecordID) {
8332 if (Error Err = Stream.EnterSubBlock(Block))
8333 return std::move(Err);
8334
8335 StringRef Strtab;
8336 while (true) {
8337 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8338 if (!MaybeEntry)
8339 return MaybeEntry.takeError();
8340 llvm::BitstreamEntry Entry = MaybeEntry.get();
8341
8342 switch (Entry.Kind) {
8344 return Strtab;
8345
8347 return error("Malformed block");
8348
8350 if (Error Err = Stream.SkipBlock())
8351 return std::move(Err);
8352 break;
8353
8355 StringRef Blob;
8357 Expected<unsigned> MaybeRecord =
8358 Stream.readRecord(Entry.ID, Record, &Blob);
8359 if (!MaybeRecord)
8360 return MaybeRecord.takeError();
8361 if (MaybeRecord.get() == RecordID)
8362 Strtab = Blob;
8363 break;
8364 }
8365 }
8366}
8367
8368//===----------------------------------------------------------------------===//
8369// External interface
8370//===----------------------------------------------------------------------===//
8371
8374 auto FOrErr = getBitcodeFileContents(Buffer);
8375 if (!FOrErr)
8376 return FOrErr.takeError();
8377 return std::move(FOrErr->Mods);
8378}
8379
8382 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8383 if (!StreamOrErr)
8384 return StreamOrErr.takeError();
8385 BitstreamCursor &Stream = *StreamOrErr;
8386
8388 while (true) {
8389 uint64_t BCBegin = Stream.getCurrentByteNo();
8390
8391 // We may be consuming bitcode from a client that leaves garbage at the end
8392 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
8393 // the end that there cannot possibly be another module, stop looking.
8394 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
8395 return F;
8396
8397 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8398 if (!MaybeEntry)
8399 return MaybeEntry.takeError();
8400 llvm::BitstreamEntry Entry = MaybeEntry.get();
8401
8402 switch (Entry.Kind) {
8405 return error("Malformed block");
8406
8408 uint64_t IdentificationBit = -1ull;
8409 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
8410 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8411 if (Error Err = Stream.SkipBlock())
8412 return std::move(Err);
8413
8414 {
8415 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8416 if (!MaybeEntry)
8417 return MaybeEntry.takeError();
8418 Entry = MaybeEntry.get();
8419 }
8420
8421 if (Entry.Kind != BitstreamEntry::SubBlock ||
8422 Entry.ID != bitc::MODULE_BLOCK_ID)
8423 return error("Malformed block");
8424 }
8425
8426 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
8427 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8428 if (Error Err = Stream.SkipBlock())
8429 return std::move(Err);
8430
8431 F.Mods.push_back({Stream.getBitcodeBytes().slice(
8432 BCBegin, Stream.getCurrentByteNo() - BCBegin),
8433 Buffer.getBufferIdentifier(), IdentificationBit,
8434 ModuleBit});
8435 continue;
8436 }
8437
8438 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
8439 Expected<StringRef> Strtab =
8441 if (!Strtab)
8442 return Strtab.takeError();
8443 // This string table is used by every preceding bitcode module that does
8444 // not have its own string table. A bitcode file may have multiple
8445 // string tables if it was created by binary concatenation, for example
8446 // with "llvm-cat -b".
8447 for (BitcodeModule &I : llvm::reverse(F.Mods)) {
8448 if (!I.Strtab.empty())
8449 break;
8450 I.Strtab = *Strtab;
8451 }
8452 // Similarly, the string table is used by every preceding symbol table;
8453 // normally there will be just one unless the bitcode file was created
8454 // by binary concatenation.
8455 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
8456 F.StrtabForSymtab = *Strtab;
8457 continue;
8458 }
8459
8460 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
8461 Expected<StringRef> SymtabOrErr =
8463 if (!SymtabOrErr)
8464 return SymtabOrErr.takeError();
8465
8466 // We can expect the bitcode file to have multiple symbol tables if it
8467 // was created by binary concatenation. In that case we silently
8468 // ignore any subsequent symbol tables, which is fine because this is a
8469 // low level function. The client is expected to notice that the number
8470 // of modules in the symbol table does not match the number of modules
8471 // in the input file and regenerate the symbol table.
8472 if (F.Symtab.empty())
8473 F.Symtab = *SymtabOrErr;
8474 continue;
8475 }
8476
8477 if (Error Err = Stream.SkipBlock())
8478 return std::move(Err);
8479 continue;
8480 }
8482 if (Error E = Stream.skipRecord(Entry.ID).takeError())
8483 return std::move(E);
8484 continue;
8485 }
8486 }
8487}
8488
8489/// Get a lazy one-at-time loading module from bitcode.
8490///
8491/// This isn't always used in a lazy context. In particular, it's also used by
8492/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
8493/// in forward-referenced functions from block address references.
8494///
8495/// \param[in] MaterializeAll Set to \c true if we should materialize
8496/// everything.
8498BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
8499 bool ShouldLazyLoadMetadata, bool IsImporting,
8500 ParserCallbacks Callbacks) {
8501 BitstreamCursor Stream(Buffer);
8502
8503 std::string ProducerIdentification;
8504 if (IdentificationBit != -1ull) {
8505 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8506 return std::move(JumpFailed);
8507 if (Error E =
8508 readIdentificationBlock(Stream).moveInto(ProducerIdentification))
8509 return std::move(E);
8510 }
8511
8512 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8513 return std::move(JumpFailed);
8514 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8515 Context);
8516
8517 std::unique_ptr<Module> M =
8518 std::make_unique<Module>(ModuleIdentifier, Context);
8519 M->setMaterializer(R);
8520
8521 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8522 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8523 IsImporting, Callbacks))
8524 return std::move(Err);
8525
8526 if (MaterializeAll) {
8527 // Read in the entire module, and destroy the BitcodeReader.
8528 if (Error Err = M->materializeAll())
8529 return std::move(Err);
8530 } else {
8531 // Resolve forward references from blockaddresses.
8532 if (Error Err = R->materializeForwardReferencedFunctions())
8533 return std::move(Err);
8534 }
8535
8536 return std::move(M);
8537}
8538
8540BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8541 bool IsImporting, ParserCallbacks Callbacks) {
8542 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8543 Callbacks);
8544}
8545
8546// Parse the specified bitcode buffer and merge the index into CombinedIndex.
8547// We don't use ModuleIdentifier here because the client may need to control the
8548// module path used in the combined summary (e.g. when reading summaries for
8549// regular LTO modules).
8551 ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8552 std::function<bool(GlobalValue::GUID)> IsPrevailing) {
8553 BitstreamCursor Stream(Buffer);
8554 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8555 return JumpFailed;
8556
8557 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8558 ModulePath, IsPrevailing);
8559 return R.parseModule();
8560}
8561
8562// Parse the specified bitcode buffer, returning the function info index.
8564 BitstreamCursor Stream(Buffer);
8565 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8566 return std::move(JumpFailed);
8567
8568 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
8569 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8570 ModuleIdentifier, 0);
8571
8572 if (Error Err = R.parseModule())
8573 return std::move(Err);
8574
8575 return std::move(Index);
8576}
8577
8580 unsigned ID,
8581 BitcodeLTOInfo &LTOInfo) {
8582 if (Error Err = Stream.EnterSubBlock(ID))
8583 return std::move(Err);
8585
8586 while (true) {
8587 BitstreamEntry Entry;
8588 std::pair<bool, bool> Result = {false,false};
8589 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8590 return std::move(E);
8591
8592 switch (Entry.Kind) {
8593 case BitstreamEntry::SubBlock: // Handled for us already.
8595 return error("Malformed block");
8597 // If no flags record found, set both flags to false.
8598 return Result;
8599 }
8601 // The interesting case.
8602 break;
8603 }
8604
8605 // Look for the FS_FLAGS record.
8606 Record.clear();
8607 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
8608 if (!MaybeBitCode)
8609 return MaybeBitCode.takeError();
8610 switch (MaybeBitCode.get()) {
8611 default: // Default behavior: ignore.
8612 break;
8613 case bitc::FS_FLAGS: { // [flags]
8614 uint64_t Flags = Record[0];
8615 // Scan flags.
8616 assert(Flags <= 0x2ff && "Unexpected bits in flag");
8617
8618 bool EnableSplitLTOUnit = Flags & 0x8;
8619 bool UnifiedLTO = Flags & 0x200;
8620 Result = {EnableSplitLTOUnit, UnifiedLTO};
8621
8622 return Result;
8623 }
8624 }
8625 }
8626 llvm_unreachable("Exit infinite loop");
8627}
8628
8629// Check if the given bitcode buffer contains a global value summary block.
8631 BitstreamCursor Stream(Buffer);
8632 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8633 return std::move(JumpFailed);
8634
8635 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
8636 return std::move(Err);
8637
8638 while (true) {
8640 if (Error E = Stream.advance().moveInto(Entry))
8641 return std::move(E);
8642
8643 switch (Entry.Kind) {
8645 return error("Malformed block");
8647 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
8648 /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8649
8651 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
8652 BitcodeLTOInfo LTOInfo;
8654 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8655 if (!Flags)
8656 return Flags.takeError();
8657 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8658 LTOInfo.IsThinLTO = true;
8659 LTOInfo.HasSummary = true;
8660 return LTOInfo;
8661 }
8662
8664 BitcodeLTOInfo LTOInfo;
8666 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8667 if (!Flags)
8668 return Flags.takeError();
8669 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8670 LTOInfo.IsThinLTO = false;
8671 LTOInfo.HasSummary = true;
8672 return LTOInfo;
8673 }
8674
8675 // Ignore other sub-blocks.
8676 if (Error Err = Stream.SkipBlock())
8677 return std::move(Err);
8678 continue;
8679
8681 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
8682 continue;
8683 else
8684 return StreamFailed.takeError();
8685 }
8686 }
8687}
8688
8691 if (!MsOrErr)
8692 return MsOrErr.takeError();
8693
8694 if (MsOrErr->size() != 1)
8695 return error("Expected a single module");
8696
8697 return (*MsOrErr)[0];
8698}
8699
8702 bool ShouldLazyLoadMetadata, bool IsImporting,
8703 ParserCallbacks Callbacks) {
8705 if (!BM)
8706 return BM.takeError();
8707
8708 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8709 Callbacks);
8710}
8711
8713 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8714 bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
8715 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8716 IsImporting, Callbacks);
8717 if (MOrErr)
8718 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8719 return MOrErr;
8720}
8721
8724 return getModuleImpl(Context, true, false, false, Callbacks);
8725 // TODO: Restore the use-lists to the in-memory state when the bitcode was
8726 // written. We must defer until the Module has been fully materialized.
8727}
8728
8731 ParserCallbacks Callbacks) {
8733 if (!BM)
8734 return BM.takeError();
8735
8736 return BM->parseModule(Context, Callbacks);
8737}
8738
8740 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8741 if (!StreamOrErr)
8742 return StreamOrErr.takeError();
8743
8744 return readTriple(*StreamOrErr);
8745}
8746
8748 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8749 if (!StreamOrErr)
8750 return StreamOrErr.takeError();
8751
8752 return hasObjCCategory(*StreamOrErr);
8753}
8754
8756 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8757 if (!StreamOrErr)
8758 return StreamOrErr.takeError();
8759
8760 return readIdentificationCode(*StreamOrErr);
8761}
8762
8764 ModuleSummaryIndex &CombinedIndex) {
8766 if (!BM)
8767 return BM.takeError();
8768
8769 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8770}
8771
8775 if (!BM)
8776 return BM.takeError();
8777
8778 return BM->getSummary();
8779}
8780
8783 if (!BM)
8784 return BM.takeError();
8785
8786 return BM->getLTOInfo();
8787}
8788
8791 bool IgnoreEmptyThinLTOIndexFile) {
8794 if (!FileOrErr)
8795 return errorCodeToError(FileOrErr.getError());
8796 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
8797 return nullptr;
8798 return getModuleSummaryIndex(**FileOrErr);
8799}
aarch64 promote const
static bool isConstant(const MachineInstr &MI)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, bool &HasTailCall)
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
static cl::opt< bool > PrintSummaryGUIDs("print-summary-global-ids", cl::init(false), cl::Hidden, cl::desc("Print the global id for each value when reading the module summary"))
static AtomicOrdering getDecodedOrdering(unsigned Val)
static std::pair< CalleeInfo::HotnessType, bool > getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)
static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags)
static std::optional< CodeModel::Model > getDecodedCodeModel(unsigned Val)
static void setSpecialRefs(SmallVectorImpl< ValueInfo > &Refs, unsigned ROCnt, unsigned WOCnt)
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
static bool getDecodedDSOLocal(unsigned Val)
static bool convertToString(ArrayRef< uint64_t > Record, unsigned Idx, StrTy &Result)
Convert a string from a record into an std::string, return true on failure.
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
static void stripTBAA(Module *M)
static Expected< std::pair< bool, bool > > getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID, BitcodeLTOInfo &LTOInfo)
static int getDecodedUnaryOpcode(unsigned Val, Type *Ty)
static Expected< std::string > readTriple(BitstreamCursor &Stream)
static void parseWholeProgramDevirtResolutionByArg(ArrayRef< uint64_t > Record, size_t &Slot, WholeProgramDevirtResolution &Wpd)
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags)
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
static Expected< uint64_t > jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
static Expected< bool > hasObjCCategoryInModule(BitstreamCursor &Stream)
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags)
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs, uint64_t AttrIdx)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
cl::opt< bool > WriteNewDbgInfoFormat
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
cl::opt< cl::boolOrDefault > LoadBitcodeIntoNewDbgInfoFormat("load-bitcode-into-experimental-debuginfo-iterators", cl::Hidden, cl::desc("Load bitcode directly into the new debug info format (regardless " "of input format)"))
Load bitcode directly into RemoveDIs format (use debug records instead of debug intrinsics).
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
bool WriteNewDbgInfoFormatToBitcode
Definition: BasicBlock.cpp:47
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
static bool hasImplicitComdat(size_t Val)
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream)
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
static void inferDSOLocal(GlobalValue *GV)
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V)
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
static cl::opt< bool > ExpandConstantExprs("expand-constant-exprs", cl::Hidden, cl::desc("Expand constant expressions to instructions for testing purposes"))
static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind)
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
static Expected< std::string > readIdentificationBlock(BitstreamCursor &Stream)
Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the "epoch" encoded in the bit...
static bool isConstExprSupported(const BitcodeConstant *BC)
static int getDecodedCastOpcode(unsigned Val)
cl::opt< bool > UseNewDbgInfoFormat
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase)
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is Live
This file defines the DenseMap class.
@ Default
Definition: DwarfDebug.cpp:87
uint64_t Addr
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
Provides ErrorOr<T> smart pointer.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
PowerPC Reduce CR logical Operation
if(PassOpts->AAPipeline)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:46
This file contains some templates that are useful if you are working with the STL at all.
static uint64_t decodeSignRotatedValue(uint64_t V)
Decode a signed value stored with the sign bit in the LSB for dense VBR encoding.
This file defines the SmallString class.
This file defines the SmallVector class.
#define error(X)
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
an instruction to allocate memory on the stack
Definition: Instructions.h:63
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
Definition: Instructions.h:151
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:99
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Definition: Instructions.h:144
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:157
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
iterator begin() const
Definition: ArrayRef.h:156
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:163
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:501
static bool isValidFailureOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:574
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
Definition: Instructions.h:652
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:569
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:704
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:716
@ Add
*p = old + v
Definition: Instructions.h:720
@ FAdd
*p = old + v
Definition: Instructions.h:741
@ USubCond
Subtract only if no unsigned overflow.
Definition: Instructions.h:764
@ Min
*p = old <signed v ? old : v
Definition: Instructions.h:734
@ Or
*p = old | v
Definition: Instructions.h:728
@ Sub
*p = old - v
Definition: Instructions.h:722
@ And
*p = old & v
Definition: Instructions.h:724
@ Xor
*p = old ^ v
Definition: Instructions.h:730
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
Definition: Instructions.h:768
@ FSub
*p = old - v
Definition: Instructions.h:744
@ UIncWrap
Increment one up to a maximum value.
Definition: Instructions.h:756
@ Max
*p = old >signed v ? old : v
Definition: Instructions.h:732
@ UMin
*p = old <unsigned v ? old : v
Definition: Instructions.h:738
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
Definition: Instructions.h:752
@ UMax
*p = old >unsigned v ? old : v
Definition: Instructions.h:736
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
Definition: Instructions.h:748
@ UDecWrap
Decrement one until a minimum value or zero.
Definition: Instructions.h:760
@ Nand
*p = ~(old & v)
Definition: Instructions.h:726
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
static Attribute getWithStructRetType(LLVMContext &Context, Type *Ty)
Definition: Attributes.cpp:260
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Definition: Attributes.cpp:95
static bool isTypeAttrKind(AttrKind Kind)
Definition: Attributes.h:105
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:86
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
Definition: Attributes.h:93
@ None
No attributes have been set.
Definition: Attributes.h:88
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
Definition: Attributes.h:92
@ EndAttrKinds
Sentinel value useful for loops.
Definition: Attributes.h:91
static bool isConstantRangeAttrKind(AttrKind Kind)
Definition: Attributes.h:108
static Attribute getWithInAllocaType(LLVMContext &Context, Type *Ty)
Definition: Attributes.cpp:272
static bool isIntAttrKind(AttrKind Kind)
Definition: Attributes.h:102
static bool isConstantRangeListAttrKind(AttrKind Kind)
Definition: Attributes.h:111
static Attribute getWithByValType(LLVMContext &Context, Type *Ty)
Definition: Attributes.cpp:256
static bool isEnumAttrKind(AttrKind Kind)
Definition: Attributes.h:99
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator end()
Definition: BasicBlock.h:474
bool empty() const
Definition: BasicBlock.h:483
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:213
void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
Definition: BasicBlock.cpp:673
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
Definition: BasicBlock.cpp:279
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition: BasicBlock.h:389
const Instruction & back() const
Definition: BasicBlock.h:486
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Represents a module in a bitcode file.
Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
Definition: ValueList.cpp:54
void push_back(Value *V, unsigned TypeID)
Definition: ValueList.h:52
Value * back() const
Definition: ValueList.h:70
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Definition: ValueList.h:81
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
Definition: ValueList.cpp:25
void shrinkTo(unsigned N)
Definition: ValueList.h:76
unsigned getTypeID(unsigned ValNo) const
Definition: ValueList.h:65
unsigned size() const
Definition: ValueList.h:48
This class maintains the abbreviations read from a block info block.
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
ArrayRef< uint8_t > getBitcodeBytes() const
Expected< word_t > Read(unsigned NumBits)
Expected< BitstreamEntry > advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Expected< BitstreamEntry > advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
void setBlockInfo(BitstreamBlockInfo *BI)
Set the block info to be used by this BitstreamCursor to interpret abbreviated records.
Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block.
Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
uint64_t getCurrentByteNo() const
bool canSkipToPos(size_t pos) const
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1897
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1112
bool isInlineAsm() const
Check if this call is an inline asm statement.
Definition: InstrTypes.h:1408
Value * getCalledOperand() const
Definition: InstrTypes.h:1334
void setAttributes(AttributeList A)
Set the attributes for this call.
Definition: InstrTypes.h:1420
Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
Definition: InstrTypes.h:1284
AttributeList getAttributes() const
Return the attributes for this call.
Definition: InstrTypes.h:1417
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo createFromIntValue(uint32_t Data)
Definition: ModRef.h:380
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition: ModRef.h:331
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:673
static CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
Definition: InstrTypes.h:780
bool isIntPredicate() const
Definition: InstrTypes.h:781
@ Largest
The linker will choose the largest COMDAT.
Definition: Comdat.h:38
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:40
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:37
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1312
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2991
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition: Constants.h:709
static Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of array type with a float element type taken from argument ...
Definition: Constants.cpp:2970
static Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
Definition: Constants.cpp:3007
static Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of vector type with a float element type taken from argument...
Definition: Constants.cpp:3044
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2555
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:2222
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2577
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2600
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition: Constants.h:1379
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
Definition: Constants.cpp:2340
static bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
Definition: Constants.cpp:2409
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1267
static bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
Definition: Constants.cpp:2458
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:157
static ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
Definition: Constants.cpp:2072
static bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
Definition: ConstantRange.h:47
bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1378
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1421
This is an important base class in LLVM.
Definition: Constant.h:42
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
Assignment ID.
DWARF expression.
Debug location.
Subprogram description.
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
Definition: Constants.cpp:1970
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
static Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
Definition: DataLayout.cpp:264
Records a position in IR for a source label (DILabel).
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition: DebugLoc.h:33
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:194
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:156
bool erase(const KeyT &Val)
Definition: DenseMap.h:321
unsigned size() const
Definition: DenseMap.h:99
bool empty() const
Definition: DenseMap.h:98
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:152
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
Base class for error info classes.
Definition: Error.h:45
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:53
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
Represents either an error or a value T.
Definition: ErrorOr.h:56
std::error_code getError() const
Definition: ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
reference get()
Returns a reference to the stored T value.
Definition: Error.h:578
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This instruction compares its operands according to the predicate given to the constructor.
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
void setFast(bool B=true)
Definition: FMF.h:97
bool any() const
Definition: FMF.h:57
void setAllowContract(bool B=true)
Definition: FMF.h:91
void setAllowReciprocal(bool B=true)
Definition: FMF.h:88
void setNoSignedZeros(bool B=true)
Definition: FMF.h:85
void setNoNaNs(bool B=true)
Definition: FMF.h:79
void setAllowReassoc(bool B=true)
Flag setters.
Definition: FMF.h:76
void setApproxFunc(bool B=true)
Definition: FMF.h:94
void setNoInfs(bool B=true)
Definition: FMF.h:82
An instruction for ordering other memory operations.
Definition: Instructions.h:424
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:791
This class represents a freeze function that returns random concrete value if an operand is either a ...
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:173
BasicBlockListType::iterator iterator
Definition: Function.h:68
bool empty() const
Definition: Function.h:871
const BasicBlock & back() const
Definition: Function.h:874
iterator begin()
Definition: Function.h:865
iterator end()
Definition: Function.h:867
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
virtual void setStripDebugInfo()=0
virtual Error materializeModule()=0
Make sure the entire Module has been completely read.
virtual Error materializeMetadata()=0
virtual Error materialize(GlobalValue *GV)=0
Make sure the given GlobalValue is fully read.
virtual std::vector< StructType * > getIdentifiedStructTypes() const =0
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Definition: Instructions.h:956
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:557
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:614
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:143
void setComdat(Comdat *C)
Definition: Globals.cpp:212
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:273
Function and variable summary information to aid decisions and implementation of importing.
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:410
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:232
bool hasLocalLinkage() const
Definition: GlobalValue.h:529
bool hasDefaultVisibility() const
Definition: GlobalValue.h:250
void setDLLStorageClass(DLLStorageClassTypes C)
Definition: GlobalValue.h:285
void setThreadLocalMode(ThreadLocalMode Val)
Definition: GlobalValue.h:268
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:530
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition: GlobalValue.h:73
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition: GlobalValue.h:76
@ DLLImportStorageClass
Function to be imported from DLL.
Definition: GlobalValue.h:75
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:596
void setDSOLocal(bool Local)
Definition: GlobalValue.h:304
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:295
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:66
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:67
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
@ ProtectedVisibility
The GV is protected.
Definition: GlobalValue.h:69
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:255
void setSanitizerMetadata(SanitizerMetadata Meta)
Definition: Globals.cpp:249
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e....
Definition: Globals.cpp:184
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:62
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:54
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:58
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
void setPartition(StringRef Part)
Definition: Globals.cpp:226
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition: Globals.cpp:534
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:43
std::vector< ConstraintInfo > ConstraintInfoVector
Definition: InlineAsm.h:121
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool isCast() const
Definition: Instruction.h:319
bool isBinaryOp() const
Definition: Instruction.h:315
const char * getOpcodeName() const
Definition: Instruction.h:312
bool isUnaryOp() const
Definition: Instruction.h:314
InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:311
@ MIN_INT_BITS
Minimum number of bits that can be specified.
Definition: DerivedTypes.h:53
@ MAX_INT_BITS
Maximum number of bits that can be specified.
Definition: DerivedTypes.h:54
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
An instruction for reading from memory.
Definition: Instructions.h:176
Metadata node.
Definition: Metadata.h:1073
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:895
A single uniqued string.
Definition: Metadata.h:724
StringRef getString() const
Definition: Metadata.cpp:616
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: MapVector.h:141
ValueT lookup(const KeyT &Key) const
Definition: MapVector.h:110
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static MemoryEffectsBase readOnly()
Create MemoryEffectsBase that can read any memory.
Definition: ModRef.h:122
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access argument memory.
Definition: ModRef.h:132
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible memory.
Definition: ModRef.h:138
static MemoryEffectsBase createFromIntValue(uint32_t Data)
Create MemoryEffectsBase from an encoded integer value (used by memory attribute).
Definition: ModRef.h:154
static MemoryEffectsBase writeOnly()
Create MemoryEffectsBase that can write any memory.
Definition: ModRef.h:127
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible or argument memory.
Definition: ModRef.h:145
static MemoryEffectsBase none()
Create MemoryEffectsBase that cannot read or write any memory.
Definition: ModRef.h:117
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
Definition: ModRef.h:112
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:103
Helper class that handles loading Metadatas and keeping them available.
Root of the metadata hierarchy.
Definition: Metadata.h:62
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
StringRef saveString(StringRef String)
void setFlags(uint64_t Flags)
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
std::set< std::string, std::less<> > & cfiFunctionDefs()
static constexpr uint64_t BitcodeSummaryVersion
std::set< std::string, std::less<> > & cfiFunctionDecls()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:297
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:298
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition: Module.cpp:304
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:611
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition: Module.cpp:354
A tuple of MDNodes.
Definition: Metadata.h:1737
void addOperand(MDNode *M)
Definition: Metadata.cpp:1431
static NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
Definition: Constants.cpp:2028
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1878
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
ArrayRef< int > getShuffleMask() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:254
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void reserve(size_type N)
Definition: SmallVector.h:663
iterator erase(const_iterator CI)
Definition: SmallVector.h:737
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:683
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
An instruction for storing to memory.
Definition: Instructions.h:292
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
StringRef first() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:144
Class to represent struct types.
Definition: DerivedTypes.h:218
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:406
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:612
void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
Definition: Type.cpp:561
Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
Definition: Type.cpp:531
Multiway switch.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
Verify that the TBAA Metadatas are valid.
Definition: Verifier.h:39
bool visitTBAAMetadata(Instruction &I, const MDNode *MD)
Visit an instruction and return true if it is valid, return false if an invalid TBAA is attached.
Definition: Verifier.cpp:7616
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Definition: DerivedTypes.h:806
static Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Definition: Type.cpp:901
See the file comment for details on the usage of the TrailingObjects type.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getHalfTy(LLVMContext &C)
Type * getStructElementType(unsigned N) const
static Type * getDoubleTy(LLVMContext &C)
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:270
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:261
static Type * getX86_FP80Ty(LLVMContext &C)
bool isLabelTy() const
Return true if this is 'label'.
Definition: Type.h:228
static Type * getBFloatTy(LLVMContext &C)
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:243
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:264
static IntegerType * getInt1Ty(LLVMContext &C)
Type * getArrayElementType() const
Definition: Type.h:411
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:153
static Type * getX86_AMXTy(LLVMContext &C)
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition: Type.h:145
static Type * getMetadataTy(LLVMContext &C)
unsigned getStructNumElements() const
uint64_t getArrayNumElements() const
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:54
static Type * getVoidTy(LLVMContext &C)
static Type * getLabelTy(LLVMContext &C)
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:258
static Type * getFP128Ty(LLVMContext &C)
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:310
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:142
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:156
static Type * getTokenTy(LLVMContext &C)
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:255
static IntegerType * getInt32Ty(LLVMContext &C)
static Type * getFloatTy(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:237
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:225
static Type * getPPC_FP128Ty(LLVMContext &C)
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:139
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:355
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition: Type.h:231
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1859
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:501
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:110
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
Definition: Value.h:810
Value & operator=(const Value &)=delete
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:193
const ParentTy * getParent() const
Definition: ilist_node.h:32
self_iterator getIterator()
Definition: ilist_node.h:132
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Key
PAL metadata keys.
AttributeMask typeIncompatible(Type *Ty, AttributeSet AS, AttributeSafetyKind ASK=ASK_ALL)
Which attributes cannot be applied to a type.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:125
@ Entry
Definition: COFF.h:844
@ MaxID
The highest possible ID. Must be some 2^k - 1.
Definition: CallingConv.h:274
@ X86_INTR
x86 hardware interrupt context.
Definition: CallingConv.h:173
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
Definition: GOFF.h:28
const uint64_t Version
Definition: CodeGenData.h:286
AttributeList getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition: LLVMContext.h:54
@ System
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:57
@ FS
Definition: X86.h:211
@ BITCODE_CURRENT_EPOCH
Definition: LLVMBitCodes.h:81
@ TYPE_CODE_METADATA
Definition: LLVMBitCodes.h:162
@ TYPE_CODE_PPC_FP128
Definition: LLVMBitCodes.h:160
@ TYPE_CODE_TARGET_TYPE
Definition: LLVMBitCodes.h:179
@ TYPE_CODE_STRUCT_ANON
Definition: LLVMBitCodes.h:166
@ TYPE_CODE_STRUCT_NAME
Definition: LLVMBitCodes.h:167
@ TYPE_CODE_X86_FP80
Definition: LLVMBitCodes.h:158
@ TYPE_CODE_OPAQUE_POINTER
Definition: LLVMBitCodes.h:177
@ TYPE_CODE_FUNCTION
Definition: LLVMBitCodes.h:170
@ TYPE_CODE_NUMENTRY
Definition: LLVMBitCodes.h:136
@ TYPE_CODE_FUNCTION_OLD
Definition: LLVMBitCodes.h:147
@ TYPE_CODE_STRUCT_NAMED
Definition: LLVMBitCodes.h:168
@ FS_CONTEXT_RADIX_TREE_ARRAY
Definition: LLVMBitCodes.h:337
@ FS_CFI_FUNCTION_DEFS
Definition: LLVMBitCodes.h:263
@ FS_PERMODULE_RELBF
Definition: LLVMBitCodes.h:272
@ FS_COMBINED_GLOBALVAR_INIT_REFS
Definition: LLVMBitCodes.h:225
@ FS_TYPE_CHECKED_LOAD_VCALLS
Definition: LLVMBitCodes.h:247
@ FS_COMBINED_PROFILE
Definition: LLVMBitCodes.h:223
@ FS_ALLOC_CONTEXT_IDS
Definition: LLVMBitCodes.h:333
@ FS_COMBINED_ORIGINAL_NAME
Definition: LLVMBitCodes.h:231
@ FS_TYPE_ID_METADATA
Definition: LLVMBitCodes.h:294
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
Definition: LLVMBitCodes.h:300
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
Definition: LLVMBitCodes.h:251
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
Definition: LLVMBitCodes.h:216
@ FS_TYPE_TEST_ASSUME_VCALLS
Definition: LLVMBitCodes.h:242
@ FS_CFI_FUNCTION_DECLS
Definition: LLVMBitCodes.h:267
@ FS_COMBINED_CALLSITE_INFO
Definition: LLVMBitCodes.h:316
@ FS_COMBINED_ALLOC_INFO
Definition: LLVMBitCodes.h:321
@ FS_PERMODULE_PROFILE
Definition: LLVMBitCodes.h:214
@ FS_PERMODULE_CALLSITE_INFO
Definition: LLVMBitCodes.h:308
@ FS_PERMODULE_ALLOC_INFO
Definition: LLVMBitCodes.h:312
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
Definition: LLVMBitCodes.h:255
@ IDENTIFICATION_CODE_EPOCH
Definition: LLVMBitCodes.h:72
@ IDENTIFICATION_CODE_STRING
Definition: LLVMBitCodes.h:71
@ CST_CODE_CE_INBOUNDS_GEP
Definition: LLVMBitCodes.h:413
@ CST_CODE_INLINEASM_OLD3
Definition: LLVMBitCodes.h:422
@ CST_CODE_BLOCKADDRESS
Definition: LLVMBitCodes.h:414
@ CST_CODE_NO_CFI_VALUE
Definition: LLVMBitCodes.h:425
@ CST_CODE_CE_SHUFVEC_EX
Definition: LLVMBitCodes.h:412
@ CST_CODE_CE_EXTRACTELT
Definition: LLVMBitCodes.h:406
@ CST_CODE_CE_GEP_OLD
Definition: LLVMBitCodes.h:404
@ CST_CODE_INLINEASM_OLD
Definition: LLVMBitCodes.h:410
@ CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
Definition: LLVMBitCodes.h:418
@ CST_CODE_CE_SHUFFLEVEC
Definition: LLVMBitCodes.h:408
@ CST_CODE_WIDE_INTEGER
Definition: LLVMBitCodes.h:397
@ CST_CODE_DSO_LOCAL_EQUIVALENT
Definition: LLVMBitCodes.h:421
@ CST_CODE_AGGREGATE
Definition: LLVMBitCodes.h:399
@ CST_CODE_CE_SELECT
Definition: LLVMBitCodes.h:405
@ CST_CODE_CE_INSERTELT
Definition: LLVMBitCodes.h:407
@ CST_CODE_INLINEASM_OLD2
Definition: LLVMBitCodes.h:416
@ CST_CODE_CE_GEP_WITH_INRANGE
Definition: LLVMBitCodes.h:430
@ CST_CODE_INLINEASM
Definition: LLVMBitCodes.h:426
@ CALL_EXPLICIT_TYPE
Definition: LLVMBitCodes.h:578
@ VST_CODE_COMBINED_ENTRY
Definition: LLVMBitCodes.h:196
@ COMDAT_SELECTION_KIND_LARGEST
Definition: LLVMBitCodes.h:797
@ COMDAT_SELECTION_KIND_ANY
Definition: LLVMBitCodes.h:795
@ COMDAT_SELECTION_KIND_SAME_SIZE
Definition: LLVMBitCodes.h:799
@ COMDAT_SELECTION_KIND_EXACT_MATCH
Definition: LLVMBitCodes.h:796
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
Definition: LLVMBitCodes.h:798
@ ATTR_KIND_STACK_PROTECT
Definition: LLVMBitCodes.h:715
@ ATTR_KIND_NO_UNWIND
Definition: LLVMBitCodes.h:707
@ ATTR_KIND_STACK_PROTECT_STRONG
Definition: LLVMBitCodes.h:717
@ ATTR_KIND_SANITIZE_MEMORY
Definition: LLVMBitCodes.h:721
@ ATTR_KIND_SAFESTACK
Definition: LLVMBitCodes.h:733
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
Definition: LLVMBitCodes.h:708
@ ATTR_KIND_SWIFT_ERROR
Definition: LLVMBitCodes.h:736
@ ATTR_KIND_INACCESSIBLEMEM_ONLY
Definition: LLVMBitCodes.h:738
@ ATTR_KIND_STRUCT_RET
Definition: LLVMBitCodes.h:718
@ ATTR_KIND_MIN_SIZE
Definition: LLVMBitCodes.h:695
@ ATTR_KIND_NO_CALLBACK
Definition: LLVMBitCodes.h:760
@ ATTR_KIND_NO_CAPTURE
Definition: LLVMBitCodes.h:700
@ ATTR_KIND_FNRETTHUNK_EXTERN
Definition: LLVMBitCodes.h:773
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
Definition: LLVMBitCodes.h:789
@ ATTR_KIND_SANITIZE_ADDRESS
Definition: LLVMBitCodes.h:719
@ ATTR_KIND_NO_IMPLICIT_FLOAT
Definition: LLVMBitCodes.h:702
@ ATTR_KIND_NO_BUILTIN
Definition: LLVMBitCodes.h:699
@ ATTR_KIND_NO_RECURSE
Definition: LLVMBitCodes.h:737
@ ATTR_KIND_DEAD_ON_UNWIND
Definition: LLVMBitCodes.h:780
@ ATTR_KIND_CONVERGENT
Definition: LLVMBitCodes.h:732
@ ATTR_KIND_RETURNED
Definition: LLVMBitCodes.h:711
@ ATTR_KIND_STACK_ALIGNMENT
Definition: LLVMBitCodes.h:714
@ ATTR_KIND_SWIFT_SELF
Definition: LLVMBitCodes.h:735
@ ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
Definition: LLVMBitCodes.h:739
@ ATTR_KIND_ALLOC_SIZE
Definition: LLVMBitCodes.h:740
@ ATTR_KIND_STACK_PROTECT_REQ
Definition: LLVMBitCodes.h:716
@ ATTR_KIND_INLINE_HINT
Definition: LLVMBitCodes.h:693
@ ATTR_KIND_NON_NULL
Definition: LLVMBitCodes.h:728
@ ATTR_KIND_NULL_POINTER_IS_VALID
Definition: LLVMBitCodes.h:756
@ ATTR_KIND_SANITIZE_HWADDRESS
Definition: LLVMBitCodes.h:744
@ ATTR_KIND_NO_RETURN
Definition: LLVMBitCodes.h:706
@ ATTR_KIND_MUSTPROGRESS
Definition: LLVMBitCodes.h:759
@ ATTR_KIND_RETURNS_TWICE
Definition: LLVMBitCodes.h:712
@ ATTR_KIND_SHADOWCALLSTACK
Definition: LLVMBitCodes.h:747
@ ATTR_KIND_OPT_FOR_FUZZING
Definition: LLVMBitCodes.h:746
@ ATTR_KIND_WRITABLE
Definition: LLVMBitCodes.h:778
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
Definition: LLVMBitCodes.h:782
@ ATTR_KIND_INITIALIZES
Definition: LLVMBitCodes.h:783
@ ATTR_KIND_ARGMEMONLY
Definition: LLVMBitCodes.h:734
@ ATTR_KIND_ALLOCATED_POINTER
Definition: LLVMBitCodes.h:770
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
Definition: LLVMBitCodes.h:767
@ ATTR_KIND_SKIP_PROFILE
Definition: LLVMBitCodes.h:774
@ ATTR_KIND_ELEMENTTYPE
Definition: LLVMBitCodes.h:766
@ ATTR_KIND_CORO_ELIDE_SAFE
Definition: LLVMBitCodes.h:787
@ ATTR_KIND_ALLOC_KIND
Definition: LLVMBitCodes.h:771
@ ATTR_KIND_NO_MERGE
Definition: LLVMBitCodes.h:755
@ ATTR_KIND_STRICT_FP
Definition: LLVMBitCodes.h:743
@ ATTR_KIND_NO_DUPLICATE
Definition: LLVMBitCodes.h:701
@ ATTR_KIND_ALLOC_ALIGN
Definition: LLVMBitCodes.h:769
@ ATTR_KIND_NON_LAZY_BIND
Definition: LLVMBitCodes.h:704
@ ATTR_KIND_DEREFERENCEABLE
Definition: LLVMBitCodes.h:730
@ ATTR_KIND_READ_NONE
Definition: LLVMBitCodes.h:709
@ ATTR_KIND_UW_TABLE
Definition: LLVMBitCodes.h:722
@ ATTR_KIND_OPTIMIZE_NONE
Definition: LLVMBitCodes.h:726
@ ATTR_KIND_WRITEONLY
Definition: LLVMBitCodes.h:741
@ ATTR_KIND_NO_RED_ZONE
Definition: LLVMBitCodes.h:705
@ ATTR_KIND_NOCF_CHECK
Definition: LLVMBitCodes.h:745
@ ATTR_KIND_NO_PROFILE
Definition: LLVMBitCodes.h:762
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
Definition: LLVMBitCodes.h:731
@ ATTR_KIND_SANITIZE_REALTIME
Definition: LLVMBitCodes.h:785
@ ATTR_KIND_IN_ALLOCA
Definition: LLVMBitCodes.h:727
@ ATTR_KIND_READ_ONLY
Definition: LLVMBitCodes.h:710
@ ATTR_KIND_ALIGNMENT
Definition: LLVMBitCodes.h:690
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
Definition: LLVMBitCodes.h:748
@ ATTR_KIND_ALWAYS_INLINE
Definition: LLVMBitCodes.h:691
@ ATTR_KIND_NOFPCLASS
Definition: LLVMBitCodes.h:776
@ ATTR_KIND_WILLRETURN
Definition: LLVMBitCodes.h:750
@ ATTR_KIND_SANITIZE_TYPE
Definition: LLVMBitCodes.h:790
@ ATTR_KIND_PRESPLIT_COROUTINE
Definition: LLVMBitCodes.h:772
@ ATTR_KIND_NO_ALIAS
Definition: LLVMBitCodes.h:698
@ ATTR_KIND_VSCALE_RANGE
Definition: LLVMBitCodes.h:763
@ ATTR_KIND_NO_SANITIZE_COVERAGE
Definition: LLVMBitCodes.h:765
@ ATTR_KIND_JUMP_TABLE
Definition: LLVMBitCodes.h:729
@ ATTR_KIND_SPECULATABLE
Definition: LLVMBitCodes.h:742
@ ATTR_KIND_NO_INLINE
Definition: LLVMBitCodes.h:703
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
Definition: LLVMBitCodes.h:786
@ ATTR_KIND_NO_SANITIZE_BOUNDS
Definition: LLVMBitCodes.h:768
@ ATTR_KIND_SANITIZE_MEMTAG
Definition: LLVMBitCodes.h:753
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
Definition: LLVMBitCodes.h:779
@ ATTR_KIND_CAPTURES
Definition: LLVMBitCodes.h:791
@ ATTR_KIND_SANITIZE_THREAD
Definition: LLVMBitCodes.h:720
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
Definition: LLVMBitCodes.h:777
@ ATTR_KIND_PREALLOCATED
Definition: LLVMBitCodes.h:754
@ ATTR_KIND_SWIFT_ASYNC
Definition: LLVMBitCodes.h:764
@ OBO_NO_SIGNED_WRAP
Definition: LLVMBitCodes.h:512
@ OBO_NO_UNSIGNED_WRAP
Definition: LLVMBitCodes.h:511
@ TIO_NO_UNSIGNED_WRAP
Definition: LLVMBitCodes.h:518
@ TIO_NO_SIGNED_WRAP
Definition: LLVMBitCodes.h:519
@ USELIST_CODE_DEFAULT
Definition: LLVMBitCodes.h:684
@ SYNC_SCOPE_NAMES_BLOCK_ID
Definition: LLVMBitCodes.h:65
@ PARAMATTR_BLOCK_ID
Definition: LLVMBitCodes.h:33
@ TYPE_BLOCK_ID_NEW
Definition: LLVMBitCodes.h:48
@ CONSTANTS_BLOCK_ID
Definition: LLVMBitCodes.h:36
@ PARAMATTR_GROUP_BLOCK_ID
Definition: LLVMBitCodes.h:34
@ METADATA_KIND_BLOCK_ID
Definition: LLVMBitCodes.h:57
@ IDENTIFICATION_BLOCK_ID
Definition: LLVMBitCodes.h:42
@ GLOBALVAL_SUMMARY_BLOCK_ID
Definition: LLVMBitCodes.h:53
@ METADATA_ATTACHMENT_ID
Definition: LLVMBitCodes.h:46
@ METADATA_BLOCK_ID
Definition: LLVMBitCodes.h:45
@ FUNCTION_BLOCK_ID
Definition: LLVMBitCodes.h:37
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
Definition: LLVMBitCodes.h:61
@ MODULE_STRTAB_BLOCK_ID
Definition: LLVMBitCodes.h:52
@ VALUE_SYMTAB_BLOCK_ID
Definition: LLVMBitCodes.h:44
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
Definition: LLVMBitCodes.h:55
@ USELIST_BLOCK_ID
Definition: LLVMBitCodes.h:50
@ CAST_ADDRSPACECAST
Definition: LLVMBitCodes.h:452
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
Definition: BitCodeEnums.h:69
@ MODULE_CODE_FUNCTION
Definition: LLVMBitCodes.h:100
@ MODULE_CODE_VERSION
Definition: LLVMBitCodes.h:85
@ MODULE_CODE_SOURCE_FILENAME
Definition: LLVMBitCodes.h:116
@ MODULE_CODE_SECTIONNAME
Definition: LLVMBitCodes.h:89
@ MODULE_CODE_TRIPLE
Definition: LLVMBitCodes.h:86
@ MODULE_CODE_DATALAYOUT
Definition: LLVMBitCodes.h:87
@ MODULE_CODE_GLOBALVAR
Definition: LLVMBitCodes.h:96
@ MODULE_CODE_ALIAS_OLD
Definition: LLVMBitCodes.h:103
@ MODULE_CODE_VSTOFFSET
Definition: LLVMBitCodes.h:108
@ MODULE_CODE_GCNAME
Definition: LLVMBitCodes.h:105
@ MODULE_CODE_DEPLIB
Definition: LLVMBitCodes.h:92
@ MODULE_CODE_COMDAT
Definition: LLVMBitCodes.h:106
@ FUNC_CODE_INST_ATOMICRMW_OLD
Definition: LLVMBitCodes.h:636
@ FUNC_CODE_INST_CATCHRET
Definition: LLVMBitCodes.h:654
@ FUNC_CODE_INST_LANDINGPAD
Definition: LLVMBitCodes.h:652
@ FUNC_CODE_INST_EXTRACTVAL
Definition: LLVMBitCodes.h:617
@ FUNC_CODE_INST_CATCHPAD
Definition: LLVMBitCodes.h:655
@ FUNC_CODE_INST_RESUME
Definition: LLVMBitCodes.h:639
@ FUNC_CODE_INST_CMP2
Definition: LLVMBitCodes.h:621
@ FUNC_CODE_INST_FENCE
Definition: LLVMBitCodes.h:632
@ FUNC_CODE_INST_CALLBR
Definition: LLVMBitCodes.h:663
@ FUNC_CODE_INST_CATCHSWITCH
Definition: LLVMBitCodes.h:657
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
Definition: LLVMBitCodes.h:624
@ FUNC_CODE_INST_VSELECT
Definition: LLVMBitCodes.h:623
@ FUNC_CODE_INST_GEP_OLD
Definition: LLVMBitCodes.h:590
@ FUNC_CODE_INST_GEP
Definition: LLVMBitCodes.h:646
@ FUNC_CODE_INST_STOREATOMIC_OLD
Definition: LLVMBitCodes.h:644
@ FUNC_CODE_INST_CLEANUPRET
Definition: LLVMBitCodes.h:653
@ FUNC_CODE_INST_LANDINGPAD_OLD
Definition: LLVMBitCodes.h:640
@ FUNC_CODE_DEBUG_RECORD_VALUE
Definition: LLVMBitCodes.h:671
@ FUNC_CODE_INST_LOADATOMIC
Definition: LLVMBitCodes.h:642
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
Definition: LLVMBitCodes.h:675
@ FUNC_CODE_INST_LOAD
Definition: LLVMBitCodes.h:608
@ FUNC_CODE_INST_STOREATOMIC
Definition: LLVMBitCodes.h:648
@ FUNC_CODE_INST_ATOMICRMW
Definition: LLVMBitCodes.h:666
@ FUNC_CODE_INST_BINOP
Definition: LLVMBitCodes.h:588
@ FUNC_CODE_INST_STORE
Definition: LLVMBitCodes.h:647
@ FUNC_CODE_DEBUG_LOC_AGAIN
Definition: LLVMBitCodes.h:627
@ FUNC_CODE_INST_EXTRACTELT
Definition: LLVMBitCodes.h:592
@ FUNC_CODE_INST_INDIRECTBR
Definition: LLVMBitCodes.h:625
@ FUNC_CODE_INST_INVOKE
Definition: LLVMBitCodes.h:600
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
Definition: LLVMBitCodes.h:678
@ FUNC_CODE_INST_INSERTVAL
Definition: LLVMBitCodes.h:618
@ FUNC_CODE_DECLAREBLOCKS
Definition: LLVMBitCodes.h:586
@ FUNC_CODE_DEBUG_RECORD_LABEL
Definition: LLVMBitCodes.h:680
@ FUNC_CODE_INST_SWITCH
Definition: LLVMBitCodes.h:599
@ FUNC_CODE_INST_PHI
Definition: LLVMBitCodes.h:604
@ FUNC_CODE_INST_RET
Definition: LLVMBitCodes.h:597
@ FUNC_CODE_INST_CALL
Definition: LLVMBitCodes.h:629
@ FUNC_CODE_INST_ALLOCA
Definition: LLVMBitCodes.h:607
@ FUNC_CODE_INST_INSERTELT
Definition: LLVMBitCodes.h:593
@ FUNC_CODE_INST_SELECT
Definition: LLVMBitCodes.h:591
@ FUNC_CODE_BLOCKADDR_USERS
Definition: LLVMBitCodes.h:669
@ FUNC_CODE_INST_CLEANUPPAD
Definition: LLVMBitCodes.h:656
@ FUNC_CODE_INST_SHUFFLEVEC
Definition: LLVMBitCodes.h:594
@ FUNC_CODE_INST_UNOP
Definition: LLVMBitCodes.h:662
@ FUNC_CODE_INST_STORE_OLD
Definition: LLVMBitCodes.h:615
@ FUNC_CODE_INST_VAARG
Definition: LLVMBitCodes.h:611
@ FUNC_CODE_INST_FREEZE
Definition: LLVMBitCodes.h:665
@ FUNC_CODE_INST_CMPXCHG
Definition: LLVMBitCodes.h:649
@ FUNC_CODE_INST_UNREACHABLE
Definition: LLVMBitCodes.h:602
@ FUNC_CODE_INST_CAST
Definition: LLVMBitCodes.h:589
@ FUNC_CODE_INST_CMPXCHG_OLD
Definition: LLVMBitCodes.h:633
@ FUNC_CODE_DEBUG_LOC
Definition: LLVMBitCodes.h:631
@ FUNC_CODE_DEBUG_RECORD_DECLARE
Definition: LLVMBitCodes.h:673
@ FUNC_CODE_OPERAND_BUNDLE
Definition: LLVMBitCodes.h:661
@ FUNC_CODE_INST_CMP
Definition: LLVMBitCodes.h:595
@ OPERAND_BUNDLE_TAG
Definition: LLVMBitCodes.h:183
@ PARAMATTR_CODE_ENTRY_OLD
Definition: LLVMBitCodes.h:128
@ PARAMATTR_GRP_CODE_ENTRY
Definition: LLVMBitCodes.h:131
@ PARAMATTR_CODE_ENTRY
Definition: LLVMBitCodes.h:130
@ ORDERING_NOTATOMIC
Definition: LLVMBitCodes.h:564
@ ORDERING_UNORDERED
Definition: LLVMBitCodes.h:565
@ ORDERING_MONOTONIC
Definition: LLVMBitCodes.h:566
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
constexpr double e
Definition: MathExtras.h:47
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
@ FalseVal
Definition: TGLexer.h:59
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
@ Offset
Definition: DWP.cpp:480
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition: STLExtras.h:854
void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
const std::error_category & BitcodeErrorCategory()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1697
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
void UpgradeInlineAsmString(std::string *AsmStr)
Upgrade comment in call to inline asm that represents an objc retain release marker.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition: STLExtras.h:2448
std::error_code make_error_code(BitcodeError E)
bool stripDebugInfo(Function &F)
Definition: DebugInfo.cpp:569
AllocFnKind
Definition: Attributes.h:49
Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:977
bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
Definition: IRMutator.cpp:667
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:657
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1291
void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
StringMapEntry< Value * > ValueName
Definition: Value.h:55
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition: STLExtras.h:1952
Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
UWTableKind
Definition: CodeGen.h:120
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:292
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
Definition: Error.h:221
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
std::string UpgradeDataLayoutString(StringRef DL, StringRef Triple)
Upgrade the datalayout string by adding a section for address space pointers.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1753
Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:608
AtomicOrdering
Atomic ordering for LLVM's memory model.
Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
MaybeAlign decodeMaybeAlign(unsigned Value)
Dual operation of the encode function above.
Definition: Alignment.h:220
DWARFExpression::Operation Op
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:217
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition: Casting.h:565
gep_type_iterator gep_type_begin(const User *GEP)
APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
Represents the EMUL and EEW of a MachineOperand.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Summary of memprof metadata on allocations.
Basic information extracted from a bitcode module to be used for LTO.
Definition: BitcodeReader.h:93
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
Class to accumulate and hold information about a callee.
static constexpr unsigned RelBlockFreqBits
The value stored in RelBlockFreq has to be interpreted as the digits of a scaled number with a scale ...
Summary of memprof callsite metadata.
Flags specific to function summaries.
Describes the uses of a parameter by the function.
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
Summary of a single MIB in a memprof metadata on allocations.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
GetContainedTypeIDTy GetContainedTypeID
std::optional< MDTypeCallbackTy > MDType
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
Definition: BitcodeReader.h:81
std::optional< DataLayoutCallbackFuncTy > DataLayout
Definition: BitcodeReader.h:73
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
Definition: BitcodeReader.h:83
A MapVector that performs no allocations if smaller than a certain size.
Definition: MapVector.h:254
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
Kind
Specifies which kind of type check we should emit for this byte array.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition: LLParser.h:53
Struct that holds a reference to a particular GUID in a global value summary.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...