LLVM 23.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"
79#include <algorithm>
80#include <cassert>
81#include <cstddef>
82#include <cstdint>
83#include <deque>
84#include <map>
85#include <memory>
86#include <optional>
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
105namespace {
106
107enum {
108 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
109};
110
111} // end anonymous namespace
112
113static Error error(const Twine &Message) {
116}
117
119 if (!Stream.canSkipToPos(4))
120 return createStringError(std::errc::illegal_byte_sequence,
121 "file too small to contain bitcode header");
122 for (unsigned C : {'B', 'C'})
123 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
124 if (Res.get() != C)
125 return createStringError(std::errc::illegal_byte_sequence,
126 "file doesn't start with bitcode header");
127 } else
128 return Res.takeError();
129 for (unsigned C : {0x0, 0xC, 0xE, 0xD})
130 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
131 if (Res.get() != C)
132 return createStringError(std::errc::illegal_byte_sequence,
133 "file doesn't start with bitcode header");
134 } else
135 return Res.takeError();
136 return Error::success();
137}
138
140 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
141 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
142
143 if (Buffer.getBufferSize() & 3)
144 return error("Invalid bitcode signature");
145
146 // If we have a wrapper header, parse it and ignore the non-bc file contents.
147 // The magic number is 0x0B17C0DE stored in little endian.
148 if (isBitcodeWrapper(BufPtr, BufEnd))
149 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
150 return error("Invalid bitcode wrapper header");
151
152 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
153 if (Error Err = hasInvalidBitcodeHeader(Stream))
154 return std::move(Err);
155
156 return std::move(Stream);
157}
158
159/// Convert a string from a record into an std::string, return true on failure.
160template <typename StrTy>
161static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
162 StrTy &Result) {
163 if (Idx > Record.size())
164 return true;
165
166 Result.append(Record.begin() + Idx, Record.end());
167 return false;
168}
169
170// Strip all the TBAA attachment for the module.
171static void stripTBAA(Module *M) {
172 for (auto &F : *M) {
173 if (F.isMaterializable())
174 continue;
175 for (auto &I : instructions(F))
176 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
177 }
178}
179
180/// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
181/// "epoch" encoded in the bitcode, and return the producer name if any.
184 return std::move(Err);
185
186 // Read all the records.
188
189 std::string ProducerIdentification;
190
191 while (true) {
192 BitstreamEntry Entry;
193 if (Error E = Stream.advance().moveInto(Entry))
194 return std::move(E);
195
196 switch (Entry.Kind) {
197 default:
199 return error("Malformed block");
201 return ProducerIdentification;
203 // The interesting case.
204 break;
205 }
206
207 // Read a record.
208 Record.clear();
209 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
210 if (!MaybeBitCode)
211 return MaybeBitCode.takeError();
212 switch (MaybeBitCode.get()) {
213 default: // Default behavior: reject
214 return error("Invalid value");
215 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
216 convertToString(Record, 0, ProducerIdentification);
217 break;
218 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
219 unsigned epoch = (unsigned)Record[0];
220 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
221 return error(
222 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
223 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
224 }
225 }
226 }
227 }
228}
229
231 // We expect a number of well-defined blocks, though we don't necessarily
232 // need to understand them all.
233 while (true) {
234 if (Stream.AtEndOfStream())
235 return "";
236
237 BitstreamEntry Entry;
238 if (Error E = Stream.advance().moveInto(Entry))
239 return std::move(E);
240
241 switch (Entry.Kind) {
244 return error("Malformed block");
245
247 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
248 return readIdentificationBlock(Stream);
249
250 // Ignore other sub-blocks.
251 if (Error Err = Stream.SkipBlock())
252 return std::move(Err);
253 continue;
255 if (Error E = Stream.skipRecord(Entry.ID).takeError())
256 return std::move(E);
257 continue;
258 }
259 }
260}
261
263 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
264 return std::move(Err);
265
267 // Read all the records for this module.
268
269 while (true) {
271 if (!MaybeEntry)
272 return MaybeEntry.takeError();
273 BitstreamEntry Entry = MaybeEntry.get();
274
275 switch (Entry.Kind) {
276 case BitstreamEntry::SubBlock: // Handled for us already.
278 return error("Malformed block");
280 return false;
282 // The interesting case.
283 break;
284 }
285
286 // Read a record.
287 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
288 if (!MaybeRecord)
289 return MaybeRecord.takeError();
290 switch (MaybeRecord.get()) {
291 default:
292 break; // Default behavior, ignore unknown content.
293 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
294 std::string S;
295 if (convertToString(Record, 0, S))
296 return error("Invalid section name record");
297
298 // Check for the i386 and other (x86_64, ARM) conventions
299
300 auto [Segment, Section] = StringRef(S).split(",");
301 Segment = Segment.trim();
302 Section = Section.trim();
303
304 if (Segment == "__DATA" && Section.starts_with("__objc_catlist"))
305 return true;
306 if (Segment == "__OBJC" && Section.starts_with("__category"))
307 return true;
308 if (Segment == "__TEXT" && Section.starts_with("__swift"))
309 return true;
310 break;
311 }
312 }
313 Record.clear();
314 }
315 llvm_unreachable("Exit infinite loop");
316}
317
319 // We expect a number of well-defined blocks, though we don't necessarily
320 // need to understand them all.
321 while (true) {
322 BitstreamEntry Entry;
323 if (Error E = Stream.advance().moveInto(Entry))
324 return std::move(E);
325
326 switch (Entry.Kind) {
328 return error("Malformed block");
330 return false;
331
333 if (Entry.ID == bitc::MODULE_BLOCK_ID)
334 return hasObjCCategoryInModule(Stream);
335
336 // Ignore other sub-blocks.
337 if (Error Err = Stream.SkipBlock())
338 return std::move(Err);
339 continue;
340
342 if (Error E = Stream.skipRecord(Entry.ID).takeError())
343 return std::move(E);
344 continue;
345 }
346 }
347}
348
350 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
351 return std::move(Err);
352
354
355 std::string Triple;
356
357 // Read all the records for this module.
358 while (true) {
360 if (!MaybeEntry)
361 return MaybeEntry.takeError();
362 BitstreamEntry Entry = MaybeEntry.get();
363
364 switch (Entry.Kind) {
365 case BitstreamEntry::SubBlock: // Handled for us already.
367 return error("Malformed block");
369 return Triple;
371 // The interesting case.
372 break;
373 }
374
375 // Read a record.
376 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
377 if (!MaybeRecord)
378 return MaybeRecord.takeError();
379 switch (MaybeRecord.get()) {
380 default: break; // Default behavior, ignore unknown content.
381 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
382 std::string S;
383 if (convertToString(Record, 0, S))
384 return error("Invalid triple record");
385 Triple = S;
386 break;
387 }
388 }
389 Record.clear();
390 }
391 llvm_unreachable("Exit infinite loop");
392}
393
395 // We expect a number of well-defined blocks, though we don't necessarily
396 // need to understand them all.
397 while (true) {
398 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
399 if (!MaybeEntry)
400 return MaybeEntry.takeError();
401 BitstreamEntry Entry = MaybeEntry.get();
402
403 switch (Entry.Kind) {
405 return error("Malformed block");
407 return "";
408
410 if (Entry.ID == bitc::MODULE_BLOCK_ID)
411 return readModuleTriple(Stream);
412
413 // Ignore other sub-blocks.
414 if (Error Err = Stream.SkipBlock())
415 return std::move(Err);
416 continue;
417
419 if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
420 continue;
421 else
422 return Skipped.takeError();
423 }
424 }
425}
426
427namespace {
428
429class BitcodeReaderBase {
430protected:
431 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
432 : Stream(std::move(Stream)), Strtab(Strtab) {
433 this->Stream.setBlockInfo(&BlockInfo);
434 }
435
436 BitstreamBlockInfo BlockInfo;
437 BitstreamCursor Stream;
438 StringRef Strtab;
439
440 /// In version 2 of the bitcode we store names of global values and comdats in
441 /// a string table rather than in the VST.
442 bool UseStrtab = false;
443
444 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
445
446 /// If this module uses a string table, pop the reference to the string table
447 /// and return the referenced string and the rest of the record. Otherwise
448 /// just return the record itself.
449 std::pair<StringRef, ArrayRef<uint64_t>>
450 readNameFromStrtab(ArrayRef<uint64_t> Record);
451
452 Error readBlockInfo();
453
454 // Contains an arbitrary and optional string identifying the bitcode producer
455 std::string ProducerIdentification;
456
457 Error error(const Twine &Message);
458};
459
460} // end anonymous namespace
461
462Error BitcodeReaderBase::error(const Twine &Message) {
463 std::string FullMsg = Message.str();
464 if (!ProducerIdentification.empty())
465 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
466 LLVM_VERSION_STRING "')";
467 return ::error(FullMsg);
468}
469
470Expected<unsigned>
471BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
472 if (Record.empty())
473 return error("Invalid version record");
474 unsigned ModuleVersion = Record[0];
475 if (ModuleVersion > 2)
476 return error("Invalid value");
477 UseStrtab = ModuleVersion >= 2;
478 return ModuleVersion;
479}
480
481std::pair<StringRef, ArrayRef<uint64_t>>
482BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
483 if (!UseStrtab)
484 return {"", Record};
485 // Invalid reference. Let the caller complain about the record being empty.
486 if (Record[0] + Record[1] > Strtab.size())
487 return {"", {}};
488 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
489}
490
491namespace {
492
493/// This represents a constant expression or constant aggregate using a custom
494/// structure internal to the bitcode reader. Later, this structure will be
495/// expanded by materializeValue() either into a constant expression/aggregate,
496/// or into an instruction sequence at the point of use. This allows us to
497/// upgrade bitcode using constant expressions even if this kind of constant
498/// expression is no longer supported.
499class BitcodeConstant final : public Value,
500 TrailingObjects<BitcodeConstant, unsigned> {
501 friend TrailingObjects;
502
503 // Value subclass ID: Pick largest possible value to avoid any clashes.
504 static constexpr uint8_t SubclassID = 255;
505
506public:
507 // Opcodes used for non-expressions. This includes constant aggregates
508 // (struct, array, vector) that might need expansion, as well as non-leaf
509 // constants that don't need expansion (no_cfi, dso_local, blockaddress),
510 // but still go through BitcodeConstant to avoid different uselist orders
511 // between the two cases.
512 static constexpr uint8_t ConstantStructOpcode = 255;
513 static constexpr uint8_t ConstantArrayOpcode = 254;
514 static constexpr uint8_t ConstantVectorOpcode = 253;
515 static constexpr uint8_t NoCFIOpcode = 252;
516 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
517 static constexpr uint8_t BlockAddressOpcode = 250;
518 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
519 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
520
521 // Separate struct to make passing different number of parameters to
522 // BitcodeConstant::create() more convenient.
523 struct ExtraInfo {
524 uint8_t Opcode;
525 uint8_t Flags;
526 unsigned BlockAddressBB = 0;
527 Type *SrcElemTy = nullptr;
528 std::optional<ConstantRange> InRange;
529
530 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, Type *SrcElemTy = nullptr,
531 std::optional<ConstantRange> InRange = std::nullopt)
532 : Opcode(Opcode), Flags(Flags), SrcElemTy(SrcElemTy),
533 InRange(std::move(InRange)) {}
534
535 ExtraInfo(uint8_t Opcode, uint8_t Flags, unsigned BlockAddressBB)
536 : Opcode(Opcode), Flags(Flags), BlockAddressBB(BlockAddressBB) {}
537 };
538
539 uint8_t Opcode;
540 uint8_t Flags;
541 unsigned NumOperands;
542 unsigned BlockAddressBB;
543 Type *SrcElemTy; // GEP source element type.
544 std::optional<ConstantRange> InRange; // GEP inrange attribute.
545
546private:
547 BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
548 : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags),
549 NumOperands(OpIDs.size()), BlockAddressBB(Info.BlockAddressBB),
550 SrcElemTy(Info.SrcElemTy), InRange(Info.InRange) {
551 llvm::uninitialized_copy(OpIDs, getTrailingObjects());
552 }
553
554 BitcodeConstant &operator=(const BitcodeConstant &) = delete;
555
556public:
557 static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty,
558 const ExtraInfo &Info,
559 ArrayRef<unsigned> OpIDs) {
560 void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()),
561 alignof(BitcodeConstant));
562 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
563 }
564
565 static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
566
567 ArrayRef<unsigned> getOperandIDs() const {
568 return ArrayRef(getTrailingObjects(), NumOperands);
569 }
570
571 std::optional<ConstantRange> getInRange() const {
572 assert(Opcode == Instruction::GetElementPtr);
573 return InRange;
574 }
575
576 const char *getOpcodeName() const {
577 return Instruction::getOpcodeName(Opcode);
578 }
579};
580
581class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
582 LLVMContext &Context;
583 Module *TheModule = nullptr;
584 // Next offset to start scanning for lazy parsing of function bodies.
585 uint64_t NextUnreadBit = 0;
586 // Last function offset found in the VST.
587 uint64_t LastFunctionBlockBit = 0;
588 bool SeenValueSymbolTable = false;
589 uint64_t VSTOffset = 0;
590
591 std::vector<std::string> SectionTable;
592 std::vector<std::string> GCTable;
593
594 std::vector<Type *> TypeList;
595 /// Track type IDs of contained types. Order is the same as the contained
596 /// types of a Type*. This is used during upgrades of typed pointer IR in
597 /// opaque pointer mode.
598 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
599 /// In some cases, we need to create a type ID for a type that was not
600 /// explicitly encoded in the bitcode, or we don't know about at the current
601 /// point. For example, a global may explicitly encode the value type ID, but
602 /// not have a type ID for the pointer to value type, for which we create a
603 /// virtual type ID instead. This map stores the new type ID that was created
604 /// for the given pair of Type and contained type ID.
605 DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;
606 DenseMap<Function *, unsigned> FunctionTypeIDs;
607 /// Allocator for BitcodeConstants. This should come before ValueList,
608 /// because the ValueList might hold ValueHandles to these constants, so
609 /// ValueList must be destroyed before Alloc.
611 BitcodeReaderValueList ValueList;
612 std::optional<MetadataLoader> MDLoader;
613 std::vector<Comdat *> ComdatList;
614 DenseSet<GlobalObject *> ImplicitComdatObjects;
615 SmallVector<Instruction *, 64> InstructionList;
616
617 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
618 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
619
620 struct FunctionOperandInfo {
621 Function *F;
622 unsigned PersonalityFn;
623 unsigned Prefix;
624 unsigned Prologue;
625 };
626 std::vector<FunctionOperandInfo> FunctionOperands;
627
628 /// The set of attributes by index. Index zero in the file is for null, and
629 /// is thus not represented here. As such all indices are off by one.
630 std::vector<AttributeList> MAttributes;
631
632 /// The set of attribute groups.
633 std::map<unsigned, AttributeList> MAttributeGroups;
634
635 /// While parsing a function body, this is a list of the basic blocks for the
636 /// function.
637 std::vector<BasicBlock*> FunctionBBs;
638
639 // When reading the module header, this list is populated with functions that
640 // have bodies later in the file.
641 std::vector<Function*> FunctionsWithBodies;
642
643 // When intrinsic functions are encountered which require upgrading they are
644 // stored here with their replacement function.
645 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
646 UpdatedIntrinsicMap UpgradedIntrinsics;
647
648 // Several operations happen after the module header has been read, but
649 // before function bodies are processed. This keeps track of whether
650 // we've done this yet.
651 bool SeenFirstFunctionBody = false;
652
653 /// When function bodies are initially scanned, this map contains info about
654 /// where to find deferred function body in the stream.
655 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
656
657 /// When Metadata block is initially scanned when parsing the module, we may
658 /// choose to defer parsing of the metadata. This vector contains info about
659 /// which Metadata blocks are deferred.
660 std::vector<uint64_t> DeferredMetadataInfo;
661
662 /// These are basic blocks forward-referenced by block addresses. They are
663 /// inserted lazily into functions when they're loaded. The basic block ID is
664 /// its index into the vector.
665 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
666 std::deque<Function *> BasicBlockFwdRefQueue;
667
668 /// These are Functions that contain BlockAddresses which refer a different
669 /// Function. When parsing the different Function, queue Functions that refer
670 /// to the different Function. Those Functions must be materialized in order
671 /// to resolve their BlockAddress constants before the different Function
672 /// gets moved into another Module.
673 std::vector<Function *> BackwardRefFunctions;
674
675 /// Indicates that we are using a new encoding for instruction operands where
676 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
677 /// instruction number, for a more compact encoding. Some instruction
678 /// operands are not relative to the instruction ID: basic block numbers, and
679 /// types. Once the old style function blocks have been phased out, we would
680 /// not need this flag.
681 bool UseRelativeIDs = false;
682
683 /// True if all functions will be materialized, negating the need to process
684 /// (e.g.) blockaddress forward references.
685 bool WillMaterializeAllForwardRefs = false;
686
687 /// Tracks whether we have seen debug intrinsics or records in this bitcode;
688 /// seeing both in a single module is currently a fatal error.
689 bool SeenDebugIntrinsic = false;
690 bool SeenDebugRecord = false;
691
692 bool StripDebugInfo = false;
693 TBAAVerifier TBAAVerifyHelper;
694
695 std::vector<std::string> BundleTags;
697
698 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
699
700public:
701 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
702 StringRef ProducerIdentification, LLVMContext &Context);
703
704 Error materializeForwardReferencedFunctions();
705
706 Error materialize(GlobalValue *GV) override;
707 Error materializeModule() override;
708 std::vector<StructType *> getIdentifiedStructTypes() const override;
709
710 /// Main interface to parsing a bitcode buffer.
711 /// \returns true if an error occurred.
712 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
713 bool IsImporting, ParserCallbacks Callbacks = {});
714
715 static uint64_t decodeSignRotatedValue(uint64_t V);
716
717 /// Materialize any deferred Metadata block.
718 Error materializeMetadata() override;
719
720 void setStripDebugInfo() override;
721
722private:
723 std::vector<StructType *> IdentifiedStructTypes;
724 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
725 StructType *createIdentifiedStructType(LLVMContext &Context);
726
727 static constexpr unsigned InvalidTypeID = ~0u;
728
729 Type *getTypeByID(unsigned ID);
730 Type *getPtrElementTypeByID(unsigned ID);
731 unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);
732 unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
733
734 void callValueTypeCallback(Value *F, unsigned TypeID);
735 Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
736 Expected<Constant *> getValueForInitializer(unsigned ID);
737
738 Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID,
739 BasicBlock *ConstExprInsertBB) {
740 if (Ty && Ty->isMetadataTy())
741 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
742 return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB);
743 }
744
745 Metadata *getFnMetadataByID(unsigned ID) {
746 return MDLoader->getMetadataFwdRefOrLoad(ID);
747 }
748
749 BasicBlock *getBasicBlock(unsigned ID) const {
750 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
751 return FunctionBBs[ID];
752 }
753
754 AttributeList getAttributes(unsigned i) const {
755 if (i-1 < MAttributes.size())
756 return MAttributes[i-1];
757 return AttributeList();
758 }
759
760 /// Read a value/type pair out of the specified record from slot 'Slot'.
761 /// Increment Slot past the number of slots used in the record. Return true on
762 /// failure.
763 bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
764 unsigned InstNum, Value *&ResVal, unsigned &TypeID,
765 BasicBlock *ConstExprInsertBB) {
766 if (Slot == Record.size()) return true;
767 unsigned ValNo = (unsigned)Record[Slot++];
768 // Adjust the ValNo, if it was encoded relative to the InstNum.
769 if (UseRelativeIDs)
770 ValNo = InstNum - ValNo;
771 if (ValNo < InstNum) {
772 // If this is not a forward reference, just return the value we already
773 // have.
774 TypeID = ValueList.getTypeID(ValNo);
775 ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB);
776 assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&
777 "Incorrect type ID stored for value");
778 return ResVal == nullptr;
779 }
780 if (Slot == Record.size())
781 return true;
782
783 TypeID = (unsigned)Record[Slot++];
784 ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID,
785 ConstExprInsertBB);
786 return ResVal == nullptr;
787 }
788
789 bool getValueOrMetadata(const SmallVectorImpl<uint64_t> &Record,
790 unsigned &Slot, unsigned InstNum, Value *&ResVal,
791 BasicBlock *ConstExprInsertBB) {
792 if (Slot == Record.size())
793 return true;
794 unsigned ValID = Record[Slot++];
795 if (ValID != static_cast<unsigned>(bitc::OB_METADATA)) {
796 unsigned TypeId;
797 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
798 ConstExprInsertBB);
799 }
800 if (Slot == Record.size())
801 return true;
802 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
803 ResVal = MetadataAsValue::get(Context, getFnMetadataByID(ValNo));
804 return false;
805 }
806
807 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
808 /// past the number of slots used by the value in the record. Return true if
809 /// there is an error.
810 bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
811 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
812 BasicBlock *ConstExprInsertBB) {
813 if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
814 return true;
815 // All values currently take a single record slot.
816 ++Slot;
817 return false;
818 }
819
820 /// Like popValue, but does not increment the Slot number.
821 bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
822 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
823 BasicBlock *ConstExprInsertBB) {
824 ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
825 return ResVal == nullptr;
826 }
827
828 /// Version of getValue that returns ResVal directly, or 0 if there is an
829 /// error.
830 Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
831 unsigned InstNum, Type *Ty, unsigned TyID,
832 BasicBlock *ConstExprInsertBB) {
833 if (Slot == Record.size()) return nullptr;
834 unsigned ValNo = (unsigned)Record[Slot];
835 // Adjust the ValNo, if it was encoded relative to the InstNum.
836 if (UseRelativeIDs)
837 ValNo = InstNum - ValNo;
838 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
839 }
840
841 /// Like getValue, but decodes signed VBRs.
842 Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
843 unsigned InstNum, Type *Ty, unsigned TyID,
844 BasicBlock *ConstExprInsertBB) {
845 if (Slot == Record.size()) return nullptr;
846 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
847 // Adjust the ValNo, if it was encoded relative to the InstNum.
848 if (UseRelativeIDs)
849 ValNo = InstNum - ValNo;
850 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
851 }
852
853 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
854 unsigned &OpNum,
855 unsigned BitWidth) {
856 if (Record.size() - OpNum < 2)
857 return error("Too few records for range");
858 if (BitWidth > 64) {
859 unsigned LowerActiveWords = Record[OpNum];
860 unsigned UpperActiveWords = Record[OpNum++] >> 32;
861 if (Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
862 return error("Too few records for range");
863 APInt Lower =
864 readWideAPInt(ArrayRef(&Record[OpNum], LowerActiveWords), BitWidth);
865 OpNum += LowerActiveWords;
866 APInt Upper =
867 readWideAPInt(ArrayRef(&Record[OpNum], UpperActiveWords), BitWidth);
868 OpNum += UpperActiveWords;
869 return ConstantRange(Lower, Upper);
870 } else {
871 int64_t Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
872 int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
873 return ConstantRange(APInt(BitWidth, Start, true),
874 APInt(BitWidth, End, true));
875 }
876 }
877
878 Expected<ConstantRange>
879 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record, unsigned &OpNum) {
880 if (Record.size() - OpNum < 1)
881 return error("Too few records for range");
882 unsigned BitWidth = Record[OpNum++];
883 return readConstantRange(Record, OpNum, BitWidth);
884 }
885
886 /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
887 /// corresponding argument's pointee type. Also upgrades intrinsics that now
888 /// require an elementtype attribute.
889 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
890
891 /// Converts alignment exponent (i.e. power of two (or zero)) to the
892 /// corresponding alignment to use. If alignment is too large, returns
893 /// a corresponding error code.
894 Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
895 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
896 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
897 ParserCallbacks Callbacks = {});
898
899 Error parseComdatRecord(ArrayRef<uint64_t> Record);
900 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
901 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
902 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
903 ArrayRef<uint64_t> Record);
904
905 Error parseAttributeBlock();
906 Error parseAttributeGroupBlock();
907 Error parseTypeTable();
908 Error parseTypeTableBody();
909 Error parseOperandBundleTags();
910 Error parseSyncScopeNames();
911
912 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
913 unsigned NameIndex, Triple &TT);
914 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
915 ArrayRef<uint64_t> Record);
916 Error parseValueSymbolTable(uint64_t Offset = 0);
917 Error parseGlobalValueSymbolTable();
918 Error parseConstants();
919 Error rememberAndSkipFunctionBodies();
920 Error rememberAndSkipFunctionBody();
921 /// Save the positions of the Metadata blocks and skip parsing the blocks.
922 Error rememberAndSkipMetadata();
923 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
924 Error parseFunctionBody(Function *F);
925 Error globalCleanup();
926 Error resolveGlobalAndIndirectSymbolInits();
927 Error parseUseLists();
928 Error findFunctionInStream(
929 Function *F,
930 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
931
932 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
933};
934
935/// Class to manage reading and parsing function summary index bitcode
936/// files/sections.
937class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
938 /// The module index built during parsing.
939 ModuleSummaryIndex &TheIndex;
940
941 /// Indicates whether we have encountered a global value summary section
942 /// yet during parsing.
943 bool SeenGlobalValSummary = false;
944
945 /// Indicates whether we have already parsed the VST, used for error checking.
946 bool SeenValueSymbolTable = false;
947
948 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
949 /// Used to enable on-demand parsing of the VST.
950 uint64_t VSTOffset = 0;
951
952 // Map to save ValueId to ValueInfo association that was recorded in the
953 // ValueSymbolTable. It is used after the VST is parsed to convert
954 // call graph edges read from the function summary from referencing
955 // callees by their ValueId to using the ValueInfo instead, which is how
956 // they are recorded in the summary index being built.
957 // We save a GUID which refers to the same global as the ValueInfo, but
958 // ignoring the linkage, i.e. for values other than local linkage they are
959 // identical (this is the second member). ValueInfo has the real GUID.
960 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
961 ValueIdToValueInfoMap;
962
963 /// Map populated during module path string table parsing, from the
964 /// module ID to a string reference owned by the index's module
965 /// path string table, used to correlate with combined index
966 /// summary records.
967 DenseMap<uint64_t, StringRef> ModuleIdMap;
968
969 /// Original source file name recorded in a bitcode record.
970 std::string SourceFileName;
971
972 /// The string identifier given to this module by the client, normally the
973 /// path to the bitcode file.
974 StringRef ModulePath;
975
976 /// Callback to ask whether a symbol is the prevailing copy when invoked
977 /// during combined index building.
978 std::function<bool(GlobalValue::GUID)> IsPrevailing;
979
980 /// Saves the stack ids from the STACK_IDS record to consult when adding stack
981 /// ids from the lists in the callsite and alloc entries to the index.
982 std::vector<uint64_t> StackIds;
983
984 /// Linearized radix tree of allocation contexts. See the description above
985 /// the CallStackRadixTreeBuilder class in ProfileData/MemProf.h for format.
986 std::vector<uint64_t> RadixArray;
987
988 /// Map from the module's stack id index to the index in the
989 /// ModuleSummaryIndex's StackIds vector. Populated lazily from the StackIds
990 /// list and used to avoid repeated hash lookups.
991 std::vector<unsigned> StackIdToIndex;
992
993public:
994 ModuleSummaryIndexBitcodeReader(
995 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
996 StringRef ModulePath,
997 std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
998
1000
1001private:
1002 void setValueGUID(uint64_t ValueID, StringRef ValueName,
1004 StringRef SourceFileName);
1005 Error parseValueSymbolTable(
1006 uint64_t Offset,
1007 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1008 SmallVector<ValueInfo, 0> makeRefList(ArrayRef<uint64_t> Record);
1010 makeCallList(ArrayRef<uint64_t> Record, bool IsOldProfileFormat,
1011 bool HasProfile, bool HasRelBF);
1012 Error parseEntireSummary(unsigned ID);
1013 Error parseModuleStringTable();
1014 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1015 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
1017 std::vector<FunctionSummary::ParamAccess>
1018 parseParamAccesses(ArrayRef<uint64_t> Record);
1019 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1020 unsigned &I);
1021
1022 // Mark uninitialized stack ID mappings for lazy population.
1023 static constexpr unsigned UninitializedStackIdIndex =
1024 std::numeric_limits<unsigned>::max();
1025
1026 unsigned getStackIdIndex(unsigned LocalIndex) {
1027 unsigned &Index = StackIdToIndex[LocalIndex];
1028 // Add the stack id to the ModuleSummaryIndex map only when first requested
1029 // and cache the result in the local StackIdToIndex map.
1030 if (Index == UninitializedStackIdIndex)
1031 Index = TheIndex.addOrGetStackIdIndex(StackIds[LocalIndex]);
1032 return Index;
1033 }
1034
1035 template <bool AllowNullValueInfo = false>
1036 std::pair<ValueInfo, GlobalValue::GUID>
1037 getValueInfoFromValueId(unsigned ValueId);
1038
1039 void addThisModule();
1040 ModuleSummaryIndex::ModuleInfo *getThisModule();
1041};
1042
1043} // end anonymous namespace
1044
1046 Error Err) {
1047 if (Err) {
1048 std::error_code EC;
1049 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
1050 EC = EIB.convertToErrorCode();
1051 Ctx.emitError(EIB.message());
1052 });
1053 return EC;
1054 }
1055 return std::error_code();
1056}
1057
1058BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
1059 StringRef ProducerIdentification,
1060 LLVMContext &Context)
1061 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
1062 ValueList(this->Stream.SizeInBytes(),
1063 [this](unsigned ValID, BasicBlock *InsertBB) {
1064 return materializeValue(ValID, InsertBB);
1065 }) {
1066 this->ProducerIdentification = std::string(ProducerIdentification);
1067}
1068
1069Error BitcodeReader::materializeForwardReferencedFunctions() {
1070 if (WillMaterializeAllForwardRefs)
1071 return Error::success();
1072
1073 // Prevent recursion.
1074 WillMaterializeAllForwardRefs = true;
1075
1076 while (!BasicBlockFwdRefQueue.empty()) {
1077 Function *F = BasicBlockFwdRefQueue.front();
1078 BasicBlockFwdRefQueue.pop_front();
1079 assert(F && "Expected valid function");
1080 if (!BasicBlockFwdRefs.count(F))
1081 // Already materialized.
1082 continue;
1083
1084 // Check for a function that isn't materializable to prevent an infinite
1085 // loop. When parsing a blockaddress stored in a global variable, there
1086 // isn't a trivial way to check if a function will have a body without a
1087 // linear search through FunctionsWithBodies, so just check it here.
1088 if (!F->isMaterializable())
1089 return error("Never resolved function from blockaddress");
1090
1091 // Try to materialize F.
1092 if (Error Err = materialize(F))
1093 return Err;
1094 }
1095 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
1096
1097 for (Function *F : BackwardRefFunctions)
1098 if (Error Err = materialize(F))
1099 return Err;
1100 BackwardRefFunctions.clear();
1101
1102 // Reset state.
1103 WillMaterializeAllForwardRefs = false;
1104 return Error::success();
1105}
1106
1107//===----------------------------------------------------------------------===//
1108// Helper functions to implement forward reference resolution, etc.
1109//===----------------------------------------------------------------------===//
1110
1111static bool hasImplicitComdat(size_t Val) {
1112 switch (Val) {
1113 default:
1114 return false;
1115 case 1: // Old WeakAnyLinkage
1116 case 4: // Old LinkOnceAnyLinkage
1117 case 10: // Old WeakODRLinkage
1118 case 11: // Old LinkOnceODRLinkage
1119 return true;
1120 }
1121}
1122
1124 switch (Val) {
1125 default: // Map unknown/new linkages to external
1126 case 0:
1128 case 2:
1130 case 3:
1132 case 5:
1133 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
1134 case 6:
1135 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
1136 case 7:
1138 case 8:
1140 case 9:
1142 case 12:
1144 case 13:
1145 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
1146 case 14:
1147 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
1148 case 15:
1149 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
1150 case 1: // Old value with implicit comdat.
1151 case 16:
1153 case 10: // Old value with implicit comdat.
1154 case 17:
1156 case 4: // Old value with implicit comdat.
1157 case 18:
1159 case 11: // Old value with implicit comdat.
1160 case 19:
1162 }
1163}
1164
1167 Flags.ReadNone = RawFlags & 0x1;
1168 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1169 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1170 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1171 Flags.NoInline = (RawFlags >> 4) & 0x1;
1172 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1173 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1174 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1175 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1176 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1177 return Flags;
1178}
1179
1180// Decode the flags for GlobalValue in the summary. The bits for each attribute:
1181//
1182// linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1183// visibility: [8, 10).
1185 uint64_t Version) {
1186 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
1187 // like getDecodedLinkage() above. Any future change to the linkage enum and
1188 // to getDecodedLinkage() will need to be taken into account here as above.
1189 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
1190 auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
1191 auto IK = GlobalValueSummary::ImportKind((RawFlags >> 10) & 1); // 1 bit
1192 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1); // 1 bit
1193 RawFlags = RawFlags >> 4;
1194 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1195 // The Live flag wasn't introduced until version 3. For dead stripping
1196 // to work correctly on earlier versions, we must conservatively treat all
1197 // values as live.
1198 bool Live = (RawFlags & 0x2) || Version < 3;
1199 bool Local = (RawFlags & 0x4);
1200 bool AutoHide = (RawFlags & 0x8);
1201
1202 return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
1203 Live, Local, AutoHide, IK,
1204 NoRenameOnPromotion);
1205}
1206
1207// Decode the flags for GlobalVariable in the summary
1210 (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
1211 (RawFlags & 0x4) ? true : false,
1212 (GlobalObject::VCallVisibility)(RawFlags >> 3));
1213}
1214
1215static std::pair<CalleeInfo::HotnessType, bool>
1217 CalleeInfo::HotnessType Hotness =
1218 static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits
1219 bool HasTailCall = (RawFlags & 0x8); // 1 bit
1220 return {Hotness, HasTailCall};
1221}
1222
1223// Deprecated, but still needed to read old bitcode files.
1224static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF,
1225 bool &HasTailCall) {
1226 static constexpr unsigned RelBlockFreqBits = 28;
1227 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1228 RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits
1229 HasTailCall = (RawFlags & (1 << RelBlockFreqBits)); // 1 bit
1230}
1231
1233 switch (Val) {
1234 default: // Map unknown visibilities to default.
1235 case 0: return GlobalValue::DefaultVisibility;
1236 case 1: return GlobalValue::HiddenVisibility;
1237 case 2: return GlobalValue::ProtectedVisibility;
1238 }
1239}
1240
1243 switch (Val) {
1244 default: // Map unknown values to default.
1245 case 0: return GlobalValue::DefaultStorageClass;
1248 }
1249}
1250
1251static bool getDecodedDSOLocal(unsigned Val) {
1252 switch(Val) {
1253 default: // Map unknown values to preemptable.
1254 case 0: return false;
1255 case 1: return true;
1256 }
1257}
1258
1259static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) {
1260 switch (Val) {
1261 case 1:
1262 return CodeModel::Tiny;
1263 case 2:
1264 return CodeModel::Small;
1265 case 3:
1266 return CodeModel::Kernel;
1267 case 4:
1268 return CodeModel::Medium;
1269 case 5:
1270 return CodeModel::Large;
1271 }
1272
1273 return {};
1274}
1275
1277 switch (Val) {
1278 case 0: return GlobalVariable::NotThreadLocal;
1279 default: // Map unknown non-zero value to general dynamic.
1283 case 4: return GlobalVariable::LocalExecTLSModel;
1284 }
1285}
1286
1288 switch (Val) {
1289 default: // Map unknown to UnnamedAddr::None.
1290 case 0: return GlobalVariable::UnnamedAddr::None;
1293 }
1294}
1295
1296static int getDecodedCastOpcode(unsigned Val) {
1297 switch (Val) {
1298 default: return -1;
1299 case bitc::CAST_TRUNC : return Instruction::Trunc;
1300 case bitc::CAST_ZEXT : return Instruction::ZExt;
1301 case bitc::CAST_SEXT : return Instruction::SExt;
1302 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
1303 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
1304 case bitc::CAST_UITOFP : return Instruction::UIToFP;
1305 case bitc::CAST_SITOFP : return Instruction::SIToFP;
1306 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1307 case bitc::CAST_FPEXT : return Instruction::FPExt;
1308 case bitc::CAST_PTRTOADDR: return Instruction::PtrToAddr;
1309 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1310 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1311 case bitc::CAST_BITCAST : return Instruction::BitCast;
1312 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1313 }
1314}
1315
1316static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1317 bool IsFP = Ty->isFPOrFPVectorTy();
1318 // UnOps are only valid for int/fp or vector of int/fp types
1319 if (!IsFP && !Ty->isIntOrIntVectorTy())
1320 return -1;
1321
1322 switch (Val) {
1323 default:
1324 return -1;
1325 case bitc::UNOP_FNEG:
1326 return IsFP ? Instruction::FNeg : -1;
1327 }
1328}
1329
1330static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
1331 bool IsFP = Ty->isFPOrFPVectorTy();
1332 // BinOps are only valid for int/fp or vector of int/fp types
1333 if (!IsFP && !Ty->isIntOrIntVectorTy())
1334 return -1;
1335
1336 switch (Val) {
1337 default:
1338 return -1;
1339 case bitc::BINOP_ADD:
1340 return IsFP ? Instruction::FAdd : Instruction::Add;
1341 case bitc::BINOP_SUB:
1342 return IsFP ? Instruction::FSub : Instruction::Sub;
1343 case bitc::BINOP_MUL:
1344 return IsFP ? Instruction::FMul : Instruction::Mul;
1345 case bitc::BINOP_UDIV:
1346 return IsFP ? -1 : Instruction::UDiv;
1347 case bitc::BINOP_SDIV:
1348 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1349 case bitc::BINOP_UREM:
1350 return IsFP ? -1 : Instruction::URem;
1351 case bitc::BINOP_SREM:
1352 return IsFP ? Instruction::FRem : Instruction::SRem;
1353 case bitc::BINOP_SHL:
1354 return IsFP ? -1 : Instruction::Shl;
1355 case bitc::BINOP_LSHR:
1356 return IsFP ? -1 : Instruction::LShr;
1357 case bitc::BINOP_ASHR:
1358 return IsFP ? -1 : Instruction::AShr;
1359 case bitc::BINOP_AND:
1360 return IsFP ? -1 : Instruction::And;
1361 case bitc::BINOP_OR:
1362 return IsFP ? -1 : Instruction::Or;
1363 case bitc::BINOP_XOR:
1364 return IsFP ? -1 : Instruction::Xor;
1365 }
1366}
1367
1369 bool &IsElementwise) {
1370 IsElementwise = Val & bitc::RMW_ELEMENTWISE_FLAG;
1371 switch (Val & ~bitc::RMW_ELEMENTWISE_FLAG) {
1372 default: return AtomicRMWInst::BAD_BINOP;
1374 case bitc::RMW_ADD: return AtomicRMWInst::Add;
1375 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1376 case bitc::RMW_AND: return AtomicRMWInst::And;
1378 case bitc::RMW_OR: return AtomicRMWInst::Or;
1379 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1380 case bitc::RMW_MAX: return AtomicRMWInst::Max;
1381 case bitc::RMW_MIN: return AtomicRMWInst::Min;
1388 case bitc::RMW_FMAXIMUM:
1390 case bitc::RMW_FMINIMUM:
1402 case bitc::RMW_USUB_SAT:
1404 }
1405}
1406
1408 switch (Val) {
1415 default: // Map unknown orderings to sequentially-consistent.
1417 }
1418}
1419
1421 switch (Val) {
1422 default: // Map unknown selection kinds to any.
1424 return Comdat::Any;
1426 return Comdat::ExactMatch;
1428 return Comdat::Largest;
1430 return Comdat::NoDeduplicate;
1432 return Comdat::SameSize;
1433 }
1434}
1435
1437 FastMathFlags FMF;
1438 if (0 != (Val & bitc::UnsafeAlgebra))
1439 FMF.setFast();
1440 if (0 != (Val & bitc::AllowReassoc))
1441 FMF.setAllowReassoc();
1442 if (0 != (Val & bitc::NoNaNs))
1443 FMF.setNoNaNs();
1444 if (0 != (Val & bitc::NoInfs))
1445 FMF.setNoInfs();
1446 if (0 != (Val & bitc::NoSignedZeros))
1447 FMF.setNoSignedZeros();
1448 if (0 != (Val & bitc::AllowReciprocal))
1449 FMF.setAllowReciprocal();
1450 if (0 != (Val & bitc::AllowContract))
1451 FMF.setAllowContract(true);
1452 if (0 != (Val & bitc::ApproxFunc))
1453 FMF.setApproxFunc();
1454 return FMF;
1455}
1456
1457static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1458 // A GlobalValue with local linkage cannot have a DLL storage class.
1459 if (GV->hasLocalLinkage())
1460 return;
1461 switch (Val) {
1464 }
1465}
1466
1467Type *BitcodeReader::getTypeByID(unsigned ID) {
1468 // The type table size is always specified correctly.
1469 if (ID >= TypeList.size())
1470 return nullptr;
1471
1472 if (Type *Ty = TypeList[ID])
1473 return Ty;
1474
1475 // If we have a forward reference, the only possible case is when it is to a
1476 // named struct. Just create a placeholder for now.
1477 return TypeList[ID] = createIdentifiedStructType(Context);
1478}
1479
1480unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
1481 auto It = ContainedTypeIDs.find(ID);
1482 if (It == ContainedTypeIDs.end())
1483 return InvalidTypeID;
1484
1485 if (Idx >= It->second.size())
1486 return InvalidTypeID;
1487
1488 return It->second[Idx];
1489}
1490
1491Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
1492 if (ID >= TypeList.size())
1493 return nullptr;
1494
1495 Type *Ty = TypeList[ID];
1496 if (!Ty->isPointerTy())
1497 return nullptr;
1498
1499 return getTypeByID(getContainedTypeID(ID, 0));
1500}
1501
1502unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
1503 ArrayRef<unsigned> ChildTypeIDs) {
1504 unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];
1505 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1506 auto It = VirtualTypeIDs.find(CacheKey);
1507 if (It != VirtualTypeIDs.end()) {
1508 // The cmpxchg return value is the only place we need more than one
1509 // contained type ID, however the second one will always be the same (i1),
1510 // so we don't need to include it in the cache key. This asserts that the
1511 // contained types are indeed as expected and there are no collisions.
1512 assert((ChildTypeIDs.empty() ||
1513 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1514 "Incorrect cached contained type IDs");
1515 return It->second;
1516 }
1517
1518 unsigned TypeID = TypeList.size();
1519 TypeList.push_back(Ty);
1520 if (!ChildTypeIDs.empty())
1521 append_range(ContainedTypeIDs[TypeID], ChildTypeIDs);
1522 VirtualTypeIDs.insert({CacheKey, TypeID});
1523 return TypeID;
1524}
1525
1527 GEPNoWrapFlags NW;
1528 if (Flags & (1 << bitc::GEP_INBOUNDS))
1530 if (Flags & (1 << bitc::GEP_NUSW))
1532 if (Flags & (1 << bitc::GEP_NUW))
1534 return NW;
1535}
1536
1537static bool isConstExprSupported(const BitcodeConstant *BC) {
1538 uint8_t Opcode = BC->Opcode;
1539
1540 // These are not real constant expressions, always consider them supported.
1541 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1542 return true;
1543
1544 // If -expand-constant-exprs is set, we want to consider all expressions
1545 // as unsupported.
1547 return false;
1548
1549 if (Instruction::isBinaryOp(Opcode))
1550 return ConstantExpr::isSupportedBinOp(Opcode);
1551
1552 if (Instruction::isCast(Opcode))
1553 return ConstantExpr::isSupportedCastOp(Opcode);
1554
1555 if (Opcode == Instruction::GetElementPtr)
1556 return ConstantExpr::isSupportedGetElementPtr(BC->SrcElemTy);
1557
1558 switch (Opcode) {
1559 case Instruction::FNeg:
1560 case Instruction::Select:
1561 case Instruction::ICmp:
1562 case Instruction::FCmp:
1563 return false;
1564 default:
1565 return true;
1566 }
1567}
1568
1569Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID,
1570 BasicBlock *InsertBB) {
1571 // Quickly handle the case where there is no BitcodeConstant to resolve.
1572 if (StartValID < ValueList.size() && ValueList[StartValID] &&
1573 !isa<BitcodeConstant>(ValueList[StartValID]))
1574 return ValueList[StartValID];
1575
1576 SmallDenseMap<unsigned, Value *> MaterializedValues;
1577 SmallVector<unsigned> Worklist;
1578 Worklist.push_back(StartValID);
1579 while (!Worklist.empty()) {
1580 unsigned ValID = Worklist.back();
1581 if (MaterializedValues.count(ValID)) {
1582 // Duplicate expression that was already handled.
1583 Worklist.pop_back();
1584 continue;
1585 }
1586
1587 if (ValID >= ValueList.size() || !ValueList[ValID])
1588 return error("Invalid value ID");
1589
1590 Value *V = ValueList[ValID];
1591 auto *BC = dyn_cast<BitcodeConstant>(V);
1592 if (!BC) {
1593 MaterializedValues.insert({ValID, V});
1594 Worklist.pop_back();
1595 continue;
1596 }
1597
1598 // Iterate in reverse, so values will get popped from the worklist in
1599 // expected order.
1601 for (unsigned OpID : reverse(BC->getOperandIDs())) {
1602 auto It = MaterializedValues.find(OpID);
1603 if (It != MaterializedValues.end())
1604 Ops.push_back(It->second);
1605 else
1606 Worklist.push_back(OpID);
1607 }
1608
1609 // Some expressions have not been resolved yet, handle them first and then
1610 // revisit this one.
1611 if (Ops.size() != BC->getOperandIDs().size())
1612 continue;
1613 std::reverse(Ops.begin(), Ops.end());
1614
1615 SmallVector<Constant *> ConstOps;
1616 for (Value *Op : Ops)
1617 if (auto *C = dyn_cast<Constant>(Op))
1618 ConstOps.push_back(C);
1619
1620 // Materialize as constant expression if possible.
1621 if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) {
1622 Constant *C;
1623 if (Instruction::isCast(BC->Opcode)) {
1624 C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType());
1625 if (!C)
1626 C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType());
1627 } else if (Instruction::isBinaryOp(BC->Opcode)) {
1628 C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags);
1629 } else {
1630 switch (BC->Opcode) {
1631 case BitcodeConstant::ConstantPtrAuthOpcode: {
1632 auto *Key = dyn_cast<ConstantInt>(ConstOps[1]);
1633 if (!Key)
1634 return error("ptrauth key operand must be ConstantInt");
1635
1636 auto *Disc = dyn_cast<ConstantInt>(ConstOps[2]);
1637 if (!Disc)
1638 return error("ptrauth disc operand must be ConstantInt");
1639
1640 Constant *DeactivationSymbol =
1641 ConstOps.size() > 4 ? ConstOps[4]
1643 ConstOps[3]->getType()));
1644 if (!DeactivationSymbol->getType()->isPointerTy())
1645 return error(
1646 "ptrauth deactivation symbol operand must be a pointer");
1647
1648 C = ConstantPtrAuth::get(ConstOps[0], Key, Disc, ConstOps[3],
1649 DeactivationSymbol);
1650 break;
1651 }
1652 case BitcodeConstant::NoCFIOpcode: {
1653 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1654 if (!GV)
1655 return error("no_cfi operand must be GlobalValue");
1656 C = NoCFIValue::get(GV);
1657 break;
1658 }
1659 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1660 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1661 if (!GV)
1662 return error("dso_local operand must be GlobalValue");
1664 break;
1665 }
1666 case BitcodeConstant::BlockAddressOpcode: {
1667 Function *Fn = dyn_cast<Function>(ConstOps[0]);
1668 if (!Fn)
1669 return error("blockaddress operand must be a function");
1670
1671 // If the function is already parsed we can insert the block address
1672 // right away.
1673 BasicBlock *BB;
1674 unsigned BBID = BC->BlockAddressBB;
1675 if (!BBID)
1676 // Invalid reference to entry block.
1677 return error("Invalid ID");
1678 if (!Fn->empty()) {
1679 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1680 for (size_t I = 0, E = BBID; I != E; ++I) {
1681 if (BBI == BBE)
1682 return error("Invalid ID");
1683 ++BBI;
1684 }
1685 BB = &*BBI;
1686 } else {
1687 // Otherwise insert a placeholder and remember it so it can be
1688 // inserted when the function is parsed.
1689 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1690 if (FwdBBs.empty())
1691 BasicBlockFwdRefQueue.push_back(Fn);
1692 if (FwdBBs.size() < BBID + 1)
1693 FwdBBs.resize(BBID + 1);
1694 if (!FwdBBs[BBID])
1695 FwdBBs[BBID] = BasicBlock::Create(Context);
1696 BB = FwdBBs[BBID];
1697 }
1698 C = BlockAddress::get(Fn->getType(), BB);
1699 break;
1700 }
1701 case BitcodeConstant::ConstantStructOpcode: {
1702 auto *ST = cast<StructType>(BC->getType());
1703 if (ST->getNumElements() != ConstOps.size())
1704 return error("Invalid number of elements in struct initializer");
1705
1706 for (const auto [Ty, Op] : zip(ST->elements(), ConstOps))
1707 if (Op->getType() != Ty)
1708 return error("Incorrect type in struct initializer");
1709
1710 C = ConstantStruct::get(ST, ConstOps);
1711 break;
1712 }
1713 case BitcodeConstant::ConstantArrayOpcode: {
1714 auto *AT = cast<ArrayType>(BC->getType());
1715 if (AT->getNumElements() != ConstOps.size())
1716 return error("Invalid number of elements in array initializer");
1717
1718 for (Constant *Op : ConstOps)
1719 if (Op->getType() != AT->getElementType())
1720 return error("Incorrect type in array initializer");
1721
1722 C = ConstantArray::get(AT, ConstOps);
1723 break;
1724 }
1725 case BitcodeConstant::ConstantVectorOpcode: {
1726 auto *VT = cast<FixedVectorType>(BC->getType());
1727 if (VT->getNumElements() != ConstOps.size())
1728 return error("Invalid number of elements in vector initializer");
1729
1730 for (Constant *Op : ConstOps)
1731 if (Op->getType() != VT->getElementType())
1732 return error("Incorrect type in vector initializer");
1733
1734 C = ConstantVector::get(ConstOps);
1735 break;
1736 }
1737 case Instruction::GetElementPtr:
1739 BC->SrcElemTy, ConstOps[0], ArrayRef(ConstOps).drop_front(),
1740 toGEPNoWrapFlags(BC->Flags), BC->getInRange());
1741 break;
1742 case Instruction::ExtractElement:
1743 C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]);
1744 break;
1745 case Instruction::InsertElement:
1746 C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1],
1747 ConstOps[2]);
1748 break;
1749 case Instruction::ShuffleVector: {
1750 SmallVector<int, 16> Mask;
1751 ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask);
1752 C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask);
1753 break;
1754 }
1755 default:
1756 llvm_unreachable("Unhandled bitcode constant");
1757 }
1758 }
1759
1760 // Cache resolved constant.
1761 ValueList.replaceValueWithoutRAUW(ValID, C);
1762 MaterializedValues.insert({ValID, C});
1763 Worklist.pop_back();
1764 continue;
1765 }
1766
1767 if (!InsertBB)
1768 return error(Twine("Value referenced by initializer is an unsupported "
1769 "constant expression of type ") +
1770 BC->getOpcodeName());
1771
1772 // Materialize as instructions if necessary.
1773 Instruction *I;
1774 if (Instruction::isCast(BC->Opcode)) {
1775 I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0],
1776 BC->getType(), "constexpr", InsertBB);
1777 } else if (Instruction::isUnaryOp(BC->Opcode)) {
1779 "constexpr", InsertBB);
1780 } else if (Instruction::isBinaryOp(BC->Opcode)) {
1782 Ops[1], "constexpr", InsertBB);
1785 I->setHasNoSignedWrap();
1787 I->setHasNoUnsignedWrap();
1788 }
1790 (BC->Flags & PossiblyExactOperator::IsExact))
1791 I->setIsExact();
1792 } else {
1793 switch (BC->Opcode) {
1794 case BitcodeConstant::ConstantVectorOpcode: {
1795 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1796 Value *V = PoisonValue::get(BC->getType());
1797 for (auto Pair : enumerate(Ops)) {
1798 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1799 V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins",
1800 InsertBB);
1801 }
1802 I = cast<Instruction>(V);
1803 break;
1804 }
1805 case BitcodeConstant::ConstantStructOpcode:
1806 case BitcodeConstant::ConstantArrayOpcode: {
1807 Value *V = PoisonValue::get(BC->getType());
1808 for (auto Pair : enumerate(Ops))
1809 V = InsertValueInst::Create(V, Pair.value(), Pair.index(),
1810 "constexpr.ins", InsertBB);
1811 I = cast<Instruction>(V);
1812 break;
1813 }
1814 case Instruction::ICmp:
1815 case Instruction::FCmp:
1817 (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1],
1818 "constexpr", InsertBB);
1819 break;
1820 case Instruction::GetElementPtr:
1821 I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0],
1822 ArrayRef(Ops).drop_front(), "constexpr",
1823 InsertBB);
1824 cast<GetElementPtrInst>(I)->setNoWrapFlags(toGEPNoWrapFlags(BC->Flags));
1825 break;
1826 case Instruction::Select:
1827 I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB);
1828 break;
1829 case Instruction::ExtractElement:
1830 I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB);
1831 break;
1832 case Instruction::InsertElement:
1833 I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr",
1834 InsertBB);
1835 break;
1836 case Instruction::ShuffleVector:
1837 I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
1838 InsertBB);
1839 break;
1840 default:
1841 llvm_unreachable("Unhandled bitcode constant");
1842 }
1843 }
1844
1845 MaterializedValues.insert({ValID, I});
1846 Worklist.pop_back();
1847 }
1848
1849 return MaterializedValues[StartValID];
1850}
1851
1852Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
1853 Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr);
1854 if (!MaybeV)
1855 return MaybeV.takeError();
1856
1857 // Result must be Constant if InsertBB is nullptr.
1858 return cast<Constant>(MaybeV.get());
1859}
1860
1861StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1862 StringRef Name) {
1863 auto *Ret = StructType::create(Context, Name);
1864 IdentifiedStructTypes.push_back(Ret);
1865 return Ret;
1866}
1867
1868StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1869 auto *Ret = StructType::create(Context);
1870 IdentifiedStructTypes.push_back(Ret);
1871 return Ret;
1872}
1873
1874//===----------------------------------------------------------------------===//
1875// Functions for parsing blocks from the bitcode file
1876//===----------------------------------------------------------------------===//
1877
1879 switch (Val) {
1883 llvm_unreachable("Synthetic enumerators which should never get here");
1884
1885 case Attribute::None: return 0;
1886 case Attribute::ZExt: return 1 << 0;
1887 case Attribute::SExt: return 1 << 1;
1888 case Attribute::NoReturn: return 1 << 2;
1889 case Attribute::InReg: return 1 << 3;
1890 case Attribute::StructRet: return 1 << 4;
1891 case Attribute::NoUnwind: return 1 << 5;
1892 case Attribute::NoAlias: return 1 << 6;
1893 case Attribute::ByVal: return 1 << 7;
1894 case Attribute::Nest: return 1 << 8;
1895 case Attribute::ReadNone: return 1 << 9;
1896 case Attribute::ReadOnly: return 1 << 10;
1897 case Attribute::NoInline: return 1 << 11;
1898 case Attribute::AlwaysInline: return 1 << 12;
1899 case Attribute::OptimizeForSize: return 1 << 13;
1900 case Attribute::StackProtect: return 1 << 14;
1901 case Attribute::StackProtectReq: return 1 << 15;
1902 case Attribute::Alignment: return 31 << 16;
1903 // 1ULL << 21 is NoCapture, which is upgraded separately.
1904 case Attribute::NoRedZone: return 1 << 22;
1905 case Attribute::NoImplicitFloat: return 1 << 23;
1906 case Attribute::Naked: return 1 << 24;
1907 case Attribute::InlineHint: return 1 << 25;
1908 case Attribute::StackAlignment: return 7 << 26;
1909 case Attribute::ReturnsTwice: return 1 << 29;
1910 case Attribute::UWTable: return 1 << 30;
1911 case Attribute::NonLazyBind: return 1U << 31;
1912 case Attribute::SanitizeAddress: return 1ULL << 32;
1913 case Attribute::MinSize: return 1ULL << 33;
1914 case Attribute::NoDuplicate: return 1ULL << 34;
1915 case Attribute::StackProtectStrong: return 1ULL << 35;
1916 case Attribute::SanitizeThread: return 1ULL << 36;
1917 case Attribute::SanitizeMemory: return 1ULL << 37;
1918 case Attribute::NoBuiltin: return 1ULL << 38;
1919 case Attribute::Returned: return 1ULL << 39;
1920 case Attribute::Cold: return 1ULL << 40;
1921 case Attribute::Builtin: return 1ULL << 41;
1922 case Attribute::OptimizeNone: return 1ULL << 42;
1923 case Attribute::InAlloca: return 1ULL << 43;
1924 case Attribute::NonNull: return 1ULL << 44;
1925 case Attribute::JumpTable: return 1ULL << 45;
1926 case Attribute::Convergent: return 1ULL << 46;
1927 case Attribute::SafeStack: return 1ULL << 47;
1928 case Attribute::NoRecurse: return 1ULL << 48;
1929 // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately.
1930 // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately.
1931 case Attribute::SwiftSelf: return 1ULL << 51;
1932 case Attribute::SwiftError: return 1ULL << 52;
1933 case Attribute::WriteOnly: return 1ULL << 53;
1934 case Attribute::Speculatable: return 1ULL << 54;
1935 case Attribute::StrictFP: return 1ULL << 55;
1936 case Attribute::SanitizeHWAddress: return 1ULL << 56;
1937 case Attribute::NoCfCheck: return 1ULL << 57;
1938 case Attribute::OptForFuzzing: return 1ULL << 58;
1939 case Attribute::ShadowCallStack: return 1ULL << 59;
1940 case Attribute::SpeculativeLoadHardening:
1941 return 1ULL << 60;
1942 case Attribute::ImmArg:
1943 return 1ULL << 61;
1944 case Attribute::WillReturn:
1945 return 1ULL << 62;
1946 case Attribute::NoFree:
1947 return 1ULL << 63;
1948 default:
1949 // Other attributes are not supported in the raw format,
1950 // as we ran out of space.
1951 return 0;
1952 }
1953 llvm_unreachable("Unsupported attribute type");
1954}
1955
1956static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1957 if (!Val) return;
1958
1960 I = Attribute::AttrKind(I + 1)) {
1961 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1962 if (I == Attribute::Alignment)
1963 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1964 else if (I == Attribute::StackAlignment)
1965 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1966 else if (Attribute::isTypeAttrKind(I))
1967 B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
1968 else
1969 B.addAttribute(I);
1970 }
1971 }
1972}
1973
1974/// This fills an AttrBuilder object with the LLVM attributes that have
1975/// been decoded from the given integer.
1976static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1977 uint64_t EncodedAttrs,
1978 uint64_t AttrIdx) {
1979 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1980 // the bits above 31 down by 11 bits.
1981 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1982 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1983 "Alignment must be a power of two.");
1984
1985 if (Alignment)
1986 B.addAlignmentAttr(Alignment);
1987
1988 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1989 (EncodedAttrs & 0xffff);
1990
1991 if (AttrIdx == AttributeList::FunctionIndex) {
1992 // Upgrade old memory attributes.
1994 if (Attrs & (1ULL << 9)) {
1995 // ReadNone
1996 Attrs &= ~(1ULL << 9);
1997 ME &= MemoryEffects::none();
1998 }
1999 if (Attrs & (1ULL << 10)) {
2000 // ReadOnly
2001 Attrs &= ~(1ULL << 10);
2003 }
2004 if (Attrs & (1ULL << 49)) {
2005 // InaccessibleMemOnly
2006 Attrs &= ~(1ULL << 49);
2008 }
2009 if (Attrs & (1ULL << 50)) {
2010 // InaccessibleMemOrArgMemOnly
2011 Attrs &= ~(1ULL << 50);
2013 }
2014 if (Attrs & (1ULL << 53)) {
2015 // WriteOnly
2016 Attrs &= ~(1ULL << 53);
2018 }
2019 if (ME != MemoryEffects::unknown())
2020 B.addMemoryAttr(ME);
2021 }
2022
2023 // Upgrade nocapture to captures(none).
2024 if (Attrs & (1ULL << 21)) {
2025 Attrs &= ~(1ULL << 21);
2026 B.addCapturesAttr(CaptureInfo::none());
2027 }
2028
2029 addRawAttributeValue(B, Attrs);
2030}
2031
2032Error BitcodeReader::parseAttributeBlock() {
2034 return Err;
2035
2036 if (!MAttributes.empty())
2037 return error("Invalid multiple blocks");
2038
2039 SmallVector<uint64_t, 64> Record;
2040
2042
2043 // Read all the records.
2044 while (true) {
2045 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2046 if (!MaybeEntry)
2047 return MaybeEntry.takeError();
2048 BitstreamEntry Entry = MaybeEntry.get();
2049
2050 switch (Entry.Kind) {
2051 case BitstreamEntry::SubBlock: // Handled for us already.
2053 return error("Malformed block");
2055 return Error::success();
2057 // The interesting case.
2058 break;
2059 }
2060
2061 // Read a record.
2062 Record.clear();
2063 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2064 if (!MaybeRecord)
2065 return MaybeRecord.takeError();
2066 switch (MaybeRecord.get()) {
2067 default: // Default behavior: ignore.
2068 break;
2069 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
2070 // Deprecated, but still needed to read old bitcode files.
2071 if (Record.size() & 1)
2072 return error("Invalid parameter attribute record");
2073
2074 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
2075 AttrBuilder B(Context);
2076 decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]);
2077 Attrs.push_back(AttributeList::get(Context, Record[i], B));
2078 }
2079
2080 MAttributes.push_back(AttributeList::get(Context, Attrs));
2081 Attrs.clear();
2082 break;
2083 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
2084 for (uint64_t Val : Record)
2085 Attrs.push_back(MAttributeGroups[Val]);
2086
2087 MAttributes.push_back(AttributeList::get(Context, Attrs));
2088 Attrs.clear();
2089 break;
2090 }
2091 }
2092}
2093
2094// Returns Attribute::None on unrecognized codes.
2096 switch (Code) {
2097 default:
2098 return Attribute::None;
2100 return Attribute::Alignment;
2102 return Attribute::AlwaysInline;
2104 return Attribute::Builtin;
2106 return Attribute::ByVal;
2108 return Attribute::InAlloca;
2110 return Attribute::Cold;
2112 return Attribute::Convergent;
2114 return Attribute::DisableSanitizerInstrumentation;
2116 return Attribute::ElementType;
2118 return Attribute::FnRetThunkExtern;
2120 return Attribute::Flatten;
2122 return Attribute::InlineHint;
2124 return Attribute::InReg;
2126 return Attribute::JumpTable;
2128 return Attribute::Memory;
2130 return Attribute::NoFPClass;
2132 return Attribute::MinSize;
2134 return Attribute::Naked;
2136 return Attribute::Nest;
2138 return Attribute::NoAlias;
2140 return Attribute::NoBuiltin;
2142 return Attribute::NoCallback;
2144 return Attribute::NoDivergenceSource;
2146 return Attribute::NoDuplicate;
2148 return Attribute::NoFree;
2150 return Attribute::NoImplicitFloat;
2152 return Attribute::NoInline;
2154 return Attribute::NoRecurse;
2156 return Attribute::NoMerge;
2158 return Attribute::NonLazyBind;
2160 return Attribute::NonNull;
2162 return Attribute::Dereferenceable;
2164 return Attribute::DereferenceableOrNull;
2166 return Attribute::AllocAlign;
2168 return Attribute::AllocKind;
2170 return Attribute::AllocSize;
2172 return Attribute::AllocatedPointer;
2174 return Attribute::NoRedZone;
2176 return Attribute::NoReturn;
2178 return Attribute::NoSync;
2180 return Attribute::NoCfCheck;
2182 return Attribute::NoProfile;
2184 return Attribute::SkipProfile;
2186 return Attribute::NoUnwind;
2188 return Attribute::NoSanitizeBounds;
2190 return Attribute::NoSanitizeCoverage;
2192 return Attribute::NullPointerIsValid;
2194 return Attribute::OptimizeForDebugging;
2196 return Attribute::OptForFuzzing;
2198 return Attribute::OptimizeForSize;
2200 return Attribute::OptimizeNone;
2202 return Attribute::ReadNone;
2204 return Attribute::ReadOnly;
2206 return Attribute::Returned;
2208 return Attribute::ReturnsTwice;
2210 return Attribute::SExt;
2212 return Attribute::Speculatable;
2214 return Attribute::StackAlignment;
2216 return Attribute::StackProtect;
2218 return Attribute::StackProtectReq;
2220 return Attribute::StackProtectStrong;
2222 return Attribute::SafeStack;
2224 return Attribute::ShadowCallStack;
2226 return Attribute::StrictFP;
2228 return Attribute::StructRet;
2230 return Attribute::SanitizeAddress;
2232 return Attribute::SanitizeHWAddress;
2234 return Attribute::SanitizeThread;
2236 return Attribute::SanitizeType;
2238 return Attribute::SanitizeMemory;
2240 return Attribute::SanitizeNumericalStability;
2242 return Attribute::SanitizeRealtime;
2244 return Attribute::SanitizeRealtimeBlocking;
2246 return Attribute::SanitizeAllocToken;
2248 return Attribute::SpeculativeLoadHardening;
2250 return Attribute::SwiftError;
2252 return Attribute::SwiftSelf;
2254 return Attribute::SwiftAsync;
2256 return Attribute::UWTable;
2258 return Attribute::VScaleRange;
2260 return Attribute::WillReturn;
2262 return Attribute::WriteOnly;
2264 return Attribute::ZExt;
2266 return Attribute::ImmArg;
2268 return Attribute::SanitizeMemTag;
2270 return Attribute::Preallocated;
2272 return Attribute::NoUndef;
2274 return Attribute::ByRef;
2276 return Attribute::MustProgress;
2278 return Attribute::Hot;
2280 return Attribute::PresplitCoroutine;
2282 return Attribute::Writable;
2284 return Attribute::CoroDestroyOnlyWhenComplete;
2286 return Attribute::DeadOnUnwind;
2288 return Attribute::Range;
2290 return Attribute::Initializes;
2292 return Attribute::CoroElideSafe;
2294 return Attribute::NoExt;
2296 return Attribute::Captures;
2298 return Attribute::DeadOnReturn;
2300 return Attribute::NoCreateUndefOrPoison;
2302 return Attribute::DenormalFPEnv;
2304 return Attribute::NoOutline;
2305 }
2306}
2307
2308Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
2309 MaybeAlign &Alignment) {
2310 // Note: Alignment in bitcode files is incremented by 1, so that zero
2311 // can be used for default alignment.
2312 if (Exponent > Value::MaxAlignmentExponent + 1)
2313 return error("Invalid alignment value");
2314 Alignment = decodeMaybeAlign(Exponent);
2315 return Error::success();
2316}
2317
2318Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2319 *Kind = getAttrFromCode(Code);
2320 if (*Kind == Attribute::None)
2321 return error("Unknown attribute kind (" + Twine(Code) + ")");
2322 return Error::success();
2323}
2324
2325static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
2326 switch (EncodedKind) {
2328 ME &= MemoryEffects::none();
2329 return true;
2332 return true;
2335 return true;
2338 return true;
2341 return true;
2344 return true;
2345 default:
2346 return false;
2347 }
2348}
2349
2350Error BitcodeReader::parseAttributeGroupBlock() {
2352 return Err;
2353
2354 if (!MAttributeGroups.empty())
2355 return error("Invalid multiple blocks");
2356
2357 SmallVector<uint64_t, 64> Record;
2358
2359 // Read all the records.
2360 while (true) {
2361 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2362 if (!MaybeEntry)
2363 return MaybeEntry.takeError();
2364 BitstreamEntry Entry = MaybeEntry.get();
2365
2366 switch (Entry.Kind) {
2367 case BitstreamEntry::SubBlock: // Handled for us already.
2369 return error("Malformed block");
2371 return Error::success();
2373 // The interesting case.
2374 break;
2375 }
2376
2377 // Read a record.
2378 Record.clear();
2379 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2380 if (!MaybeRecord)
2381 return MaybeRecord.takeError();
2382 switch (MaybeRecord.get()) {
2383 default: // Default behavior: ignore.
2384 break;
2385 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
2386 if (Record.size() < 3)
2387 return error("Invalid grp record");
2388
2389 uint64_t GrpID = Record[0];
2390 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
2391
2392 AttrBuilder B(Context);
2394 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2395 if (Record[i] == 0) { // Enum attribute
2396 Attribute::AttrKind Kind;
2397 uint64_t EncodedKind = Record[++i];
2398 if (Idx == AttributeList::FunctionIndex &&
2399 upgradeOldMemoryAttribute(ME, EncodedKind))
2400 continue;
2401
2402 if (EncodedKind == bitc::ATTR_KIND_NO_CAPTURE) {
2403 B.addCapturesAttr(CaptureInfo::none());
2404 continue;
2405 }
2406
2407 if (Error Err = parseAttrKind(EncodedKind, &Kind))
2408 return Err;
2409
2410 // Upgrade old-style byval attribute to one with a type, even if it's
2411 // nullptr. We will have to insert the real type when we associate
2412 // this AttributeList with a function.
2413 if (Kind == Attribute::ByVal)
2414 B.addByValAttr(nullptr);
2415 else if (Kind == Attribute::StructRet)
2416 B.addStructRetAttr(nullptr);
2417 else if (Kind == Attribute::InAlloca)
2418 B.addInAllocaAttr(nullptr);
2419 else if (Kind == Attribute::UWTable)
2420 B.addUWTableAttr(UWTableKind::Default);
2421 else if (Kind == Attribute::DeadOnReturn)
2422 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2423 else if (Attribute::isEnumAttrKind(Kind))
2424 B.addAttribute(Kind);
2425 else
2426 return error("Not an enum attribute");
2427 } else if (Record[i] == 1) { // Integer attribute
2428 Attribute::AttrKind Kind;
2429 if (Error Err = parseAttrKind(Record[++i], &Kind))
2430 return Err;
2431 if (!Attribute::isIntAttrKind(Kind))
2432 return error("Not an int attribute");
2433 if (Kind == Attribute::Alignment)
2434 B.addAlignmentAttr(Record[++i]);
2435 else if (Kind == Attribute::StackAlignment)
2436 B.addStackAlignmentAttr(Record[++i]);
2437 else if (Kind == Attribute::Dereferenceable)
2438 B.addDereferenceableAttr(Record[++i]);
2439 else if (Kind == Attribute::DereferenceableOrNull)
2440 B.addDereferenceableOrNullAttr(Record[++i]);
2441 else if (Kind == Attribute::DeadOnReturn)
2442 B.addDeadOnReturnAttr(
2444 else if (Kind == Attribute::AllocSize)
2445 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2446 else if (Kind == Attribute::VScaleRange)
2447 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2448 else if (Kind == Attribute::UWTable)
2449 B.addUWTableAttr(UWTableKind(Record[++i]));
2450 else if (Kind == Attribute::AllocKind)
2451 B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
2452 else if (Kind == Attribute::Memory) {
2453 uint64_t EncodedME = Record[++i];
2454 const uint8_t Version = (EncodedME >> 56);
2455 if (Version == 0) {
2456 // Errno memory location was previously encompassed into default
2457 // memory. Ensure this is taken into account while reconstructing
2458 // the memory attribute prior to its introduction.
2459 ModRefInfo ArgMem = ModRefInfo((EncodedME >> 0) & 3);
2460 ModRefInfo InaccessibleMem = ModRefInfo((EncodedME >> 2) & 3);
2461 ModRefInfo OtherMem = ModRefInfo((EncodedME >> 4) & 3);
2464 MemoryEffects::errnoMemOnly(OtherMem) |
2466 B.addMemoryAttr(ME);
2467 } else {
2468 // Construct the memory attribute directly from the encoded base
2469 // on newer versions.
2471 EncodedME & 0x00FFFFFFFFFFFFFFULL));
2472 }
2473 } else if (Kind == Attribute::Captures)
2474 B.addCapturesAttr(CaptureInfo::createFromIntValue(Record[++i]));
2475 else if (Kind == Attribute::NoFPClass)
2476 B.addNoFPClassAttr(
2477 static_cast<FPClassTest>(Record[++i] & fcAllFlags));
2478 else if (Kind == Attribute::DenormalFPEnv) {
2479 B.addDenormalFPEnvAttr(
2481 }
2482 } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
2483 bool HasValue = (Record[i++] == 4);
2484 SmallString<64> KindStr;
2485 SmallString<64> ValStr;
2486
2487 while (Record[i] != 0 && i != e)
2488 KindStr += Record[i++];
2489 assert(Record[i] == 0 && "Kind string not null terminated");
2490
2491 if (HasValue) {
2492 // Has a value associated with it.
2493 ++i; // Skip the '0' that terminates the "kind" string.
2494 while (Record[i] != 0 && i != e)
2495 ValStr += Record[i++];
2496 assert(Record[i] == 0 && "Value string not null terminated");
2497 }
2498
2499 B.addAttribute(KindStr.str(), ValStr.str());
2500 } else if (Record[i] == 5 || Record[i] == 6) {
2501 bool HasType = Record[i] == 6;
2502 Attribute::AttrKind Kind;
2503 if (Error Err = parseAttrKind(Record[++i], &Kind))
2504 return Err;
2505 if (!Attribute::isTypeAttrKind(Kind))
2506 return error("Not a type attribute");
2507
2508 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
2509 } else if (Record[i] == 7) {
2510 Attribute::AttrKind Kind;
2511
2512 i++;
2513 if (Error Err = parseAttrKind(Record[i++], &Kind))
2514 return Err;
2515 if (!Attribute::isConstantRangeAttrKind(Kind))
2516 return error("Not a ConstantRange attribute");
2517
2518 Expected<ConstantRange> MaybeCR =
2519 readBitWidthAndConstantRange(Record, i);
2520 if (!MaybeCR)
2521 return MaybeCR.takeError();
2522 i--;
2523
2524 B.addConstantRangeAttr(Kind, MaybeCR.get());
2525 } else if (Record[i] == 8) {
2526 Attribute::AttrKind Kind;
2527
2528 i++;
2529 if (Error Err = parseAttrKind(Record[i++], &Kind))
2530 return Err;
2531 if (!Attribute::isConstantRangeListAttrKind(Kind))
2532 return error("Not a constant range list attribute");
2533
2535 if (i + 2 > e)
2536 return error("Too few records for constant range list");
2537 unsigned RangeSize = Record[i++];
2538 unsigned BitWidth = Record[i++];
2539 for (unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2540 Expected<ConstantRange> MaybeCR =
2541 readConstantRange(Record, i, BitWidth);
2542 if (!MaybeCR)
2543 return MaybeCR.takeError();
2544 Val.push_back(MaybeCR.get());
2545 }
2546 i--;
2547
2549 return error("Invalid (unordered or overlapping) range list");
2550 B.addConstantRangeListAttr(Kind, Val);
2551 } else {
2552 return error("Invalid attribute group entry");
2553 }
2554 }
2555
2556 if (ME != MemoryEffects::unknown())
2557 B.addMemoryAttr(ME);
2558
2560 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
2561 break;
2562 }
2563 }
2564 }
2565}
2566
2567Error BitcodeReader::parseTypeTable() {
2569 return Err;
2570
2571 return parseTypeTableBody();
2572}
2573
2574Error BitcodeReader::parseTypeTableBody() {
2575 if (!TypeList.empty())
2576 return error("Invalid multiple blocks");
2577
2578 SmallVector<uint64_t, 64> Record;
2579 unsigned NumRecords = 0;
2580
2581 SmallString<64> TypeName;
2582
2583 // Read all the records for this type table.
2584 while (true) {
2585 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2586 if (!MaybeEntry)
2587 return MaybeEntry.takeError();
2588 BitstreamEntry Entry = MaybeEntry.get();
2589
2590 switch (Entry.Kind) {
2591 case BitstreamEntry::SubBlock: // Handled for us already.
2593 return error("Malformed block");
2595 if (NumRecords != TypeList.size())
2596 return error("Malformed block");
2597 return Error::success();
2599 // The interesting case.
2600 break;
2601 }
2602
2603 // Read a record.
2604 Record.clear();
2605 Type *ResultTy = nullptr;
2606 SmallVector<unsigned> ContainedIDs;
2607 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2608 if (!MaybeRecord)
2609 return MaybeRecord.takeError();
2610 switch (MaybeRecord.get()) {
2611 default:
2612 return error("Invalid value");
2613 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
2614 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2615 // type list. This allows us to reserve space.
2616 if (Record.empty())
2617 return error("Invalid numentry record");
2618 TypeList.resize(Record[0]);
2619 continue;
2620 case bitc::TYPE_CODE_VOID: // VOID
2621 ResultTy = Type::getVoidTy(Context);
2622 break;
2623 case bitc::TYPE_CODE_HALF: // HALF
2624 ResultTy = Type::getHalfTy(Context);
2625 break;
2626 case bitc::TYPE_CODE_BFLOAT: // BFLOAT
2627 ResultTy = Type::getBFloatTy(Context);
2628 break;
2629 case bitc::TYPE_CODE_FLOAT: // FLOAT
2630 ResultTy = Type::getFloatTy(Context);
2631 break;
2632 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
2633 ResultTy = Type::getDoubleTy(Context);
2634 break;
2635 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
2636 ResultTy = Type::getX86_FP80Ty(Context);
2637 break;
2638 case bitc::TYPE_CODE_FP128: // FP128
2639 ResultTy = Type::getFP128Ty(Context);
2640 break;
2641 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
2642 ResultTy = Type::getPPC_FP128Ty(Context);
2643 break;
2644 case bitc::TYPE_CODE_LABEL: // LABEL
2645 ResultTy = Type::getLabelTy(Context);
2646 break;
2647 case bitc::TYPE_CODE_METADATA: // METADATA
2648 ResultTy = Type::getMetadataTy(Context);
2649 break;
2650 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
2651 // Deprecated: decodes as <1 x i64>
2652 ResultTy =
2654 break;
2655 case bitc::TYPE_CODE_X86_AMX: // X86_AMX
2656 ResultTy = Type::getX86_AMXTy(Context);
2657 break;
2658 case bitc::TYPE_CODE_TOKEN: // TOKEN
2659 ResultTy = Type::getTokenTy(Context);
2660 break;
2661 case bitc::TYPE_CODE_BYTE: { // BYTE: [width]
2662 if (Record.empty())
2663 return error("Invalid record");
2664
2665 uint64_t NumBits = Record[0];
2666 if (NumBits < ByteType::MIN_BYTE_BITS ||
2667 NumBits > ByteType::MAX_BYTE_BITS)
2668 return error("Bitwidth for byte type out of range");
2669 ResultTy = ByteType::get(Context, NumBits);
2670 break;
2671 }
2672 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2673 if (Record.empty())
2674 return error("Invalid integer record");
2675
2676 uint64_t NumBits = Record[0];
2677 if (NumBits < IntegerType::MIN_INT_BITS ||
2678 NumBits > IntegerType::MAX_INT_BITS)
2679 return error("Bitwidth for integer type out of range");
2680 ResultTy = IntegerType::get(Context, NumBits);
2681 break;
2682 }
2683 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
2684 // [pointee type, address space]
2685 if (Record.empty())
2686 return error("Invalid pointer record");
2687 unsigned AddressSpace = 0;
2688 if (Record.size() == 2)
2689 AddressSpace = Record[1];
2690 ResultTy = getTypeByID(Record[0]);
2691 if (!ResultTy ||
2692 !PointerType::isValidElementType(ResultTy))
2693 return error("Invalid type");
2694 ContainedIDs.push_back(Record[0]);
2695 ResultTy = PointerType::get(ResultTy->getContext(), AddressSpace);
2696 break;
2697 }
2698 case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2699 if (Record.size() != 1)
2700 return error("Invalid opaque pointer record");
2701 unsigned AddressSpace = Record[0];
2702 ResultTy = PointerType::get(Context, AddressSpace);
2703 break;
2704 }
2706 // Deprecated, but still needed to read old bitcode files.
2707 // FUNCTION: [vararg, attrid, retty, paramty x N]
2708 if (Record.size() < 3)
2709 return error("Invalid function record");
2710 SmallVector<Type*, 8> ArgTys;
2711 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
2712 if (Type *T = getTypeByID(Record[i]))
2713 ArgTys.push_back(T);
2714 else
2715 break;
2716 }
2717
2718 ResultTy = getTypeByID(Record[2]);
2719 if (!ResultTy || ArgTys.size() < Record.size()-3)
2720 return error("Invalid type");
2721
2722 ContainedIDs.append(Record.begin() + 2, Record.end());
2723 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2724 break;
2725 }
2727 // FUNCTION: [vararg, retty, paramty x N]
2728 if (Record.size() < 2)
2729 return error("Invalid function record");
2730 SmallVector<Type*, 8> ArgTys;
2731 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2732 if (Type *T = getTypeByID(Record[i])) {
2733 if (!FunctionType::isValidArgumentType(T))
2734 return error("Invalid function argument type");
2735 ArgTys.push_back(T);
2736 }
2737 else
2738 break;
2739 }
2740
2741 ResultTy = getTypeByID(Record[1]);
2742 if (!ResultTy || ArgTys.size() < Record.size()-2)
2743 return error("Invalid type");
2744
2745 ContainedIDs.append(Record.begin() + 1, Record.end());
2746 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2747 break;
2748 }
2749 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
2750 if (Record.empty())
2751 return error("Invalid anon struct record");
2752 SmallVector<Type*, 8> EltTys;
2753 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2754 if (Type *T = getTypeByID(Record[i]))
2755 EltTys.push_back(T);
2756 else
2757 break;
2758 }
2759 if (EltTys.size() != Record.size()-1)
2760 return error("Invalid type");
2761 ContainedIDs.append(Record.begin() + 1, Record.end());
2762 ResultTy = StructType::get(Context, EltTys, Record[0]);
2763 break;
2764 }
2765 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
2766 if (convertToString(Record, 0, TypeName))
2767 return error("Invalid struct name record");
2768 continue;
2769
2770 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2771 if (Record.empty())
2772 return error("Invalid named struct record");
2773
2774 if (NumRecords >= TypeList.size())
2775 return error("Invalid TYPE table");
2776
2777 // Check to see if this was forward referenced, if so fill in the temp.
2778 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2779 if (Res) {
2780 Res->setName(TypeName);
2781 TypeList[NumRecords] = nullptr;
2782 } else // Otherwise, create a new struct.
2783 Res = createIdentifiedStructType(Context, TypeName);
2784 TypeName.clear();
2785
2786 SmallVector<Type*, 8> EltTys;
2787 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2788 if (Type *T = getTypeByID(Record[i]))
2789 EltTys.push_back(T);
2790 else
2791 break;
2792 }
2793 if (EltTys.size() != Record.size()-1)
2794 return error("Invalid named struct record");
2795 if (auto E = Res->setBodyOrError(EltTys, Record[0]))
2796 return E;
2797 ContainedIDs.append(Record.begin() + 1, Record.end());
2798 ResultTy = Res;
2799 break;
2800 }
2801 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
2802 if (Record.size() != 1)
2803 return error("Invalid opaque type record");
2804
2805 if (NumRecords >= TypeList.size())
2806 return error("Invalid TYPE table");
2807
2808 // Check to see if this was forward referenced, if so fill in the temp.
2809 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2810 if (Res) {
2811 Res->setName(TypeName);
2812 TypeList[NumRecords] = nullptr;
2813 } else // Otherwise, create a new struct with no body.
2814 Res = createIdentifiedStructType(Context, TypeName);
2815 TypeName.clear();
2816 ResultTy = Res;
2817 break;
2818 }
2819 case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2820 if (Record.size() < 1)
2821 return error("Invalid target extension type record");
2822
2823 if (NumRecords >= TypeList.size())
2824 return error("Invalid TYPE table");
2825
2826 if (Record[0] >= Record.size())
2827 return error("Too many type parameters");
2828
2829 unsigned NumTys = Record[0];
2830 SmallVector<Type *, 4> TypeParams;
2831 SmallVector<unsigned, 8> IntParams;
2832 for (unsigned i = 0; i < NumTys; i++) {
2833 if (Type *T = getTypeByID(Record[i + 1]))
2834 TypeParams.push_back(T);
2835 else
2836 return error("Invalid type");
2837 }
2838
2839 for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) {
2840 if (Record[i] > UINT_MAX)
2841 return error("Integer parameter too large");
2842 IntParams.push_back(Record[i]);
2843 }
2844 auto TTy =
2845 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
2846 if (auto E = TTy.takeError())
2847 return E;
2848 ResultTy = *TTy;
2849 TypeName.clear();
2850 break;
2851 }
2852 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
2853 if (Record.size() < 2)
2854 return error("Invalid array type record");
2855 ResultTy = getTypeByID(Record[1]);
2856 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2857 return error("Invalid type");
2858 ContainedIDs.push_back(Record[1]);
2859 ResultTy = ArrayType::get(ResultTy, Record[0]);
2860 break;
2861 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or
2862 // [numelts, eltty, scalable]
2863 if (Record.size() < 2)
2864 return error("Invalid vector type record");
2865 if (Record[0] == 0)
2866 return error("Invalid vector length");
2867 ResultTy = getTypeByID(Record[1]);
2868 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2869 return error("Invalid type");
2870 bool Scalable = Record.size() > 2 ? Record[2] : false;
2871 ContainedIDs.push_back(Record[1]);
2872 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2873 break;
2874 }
2875
2876 if (NumRecords >= TypeList.size())
2877 return error("Invalid TYPE table");
2878 if (TypeList[NumRecords])
2879 return error(
2880 "Invalid TYPE table: Only named structs can be forward referenced");
2881 assert(ResultTy && "Didn't read a type?");
2882 TypeList[NumRecords] = ResultTy;
2883 if (!ContainedIDs.empty())
2884 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2885 ++NumRecords;
2886 }
2887}
2888
2889Error BitcodeReader::parseOperandBundleTags() {
2891 return Err;
2892
2893 if (!BundleTags.empty())
2894 return error("Invalid multiple blocks");
2895
2896 SmallVector<uint64_t, 64> Record;
2897
2898 while (true) {
2899 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2900 if (!MaybeEntry)
2901 return MaybeEntry.takeError();
2902 BitstreamEntry Entry = MaybeEntry.get();
2903
2904 switch (Entry.Kind) {
2905 case BitstreamEntry::SubBlock: // Handled for us already.
2907 return error("Malformed block");
2909 return Error::success();
2911 // The interesting case.
2912 break;
2913 }
2914
2915 // Tags are implicitly mapped to integers by their order.
2916
2917 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2918 if (!MaybeRecord)
2919 return MaybeRecord.takeError();
2920 if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
2921 return error("Invalid operand bundle record");
2922
2923 // OPERAND_BUNDLE_TAG: [strchr x N]
2924 BundleTags.emplace_back();
2925 if (convertToString(Record, 0, BundleTags.back()))
2926 return error("Invalid operand bundle record");
2927 Record.clear();
2928 }
2929}
2930
2931Error BitcodeReader::parseSyncScopeNames() {
2933 return Err;
2934
2935 if (!SSIDs.empty())
2936 return error("Invalid multiple synchronization scope names blocks");
2937
2938 SmallVector<uint64_t, 64> Record;
2939 while (true) {
2940 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2941 if (!MaybeEntry)
2942 return MaybeEntry.takeError();
2943 BitstreamEntry Entry = MaybeEntry.get();
2944
2945 switch (Entry.Kind) {
2946 case BitstreamEntry::SubBlock: // Handled for us already.
2948 return error("Malformed block");
2950 if (SSIDs.empty())
2951 return error("Invalid empty synchronization scope names block");
2952 return Error::success();
2954 // The interesting case.
2955 break;
2956 }
2957
2958 // Synchronization scope names are implicitly mapped to synchronization
2959 // scope IDs by their order.
2960
2961 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2962 if (!MaybeRecord)
2963 return MaybeRecord.takeError();
2964 if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2965 return error("Invalid sync scope record");
2966
2967 SmallString<16> SSN;
2968 if (convertToString(Record, 0, SSN))
2969 return error("Invalid sync scope record");
2970
2971 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2972 Record.clear();
2973 }
2974}
2975
2976/// Associate a value with its name from the given index in the provided record.
2977Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2978 unsigned NameIndex, Triple &TT) {
2979 SmallString<128> ValueName;
2980 if (convertToString(Record, NameIndex, ValueName))
2981 return error("Invalid record");
2982 unsigned ValueID = Record[0];
2983 if (ValueID >= ValueList.size() || !ValueList[ValueID])
2984 return error("Invalid record");
2985 Value *V = ValueList[ValueID];
2986
2987 StringRef NameStr(ValueName.data(), ValueName.size());
2988 if (NameStr.contains(0))
2989 return error("Invalid value name");
2990 V->setName(NameStr);
2991 auto *GO = dyn_cast<GlobalObject>(V);
2992 if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
2993 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2994 return V;
2995}
2996
2997/// Helper to note and return the current location, and jump to the given
2998/// offset.
3000 BitstreamCursor &Stream) {
3001 // Save the current parsing location so we can jump back at the end
3002 // of the VST read.
3003 uint64_t CurrentBit = Stream.GetCurrentBitNo();
3004 if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
3005 return std::move(JumpFailed);
3006 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
3007 if (!MaybeEntry)
3008 return MaybeEntry.takeError();
3009 if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
3010 MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
3011 return error("Expected value symbol table subblock");
3012 return CurrentBit;
3013}
3014
3015void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
3016 Function *F,
3017 ArrayRef<uint64_t> Record) {
3018 // Note that we subtract 1 here because the offset is relative to one word
3019 // before the start of the identification or module block, which was
3020 // historically always the start of the regular bitcode header.
3021 uint64_t FuncWordOffset = Record[1] - 1;
3022 uint64_t FuncBitOffset = FuncWordOffset * 32;
3023 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3024 // Set the LastFunctionBlockBit to point to the last function block.
3025 // Later when parsing is resumed after function materialization,
3026 // we can simply skip that last function block.
3027 if (FuncBitOffset > LastFunctionBlockBit)
3028 LastFunctionBlockBit = FuncBitOffset;
3029}
3030
3031/// Read a new-style GlobalValue symbol table.
3032Error BitcodeReader::parseGlobalValueSymbolTable() {
3033 unsigned FuncBitcodeOffsetDelta =
3035
3037 return Err;
3038
3039 SmallVector<uint64_t, 64> Record;
3040 while (true) {
3041 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3042 if (!MaybeEntry)
3043 return MaybeEntry.takeError();
3044 BitstreamEntry Entry = MaybeEntry.get();
3045
3046 switch (Entry.Kind) {
3049 return error("Malformed block");
3051 return Error::success();
3053 break;
3054 }
3055
3056 Record.clear();
3057 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3058 if (!MaybeRecord)
3059 return MaybeRecord.takeError();
3060 switch (MaybeRecord.get()) {
3061 case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
3062 unsigned ValueID = Record[0];
3063 if (ValueID >= ValueList.size() || !ValueList[ValueID])
3064 return error("Invalid value reference in symbol table");
3065 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3066 cast<Function>(ValueList[ValueID]), Record);
3067 break;
3068 }
3069 }
3070 }
3071}
3072
3073/// Parse the value symbol table at either the current parsing location or
3074/// at the given bit offset if provided.
3075Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
3076 uint64_t CurrentBit;
3077 // Pass in the Offset to distinguish between calling for the module-level
3078 // VST (where we want to jump to the VST offset) and the function-level
3079 // VST (where we don't).
3080 if (Offset > 0) {
3081 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
3082 if (!MaybeCurrentBit)
3083 return MaybeCurrentBit.takeError();
3084 CurrentBit = MaybeCurrentBit.get();
3085 // If this module uses a string table, read this as a module-level VST.
3086 if (UseStrtab) {
3087 if (Error Err = parseGlobalValueSymbolTable())
3088 return Err;
3089 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
3090 return JumpFailed;
3091 return Error::success();
3092 }
3093 // Otherwise, the VST will be in a similar format to a function-level VST,
3094 // and will contain symbol names.
3095 }
3096
3097 // Compute the delta between the bitcode indices in the VST (the word offset
3098 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
3099 // expected by the lazy reader. The reader's EnterSubBlock expects to have
3100 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
3101 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
3102 // just before entering the VST subblock because: 1) the EnterSubBlock
3103 // changes the AbbrevID width; 2) the VST block is nested within the same
3104 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
3105 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
3106 // jump to the FUNCTION_BLOCK using this offset later, we don't want
3107 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
3108 unsigned FuncBitcodeOffsetDelta =
3110
3112 return Err;
3113
3114 SmallVector<uint64_t, 64> Record;
3115
3116 Triple TT(TheModule->getTargetTriple());
3117
3118 // Read all the records for this value table.
3119 SmallString<128> ValueName;
3120
3121 while (true) {
3122 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3123 if (!MaybeEntry)
3124 return MaybeEntry.takeError();
3125 BitstreamEntry Entry = MaybeEntry.get();
3126
3127 switch (Entry.Kind) {
3128 case BitstreamEntry::SubBlock: // Handled for us already.
3130 return error("Malformed block");
3132 if (Offset > 0)
3133 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
3134 return JumpFailed;
3135 return Error::success();
3137 // The interesting case.
3138 break;
3139 }
3140
3141 // Read a record.
3142 Record.clear();
3143 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3144 if (!MaybeRecord)
3145 return MaybeRecord.takeError();
3146 switch (MaybeRecord.get()) {
3147 default: // Default behavior: unknown type.
3148 break;
3149 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
3150 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3151 if (Error Err = ValOrErr.takeError())
3152 return Err;
3153 ValOrErr.get();
3154 break;
3155 }
3157 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
3158 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3159 if (Error Err = ValOrErr.takeError())
3160 return Err;
3161 Value *V = ValOrErr.get();
3162
3163 // Ignore function offsets emitted for aliases of functions in older
3164 // versions of LLVM.
3165 if (auto *F = dyn_cast<Function>(V))
3166 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
3167 break;
3168 }
3170 if (convertToString(Record, 1, ValueName))
3171 return error("Invalid bbentry record");
3172 BasicBlock *BB = getBasicBlock(Record[0]);
3173 if (!BB)
3174 return error("Invalid bbentry record");
3175
3176 BB->setName(ValueName.str());
3177 ValueName.clear();
3178 break;
3179 }
3180 }
3181 }
3182}
3183
3184/// Decode a signed value stored with the sign bit in the LSB for dense VBR
3185/// encoding.
3186uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3187 if ((V & 1) == 0)
3188 return V >> 1;
3189 if (V != 1)
3190 return -(V >> 1);
3191 // There is no such thing as -0 with integers. "-0" really means MININT.
3192 return 1ULL << 63;
3193}
3194
3195/// Resolve all of the initializers for global values and aliases that we can.
3196Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3197 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3198 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3199 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3200
3201 GlobalInitWorklist.swap(GlobalInits);
3202 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3203 FunctionOperandWorklist.swap(FunctionOperands);
3204
3205 while (!GlobalInitWorklist.empty()) {
3206 unsigned ValID = GlobalInitWorklist.back().second;
3207 if (ValID >= ValueList.size()) {
3208 // Not ready to resolve this yet, it requires something later in the file.
3209 GlobalInits.push_back(GlobalInitWorklist.back());
3210 } else {
3211 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3212 if (!MaybeC)
3213 return MaybeC.takeError();
3214 GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
3215 }
3216 GlobalInitWorklist.pop_back();
3217 }
3218
3219 while (!IndirectSymbolInitWorklist.empty()) {
3220 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3221 if (ValID >= ValueList.size()) {
3222 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3223 } else {
3224 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3225 if (!MaybeC)
3226 return MaybeC.takeError();
3227 Constant *C = MaybeC.get();
3228 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3229 if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
3230 if (C->getType() != GV->getType())
3231 return error("Alias and aliasee types don't match");
3232 GA->setAliasee(C);
3233 } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
3234 GI->setResolver(C);
3235 } else {
3236 return error("Expected an alias or an ifunc");
3237 }
3238 }
3239 IndirectSymbolInitWorklist.pop_back();
3240 }
3241
3242 while (!FunctionOperandWorklist.empty()) {
3243 FunctionOperandInfo &Info = FunctionOperandWorklist.back();
3244 if (Info.PersonalityFn) {
3245 unsigned ValID = Info.PersonalityFn - 1;
3246 if (ValID < ValueList.size()) {
3247 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3248 if (!MaybeC)
3249 return MaybeC.takeError();
3250 Info.F->setPersonalityFn(MaybeC.get());
3251 Info.PersonalityFn = 0;
3252 }
3253 }
3254 if (Info.Prefix) {
3255 unsigned ValID = Info.Prefix - 1;
3256 if (ValID < ValueList.size()) {
3257 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3258 if (!MaybeC)
3259 return MaybeC.takeError();
3260 Info.F->setPrefixData(MaybeC.get());
3261 Info.Prefix = 0;
3262 }
3263 }
3264 if (Info.Prologue) {
3265 unsigned ValID = Info.Prologue - 1;
3266 if (ValID < ValueList.size()) {
3267 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3268 if (!MaybeC)
3269 return MaybeC.takeError();
3270 Info.F->setPrologueData(MaybeC.get());
3271 Info.Prologue = 0;
3272 }
3273 }
3274 if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
3275 FunctionOperands.push_back(Info);
3276 FunctionOperandWorklist.pop_back();
3277 }
3278
3279 return Error::success();
3280}
3281
3283 SmallVector<uint64_t, 8> Words(Vals.size());
3284 transform(Vals, Words.begin(),
3285 BitcodeReader::decodeSignRotatedValue);
3286
3287 return APInt(TypeBits, Words);
3288}
3289
3290Error BitcodeReader::parseConstants() {
3292 return Err;
3293
3295
3296 // Read all the records for this value table.
3297 Type *CurTy = Type::getInt32Ty(Context);
3298 unsigned Int32TyID = getVirtualTypeID(CurTy);
3299 unsigned CurTyID = Int32TyID;
3300 Type *CurElemTy = nullptr;
3301 unsigned NextCstNo = ValueList.size();
3302
3303 while (true) {
3305 if (!MaybeEntry)
3306 return MaybeEntry.takeError();
3307 BitstreamEntry Entry = MaybeEntry.get();
3308
3309 switch (Entry.Kind) {
3310 case BitstreamEntry::SubBlock: // Handled for us already.
3312 return error("Malformed block");
3314 if (NextCstNo != ValueList.size())
3315 return error("Invalid constant reference");
3316 return Error::success();
3318 // The interesting case.
3319 break;
3320 }
3321
3322 // Read a record.
3323 Record.clear();
3324 Type *VoidType = Type::getVoidTy(Context);
3325 Value *V = nullptr;
3326 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3327 if (!MaybeBitCode)
3328 return MaybeBitCode.takeError();
3329 switch (unsigned BitCode = MaybeBitCode.get()) {
3330 default: // Default behavior: unknown constant
3331 case bitc::CST_CODE_UNDEF: // UNDEF
3332 V = UndefValue::get(CurTy);
3333 break;
3334 case bitc::CST_CODE_POISON: // POISON
3335 V = PoisonValue::get(CurTy);
3336 break;
3337 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
3338 if (Record.empty())
3339 return error("Invalid settype record");
3340 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3341 return error("Invalid settype record");
3342 if (TypeList[Record[0]] == VoidType)
3343 return error("Invalid constant type");
3344 CurTyID = Record[0];
3345 CurTy = TypeList[CurTyID];
3346 CurElemTy = getPtrElementTypeByID(CurTyID);
3347 continue; // Skip the ValueList manipulation.
3348 case bitc::CST_CODE_NULL: // NULL
3349 if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
3350 return error("Invalid type for a constant null value");
3351 if (auto *TETy = dyn_cast<TargetExtType>(CurTy))
3352 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
3353 return error("Invalid type for a constant null value");
3354 V = Constant::getNullValue(CurTy);
3355 break;
3356 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
3357 if (!CurTy->isIntOrIntVectorTy() || Record.empty())
3358 return error("Invalid integer const record");
3359 V = ConstantInt::getSigned(CurTy, decodeSignRotatedValue(Record[0]));
3360 break;
3361 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
3362 if (!CurTy->isIntOrIntVectorTy() || Record.empty())
3363 return error("Invalid wide integer const record");
3364
3365 auto *ScalarTy = cast<IntegerType>(CurTy->getScalarType());
3366 APInt VInt = readWideAPInt(Record, ScalarTy->getBitWidth());
3367 V = ConstantInt::get(CurTy, VInt);
3368 break;
3369 }
3370 case bitc::CST_CODE_BYTE: // BYTE: [byteval]
3371 if (!CurTy->isByteOrByteVectorTy() || Record.empty())
3372 return error("Invalid byte const record");
3373 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]));
3374 break;
3375 case bitc::CST_CODE_WIDE_BYTE: { // WIDE_BYTE: [n x byteval]
3376 if (!CurTy->isByteOrByteVectorTy() || Record.empty())
3377 return error("Invalid wide byte const record");
3378
3379 auto *ScalarTy = cast<ByteType>(CurTy->getScalarType());
3380 APInt VByte = readWideAPInt(Record, ScalarTy->getBitWidth());
3381 V = ConstantByte::get(CurTy, VByte);
3382 break;
3383 }
3384 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
3385 if (Record.empty())
3386 return error("Invalid float const record");
3387
3388 auto *ScalarTy = CurTy->getScalarType();
3389 if (ScalarTy->isHalfTy())
3390 V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEhalf(),
3391 APInt(16, (uint16_t)Record[0])));
3392 else if (ScalarTy->isBFloatTy())
3393 V = ConstantFP::get(
3394 CurTy, APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3395 else if (ScalarTy->isFloatTy())
3396 V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEsingle(),
3397 APInt(32, (uint32_t)Record[0])));
3398 else if (ScalarTy->isDoubleTy())
3399 V = ConstantFP::get(
3400 CurTy, APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3401 else if (ScalarTy->isX86_FP80Ty()) {
3402 // Bits are not stored the same way as a normal i80 APInt, compensate.
3403 uint64_t Rearrange[2];
3404 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3405 Rearrange[1] = Record[0] >> 48;
3406 V = ConstantFP::get(
3407 CurTy, APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3408 } else if (ScalarTy->isFP128Ty())
3409 V = ConstantFP::get(CurTy,
3410 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3411 else if (ScalarTy->isPPC_FP128Ty())
3412 V = ConstantFP::get(
3413 CurTy, APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3414 else
3415 V = PoisonValue::get(CurTy);
3416 break;
3417 }
3418
3419 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3420 if (Record.empty())
3421 return error("Invalid aggregate record");
3422
3423 SmallVector<unsigned, 16> Elts;
3424 llvm::append_range(Elts, Record);
3425
3426 if (isa<StructType>(CurTy)) {
3427 V = BitcodeConstant::create(
3428 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3429 } else if (isa<ArrayType>(CurTy)) {
3430 V = BitcodeConstant::create(Alloc, CurTy,
3431 BitcodeConstant::ConstantArrayOpcode, Elts);
3432 } else if (isa<VectorType>(CurTy)) {
3433 V = BitcodeConstant::create(
3434 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3435 } else {
3436 V = PoisonValue::get(CurTy);
3437 }
3438 break;
3439 }
3440 case bitc::CST_CODE_STRING: // STRING: [values]
3441 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3442 if (Record.empty())
3443 return error("Invalid string record");
3444
3445 SmallString<16> Elts(Record.begin(), Record.end());
3447 Context, Elts, BitCode == bitc::CST_CODE_CSTRING,
3448 cast<ArrayType>(CurTy)->getElementType()->isByteTy());
3449 break;
3450 }
3451 case bitc::CST_CODE_DATA: {// DATA: [n x value]
3452 if (Record.empty())
3453 return error("Invalid data record");
3454
3455 Type *EltTy = CurTy->getContainedType(0);
3457 return error("Invalid type for value");
3458
3459 const unsigned EltBytes = EltTy->getScalarSizeInBits() / 8;
3460 SmallString<128> RawData;
3461 RawData.reserve(Record.size() * EltBytes);
3462 for (uint64_t Val : Record) {
3463 const char *Src = reinterpret_cast<const char *>(&Val);
3464 if constexpr (sys::IsBigEndianHost)
3465 Src += sizeof(uint64_t) - EltBytes;
3466 RawData.append(Src, Src + EltBytes);
3467 }
3468
3469 V = isa<VectorType>(CurTy)
3470 ? ConstantDataVector::getRaw(RawData.str(), Record.size(), EltTy)
3471 : ConstantDataArray::getRaw(RawData.str(), Record.size(), EltTy);
3472 break;
3473 }
3474 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
3475 if (Record.size() < 2)
3476 return error("Invalid unary op constexpr record");
3477 int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
3478 if (Opc < 0) {
3479 V = PoisonValue::get(CurTy); // Unknown unop.
3480 } else {
3481 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
3482 }
3483 break;
3484 }
3485 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
3486 if (Record.size() < 3)
3487 return error("Invalid binary op constexpr record");
3488 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3489 if (Opc < 0) {
3490 V = PoisonValue::get(CurTy); // Unknown binop.
3491 } else {
3492 uint8_t Flags = 0;
3493 if (Record.size() >= 4) {
3494 if (Opc == Instruction::Add ||
3495 Opc == Instruction::Sub ||
3496 Opc == Instruction::Mul ||
3497 Opc == Instruction::Shl) {
3498 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3500 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3502 } else if (Opc == Instruction::SDiv ||
3503 Opc == Instruction::UDiv ||
3504 Opc == Instruction::LShr ||
3505 Opc == Instruction::AShr) {
3506 if (Record[3] & (1 << bitc::PEO_EXACT))
3508 }
3509 }
3510 V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
3511 {(unsigned)Record[1], (unsigned)Record[2]});
3512 }
3513 break;
3514 }
3515 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
3516 if (Record.size() < 3)
3517 return error("Invalid cast constexpr record");
3518 int Opc = getDecodedCastOpcode(Record[0]);
3519 if (Opc < 0) {
3520 V = PoisonValue::get(CurTy); // Unknown cast.
3521 } else {
3522 unsigned OpTyID = Record[1];
3523 Type *OpTy = getTypeByID(OpTyID);
3524 if (!OpTy)
3525 return error("Invalid cast constexpr record");
3526 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
3527 }
3528 break;
3529 }
3530 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
3531 case bitc::CST_CODE_CE_GEP_OLD: // [ty, n x operands]
3532 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD: // [ty, flags, n x
3533 // operands]
3534 case bitc::CST_CODE_CE_GEP: // [ty, flags, n x operands]
3535 case bitc::CST_CODE_CE_GEP_WITH_INRANGE: { // [ty, flags, start, end, n x
3536 // operands]
3537 if (Record.size() < 2)
3538 return error("Constant GEP record must have at least two elements");
3539 unsigned OpNum = 0;
3540 Type *PointeeType = nullptr;
3543 BitCode == bitc::CST_CODE_CE_GEP || Record.size() % 2)
3544 PointeeType = getTypeByID(Record[OpNum++]);
3545
3546 uint64_t Flags = 0;
3547 std::optional<ConstantRange> InRange;
3549 uint64_t Op = Record[OpNum++];
3550 Flags = Op & 1; // inbounds
3551 unsigned InRangeIndex = Op >> 1;
3552 // "Upgrade" inrange by dropping it. The feature is too niche to
3553 // bother.
3554 (void)InRangeIndex;
3555 } else if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE) {
3556 Flags = Record[OpNum++];
3557 Expected<ConstantRange> MaybeInRange =
3558 readBitWidthAndConstantRange(Record, OpNum);
3559 if (!MaybeInRange)
3560 return MaybeInRange.takeError();
3561 InRange = MaybeInRange.get();
3562 } else if (BitCode == bitc::CST_CODE_CE_GEP) {
3563 Flags = Record[OpNum++];
3564 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
3565 Flags = (1 << bitc::GEP_INBOUNDS);
3566
3567 SmallVector<unsigned, 16> Elts;
3568 unsigned BaseTypeID = Record[OpNum];
3569 while (OpNum != Record.size()) {
3570 unsigned ElTyID = Record[OpNum++];
3571 Type *ElTy = getTypeByID(ElTyID);
3572 if (!ElTy)
3573 return error("Invalid getelementptr constexpr record");
3574 Elts.push_back(Record[OpNum++]);
3575 }
3576
3577 if (Elts.size() < 1)
3578 return error("Invalid gep with no operands");
3579
3580 Type *BaseType = getTypeByID(BaseTypeID);
3582 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3583 BaseType = getTypeByID(BaseTypeID);
3584 }
3585
3587 if (!OrigPtrTy)
3588 return error("GEP base operand must be pointer or vector of pointer");
3589
3590 if (!PointeeType) {
3591 PointeeType = getPtrElementTypeByID(BaseTypeID);
3592 if (!PointeeType)
3593 return error("Missing element type for old-style constant GEP");
3594 }
3595
3596 V = BitcodeConstant::create(
3597 Alloc, CurTy,
3598 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType, InRange},
3599 Elts);
3600 break;
3601 }
3602 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
3603 if (Record.size() < 3)
3604 return error("Invalid select constexpr record");
3605
3606 V = BitcodeConstant::create(
3607 Alloc, CurTy, Instruction::Select,
3608 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3609 break;
3610 }
3612 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3613 if (Record.size() < 3)
3614 return error("Invalid extractelement constexpr record");
3615 unsigned OpTyID = Record[0];
3616 VectorType *OpTy =
3617 dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
3618 if (!OpTy)
3619 return error("Invalid extractelement constexpr record");
3620 unsigned IdxRecord;
3621 if (Record.size() == 4) {
3622 unsigned IdxTyID = Record[2];
3623 Type *IdxTy = getTypeByID(IdxTyID);
3624 if (!IdxTy)
3625 return error("Invalid extractelement constexpr record");
3626 IdxRecord = Record[3];
3627 } else {
3628 // Deprecated, but still needed to read old bitcode files.
3629 IdxRecord = Record[2];
3630 }
3631 V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
3632 {(unsigned)Record[1], IdxRecord});
3633 break;
3634 }
3636 : { // CE_INSERTELT: [opval, opval, opty, opval]
3637 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3638 if (Record.size() < 3 || !OpTy)
3639 return error("Invalid insertelement constexpr record");
3640 unsigned IdxRecord;
3641 if (Record.size() == 4) {
3642 unsigned IdxTyID = Record[2];
3643 Type *IdxTy = getTypeByID(IdxTyID);
3644 if (!IdxTy)
3645 return error("Invalid insertelement constexpr record");
3646 IdxRecord = Record[3];
3647 } else {
3648 // Deprecated, but still needed to read old bitcode files.
3649 IdxRecord = Record[2];
3650 }
3651 V = BitcodeConstant::create(
3652 Alloc, CurTy, Instruction::InsertElement,
3653 {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
3654 break;
3655 }
3656 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3657 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3658 if (Record.size() < 3 || !OpTy)
3659 return error("Invalid shufflevector constexpr record");
3660 V = BitcodeConstant::create(
3661 Alloc, CurTy, Instruction::ShuffleVector,
3662 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3663 break;
3664 }
3665 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3666 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3667 VectorType *OpTy =
3668 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3669 if (Record.size() < 4 || !RTy || !OpTy)
3670 return error("Invalid shufflevector constexpr record");
3671 V = BitcodeConstant::create(
3672 Alloc, CurTy, Instruction::ShuffleVector,
3673 {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
3674 break;
3675 }
3676 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
3677 if (Record.size() < 4)
3678 return error("Invalid cmp constexpt record");
3679 unsigned OpTyID = Record[0];
3680 Type *OpTy = getTypeByID(OpTyID);
3681 if (!OpTy)
3682 return error("Invalid cmp constexpr record");
3683 V = BitcodeConstant::create(
3684 Alloc, CurTy,
3685 {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
3686 : Instruction::ICmp),
3687 (uint8_t)Record[3]},
3688 {(unsigned)Record[1], (unsigned)Record[2]});
3689 break;
3690 }
3691 // This maintains backward compatibility, pre-asm dialect keywords.
3692 // Deprecated, but still needed to read old bitcode files.
3694 if (Record.size() < 2)
3695 return error("Invalid inlineasm record");
3696 std::string AsmStr, ConstrStr;
3697 bool HasSideEffects = Record[0] & 1;
3698 bool IsAlignStack = Record[0] >> 1;
3699 unsigned AsmStrSize = Record[1];
3700 if (2+AsmStrSize >= Record.size())
3701 return error("Invalid inlineasm record");
3702 unsigned ConstStrSize = Record[2+AsmStrSize];
3703 if (3+AsmStrSize+ConstStrSize > Record.size())
3704 return error("Invalid inlineasm record");
3705
3706 for (unsigned i = 0; i != AsmStrSize; ++i)
3707 AsmStr += (char)Record[2+i];
3708 for (unsigned i = 0; i != ConstStrSize; ++i)
3709 ConstrStr += (char)Record[3+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 break;
3716 }
3717 // This version adds support for the asm dialect keywords (e.g.,
3718 // inteldialect).
3720 if (Record.size() < 2)
3721 return error("Invalid inlineasm record");
3722 std::string AsmStr, ConstrStr;
3723 bool HasSideEffects = Record[0] & 1;
3724 bool IsAlignStack = (Record[0] >> 1) & 1;
3725 unsigned AsmDialect = Record[0] >> 2;
3726 unsigned AsmStrSize = Record[1];
3727 if (2+AsmStrSize >= Record.size())
3728 return error("Invalid inlineasm record");
3729 unsigned ConstStrSize = Record[2+AsmStrSize];
3730 if (3+AsmStrSize+ConstStrSize > Record.size())
3731 return error("Invalid inlineasm record");
3732
3733 for (unsigned i = 0; i != AsmStrSize; ++i)
3734 AsmStr += (char)Record[2+i];
3735 for (unsigned i = 0; i != ConstStrSize; ++i)
3736 ConstrStr += (char)Record[3+AsmStrSize+i];
3737 UpgradeInlineAsmString(&AsmStr);
3738 if (!CurElemTy)
3739 return error("Missing element type for old-style inlineasm");
3740 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3741 HasSideEffects, IsAlignStack,
3742 InlineAsm::AsmDialect(AsmDialect));
3743 break;
3744 }
3745 // This version adds support for the unwind keyword.
3747 if (Record.size() < 2)
3748 return error("Invalid inlineasm record");
3749 unsigned OpNum = 0;
3750 std::string AsmStr, ConstrStr;
3751 bool HasSideEffects = Record[OpNum] & 1;
3752 bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3753 unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3754 bool CanThrow = (Record[OpNum] >> 3) & 1;
3755 ++OpNum;
3756 unsigned AsmStrSize = Record[OpNum];
3757 ++OpNum;
3758 if (OpNum + AsmStrSize >= Record.size())
3759 return error("Invalid inlineasm record");
3760 unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3761 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3762 return error("Invalid inlineasm record");
3763
3764 for (unsigned i = 0; i != AsmStrSize; ++i)
3765 AsmStr += (char)Record[OpNum + i];
3766 ++OpNum;
3767 for (unsigned i = 0; i != ConstStrSize; ++i)
3768 ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3769 UpgradeInlineAsmString(&AsmStr);
3770 if (!CurElemTy)
3771 return error("Missing element type for old-style inlineasm");
3772 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3773 HasSideEffects, IsAlignStack,
3774 InlineAsm::AsmDialect(AsmDialect), CanThrow);
3775 break;
3776 }
3777 // This version adds explicit function type.
3779 if (Record.size() < 3)
3780 return error("Invalid inlineasm record");
3781 unsigned OpNum = 0;
3782 auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
3783 ++OpNum;
3784 if (!FnTy)
3785 return error("Invalid inlineasm record");
3786 std::string AsmStr, ConstrStr;
3787 bool HasSideEffects = Record[OpNum] & 1;
3788 bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3789 unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3790 bool CanThrow = (Record[OpNum] >> 3) & 1;
3791 ++OpNum;
3792 unsigned AsmStrSize = Record[OpNum];
3793 ++OpNum;
3794 if (OpNum + AsmStrSize >= Record.size())
3795 return error("Invalid inlineasm record");
3796 unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3797 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3798 return error("Invalid inlineasm record");
3799
3800 for (unsigned i = 0; i != AsmStrSize; ++i)
3801 AsmStr += (char)Record[OpNum + i];
3802 ++OpNum;
3803 for (unsigned i = 0; i != ConstStrSize; ++i)
3804 ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3805 UpgradeInlineAsmString(&AsmStr);
3806 V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3807 InlineAsm::AsmDialect(AsmDialect), CanThrow);
3808 break;
3809 }
3811 if (Record.size() < 3)
3812 return error("Invalid blockaddress record");
3813 unsigned FnTyID = Record[0];
3814 Type *FnTy = getTypeByID(FnTyID);
3815 if (!FnTy)
3816 return error("Invalid blockaddress record");
3817 V = BitcodeConstant::create(
3818 Alloc, CurTy,
3819 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3820 Record[1]);
3821 break;
3822 }
3824 if (Record.size() < 2)
3825 return error("Invalid dso_local record");
3826 unsigned GVTyID = Record[0];
3827 Type *GVTy = getTypeByID(GVTyID);
3828 if (!GVTy)
3829 return error("Invalid dso_local record");
3830 V = BitcodeConstant::create(
3831 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3832 break;
3833 }
3835 if (Record.size() < 2)
3836 return error("Invalid no_cfi record");
3837 unsigned GVTyID = Record[0];
3838 Type *GVTy = getTypeByID(GVTyID);
3839 if (!GVTy)
3840 return error("Invalid no_cfi record");
3841 V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3842 Record[1]);
3843 break;
3844 }
3846 if (Record.size() < 4)
3847 return error("Invalid ptrauth record");
3848 // Ptr, Key, Disc, AddrDisc
3849 V = BitcodeConstant::create(Alloc, CurTy,
3850 BitcodeConstant::ConstantPtrAuthOpcode,
3851 {(unsigned)Record[0], (unsigned)Record[1],
3852 (unsigned)Record[2], (unsigned)Record[3]});
3853 break;
3854 }
3856 if (Record.size() < 5)
3857 return error("Invalid ptrauth record");
3858 // Ptr, Key, Disc, AddrDisc, DeactivationSymbol
3859 V = BitcodeConstant::create(
3860 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3861 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2],
3862 (unsigned)Record[3], (unsigned)Record[4]});
3863 break;
3864 }
3865 }
3866
3867 assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
3868 if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
3869 return Err;
3870 ++NextCstNo;
3871 }
3872}
3873
3874Error BitcodeReader::parseUseLists() {
3875 if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3876 return Err;
3877
3878 // Read all the records.
3879 SmallVector<uint64_t, 64> Record;
3880
3881 while (true) {
3882 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3883 if (!MaybeEntry)
3884 return MaybeEntry.takeError();
3885 BitstreamEntry Entry = MaybeEntry.get();
3886
3887 switch (Entry.Kind) {
3888 case BitstreamEntry::SubBlock: // Handled for us already.
3890 return error("Malformed block");
3892 return Error::success();
3894 // The interesting case.
3895 break;
3896 }
3897
3898 // Read a use list record.
3899 Record.clear();
3900 bool IsBB = false;
3901 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3902 if (!MaybeRecord)
3903 return MaybeRecord.takeError();
3904 switch (MaybeRecord.get()) {
3905 default: // Default behavior: unknown type.
3906 break;
3908 IsBB = true;
3909 [[fallthrough]];
3911 unsigned RecordLength = Record.size();
3912 if (RecordLength < 3)
3913 // Records should have at least an ID and two indexes.
3914 return error("Invalid uselist record");
3915 unsigned ID = Record.pop_back_val();
3916
3917 Value *V;
3918 if (IsBB) {
3919 assert(ID < FunctionBBs.size() && "Basic block not found");
3920 V = FunctionBBs[ID];
3921 } else
3922 V = ValueList[ID];
3923
3924 if (!V->hasUseList())
3925 break;
3926
3927 unsigned NumUses = 0;
3928 SmallDenseMap<const Use *, unsigned, 16> Order;
3929 for (const Use &U : V->materialized_uses()) {
3930 if (++NumUses > Record.size())
3931 break;
3932 Order[&U] = Record[NumUses - 1];
3933 }
3934 if (Order.size() != Record.size() || NumUses > Record.size())
3935 // Mismatches can happen if the functions are being materialized lazily
3936 // (out-of-order), or a value has been upgraded.
3937 break;
3938
3939 V->sortUseList([&](const Use &L, const Use &R) {
3940 return Order.lookup(&L) < Order.lookup(&R);
3941 });
3942 break;
3943 }
3944 }
3945 }
3946}
3947
3948/// When we see the block for metadata, remember where it is and then skip it.
3949/// This lets us lazily deserialize the metadata.
3950Error BitcodeReader::rememberAndSkipMetadata() {
3951 // Save the current stream state.
3952 uint64_t CurBit = Stream.GetCurrentBitNo();
3953 DeferredMetadataInfo.push_back(CurBit);
3954
3955 // Skip over the block for now.
3956 if (Error Err = Stream.SkipBlock())
3957 return Err;
3958 return Error::success();
3959}
3960
3961Error BitcodeReader::materializeMetadata() {
3962 for (uint64_t BitPos : DeferredMetadataInfo) {
3963 // Move the bit stream to the saved position.
3964 if (Error JumpFailed = Stream.JumpToBit(BitPos))
3965 return JumpFailed;
3966 if (Error Err = MDLoader->parseModuleMetadata())
3967 return Err;
3968 }
3969
3970 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3971 // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3972 // multiple times.
3973 if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3974 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3975 NamedMDNode *LinkerOpts =
3976 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3977 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3978 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3979 }
3980 }
3981
3982 UpgradeCFIFunctionsMetadata(*TheModule);
3983
3984 DeferredMetadataInfo.clear();
3985 return Error::success();
3986}
3987
3988void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3989
3990/// When we see the block for a function body, remember where it is and then
3991/// skip it. This lets us lazily deserialize the functions.
3992Error BitcodeReader::rememberAndSkipFunctionBody() {
3993 // Get the function we are talking about.
3994 if (FunctionsWithBodies.empty())
3995 return error("Insufficient function protos");
3996
3997 Function *Fn = FunctionsWithBodies.back();
3998 FunctionsWithBodies.pop_back();
3999
4000 // Save the current stream state.
4001 uint64_t CurBit = Stream.GetCurrentBitNo();
4002 assert(
4003 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4004 "Mismatch between VST and scanned function offsets");
4005 DeferredFunctionInfo[Fn] = CurBit;
4006
4007 // Skip over the function block for now.
4008 if (Error Err = Stream.SkipBlock())
4009 return Err;
4010 return Error::success();
4011}
4012
4013Error BitcodeReader::globalCleanup() {
4014 // Patch the initializers for globals and aliases up.
4015 if (Error Err = resolveGlobalAndIndirectSymbolInits())
4016 return Err;
4017 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4018 return error("Malformed global initializer set");
4019
4020 // Look for intrinsic functions which need to be upgraded at some point
4021 // and functions that need to have their function attributes upgraded.
4022 for (Function &F : *TheModule) {
4023 MDLoader->upgradeDebugIntrinsics(F);
4024 Function *NewFn;
4025 if (UpgradeIntrinsicFunction(&F, NewFn))
4026 UpgradedIntrinsics[&F] = NewFn;
4027 // Look for functions that rely on old function attribute behavior.
4029 }
4030
4031 // Look for global variables which need to be renamed.
4032 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4033 for (GlobalVariable &GV : TheModule->globals())
4034 if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
4035 UpgradedVariables.emplace_back(&GV, Upgraded);
4036 for (auto &Pair : UpgradedVariables) {
4037 Pair.first->eraseFromParent();
4038 TheModule->insertGlobalVariable(Pair.second);
4039 }
4040
4041 // Force deallocation of memory for these vectors to favor the client that
4042 // want lazy deserialization.
4043 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
4044 std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
4045 return Error::success();
4046}
4047
4048/// Support for lazy parsing of function bodies. This is required if we
4049/// either have an old bitcode file without a VST forward declaration record,
4050/// or if we have an anonymous function being materialized, since anonymous
4051/// functions do not have a name and are therefore not in the VST.
4052Error BitcodeReader::rememberAndSkipFunctionBodies() {
4053 if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
4054 return JumpFailed;
4055
4056 if (Stream.AtEndOfStream())
4057 return error("Could not find function in stream");
4058
4059 if (!SeenFirstFunctionBody)
4060 return error("Trying to materialize functions before seeing function blocks");
4061
4062 // An old bitcode file with the symbol table at the end would have
4063 // finished the parse greedily.
4064 assert(SeenValueSymbolTable);
4065
4066 while (true) {
4067 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4068 if (!MaybeEntry)
4069 return MaybeEntry.takeError();
4070 llvm::BitstreamEntry Entry = MaybeEntry.get();
4071
4072 switch (Entry.Kind) {
4073 default:
4074 return error("Expect SubBlock");
4076 switch (Entry.ID) {
4077 default:
4078 return error("Expect function block");
4080 if (Error Err = rememberAndSkipFunctionBody())
4081 return Err;
4082 NextUnreadBit = Stream.GetCurrentBitNo();
4083 return Error::success();
4084 }
4085 }
4086 }
4087}
4088
4089Error BitcodeReaderBase::readBlockInfo() {
4090 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4091 Stream.ReadBlockInfoBlock();
4092 if (!MaybeNewBlockInfo)
4093 return MaybeNewBlockInfo.takeError();
4094 std::optional<BitstreamBlockInfo> NewBlockInfo =
4095 std::move(MaybeNewBlockInfo.get());
4096 if (!NewBlockInfo)
4097 return error("Malformed block");
4098 BlockInfo = std::move(*NewBlockInfo);
4099 return Error::success();
4100}
4101
4102Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4103 // v1: [selection_kind, name]
4104 // v2: [strtab_offset, strtab_size, selection_kind]
4105 StringRef Name;
4106 std::tie(Name, Record) = readNameFromStrtab(Record);
4107
4108 if (Record.empty())
4109 return error("Invalid comdat record");
4111 std::string OldFormatName;
4112 if (!UseStrtab) {
4113 if (Record.size() < 2)
4114 return error("Invalid comdat record");
4115 unsigned ComdatNameSize = Record[1];
4116 if (ComdatNameSize > Record.size() - 2)
4117 return error("Comdat name size too large");
4118 OldFormatName.reserve(ComdatNameSize);
4119 for (unsigned i = 0; i != ComdatNameSize; ++i)
4120 OldFormatName += (char)Record[2 + i];
4121 Name = OldFormatName;
4122 }
4123 Comdat *C = TheModule->getOrInsertComdat(Name);
4124 C->setSelectionKind(SK);
4125 ComdatList.push_back(C);
4126 return Error::success();
4127}
4128
4129static void inferDSOLocal(GlobalValue *GV) {
4130 // infer dso_local from linkage and visibility if it is not encoded.
4131 if (GV->hasLocalLinkage() ||
4133 GV->setDSOLocal(true);
4134}
4135
4138 if (V & (1 << 0))
4139 Meta.NoAddress = true;
4140 if (V & (1 << 1))
4141 Meta.NoHWAddress = true;
4142 if (V & (1 << 2))
4143 Meta.Memtag = true;
4144 if (V & (1 << 3))
4145 Meta.IsDynInit = true;
4146 return Meta;
4147}
4148
4149Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4150 // v1: [pointer type, isconst, initid, linkage, alignment, section,
4151 // visibility, threadlocal, unnamed_addr, externally_initialized,
4152 // dllstorageclass, comdat, attributes, preemption specifier,
4153 // partition strtab offset, partition strtab size] (name in VST)
4154 // v2: [strtab_offset, strtab_size, v1]
4155 // v3: [v2, code_model]
4156 StringRef Name;
4157 std::tie(Name, Record) = readNameFromStrtab(Record);
4158
4159 if (Record.size() < 6)
4160 return error("Invalid global variable record");
4161 unsigned TyID = Record[0];
4162 Type *Ty = getTypeByID(TyID);
4163 if (!Ty)
4164 return error("Invalid global variable record");
4165 bool isConstant = Record[1] & 1;
4166 bool explicitType = Record[1] & 2;
4167 unsigned AddressSpace;
4168 if (explicitType) {
4169 AddressSpace = Record[1] >> 2;
4170 } else {
4171 if (!Ty->isPointerTy())
4172 return error("Invalid type for value");
4173 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
4174 TyID = getContainedTypeID(TyID);
4175 Ty = getTypeByID(TyID);
4176 if (!Ty)
4177 return error("Missing element type for old-style global");
4178 }
4179
4180 uint64_t RawLinkage = Record[3];
4182 MaybeAlign Alignment;
4183 if (Error Err = parseAlignmentValue(Record[4], Alignment))
4184 return Err;
4185 std::string Section;
4186 if (Record[5]) {
4187 if (Record[5] - 1 >= SectionTable.size())
4188 return error("Invalid ID");
4189 Section = SectionTable[Record[5] - 1];
4190 }
4192 // Local linkage must have default visibility.
4193 // auto-upgrade `hidden` and `protected` for old bitcode.
4194 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
4195 Visibility = getDecodedVisibility(Record[6]);
4196
4197 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4198 if (Record.size() > 7)
4199 TLM = getDecodedThreadLocalMode(Record[7]);
4200
4201 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4202 if (Record.size() > 8)
4203 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
4204
4205 bool ExternallyInitialized = false;
4206 if (Record.size() > 9)
4207 ExternallyInitialized = Record[9];
4208
4209 GlobalVariable *NewGV =
4210 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
4211 nullptr, TLM, AddressSpace, ExternallyInitialized);
4212 if (Alignment)
4213 NewGV->setAlignment(*Alignment);
4214 if (!Section.empty())
4215 NewGV->setSection(Section);
4216 NewGV->setVisibility(Visibility);
4217 NewGV->setUnnamedAddr(UnnamedAddr);
4218
4219 if (Record.size() > 10) {
4220 // A GlobalValue with local linkage cannot have a DLL storage class.
4221 if (!NewGV->hasLocalLinkage()) {
4223 }
4224 } else {
4225 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
4226 }
4227
4228 ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
4229
4230 // Remember which value to use for the global initializer.
4231 if (unsigned InitID = Record[2])
4232 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4233
4234 if (Record.size() > 11) {
4235 if (unsigned ComdatID = Record[11]) {
4236 if (ComdatID > ComdatList.size())
4237 return error("Invalid global variable comdat ID");
4238 NewGV->setComdat(ComdatList[ComdatID - 1]);
4239 }
4240 } else if (hasImplicitComdat(RawLinkage)) {
4241 ImplicitComdatObjects.insert(NewGV);
4242 }
4243
4244 if (Record.size() > 12) {
4245 auto AS = getAttributes(Record[12]).getFnAttrs();
4246 NewGV->setAttributes(AS);
4247 }
4248
4249 if (Record.size() > 13) {
4250 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
4251 }
4252 inferDSOLocal(NewGV);
4253
4254 // Check whether we have enough values to read a partition name.
4255 if (Record.size() > 15)
4256 NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
4257
4258 if (Record.size() > 16 && Record[16]) {
4259 llvm::GlobalValue::SanitizerMetadata Meta =
4260 deserializeSanitizerMetadata(Record[16]);
4261 NewGV->setSanitizerMetadata(Meta);
4262 }
4263
4264 if (Record.size() > 17 && Record[17]) {
4265 if (auto CM = getDecodedCodeModel(Record[17]))
4266 NewGV->setCodeModel(*CM);
4267 else
4268 return error("Invalid global variable code model");
4269 }
4270
4271 return Error::success();
4272}
4273
4274void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) {
4275 if (ValueTypeCallback) {
4276 (*ValueTypeCallback)(
4277 F, TypeID, [this](unsigned I) { return getTypeByID(I); },
4278 [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); });
4279 }
4280}
4281
4282Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4283 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
4284 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
4285 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
4286 // v2: [strtab_offset, strtab_size, v1]
4287 StringRef Name;
4288 std::tie(Name, Record) = readNameFromStrtab(Record);
4289
4290 if (Record.size() < 8)
4291 return error("Invalid function record");
4292 unsigned FTyID = Record[0];
4293 Type *FTy = getTypeByID(FTyID);
4294 if (!FTy)
4295 return error("Invalid function record");
4296 if (isa<PointerType>(FTy)) {
4297 FTyID = getContainedTypeID(FTyID, 0);
4298 FTy = getTypeByID(FTyID);
4299 if (!FTy)
4300 return error("Missing element type for old-style function");
4301 }
4302
4303 if (!isa<FunctionType>(FTy))
4304 return error("Invalid type for value");
4305 auto CC = static_cast<CallingConv::ID>(Record[1]);
4306 if (CC & ~CallingConv::MaxID)
4307 return error("Invalid calling convention ID");
4308
4309 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4310 if (Record.size() > 16)
4311 AddrSpace = Record[16];
4312
4313 Function *Func =
4315 AddrSpace, Name, TheModule);
4316
4317 assert(Func->getFunctionType() == FTy &&
4318 "Incorrect fully specified type provided for function");
4319 FunctionTypeIDs[Func] = FTyID;
4320
4321 Func->setCallingConv(CC);
4322 bool isProto = Record[2];
4323 uint64_t RawLinkage = Record[3];
4324 Func->setLinkage(getDecodedLinkage(RawLinkage));
4325 Func->setAttributes(getAttributes(Record[4]));
4326 callValueTypeCallback(Func, FTyID);
4327
4328 // Upgrade any old-style byval or sret without a type by propagating the
4329 // argument's pointee type. There should be no opaque pointers where the byval
4330 // type is implicit.
4331 for (unsigned i = 0; i != Func->arg_size(); ++i) {
4332 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4333 Attribute::InAlloca}) {
4334 if (!Func->hasParamAttribute(i, Kind))
4335 continue;
4336
4337 if (Func->getParamAttribute(i, Kind).getValueAsType())
4338 continue;
4339
4340 Func->removeParamAttr(i, Kind);
4341
4342 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4343 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4344 if (!PtrEltTy)
4345 return error("Missing param element type for attribute upgrade");
4346
4347 Attribute NewAttr;
4348 switch (Kind) {
4349 case Attribute::ByVal:
4350 NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4351 break;
4352 case Attribute::StructRet:
4353 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4354 break;
4355 case Attribute::InAlloca:
4356 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4357 break;
4358 default:
4359 llvm_unreachable("not an upgraded type attribute");
4360 }
4361
4362 Func->addParamAttr(i, NewAttr);
4363 }
4364 }
4365
4366 if (Func->getCallingConv() == CallingConv::X86_INTR &&
4367 !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
4368 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4369 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4370 if (!ByValTy)
4371 return error("Missing param element type for x86_intrcc upgrade");
4372 Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
4373 Func->addParamAttr(0, NewAttr);
4374 }
4375
4376 MaybeAlign Alignment;
4377 if (Error Err = parseAlignmentValue(Record[5], Alignment))
4378 return Err;
4379 if (Alignment)
4380 Func->setAlignment(*Alignment);
4381 if (Record[6]) {
4382 if (Record[6] - 1 >= SectionTable.size())
4383 return error("Invalid ID");
4384 Func->setSection(SectionTable[Record[6] - 1]);
4385 }
4386 // Local linkage must have default visibility.
4387 // auto-upgrade `hidden` and `protected` for old bitcode.
4388 if (!Func->hasLocalLinkage())
4389 Func->setVisibility(getDecodedVisibility(Record[7]));
4390 if (Record.size() > 8 && Record[8]) {
4391 if (Record[8] - 1 >= GCTable.size())
4392 return error("Invalid ID");
4393 Func->setGC(GCTable[Record[8] - 1]);
4394 }
4395 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4396 if (Record.size() > 9)
4397 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
4398 Func->setUnnamedAddr(UnnamedAddr);
4399
4400 FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
4401 if (Record.size() > 10)
4402 OperandInfo.Prologue = Record[10];
4403
4404 if (Record.size() > 11) {
4405 // A GlobalValue with local linkage cannot have a DLL storage class.
4406 if (!Func->hasLocalLinkage()) {
4407 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
4408 }
4409 } else {
4410 upgradeDLLImportExportLinkage(Func, RawLinkage);
4411 }
4412
4413 if (Record.size() > 12) {
4414 if (unsigned ComdatID = Record[12]) {
4415 if (ComdatID > ComdatList.size())
4416 return error("Invalid function comdat ID");
4417 Func->setComdat(ComdatList[ComdatID - 1]);
4418 }
4419 } else if (hasImplicitComdat(RawLinkage)) {
4420 ImplicitComdatObjects.insert(Func);
4421 }
4422
4423 if (Record.size() > 13)
4424 OperandInfo.Prefix = Record[13];
4425
4426 if (Record.size() > 14)
4427 OperandInfo.PersonalityFn = Record[14];
4428
4429 if (Record.size() > 15) {
4430 Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
4431 }
4432 inferDSOLocal(Func);
4433
4434 // Record[16] is the address space number.
4435
4436 // Check whether we have enough values to read a partition name. Also make
4437 // sure Strtab has enough values.
4438 if (Record.size() > 18 && Strtab.data() &&
4439 Record[17] + Record[18] <= Strtab.size()) {
4440 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4441 }
4442
4443 if (Record.size() > 19) {
4444 MaybeAlign PrefAlignment;
4445 if (Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4446 return Err;
4447 Func->setPreferredAlignment(PrefAlignment);
4448 }
4449
4450 ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
4451
4452 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4453 FunctionOperands.push_back(OperandInfo);
4454
4455 // If this is a function with a body, remember the prototype we are
4456 // creating now, so that we can match up the body with them later.
4457 if (!isProto) {
4458 Func->setIsMaterializable(true);
4459 FunctionsWithBodies.push_back(Func);
4460 DeferredFunctionInfo[Func] = 0;
4461 }
4462 return Error::success();
4463}
4464
4465Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4466 unsigned BitCode, ArrayRef<uint64_t> Record) {
4467 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
4468 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4469 // dllstorageclass, threadlocal, unnamed_addr,
4470 // preemption specifier] (name in VST)
4471 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
4472 // visibility, dllstorageclass, threadlocal, unnamed_addr,
4473 // preemption specifier] (name in VST)
4474 // v2: [strtab_offset, strtab_size, v1]
4475 StringRef Name;
4476 std::tie(Name, Record) = readNameFromStrtab(Record);
4477
4478 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
4479 if (Record.size() < (3 + (unsigned)NewRecord))
4480 return error("Invalid global indirect symbol record");
4481 unsigned OpNum = 0;
4482 unsigned TypeID = Record[OpNum++];
4483 Type *Ty = getTypeByID(TypeID);
4484 if (!Ty)
4485 return error("Invalid global indirect symbol record");
4486
4487 unsigned AddrSpace;
4488 if (!NewRecord) {
4489 auto *PTy = dyn_cast<PointerType>(Ty);
4490 if (!PTy)
4491 return error("Invalid type for value");
4492 AddrSpace = PTy->getAddressSpace();
4493 TypeID = getContainedTypeID(TypeID);
4494 Ty = getTypeByID(TypeID);
4495 if (!Ty)
4496 return error("Missing element type for old-style indirect symbol");
4497 } else {
4498 AddrSpace = Record[OpNum++];
4499 }
4500
4501 auto Val = Record[OpNum++];
4502 auto Linkage = Record[OpNum++];
4503 GlobalValue *NewGA;
4504 if (BitCode == bitc::MODULE_CODE_ALIAS ||
4505 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4506 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4507 TheModule);
4508 else
4509 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4510 nullptr, TheModule);
4511
4512 // Local linkage must have default visibility.
4513 // auto-upgrade `hidden` and `protected` for old bitcode.
4514 if (OpNum != Record.size()) {
4515 auto VisInd = OpNum++;
4516 if (!NewGA->hasLocalLinkage())
4517 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
4518 }
4519 if (BitCode == bitc::MODULE_CODE_ALIAS ||
4520 BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4521 if (OpNum != Record.size()) {
4522 auto S = Record[OpNum++];
4523 // A GlobalValue with local linkage cannot have a DLL storage class.
4524 if (!NewGA->hasLocalLinkage())
4526 }
4527 else
4529 if (OpNum != Record.size())
4530 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
4531 if (OpNum != Record.size())
4532 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
4533 }
4534 if (OpNum != Record.size())
4535 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
4536 inferDSOLocal(NewGA);
4537
4538 // Check whether we have enough values to read a partition name.
4539 if (OpNum + 1 < Record.size()) {
4540 // Check Strtab has enough values for the partition.
4541 if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
4542 return error("Malformed partition, too large.");
4543 NewGA->setPartition(
4544 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4545 }
4546
4547 ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
4548 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4549 return Error::success();
4550}
4551
4552Error BitcodeReader::parseModule(uint64_t ResumeBit,
4553 bool ShouldLazyLoadMetadata,
4554 ParserCallbacks Callbacks) {
4555 this->ValueTypeCallback = std::move(Callbacks.ValueType);
4556 if (ResumeBit) {
4557 if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
4558 return JumpFailed;
4559 } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4560 return Err;
4561
4562 SmallVector<uint64_t, 64> Record;
4563
4564 // Parts of bitcode parsing depend on the datalayout. Make sure we
4565 // finalize the datalayout before we run any of that code.
4566 bool ResolvedDataLayout = false;
4567 // In order to support importing modules with illegal data layout strings,
4568 // delay parsing the data layout string until after upgrades and overrides
4569 // have been applied, allowing to fix illegal data layout strings.
4570 // Initialize to the current module's layout string in case none is specified.
4571 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4572
4573 auto ResolveDataLayout = [&]() -> Error {
4574 if (ResolvedDataLayout)
4575 return Error::success();
4576
4577 // Datalayout and triple can't be parsed after this point.
4578 ResolvedDataLayout = true;
4579
4580 // Auto-upgrade the layout string
4581 TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4582 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4583
4584 // Apply override
4585 if (Callbacks.DataLayout) {
4586 if (auto LayoutOverride = (*Callbacks.DataLayout)(
4587 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4588 TentativeDataLayoutStr = *LayoutOverride;
4589 }
4590
4591 // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4592 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
4593 if (!MaybeDL)
4594 return MaybeDL.takeError();
4595
4596 TheModule->setDataLayout(MaybeDL.get());
4597 return Error::success();
4598 };
4599
4600 // Read all the records for this module.
4601 while (true) {
4602 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4603 if (!MaybeEntry)
4604 return MaybeEntry.takeError();
4605 llvm::BitstreamEntry Entry = MaybeEntry.get();
4606
4607 switch (Entry.Kind) {
4609 return error("Malformed block");
4611 if (Error Err = ResolveDataLayout())
4612 return Err;
4613 return globalCleanup();
4614
4616 switch (Entry.ID) {
4617 default: // Skip unknown content.
4618 if (Error Err = Stream.SkipBlock())
4619 return Err;
4620 break;
4622 if (Error Err = readBlockInfo())
4623 return Err;
4624 break;
4626 if (Error Err = parseAttributeBlock())
4627 return Err;
4628 break;
4630 if (Error Err = parseAttributeGroupBlock())
4631 return Err;
4632 break;
4634 if (Error Err = parseTypeTable())
4635 return Err;
4636 break;
4638 if (!SeenValueSymbolTable) {
4639 // Either this is an old form VST without function index and an
4640 // associated VST forward declaration record (which would have caused
4641 // the VST to be jumped to and parsed before it was encountered
4642 // normally in the stream), or there were no function blocks to
4643 // trigger an earlier parsing of the VST.
4644 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4645 if (Error Err = parseValueSymbolTable())
4646 return Err;
4647 SeenValueSymbolTable = true;
4648 } else {
4649 // We must have had a VST forward declaration record, which caused
4650 // the parser to jump to and parse the VST earlier.
4651 assert(VSTOffset > 0);
4652 if (Error Err = Stream.SkipBlock())
4653 return Err;
4654 }
4655 break;
4657 if (Error Err = parseConstants())
4658 return Err;
4659 if (Error Err = resolveGlobalAndIndirectSymbolInits())
4660 return Err;
4661 break;
4663 if (ShouldLazyLoadMetadata) {
4664 if (Error Err = rememberAndSkipMetadata())
4665 return Err;
4666 break;
4667 }
4668 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
4669 if (Error Err = MDLoader->parseModuleMetadata())
4670 return Err;
4671 break;
4673 if (Error Err = MDLoader->parseMetadataKinds())
4674 return Err;
4675 break;
4677 if (Error Err = ResolveDataLayout())
4678 return Err;
4679
4680 // If this is the first function body we've seen, reverse the
4681 // FunctionsWithBodies list.
4682 if (!SeenFirstFunctionBody) {
4683 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4684 if (Error Err = globalCleanup())
4685 return Err;
4686 SeenFirstFunctionBody = true;
4687 }
4688
4689 if (VSTOffset > 0) {
4690 // If we have a VST forward declaration record, make sure we
4691 // parse the VST now if we haven't already. It is needed to
4692 // set up the DeferredFunctionInfo vector for lazy reading.
4693 if (!SeenValueSymbolTable) {
4694 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4695 return Err;
4696 SeenValueSymbolTable = true;
4697 // Fall through so that we record the NextUnreadBit below.
4698 // This is necessary in case we have an anonymous function that
4699 // is later materialized. Since it will not have a VST entry we
4700 // need to fall back to the lazy parse to find its offset.
4701 } else {
4702 // If we have a VST forward declaration record, but have already
4703 // parsed the VST (just above, when the first function body was
4704 // encountered here), then we are resuming the parse after
4705 // materializing functions. The ResumeBit points to the
4706 // start of the last function block recorded in the
4707 // DeferredFunctionInfo map. Skip it.
4708 if (Error Err = Stream.SkipBlock())
4709 return Err;
4710 continue;
4711 }
4712 }
4713
4714 // Support older bitcode files that did not have the function
4715 // index in the VST, nor a VST forward declaration record, as
4716 // well as anonymous functions that do not have VST entries.
4717 // Build the DeferredFunctionInfo vector on the fly.
4718 if (Error Err = rememberAndSkipFunctionBody())
4719 return Err;
4720
4721 // Suspend parsing when we reach the function bodies. Subsequent
4722 // materialization calls will resume it when necessary. If the bitcode
4723 // file is old, the symbol table will be at the end instead and will not
4724 // have been seen yet. In this case, just finish the parse now.
4725 if (SeenValueSymbolTable) {
4726 NextUnreadBit = Stream.GetCurrentBitNo();
4727 // After the VST has been parsed, we need to make sure intrinsic name
4728 // are auto-upgraded.
4729 return globalCleanup();
4730 }
4731 break;
4733 if (Error Err = parseUseLists())
4734 return Err;
4735 break;
4737 if (Error Err = parseOperandBundleTags())
4738 return Err;
4739 break;
4741 if (Error Err = parseSyncScopeNames())
4742 return Err;
4743 break;
4744 }
4745 continue;
4746
4748 // The interesting case.
4749 break;
4750 }
4751
4752 // Read a record.
4753 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4754 if (!MaybeBitCode)
4755 return MaybeBitCode.takeError();
4756 switch (unsigned BitCode = MaybeBitCode.get()) {
4757 default: break; // Default behavior, ignore unknown content.
4759 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4760 if (!VersionOrErr)
4761 return VersionOrErr.takeError();
4762 UseRelativeIDs = *VersionOrErr >= 1;
4763 break;
4764 }
4765 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
4766 if (ResolvedDataLayout)
4767 return error("target triple too late in module");
4768 std::string S;
4769 if (convertToString(Record, 0, S))
4770 return error("Invalid triple record");
4771 TheModule->setTargetTriple(Triple(std::move(S)));
4772 break;
4773 }
4774 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
4775 if (ResolvedDataLayout)
4776 return error("datalayout too late in module");
4777 if (convertToString(Record, 0, TentativeDataLayoutStr))
4778 return error("Invalid data layout record");
4779 break;
4780 }
4781 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
4782 std::string S;
4783 if (convertToString(Record, 0, S))
4784 return error("Invalid asm record");
4785 TheModule->setModuleInlineAsm(S);
4786 break;
4787 }
4788 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
4789 // Deprecated, but still needed to read old bitcode files.
4790 std::string S;
4791 if (convertToString(Record, 0, S))
4792 return error("Invalid deplib record");
4793 // Ignore value.
4794 break;
4795 }
4796 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4797 std::string S;
4798 if (convertToString(Record, 0, S))
4799 return error("Invalid section name record");
4800 SectionTable.push_back(S);
4801 break;
4802 }
4803 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
4804 std::string S;
4805 if (convertToString(Record, 0, S))
4806 return error("Invalid gcname record");
4807 GCTable.push_back(S);
4808 break;
4809 }
4811 if (Error Err = parseComdatRecord(Record))
4812 return Err;
4813 break;
4814 // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4815 // written by ThinLinkBitcodeWriter. See
4816 // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4817 // record
4818 // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4820 if (Error Err = parseGlobalVarRecord(Record))
4821 return Err;
4822 break;
4824 if (Error Err = ResolveDataLayout())
4825 return Err;
4826 if (Error Err = parseFunctionRecord(Record))
4827 return Err;
4828 break;
4832 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4833 return Err;
4834 break;
4835 /// MODULE_CODE_VSTOFFSET: [offset]
4837 if (Record.empty())
4838 return error("Invalid vstoffset record");
4839 // Note that we subtract 1 here because the offset is relative to one word
4840 // before the start of the identification or module block, which was
4841 // historically always the start of the regular bitcode header.
4842 VSTOffset = Record[0] - 1;
4843 break;
4844 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4846 SmallString<128> ValueName;
4847 if (convertToString(Record, 0, ValueName))
4848 return error("Invalid source filename record");
4849 TheModule->setSourceFileName(ValueName);
4850 break;
4851 }
4852 Record.clear();
4853 }
4854 this->ValueTypeCallback = std::nullopt;
4855 return Error::success();
4856}
4857
4858Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
4859 bool IsImporting,
4860 ParserCallbacks Callbacks) {
4861 TheModule = M;
4862 MetadataLoaderCallbacks MDCallbacks;
4863 MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4864 MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4865 return getContainedTypeID(I, J);
4866 };
4867 MDCallbacks.MDType = Callbacks.MDType;
4868 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4869 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4870}
4871
4872Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4873 if (!isa<PointerType>(PtrType))
4874 return error("Load/Store operand is not a pointer type");
4875 if (!PointerType::isLoadableOrStorableType(ValType))
4876 return error("Cannot load/store from pointer");
4877 return Error::success();
4878}
4879
4880Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4881 ArrayRef<unsigned> ArgTyIDs) {
4882 AttributeList Attrs = CB->getAttributes();
4883 for (unsigned i = 0; i != CB->arg_size(); ++i) {
4884 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4885 Attribute::InAlloca}) {
4886 if (!Attrs.hasParamAttr(i, Kind) ||
4887 Attrs.getParamAttr(i, Kind).getValueAsType())
4888 continue;
4889
4890 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4891 if (!PtrEltTy)
4892 return error("Missing element type for typed attribute upgrade");
4893
4894 Attribute NewAttr;
4895 switch (Kind) {
4896 case Attribute::ByVal:
4897 NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4898 break;
4899 case Attribute::StructRet:
4900 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4901 break;
4902 case Attribute::InAlloca:
4903 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4904 break;
4905 default:
4906 llvm_unreachable("not an upgraded type attribute");
4907 }
4908
4909 Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4910 }
4911 }
4912
4913 if (CB->isInlineAsm()) {
4914 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
4915 unsigned ArgNo = 0;
4916 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4917 if (!CI.hasArg())
4918 continue;
4919
4920 if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
4921 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4922 if (!ElemTy)
4923 return error("Missing element type for inline asm upgrade");
4924 Attrs = Attrs.addParamAttribute(
4925 Context, ArgNo,
4926 Attribute::get(Context, Attribute::ElementType, ElemTy));
4927 }
4928
4929 ArgNo++;
4930 }
4931 }
4932
4933 switch (CB->getIntrinsicID()) {
4934 case Intrinsic::preserve_array_access_index:
4935 case Intrinsic::preserve_struct_access_index:
4936 case Intrinsic::aarch64_ldaxr:
4937 case Intrinsic::aarch64_ldxr:
4938 case Intrinsic::aarch64_stlxr:
4939 case Intrinsic::aarch64_stxr:
4940 case Intrinsic::arm_ldaex:
4941 case Intrinsic::arm_ldrex:
4942 case Intrinsic::arm_stlex:
4943 case Intrinsic::arm_strex: {
4944 unsigned ArgNo;
4945 switch (CB->getIntrinsicID()) {
4946 case Intrinsic::aarch64_stlxr:
4947 case Intrinsic::aarch64_stxr:
4948 case Intrinsic::arm_stlex:
4949 case Intrinsic::arm_strex:
4950 ArgNo = 1;
4951 break;
4952 default:
4953 ArgNo = 0;
4954 break;
4955 }
4956 if (!Attrs.getParamElementType(ArgNo)) {
4957 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4958 if (!ElTy)
4959 return error("Missing element type for elementtype upgrade");
4960 Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
4961 Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4962 }
4963 break;
4964 }
4965 default:
4966 break;
4967 }
4968
4969 CB->setAttributes(Attrs);
4970 return Error::success();
4971}
4972
4973/// Lazily parse the specified function body block.
4974Error BitcodeReader::parseFunctionBody(Function *F) {
4976 return Err;
4977
4978 // Unexpected unresolved metadata when parsing function.
4979 if (MDLoader->hasFwdRefs())
4980 return error("Invalid function metadata: incoming forward references");
4981
4982 InstructionList.clear();
4983 unsigned ModuleValueListSize = ValueList.size();
4984 unsigned ModuleMDLoaderSize = MDLoader->size();
4985
4986 // Add all the function arguments to the value table.
4987 unsigned ArgNo = 0;
4988 unsigned FTyID = FunctionTypeIDs[F];
4989 for (Argument &I : F->args()) {
4990 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4991 assert(I.getType() == getTypeByID(ArgTyID) &&
4992 "Incorrect fully specified type for Function Argument");
4993 ValueList.push_back(&I, ArgTyID);
4994 ++ArgNo;
4995 }
4996 unsigned NextValueNo = ValueList.size();
4997 BasicBlock *CurBB = nullptr;
4998 unsigned CurBBNo = 0;
4999 // Block into which constant expressions from phi nodes are materialized.
5000 BasicBlock *PhiConstExprBB = nullptr;
5001 // Edge blocks for phi nodes into which constant expressions have been
5002 // expanded.
5003 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
5004 ConstExprEdgeBBs;
5005
5006 DebugLoc LastLoc;
5007 auto getLastInstruction = [&]() -> Instruction * {
5008 if (CurBB && !CurBB->empty())
5009 return &CurBB->back();
5010 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5011 !FunctionBBs[CurBBNo - 1]->empty())
5012 return &FunctionBBs[CurBBNo - 1]->back();
5013 return nullptr;
5014 };
5015
5016 std::vector<OperandBundleDef> OperandBundles;
5017
5018 // Read all the records.
5019 SmallVector<uint64_t, 64> Record;
5020
5021 while (true) {
5022 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5023 if (!MaybeEntry)
5024 return MaybeEntry.takeError();
5025 llvm::BitstreamEntry Entry = MaybeEntry.get();
5026
5027 switch (Entry.Kind) {
5029 return error("Malformed block");
5031 goto OutOfRecordLoop;
5032
5034 switch (Entry.ID) {
5035 default: // Skip unknown content.
5036 if (Error Err = Stream.SkipBlock())
5037 return Err;
5038 break;
5040 if (Error Err = parseConstants())
5041 return Err;
5042 NextValueNo = ValueList.size();
5043 break;
5045 if (Error Err = parseValueSymbolTable())
5046 return Err;
5047 break;
5049 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
5050 return Err;
5051 break;
5053 assert(DeferredMetadataInfo.empty() &&
5054 "Must read all module-level metadata before function-level");
5055 if (Error Err = MDLoader->parseFunctionMetadata())
5056 return Err;
5057 break;
5059 if (Error Err = parseUseLists())
5060 return Err;
5061 break;
5062 }
5063 continue;
5064
5066 // The interesting case.
5067 break;
5068 }
5069
5070 // Read a record.
5071 Record.clear();
5072 Instruction *I = nullptr;
5073 unsigned ResTypeID = InvalidTypeID;
5074 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5075 if (!MaybeBitCode)
5076 return MaybeBitCode.takeError();
5077 switch (unsigned BitCode = MaybeBitCode.get()) {
5078 default: // Default behavior: reject
5079 return error("Invalid value");
5080 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
5081 if (Record.empty() || Record[0] == 0)
5082 return error("Invalid declareblocks record");
5083 // Create all the basic blocks for the function.
5084 FunctionBBs.resize(Record[0]);
5085
5086 // See if anything took the address of blocks in this function.
5087 auto BBFRI = BasicBlockFwdRefs.find(F);
5088 if (BBFRI == BasicBlockFwdRefs.end()) {
5089 for (BasicBlock *&BB : FunctionBBs)
5090 BB = BasicBlock::Create(Context, "", F);
5091 } else {
5092 auto &BBRefs = BBFRI->second;
5093 // Check for invalid basic block references.
5094 if (BBRefs.size() > FunctionBBs.size())
5095 return error("Invalid ID");
5096 assert(!BBRefs.empty() && "Unexpected empty array");
5097 assert(!BBRefs.front() && "Invalid reference to entry block");
5098 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
5099 ++I)
5100 if (I < RE && BBRefs[I]) {
5101 BBRefs[I]->insertInto(F);
5102 FunctionBBs[I] = BBRefs[I];
5103 } else {
5104 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
5105 }
5106
5107 // Erase from the table.
5108 BasicBlockFwdRefs.erase(BBFRI);
5109 }
5110
5111 CurBB = FunctionBBs[0];
5112 continue;
5113 }
5114
5115 case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
5116 // The record should not be emitted if it's an empty list.
5117 if (Record.empty())
5118 return error("Invalid blockaddr users record");
5119 // When we have the RARE case of a BlockAddress Constant that is not
5120 // scoped to the Function it refers to, we need to conservatively
5121 // materialize the referred to Function, regardless of whether or not
5122 // that Function will ultimately be linked, otherwise users of
5123 // BitcodeReader might start splicing out Function bodies such that we
5124 // might no longer be able to materialize the BlockAddress since the
5125 // BasicBlock (and entire body of the Function) the BlockAddress refers
5126 // to may have been moved. In the case that the user of BitcodeReader
5127 // decides ultimately not to link the Function body, materializing here
5128 // could be considered wasteful, but it's better than a deserialization
5129 // failure as described. This keeps BitcodeReader unaware of complex
5130 // linkage policy decisions such as those use by LTO, leaving those
5131 // decisions "one layer up."
5132 for (uint64_t ValID : Record)
5133 if (auto *F = dyn_cast<Function>(ValueList[ValID]))
5134 BackwardRefFunctions.push_back(F);
5135 else
5136 return error("Invalid blockaddr users record");
5137
5138 continue;
5139
5140 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
5141 // This record indicates that the last instruction is at the same
5142 // location as the previous instruction with a location.
5143 I = getLastInstruction();
5144
5145 if (!I)
5146 return error("Invalid debug_loc_again record");
5147 I->setDebugLoc(LastLoc);
5148 I = nullptr;
5149 continue;
5150
5151 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
5152 I = getLastInstruction();
5153 if (!I || Record.size() < 4)
5154 return error("Invalid debug loc record");
5155
5156 unsigned Line = Record[0], Col = Record[1];
5157 unsigned ScopeID = Record[2], IAID = Record[3];
5158 bool isImplicitCode = Record.size() >= 5 && Record[4];
5159 uint64_t AtomGroup = Record.size() == 7 ? Record[5] : 0;
5160 uint8_t AtomRank = Record.size() == 7 ? Record[6] : 0;
5161
5162 MDNode *Scope = nullptr, *IA = nullptr;
5163 if (ScopeID) {
5165 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5166 if (!Scope)
5167 return error("Invalid debug loc record");
5168 }
5169 if (IAID) {
5171 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5172 if (!IA)
5173 return error("Invalid debug loc record");
5174 }
5175
5176 LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
5177 isImplicitCode, AtomGroup, AtomRank);
5178 I->setDebugLoc(LastLoc);
5179 I = nullptr;
5180 continue;
5181 }
5182 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
5183 unsigned OpNum = 0;
5184 Value *LHS;
5185 unsigned TypeID;
5186 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
5187 OpNum+1 > Record.size())
5188 return error("Invalid unary operator record");
5189
5190 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
5191 if (Opc == -1)
5192 return error("Invalid unary operator record");
5194 ResTypeID = TypeID;
5195 InstructionList.push_back(I);
5196 if (OpNum < Record.size()) {
5197 if (isa<FPMathOperator>(I)) {
5198 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5199 if (FMF.any())
5200 I->setFastMathFlags(FMF);
5201 }
5202 }
5203 break;
5204 }
5205 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
5206 unsigned OpNum = 0;
5207 Value *LHS, *RHS;
5208 unsigned TypeID;
5209 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
5210 popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
5211 CurBB) ||
5212 OpNum+1 > Record.size())
5213 return error("Invalid binary operator record");
5214
5215 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
5216 if (Opc == -1)
5217 return error("Invalid binary operator record");
5219 ResTypeID = TypeID;
5220 InstructionList.push_back(I);
5221 if (OpNum < Record.size()) {
5222 if (Opc == Instruction::Add ||
5223 Opc == Instruction::Sub ||
5224 Opc == Instruction::Mul ||
5225 Opc == Instruction::Shl) {
5226 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
5227 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
5228 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
5229 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
5230 } else if (Opc == Instruction::SDiv ||
5231 Opc == Instruction::UDiv ||
5232 Opc == Instruction::LShr ||
5233 Opc == Instruction::AShr) {
5234 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
5235 cast<BinaryOperator>(I)->setIsExact(true);
5236 } else if (Opc == Instruction::Or) {
5237 if (Record[OpNum] & (1 << bitc::PDI_DISJOINT))
5238 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
5239 } else if (isa<FPMathOperator>(I)) {
5240 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5241 if (FMF.any())
5242 I->setFastMathFlags(FMF);
5243 }
5244 }
5245 break;
5246 }
5247 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
5248 unsigned OpNum = 0;
5249 Value *Op;
5250 unsigned OpTypeID;
5251 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
5252 OpNum + 1 > Record.size())
5253 return error("Invalid cast record");
5254
5255 ResTypeID = Record[OpNum++];
5256 Type *ResTy = getTypeByID(ResTypeID);
5257 int Opc = getDecodedCastOpcode(Record[OpNum++]);
5258
5259 if (Opc == -1 || !ResTy)
5260 return error("Invalid cast record");
5261 Instruction *Temp = nullptr;
5262 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
5263 if (Temp) {
5264 InstructionList.push_back(Temp);
5265 assert(CurBB && "No current BB?");
5266 Temp->insertInto(CurBB, CurBB->end());
5267 }
5268 } else {
5269 auto CastOp = (Instruction::CastOps)Opc;
5270 if (!CastInst::castIsValid(CastOp, Op, ResTy))
5271 return error("Invalid cast");
5272 I = CastInst::Create(CastOp, Op, ResTy);
5273 }
5274
5275 if (OpNum < Record.size()) {
5276 if (Opc == Instruction::ZExt || Opc == Instruction::UIToFP) {
5277 if (Record[OpNum] & (1 << bitc::PNNI_NON_NEG))
5278 cast<PossiblyNonNegInst>(I)->setNonNeg(true);
5279 } else if (Opc == Instruction::Trunc) {
5280 if (Record[OpNum] & (1 << bitc::TIO_NO_UNSIGNED_WRAP))
5281 cast<TruncInst>(I)->setHasNoUnsignedWrap(true);
5282 if (Record[OpNum] & (1 << bitc::TIO_NO_SIGNED_WRAP))
5283 cast<TruncInst>(I)->setHasNoSignedWrap(true);
5284 }
5285 if (isa<FPMathOperator>(I)) {
5286 uint64_t Flags = Record[OpNum];
5287 if (isa<UIToFPInst>(I))
5288 Flags >>= 1;
5289 FastMathFlags FMF = getDecodedFastMathFlags(Flags);
5290 if (FMF.any())
5291 I->setFastMathFlags(FMF);
5292 }
5293 }
5294
5295 InstructionList.push_back(I);
5296 break;
5297 }
5300 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
5301 unsigned OpNum = 0;
5302
5303 unsigned TyID;
5304 Type *Ty;
5305 GEPNoWrapFlags NW;
5306
5307 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
5308 NW = toGEPNoWrapFlags(Record[OpNum++]);
5309 TyID = Record[OpNum++];
5310 Ty = getTypeByID(TyID);
5311 } else {
5314 TyID = InvalidTypeID;
5315 Ty = nullptr;
5316 }
5317
5318 Value *BasePtr;
5319 unsigned BasePtrTypeID;
5320 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5321 CurBB))
5322 return error("Invalid gep record");
5323
5324 if (!Ty) {
5325 TyID = getContainedTypeID(BasePtrTypeID);
5326 if (BasePtr->getType()->isVectorTy())
5327 TyID = getContainedTypeID(TyID);
5328 Ty = getTypeByID(TyID);
5329 }
5330
5331 SmallVector<Value*, 16> GEPIdx;
5332 while (OpNum != Record.size()) {
5333 Value *Op;
5334 unsigned OpTypeID;
5335 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5336 return error("Invalid gep record");
5337 GEPIdx.push_back(Op);
5338 }
5339
5340 auto *GEP = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
5341 I = GEP;
5342
5343 ResTypeID = TyID;
5344 if (cast<GEPOperator>(I)->getNumIndices() != 0) {
5345 auto GTI = std::next(gep_type_begin(I));
5346 for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
5347 unsigned SubType = 0;
5348 if (GTI.isStruct()) {
5349 ConstantInt *IdxC =
5350 Idx->getType()->isVectorTy()
5352 : cast<ConstantInt>(Idx);
5353 SubType = IdxC->getZExtValue();
5354 }
5355 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5356 ++GTI;
5357 }
5358 }
5359
5360 // At this point ResTypeID is the result element type. We need a pointer
5361 // or vector of pointer to it.
5362 ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
5363 if (I->getType()->isVectorTy())
5364 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5365
5366 InstructionList.push_back(I);
5367 GEP->setNoWrapFlags(NW);
5368 break;
5369 }
5370
5372 // EXTRACTVAL: [opty, opval, n x indices]
5373 unsigned OpNum = 0;
5374 Value *Agg;
5375 unsigned AggTypeID;
5376 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5377 return error("Invalid extractvalue record");
5378 Type *Ty = Agg->getType();
5379
5380 unsigned RecSize = Record.size();
5381 if (OpNum == RecSize)
5382 return error("EXTRACTVAL: Invalid instruction with 0 indices");
5383
5384 SmallVector<unsigned, 4> EXTRACTVALIdx;
5385 ResTypeID = AggTypeID;
5386 for (; OpNum != RecSize; ++OpNum) {
5387 bool IsArray = Ty->isArrayTy();
5388 bool IsStruct = Ty->isStructTy();
5389 uint64_t Index = Record[OpNum];
5390
5391 if (!IsStruct && !IsArray)
5392 return error("EXTRACTVAL: Invalid type");
5393 if ((unsigned)Index != Index)
5394 return error("Invalid value");
5395 if (IsStruct && Index >= Ty->getStructNumElements())
5396 return error("EXTRACTVAL: Invalid struct index");
5397 if (IsArray && Index >= Ty->getArrayNumElements())
5398 return error("EXTRACTVAL: Invalid array index");
5399 EXTRACTVALIdx.push_back((unsigned)Index);
5400
5401 if (IsStruct) {
5402 Ty = Ty->getStructElementType(Index);
5403 ResTypeID = getContainedTypeID(ResTypeID, Index);
5404 } else {
5405 Ty = Ty->getArrayElementType();
5406 ResTypeID = getContainedTypeID(ResTypeID);
5407 }
5408 }
5409
5410 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
5411 InstructionList.push_back(I);
5412 break;
5413 }
5414
5416 // INSERTVAL: [opty, opval, opty, opval, n x indices]
5417 unsigned OpNum = 0;
5418 Value *Agg;
5419 unsigned AggTypeID;
5420 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5421 return error("Invalid insertvalue record");
5422 Value *Val;
5423 unsigned ValTypeID;
5424 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5425 return error("Invalid insertvalue record");
5426
5427 unsigned RecSize = Record.size();
5428 if (OpNum == RecSize)
5429 return error("INSERTVAL: Invalid instruction with 0 indices");
5430
5431 SmallVector<unsigned, 4> INSERTVALIdx;
5432 Type *CurTy = Agg->getType();
5433 for (; OpNum != RecSize; ++OpNum) {
5434 bool IsArray = CurTy->isArrayTy();
5435 bool IsStruct = CurTy->isStructTy();
5436 uint64_t Index = Record[OpNum];
5437
5438 if (!IsStruct && !IsArray)
5439 return error("INSERTVAL: Invalid type");
5440 if ((unsigned)Index != Index)
5441 return error("Invalid value");
5442 if (IsStruct && Index >= CurTy->getStructNumElements())
5443 return error("INSERTVAL: Invalid struct index");
5444 if (IsArray && Index >= CurTy->getArrayNumElements())
5445 return error("INSERTVAL: Invalid array index");
5446
5447 INSERTVALIdx.push_back((unsigned)Index);
5448 if (IsStruct)
5449 CurTy = CurTy->getStructElementType(Index);
5450 else
5451 CurTy = CurTy->getArrayElementType();
5452 }
5453
5454 if (CurTy != Val->getType())
5455 return error("Inserted value type doesn't match aggregate type");
5456
5457 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
5458 ResTypeID = AggTypeID;
5459 InstructionList.push_back(I);
5460 break;
5461 }
5462
5463 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
5464 // obsolete form of select
5465 // handles select i1 ... in old bitcode
5466 unsigned OpNum = 0;
5468 unsigned TypeID;
5469 Type *CondType = Type::getInt1Ty(Context);
5470 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
5471 CurBB) ||
5472 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
5473 FalseVal, CurBB) ||
5474 popValue(Record, OpNum, NextValueNo, CondType,
5475 getVirtualTypeID(CondType), Cond, CurBB))
5476 return error("Invalid select record");
5477
5478 I = SelectInst::Create(Cond, TrueVal, FalseVal);
5479 ResTypeID = TypeID;
5480 InstructionList.push_back(I);
5481 break;
5482 }
5483
5484 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
5485 // new form of select
5486 // handles select i1 or select [N x i1]
5487 unsigned OpNum = 0;
5489 unsigned ValTypeID, CondTypeID;
5490 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5491 CurBB) ||
5492 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
5493 FalseVal, CurBB) ||
5494 getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
5495 return error("Invalid vector select record");
5496
5497 // select condition can be either i1 or [N x i1]
5498 if (VectorType* vector_type =
5499 dyn_cast<VectorType>(Cond->getType())) {
5500 // expect <n x i1>
5501 if (vector_type->getElementType() != Type::getInt1Ty(Context))
5502 return error("Invalid type for value");
5503 } else {
5504 // expect i1
5505 if (Cond->getType() != Type::getInt1Ty(Context))
5506 return error("Invalid type for value");
5507 }
5508
5509 I = SelectInst::Create(Cond, TrueVal, FalseVal);
5510 ResTypeID = ValTypeID;
5511 InstructionList.push_back(I);
5512 if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
5513 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5514 if (FMF.any())
5515 I->setFastMathFlags(FMF);
5516 }
5517 break;
5518 }
5519
5520 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
5521 unsigned OpNum = 0;
5522 Value *Vec, *Idx;
5523 unsigned VecTypeID, IdxTypeID;
5524 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5525 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5526 return error("Invalid extractelement record");
5527 if (!Vec->getType()->isVectorTy())
5528 return error("Invalid type for value");
5529 I = ExtractElementInst::Create(Vec, Idx);
5530 ResTypeID = getContainedTypeID(VecTypeID);
5531 InstructionList.push_back(I);
5532 break;
5533 }
5534
5535 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
5536 unsigned OpNum = 0;
5537 Value *Vec, *Elt, *Idx;
5538 unsigned VecTypeID, IdxTypeID;
5539 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5540 return error("Invalid insertelement record");
5541 if (!Vec->getType()->isVectorTy())
5542 return error("Invalid type for value");
5543 if (popValue(Record, OpNum, NextValueNo,
5544 cast<VectorType>(Vec->getType())->getElementType(),
5545 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5546 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5547 return error("Invalid insert element record");
5548 I = InsertElementInst::Create(Vec, Elt, Idx);
5549 ResTypeID = VecTypeID;
5550 InstructionList.push_back(I);
5551 break;
5552 }
5553
5554 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5555 unsigned OpNum = 0;
5556 Value *Vec1, *Vec2, *Mask;
5557 unsigned Vec1TypeID;
5558 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5559 CurBB) ||
5560 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
5561 Vec2, CurBB))
5562 return error("Invalid shufflevector record");
5563
5564 unsigned MaskTypeID;
5565 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5566 return error("Invalid shufflevector record");
5567 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
5568 return error("Invalid type for value");
5569
5570 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
5571 ResTypeID =
5572 getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
5573 InstructionList.push_back(I);
5574 break;
5575 }
5576
5577 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
5578 // Old form of ICmp/FCmp returning bool
5579 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5580 // both legal on vectors but had different behaviour.
5581 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
5582 // FCmp/ICmp returning bool or vector of bool
5583
5584 unsigned OpNum = 0;
5585 Value *LHS, *RHS;
5586 unsigned LHSTypeID;
5587 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5588 popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
5589 CurBB))
5590 return error("Invalid comparison record");
5591
5592 if (OpNum >= Record.size())
5593 return error(
5594 "Invalid record: operand number exceeded available operands");
5595
5596 CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
5597 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5598 FastMathFlags FMF;
5599 if (IsFP && Record.size() > OpNum+1)
5600 FMF = getDecodedFastMathFlags(Record[++OpNum]);
5601
5602 if (IsFP) {
5603 if (!CmpInst::isFPPredicate(PredVal))
5604 return error("Invalid fcmp predicate");
5605 I = new FCmpInst(PredVal, LHS, RHS);
5606 } else {
5607 if (!CmpInst::isIntPredicate(PredVal))
5608 return error("Invalid icmp predicate");
5609 I = new ICmpInst(PredVal, LHS, RHS);
5610 if (Record.size() > OpNum + 1 &&
5611 (Record[++OpNum] & (1 << bitc::ICMP_SAME_SIGN)))
5612 cast<ICmpInst>(I)->setSameSign();
5613 }
5614
5615 if (OpNum + 1 != Record.size())
5616 return error("Invalid comparison record");
5617
5618 ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
5619 if (LHS->getType()->isVectorTy())
5620 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5621
5622 if (FMF.any())
5623 I->setFastMathFlags(FMF);
5624 InstructionList.push_back(I);
5625 break;
5626 }
5627
5628 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5629 {
5630 unsigned Size = Record.size();
5631 if (Size == 0) {
5633 InstructionList.push_back(I);
5634 break;
5635 }
5636
5637 unsigned OpNum = 0;
5638 Value *Op = nullptr;
5639 unsigned OpTypeID;
5640 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5641 return error("Invalid ret record");
5642 if (OpNum != Record.size())
5643 return error("Invalid ret record");
5644
5646 InstructionList.push_back(I);
5647 break;
5648 }
5649 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5650 if (Record.size() != 1 && Record.size() != 3)
5651 return error("Invalid br record");
5652 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5653 if (!TrueDest)
5654 return error("Invalid br record");
5655
5656 if (Record.size() == 1) {
5657 I = UncondBrInst::Create(TrueDest);
5658 InstructionList.push_back(I);
5659 }
5660 else {
5661 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5662 Type *CondType = Type::getInt1Ty(Context);
5663 Value *Cond = getValue(Record, 2, NextValueNo, CondType,
5664 getVirtualTypeID(CondType), CurBB);
5665 if (!FalseDest || !Cond)
5666 return error("Invalid br record");
5667 I = CondBrInst::Create(Cond, TrueDest, FalseDest);
5668 InstructionList.push_back(I);
5669 }
5670 break;
5671 }
5672 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5673 if (Record.size() != 1 && Record.size() != 2)
5674 return error("Invalid cleanupret record");
5675 unsigned Idx = 0;
5676 Type *TokenTy = Type::getTokenTy(Context);
5677 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5678 getVirtualTypeID(TokenTy), CurBB);
5679 if (!CleanupPad)
5680 return error("Invalid cleanupret record");
5681 BasicBlock *UnwindDest = nullptr;
5682 if (Record.size() == 2) {
5683 UnwindDest = getBasicBlock(Record[Idx++]);
5684 if (!UnwindDest)
5685 return error("Invalid cleanupret record");
5686 }
5687
5688 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5689 InstructionList.push_back(I);
5690 break;
5691 }
5692 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5693 if (Record.size() != 2)
5694 return error("Invalid catchret record");
5695 unsigned Idx = 0;
5696 Type *TokenTy = Type::getTokenTy(Context);
5697 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5698 getVirtualTypeID(TokenTy), CurBB);
5699 if (!CatchPad)
5700 return error("Invalid catchret record");
5701 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5702 if (!BB)
5703 return error("Invalid catchret record");
5704
5705 I = CatchReturnInst::Create(CatchPad, BB);
5706 InstructionList.push_back(I);
5707 break;
5708 }
5709 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5710 // We must have, at minimum, the outer scope and the number of arguments.
5711 if (Record.size() < 2)
5712 return error("Invalid catchswitch record");
5713
5714 unsigned Idx = 0;
5715
5716 Type *TokenTy = Type::getTokenTy(Context);
5717 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5718 getVirtualTypeID(TokenTy), CurBB);
5719 if (!ParentPad)
5720 return error("Invalid catchswitch record");
5721
5722 unsigned NumHandlers = Record[Idx++];
5723
5725 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5726 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5727 if (!BB)
5728 return error("Invalid catchswitch record");
5729 Handlers.push_back(BB);
5730 }
5731
5732 BasicBlock *UnwindDest = nullptr;
5733 if (Idx + 1 == Record.size()) {
5734 UnwindDest = getBasicBlock(Record[Idx++]);
5735 if (!UnwindDest)
5736 return error("Invalid catchswitch record");
5737 }
5738
5739 if (Record.size() != Idx)
5740 return error("Invalid catchswitch record");
5741
5742 auto *CatchSwitch =
5743 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5744 for (BasicBlock *Handler : Handlers)
5745 CatchSwitch->addHandler(Handler);
5746 I = CatchSwitch;
5747 ResTypeID = getVirtualTypeID(I->getType());
5748 InstructionList.push_back(I);
5749 break;
5750 }
5752 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5753 // We must have, at minimum, the outer scope and the number of arguments.
5754 if (Record.size() < 2)
5755 return error("Invalid catchpad/cleanuppad record");
5756
5757 unsigned Idx = 0;
5758
5759 Type *TokenTy = Type::getTokenTy(Context);
5760 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5761 getVirtualTypeID(TokenTy), CurBB);
5762 if (!ParentPad)
5763 return error("Invalid catchpad/cleanuppad record");
5764
5765 unsigned NumArgOperands = Record[Idx++];
5766
5767 SmallVector<Value *, 2> Args;
5768 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5769 Value *Val;
5770 unsigned ValTypeID;
5771 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
5772 return error("Invalid catchpad/cleanuppad record");
5773 Args.push_back(Val);
5774 }
5775
5776 if (Record.size() != Idx)
5777 return error("Invalid catchpad/cleanuppad record");
5778
5779 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5780 I = CleanupPadInst::Create(ParentPad, Args);
5781 else
5782 I = CatchPadInst::Create(ParentPad, Args);
5783 ResTypeID = getVirtualTypeID(I->getType());
5784 InstructionList.push_back(I);
5785 break;
5786 }
5787 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5788 // Check magic
5789 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5790 // "New" SwitchInst format with case ranges. The changes to write this
5791 // format were reverted but we still recognize bitcode that uses it.
5792 // Hopefully someday we will have support for case ranges and can use
5793 // this format again.
5794
5795 unsigned OpTyID = Record[1];
5796 Type *OpTy = getTypeByID(OpTyID);
5797 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5798
5799 Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5800 BasicBlock *Default = getBasicBlock(Record[3]);
5801 if (!OpTy || !Cond || !Default)
5802 return error("Invalid switch record");
5803
5804 unsigned NumCases = Record[4];
5805
5806 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5807 InstructionList.push_back(SI);
5808
5809 unsigned CurIdx = 5;
5810 for (unsigned i = 0; i != NumCases; ++i) {
5812 unsigned NumItems = Record[CurIdx++];
5813 for (unsigned ci = 0; ci != NumItems; ++ci) {
5814 bool isSingleNumber = Record[CurIdx++];
5815
5816 APInt Low;
5817 unsigned ActiveWords = 1;
5818 if (ValueBitWidth > 64)
5819 ActiveWords = Record[CurIdx++];
5820 Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5821 ValueBitWidth);
5822 CurIdx += ActiveWords;
5823
5824 if (!isSingleNumber) {
5825 ActiveWords = 1;
5826 if (ValueBitWidth > 64)
5827 ActiveWords = Record[CurIdx++];
5828 APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5829 ValueBitWidth);
5830 CurIdx += ActiveWords;
5831
5832 // FIXME: It is not clear whether values in the range should be
5833 // compared as signed or unsigned values. The partially
5834 // implemented changes that used this format in the past used
5835 // unsigned comparisons.
5836 for ( ; Low.ule(High); ++Low)
5837 CaseVals.push_back(ConstantInt::get(Context, Low));
5838 } else
5839 CaseVals.push_back(ConstantInt::get(Context, Low));
5840 }
5841 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5842 for (ConstantInt *Cst : CaseVals)
5843 SI->addCase(Cst, DestBB);
5844 }
5845 I = SI;
5846 break;
5847 }
5848
5849 // Old SwitchInst format without case ranges.
5850
5851 if (Record.size() < 3 || (Record.size() & 1) == 0)
5852 return error("Invalid switch record");
5853 unsigned OpTyID = Record[0];
5854 Type *OpTy = getTypeByID(OpTyID);
5855 Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5856 BasicBlock *Default = getBasicBlock(Record[2]);
5857 if (!OpTy || !Cond || !Default)
5858 return error("Invalid switch record");
5859 unsigned NumCases = (Record.size()-3)/2;
5860 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5861 InstructionList.push_back(SI);
5862 for (unsigned i = 0, e = NumCases; i != e; ++i) {
5863 ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
5864 getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
5865 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5866 if (!CaseVal || !DestBB) {
5867 delete SI;
5868 return error("Invalid switch record");
5869 }
5870 SI->addCase(CaseVal, DestBB);
5871 }
5872 I = SI;
5873 break;
5874 }
5875 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5876 if (Record.size() < 2)
5877 return error("Invalid indirectbr record");
5878 unsigned OpTyID = Record[0];
5879 Type *OpTy = getTypeByID(OpTyID);
5880 Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5881 if (!OpTy || !Address)
5882 return error("Invalid indirectbr record");
5883 unsigned NumDests = Record.size()-2;
5884 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5885 InstructionList.push_back(IBI);
5886 for (unsigned i = 0, e = NumDests; i != e; ++i) {
5887 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5888 IBI->addDestination(DestBB);
5889 } else {
5890 delete IBI;
5891 return error("Invalid indirectbr record");
5892 }
5893 }
5894 I = IBI;
5895 break;
5896 }
5897
5899 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5900 if (Record.size() < 4)
5901 return error("Invalid invoke record");
5902 unsigned OpNum = 0;
5903 AttributeList PAL = getAttributes(Record[OpNum++]);
5904 unsigned CCInfo = Record[OpNum++];
5905 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5906 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5907
5908 unsigned FTyID = InvalidTypeID;
5909 FunctionType *FTy = nullptr;
5910 if ((CCInfo >> 13) & 1) {
5911 FTyID = Record[OpNum++];
5912 FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5913 if (!FTy)
5914 return error("Explicit invoke type is not a function type");
5915 }
5916
5917 Value *Callee;
5918 unsigned CalleeTypeID;
5919 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5920 CurBB))
5921 return error("Invalid invoke record");
5922
5923 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5924 if (!CalleeTy)
5925 return error("Callee is not a pointer");
5926 if (!FTy) {
5927 FTyID = getContainedTypeID(CalleeTypeID);
5928 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5929 if (!FTy)
5930 return error("Callee is not of pointer to function type");
5931 }
5932 if (Record.size() < FTy->getNumParams() + OpNum)
5933 return error("Insufficient operands to call");
5934
5935 SmallVector<Value*, 16> Ops;
5936 SmallVector<unsigned, 16> ArgTyIDs;
5937 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5938 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5939 Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5940 ArgTyID, CurBB));
5941 ArgTyIDs.push_back(ArgTyID);
5942 if (!Ops.back())
5943 return error("Invalid invoke record");
5944 }
5945
5946 if (!FTy->isVarArg()) {
5947 if (Record.size() != OpNum)
5948 return error("Invalid invoke record");
5949 } else {
5950 // Read type/value pairs for varargs params.
5951 while (OpNum != Record.size()) {
5952 Value *Op;
5953 unsigned OpTypeID;
5954 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5955 return error("Invalid invoke record");
5956 Ops.push_back(Op);
5957 ArgTyIDs.push_back(OpTypeID);
5958 }
5959 }
5960
5961 // Upgrade the bundles if needed.
5962 if (!OperandBundles.empty())
5963 UpgradeOperandBundles(OperandBundles);
5964
5965 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
5966 OperandBundles);
5967 ResTypeID = getContainedTypeID(FTyID);
5968 OperandBundles.clear();
5969 InstructionList.push_back(I);
5970 cast<InvokeInst>(I)->setCallingConv(
5971 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5972 cast<InvokeInst>(I)->setAttributes(PAL);
5973 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5974 I->deleteValue();
5975 return Err;
5976 }
5977
5978 break;
5979 }
5980 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5981 unsigned Idx = 0;
5982 Value *Val = nullptr;
5983 unsigned ValTypeID;
5984 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5985 return error("Invalid resume record");
5986 I = ResumeInst::Create(Val);
5987 InstructionList.push_back(I);
5988 break;
5989 }
5991 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5992 unsigned OpNum = 0;
5993 AttributeList PAL = getAttributes(Record[OpNum++]);
5994 unsigned CCInfo = Record[OpNum++];
5995
5996 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5997 unsigned NumIndirectDests = Record[OpNum++];
5998 SmallVector<BasicBlock *, 16> IndirectDests;
5999 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
6000 IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
6001
6002 unsigned FTyID = InvalidTypeID;
6003 FunctionType *FTy = nullptr;
6004 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
6005 FTyID = Record[OpNum++];
6006 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6007 if (!FTy)
6008 return error("Explicit call type is not a function type");
6009 }
6010
6011 Value *Callee;
6012 unsigned CalleeTypeID;
6013 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6014 CurBB))
6015 return error("Invalid callbr record");
6016
6017 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
6018 if (!OpTy)
6019 return error("Callee is not a pointer type");
6020 if (!FTy) {
6021 FTyID = getContainedTypeID(CalleeTypeID);
6022 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6023 if (!FTy)
6024 return error("Callee is not of pointer to function type");
6025 }
6026 if (Record.size() < FTy->getNumParams() + OpNum)
6027 return error("Insufficient operands to call");
6028
6029 SmallVector<Value*, 16> Args;
6030 SmallVector<unsigned, 16> ArgTyIDs;
6031 // Read the fixed params.
6032 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6033 Value *Arg;
6034 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6035 if (FTy->getParamType(i)->isLabelTy())
6036 Arg = getBasicBlock(Record[OpNum]);
6037 else
6038 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6039 ArgTyID, CurBB);
6040 if (!Arg)
6041 return error("Invalid callbr record");
6042 Args.push_back(Arg);
6043 ArgTyIDs.push_back(ArgTyID);
6044 }
6045
6046 // Read type/value pairs for varargs params.
6047 if (!FTy->isVarArg()) {
6048 if (OpNum != Record.size())
6049 return error("Invalid callbr record");
6050 } else {
6051 while (OpNum != Record.size()) {
6052 Value *Op;
6053 unsigned OpTypeID;
6054 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6055 return error("Invalid callbr record");
6056 Args.push_back(Op);
6057 ArgTyIDs.push_back(OpTypeID);
6058 }
6059 }
6060
6061 // Upgrade the bundles if needed.
6062 if (!OperandBundles.empty())
6063 UpgradeOperandBundles(OperandBundles);
6064
6065 if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
6066 InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
6067 auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
6068 return CI.Type == InlineAsm::isLabel;
6069 };
6070 if (none_of(ConstraintInfo, IsLabelConstraint)) {
6071 // Upgrade explicit blockaddress arguments to label constraints.
6072 // Verify that the last arguments are blockaddress arguments that
6073 // match the indirect destinations. Clang always generates callbr
6074 // in this form. We could support reordering with more effort.
6075 unsigned FirstBlockArg = Args.size() - IndirectDests.size();
6076 for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
6077 unsigned LabelNo = ArgNo - FirstBlockArg;
6078 auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
6079 if (!BA || BA->getFunction() != F ||
6080 LabelNo > IndirectDests.size() ||
6081 BA->getBasicBlock() != IndirectDests[LabelNo])
6082 return error("callbr argument does not match indirect dest");
6083 }
6084
6085 // Remove blockaddress arguments.
6086 Args.erase(Args.begin() + FirstBlockArg, Args.end());
6087 ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
6088
6089 // Recreate the function type with less arguments.
6090 SmallVector<Type *> ArgTys;
6091 for (Value *Arg : Args)
6092 ArgTys.push_back(Arg->getType());
6093 FTy =
6094 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6095
6096 // Update constraint string to use label constraints.
6097 std::string Constraints = IA->getConstraintString().str();
6098 unsigned ArgNo = 0;
6099 size_t Pos = 0;
6100 for (const auto &CI : ConstraintInfo) {
6101 if (CI.hasArg()) {
6102 if (ArgNo >= FirstBlockArg)
6103 Constraints.insert(Pos, "!");
6104 ++ArgNo;
6105 }
6106
6107 // Go to next constraint in string.
6108 Pos = Constraints.find(',', Pos);
6109 if (Pos == std::string::npos)
6110 break;
6111 ++Pos;
6112 }
6113
6114 Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
6115 IA->hasSideEffects(), IA->isAlignStack(),
6116 IA->getDialect(), IA->canThrow());
6117 }
6118 }
6119
6120 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
6121 OperandBundles);
6122 ResTypeID = getContainedTypeID(FTyID);
6123 OperandBundles.clear();
6124 InstructionList.push_back(I);
6125 cast<CallBrInst>(I)->setCallingConv(
6126 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6127 cast<CallBrInst>(I)->setAttributes(PAL);
6128 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
6129 I->deleteValue();
6130 return Err;
6131 }
6132 break;
6133 }
6134 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
6135 I = new UnreachableInst(Context);
6136 InstructionList.push_back(I);
6137 break;
6138 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
6139 if (Record.empty())
6140 return error("Invalid phi record");
6141 // The first record specifies the type.
6142 unsigned TyID = Record[0];
6143 Type *Ty = getTypeByID(TyID);
6144 if (!Ty)
6145 return error("Invalid phi record");
6146
6147 // Phi arguments are pairs of records of [value, basic block].
6148 // There is an optional final record for fast-math-flags if this phi has a
6149 // floating-point type.
6150 size_t NumArgs = (Record.size() - 1) / 2;
6151 PHINode *PN = PHINode::Create(Ty, NumArgs);
6152 if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
6153 PN->deleteValue();
6154 return error("Invalid phi record");
6155 }
6156 InstructionList.push_back(PN);
6157
6158 SmallDenseMap<BasicBlock *, Value *> Args;
6159 for (unsigned i = 0; i != NumArgs; i++) {
6160 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6161 if (!BB) {
6162 PN->deleteValue();
6163 return error("Invalid phi BB");
6164 }
6165
6166 // Phi nodes may contain the same predecessor multiple times, in which
6167 // case the incoming value must be identical. Directly reuse the already
6168 // seen value here, to avoid expanding a constant expression multiple
6169 // times.
6170 auto It = Args.find(BB);
6171 BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
6172 if (It != Args.end()) {
6173 // If this predecessor was also replaced with a constexpr basic
6174 // block, it must be de-duplicated.
6175 if (!EdgeBB) {
6176 PN->addIncoming(It->second, BB);
6177 }
6178 continue;
6179 }
6180
6181 // If there already is a block for this edge (from a different phi),
6182 // use it.
6183 if (!EdgeBB) {
6184 // Otherwise, use a temporary block (that we will discard if it
6185 // turns out to be unnecessary).
6186 if (!PhiConstExprBB)
6187 PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
6188 EdgeBB = PhiConstExprBB;
6189 }
6190
6191 // With the new function encoding, it is possible that operands have
6192 // negative IDs (for forward references). Use a signed VBR
6193 // representation to keep the encoding small.
6194 Value *V;
6195 if (UseRelativeIDs)
6196 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6197 else
6198 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6199 if (!V) {
6200 PN->deleteValue();
6201 PhiConstExprBB->eraseFromParent();
6202 return error("Invalid phi record");
6203 }
6204
6205 if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
6206 ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
6207 PhiConstExprBB = nullptr;
6208 }
6209 PN->addIncoming(V, BB);
6210 Args.insert({BB, V});
6211 }
6212 I = PN;
6213 ResTypeID = TyID;
6214
6215 // If there are an even number of records, the final record must be FMF.
6216 if (Record.size() % 2 == 0) {
6217 assert(isa<FPMathOperator>(I) && "Unexpected phi type");
6218 FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
6219 if (FMF.any())
6220 I->setFastMathFlags(FMF);
6221 }
6222
6223 break;
6224 }
6225
6228 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
6229 unsigned Idx = 0;
6230 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
6231 if (Record.size() < 3)
6232 return error("Invalid landingpad record");
6233 } else {
6235 if (Record.size() < 4)
6236 return error("Invalid landingpad record");
6237 }
6238 ResTypeID = Record[Idx++];
6239 Type *Ty = getTypeByID(ResTypeID);
6240 if (!Ty)
6241 return error("Invalid landingpad record");
6242 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
6243 Value *PersFn = nullptr;
6244 unsigned PersFnTypeID;
6245 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6246 nullptr))
6247 return error("Invalid landingpad record");
6248
6249 if (!F->hasPersonalityFn())
6250 F->setPersonalityFn(cast<Constant>(PersFn));
6251 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
6252 return error("Personality function mismatch");
6253 }
6254
6255 bool IsCleanup = !!Record[Idx++];
6256 unsigned NumClauses = Record[Idx++];
6257 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
6258 LP->setCleanup(IsCleanup);
6259 for (unsigned J = 0; J != NumClauses; ++J) {
6261 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
6262 Value *Val;
6263 unsigned ValTypeID;
6264
6265 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6266 nullptr)) {
6267 delete LP;
6268 return error("Invalid landingpad record");
6269 }
6270
6272 !isa<ArrayType>(Val->getType())) &&
6273 "Catch clause has a invalid type!");
6275 isa<ArrayType>(Val->getType())) &&
6276 "Filter clause has invalid type!");
6277 LP->addClause(cast<Constant>(Val));
6278 }
6279
6280 I = LP;
6281 InstructionList.push_back(I);
6282 break;
6283 }
6284
6285 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
6286 if (Record.size() != 4 && Record.size() != 5)
6287 return error("Invalid alloca record");
6288 using APV = AllocaPackedValues;
6289 const uint64_t Rec = Record[3];
6290 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
6291 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
6292 unsigned TyID = Record[0];
6293 Type *Ty = getTypeByID(TyID);
6295 TyID = getContainedTypeID(TyID);
6296 Ty = getTypeByID(TyID);
6297 if (!Ty)
6298 return error("Missing element type for old-style alloca");
6299 }
6300 unsigned OpTyID = Record[1];
6301 Type *OpTy = getTypeByID(OpTyID);
6302 Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6303 MaybeAlign Align;
6304 uint64_t AlignExp =
6306 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
6307 if (Error Err = parseAlignmentValue(AlignExp, Align)) {
6308 return Err;
6309 }
6310 if (!Ty || !Size)
6311 return error("Invalid alloca record");
6312
6313 const DataLayout &DL = TheModule->getDataLayout();
6314 unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
6315
6316 SmallPtrSet<Type *, 4> Visited;
6317 if (!Align && !Ty->isSized(&Visited))
6318 return error("alloca of unsized type");
6319 if (!Align)
6320 Align = DL.getPrefTypeAlign(Ty);
6321
6322 if (!Size->getType()->isIntegerTy())
6323 return error("alloca element count must have integer type");
6324
6325 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
6326 AI->setUsedWithInAlloca(InAlloca);
6327 AI->setSwiftError(SwiftError);
6328 I = AI;
6329 ResTypeID = getVirtualTypeID(AI->getType(), TyID);
6330 InstructionList.push_back(I);
6331 break;
6332 }
6333 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
6334 unsigned OpNum = 0;
6335 Value *Op;
6336 unsigned OpTypeID;
6337 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6338 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
6339 return error("Invalid load record");
6340
6341 if (!isa<PointerType>(Op->getType()))
6342 return error("Load operand is not a pointer type");
6343
6344 Type *Ty = nullptr;
6345 if (OpNum + 3 == Record.size()) {
6346 ResTypeID = Record[OpNum++];
6347 Ty = getTypeByID(ResTypeID);
6348 } else {
6349 ResTypeID = getContainedTypeID(OpTypeID);
6350 Ty = getTypeByID(ResTypeID);
6351 }
6352
6353 if (!Ty)
6354 return error("Missing load type");
6355
6356 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6357 return Err;
6358
6359 MaybeAlign Align;
6360 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6361 return Err;
6362 SmallPtrSet<Type *, 4> Visited;
6363 if (!Align && !Ty->isSized(&Visited))
6364 return error("load of unsized type");
6365 if (!Align)
6366 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6367 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
6368 InstructionList.push_back(I);
6369 break;
6370 }
6372 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
6373 unsigned OpNum = 0;
6374 Value *Op;
6375 unsigned OpTypeID;
6376 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6377 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
6378 return error("Invalid load atomic record");
6379
6380 if (!isa<PointerType>(Op->getType()))
6381 return error("Load operand is not a pointer type");
6382
6383 Type *Ty = nullptr;
6384 if (OpNum + 5 == Record.size()) {
6385 ResTypeID = Record[OpNum++];
6386 Ty = getTypeByID(ResTypeID);
6387 } else {
6388 ResTypeID = getContainedTypeID(OpTypeID);
6389 Ty = getTypeByID(ResTypeID);
6390 }
6391
6392 if (!Ty)
6393 return error("Missing atomic load type");
6394
6395 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6396 return Err;
6397
6398 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6399 if (Ordering == AtomicOrdering::NotAtomic ||
6400 Ordering == AtomicOrdering::Release ||
6401 Ordering == AtomicOrdering::AcquireRelease)
6402 return error("Invalid load atomic record");
6403 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6404 return error("Invalid load atomic record");
6405 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6406
6407 MaybeAlign Align;
6408 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6409 return Err;
6410 if (!Align)
6411 return error("Alignment missing from atomic load");
6412 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
6413 InstructionList.push_back(I);
6414 break;
6415 }
6417 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
6418 unsigned OpNum = 0;
6419 Value *Val, *Ptr;
6420 unsigned PtrTypeID, ValTypeID;
6421 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6422 return error("Invalid store record");
6423
6424 if (BitCode == bitc::FUNC_CODE_INST_STORE) {
6425 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6426 return error("Invalid store record");
6427 } else {
6428 ValTypeID = getContainedTypeID(PtrTypeID);
6429 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6430 ValTypeID, Val, CurBB))
6431 return error("Invalid store record");
6432 }
6433
6434 if (OpNum + 2 != Record.size())
6435 return error("Invalid store record");
6436
6437 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6438 return Err;
6439 MaybeAlign Align;
6440 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6441 return Err;
6442 SmallPtrSet<Type *, 4> Visited;
6443 if (!Align && !Val->getType()->isSized(&Visited))
6444 return error("store of unsized type");
6445 if (!Align)
6446 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
6447 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6448 InstructionList.push_back(I);
6449 break;
6450 }
6453 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
6454 unsigned OpNum = 0;
6455 Value *Val, *Ptr;
6456 unsigned PtrTypeID, ValTypeID;
6457 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6458 !isa<PointerType>(Ptr->getType()))
6459 return error("Invalid store atomic record");
6460 if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
6461 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6462 return error("Invalid store atomic record");
6463 } else {
6464 ValTypeID = getContainedTypeID(PtrTypeID);
6465 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6466 ValTypeID, Val, CurBB))
6467 return error("Invalid store atomic record");
6468 }
6469
6470 if (OpNum + 4 != Record.size())
6471 return error("Invalid store atomic record");
6472
6473 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6474 return Err;
6475 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6476 if (Ordering == AtomicOrdering::NotAtomic ||
6477 Ordering == AtomicOrdering::Acquire ||
6478 Ordering == AtomicOrdering::AcquireRelease)
6479 return error("Invalid store atomic record");
6480 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6481 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6482 return error("Invalid store atomic record");
6483
6484 MaybeAlign Align;
6485 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6486 return Err;
6487 if (!Align)
6488 return error("Alignment missing from atomic store");
6489 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6490 InstructionList.push_back(I);
6491 break;
6492 }
6494 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, syncscope,
6495 // failure_ordering?, weak?]
6496 const size_t NumRecords = Record.size();
6497 unsigned OpNum = 0;
6498 Value *Ptr = nullptr;
6499 unsigned PtrTypeID;
6500 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6501 return error("Invalid cmpxchg record");
6502
6503 if (!isa<PointerType>(Ptr->getType()))
6504 return error("Cmpxchg operand is not a pointer type");
6505
6506 Value *Cmp = nullptr;
6507 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6508 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6509 CmpTypeID, Cmp, CurBB))
6510 return error("Invalid cmpxchg record");
6511
6512 Value *New = nullptr;
6513 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
6514 New, CurBB) ||
6515 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6516 return error("Invalid cmpxchg record");
6517
6518 const AtomicOrdering SuccessOrdering =
6519 getDecodedOrdering(Record[OpNum + 1]);
6520 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6521 SuccessOrdering == AtomicOrdering::Unordered)
6522 return error("Invalid cmpxchg record");
6523
6524 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6525
6526 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6527 return Err;
6528
6529 const AtomicOrdering FailureOrdering =
6530 NumRecords < 7
6532 : getDecodedOrdering(Record[OpNum + 3]);
6533
6534 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6535 FailureOrdering == AtomicOrdering::Unordered)
6536 return error("Invalid cmpxchg record");
6537
6538 const Align Alignment(
6539 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6540
6541 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6542 FailureOrdering, SSID);
6543 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
6544
6545 if (NumRecords < 8) {
6546 // Before weak cmpxchgs existed, the instruction simply returned the
6547 // value loaded from memory, so bitcode files from that era will be
6548 // expecting the first component of a modern cmpxchg.
6549 I->insertInto(CurBB, CurBB->end());
6551 ResTypeID = CmpTypeID;
6552 } else {
6553 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
6554 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6555 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6556 }
6557
6558 InstructionList.push_back(I);
6559 break;
6560 }
6562 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, syncscope,
6563 // failure_ordering, weak, align?]
6564 const size_t NumRecords = Record.size();
6565 unsigned OpNum = 0;
6566 Value *Ptr = nullptr;
6567 unsigned PtrTypeID;
6568 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6569 return error("Invalid cmpxchg record");
6570
6571 if (!isa<PointerType>(Ptr->getType()))
6572 return error("Cmpxchg operand is not a pointer type");
6573
6574 Value *Cmp = nullptr;
6575 unsigned CmpTypeID;
6576 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6577 return error("Invalid cmpxchg record");
6578
6579 Value *Val = nullptr;
6580 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
6581 CurBB))
6582 return error("Invalid cmpxchg record");
6583
6584 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6585 return error("Invalid cmpxchg record");
6586
6587 const bool IsVol = Record[OpNum];
6588
6589 const AtomicOrdering SuccessOrdering =
6590 getDecodedOrdering(Record[OpNum + 1]);
6591 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6592 return error("Invalid cmpxchg success ordering");
6593
6594 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6595
6596 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6597 return Err;
6598
6599 const AtomicOrdering FailureOrdering =
6600 getDecodedOrdering(Record[OpNum + 3]);
6601 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6602 return error("Invalid cmpxchg failure ordering");
6603
6604 const bool IsWeak = Record[OpNum + 4];
6605
6606 MaybeAlign Alignment;
6607
6608 if (NumRecords == (OpNum + 6)) {
6609 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6610 return Err;
6611 }
6612 if (!Alignment)
6613 Alignment =
6614 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6615
6616 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6617 FailureOrdering, SSID);
6618 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6619 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6620
6621 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6622 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6623
6624 InstructionList.push_back(I);
6625 break;
6626 }
6629 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6630 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6631 const size_t NumRecords = Record.size();
6632 unsigned OpNum = 0;
6633
6634 Value *Ptr = nullptr;
6635 unsigned PtrTypeID;
6636 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6637 return error("Invalid atomicrmw record");
6638
6639 if (!isa<PointerType>(Ptr->getType()))
6640 return error("Invalid atomicrmw record");
6641
6642 Value *Val = nullptr;
6643 unsigned ValTypeID = InvalidTypeID;
6644 if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
6645 ValTypeID = getContainedTypeID(PtrTypeID);
6646 if (popValue(Record, OpNum, NextValueNo,
6647 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6648 return error("Invalid atomicrmw record");
6649 } else {
6650 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6651 return error("Invalid atomicrmw record");
6652 }
6653
6654 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6655 return error("Invalid atomicrmw record");
6656
6657 bool IsElementwise = false;
6659 getDecodedRMWOperation(Record[OpNum], IsElementwise);
6662 return error("Invalid atomicrmw record");
6663
6664 const bool IsVol = Record[OpNum + 1];
6665
6666 const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6667 if (Ordering == AtomicOrdering::NotAtomic ||
6668 Ordering == AtomicOrdering::Unordered)
6669 return error("Invalid atomicrmw record");
6670
6671 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6672
6673 MaybeAlign Alignment;
6674
6675 if (NumRecords == (OpNum + 5)) {
6676 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6677 return Err;
6678 }
6679
6680 if (!Alignment)
6681 Alignment =
6682 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6683
6684 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID,
6685 IsElementwise);
6686 ResTypeID = ValTypeID;
6687 cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6688
6689 InstructionList.push_back(I);
6690 break;
6691 }
6692 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
6693 if (2 != Record.size())
6694 return error("Invalid fence record");
6696 if (Ordering == AtomicOrdering::NotAtomic ||
6697 Ordering == AtomicOrdering::Unordered ||
6698 Ordering == AtomicOrdering::Monotonic)
6699 return error("Invalid fence record");
6700 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
6701 I = new FenceInst(Context, Ordering, SSID);
6702 InstructionList.push_back(I);
6703 break;
6704 }
6706 // DbgLabelRecords are placed after the Instructions that they are
6707 // attached to.
6708 SeenDebugRecord = true;
6709 Instruction *Inst = getLastInstruction();
6710 if (!Inst)
6711 return error("Invalid dbg record: missing instruction");
6712 DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[0]));
6713 DILabel *Label = cast<DILabel>(getFnMetadataByID(Record[1]));
6714 Inst->getParent()->insertDbgRecordBefore(
6715 new DbgLabelRecord(Label, DebugLoc(DIL)), Inst->getIterator());
6716 continue; // This isn't an instruction.
6717 }
6723 // DbgVariableRecords are placed after the Instructions that they are
6724 // attached to.
6725 SeenDebugRecord = true;
6726 Instruction *Inst = getLastInstruction();
6727 if (!Inst)
6728 return error("Invalid dbg record: missing instruction");
6729
6730 // First 3 fields are common to all kinds:
6731 // DILocation, DILocalVariable, DIExpression
6732 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
6733 // ..., LocationMetadata
6734 // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
6735 // ..., Value
6736 // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
6737 // ..., LocationMetadata
6738 // dbg_declare_value (FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE)
6739 // ..., LocationMetadata
6740 // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
6741 // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
6742 unsigned Slot = 0;
6743 // Common fields (0-2).
6744 DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[Slot++]));
6745 DILocalVariable *Var =
6746 cast<DILocalVariable>(getFnMetadataByID(Record[Slot++]));
6747 DIExpression *Expr =
6748 cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6749
6750 // Union field (3: LocationMetadata | Value).
6751 Metadata *RawLocation = nullptr;
6753 Value *V = nullptr;
6754 unsigned TyID = 0;
6755 // We never expect to see a fwd reference value here because
6756 // use-before-defs are encoded with the standard non-abbrev record
6757 // type (they'd require encoding the type too, and they're rare). As a
6758 // result, getValueTypePair only ever increments Slot by one here (once
6759 // for the value, never twice for value and type).
6760 unsigned SlotBefore = Slot;
6761 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6762 return error("Invalid dbg record: invalid value");
6763 (void)SlotBefore;
6764 assert((SlotBefore == Slot - 1) && "unexpected fwd ref");
6765 RawLocation = ValueAsMetadata::get(V);
6766 } else {
6767 RawLocation = getFnMetadataByID(Record[Slot++]);
6768 }
6769
6770 DbgVariableRecord *DVR = nullptr;
6771 switch (BitCode) {
6774 DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6775 DbgVariableRecord::LocationType::Value);
6776 break;
6778 DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6779 DbgVariableRecord::LocationType::Declare);
6780 break;
6782 DVR = new DbgVariableRecord(
6783 RawLocation, Var, Expr, DIL,
6784 DbgVariableRecord::LocationType::DeclareValue);
6785 break;
6787 DIAssignID *ID = cast<DIAssignID>(getFnMetadataByID(Record[Slot++]));
6788 DIExpression *AddrExpr =
6789 cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6790 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6791 DVR = new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
6792 DIL);
6793 break;
6794 }
6795 default:
6796 llvm_unreachable("Unknown DbgVariableRecord bitcode");
6797 }
6798 Inst->getParent()->insertDbgRecordBefore(DVR, Inst->getIterator());
6799 continue; // This isn't an instruction.
6800 }
6802 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6803 if (Record.size() < 3)
6804 return error("Invalid call record");
6805
6806 unsigned OpNum = 0;
6807 AttributeList PAL = getAttributes(Record[OpNum++]);
6808 unsigned CCInfo = Record[OpNum++];
6809
6810 FastMathFlags FMF;
6811 if ((CCInfo >> bitc::CALL_FMF) & 1) {
6812 FMF = getDecodedFastMathFlags(Record[OpNum++]);
6813 if (!FMF.any())
6814 return error("Fast math flags indicator set for call with no FMF");
6815 }
6816
6817 unsigned FTyID = InvalidTypeID;
6818 FunctionType *FTy = nullptr;
6819 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
6820 FTyID = Record[OpNum++];
6821 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6822 if (!FTy)
6823 return error("Explicit call type is not a function type");
6824 }
6825
6826 Value *Callee;
6827 unsigned CalleeTypeID;
6828 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6829 CurBB))
6830 return error("Invalid call record");
6831
6832 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
6833 if (!OpTy)
6834 return error("Callee is not a pointer type");
6835 if (!FTy) {
6836 FTyID = getContainedTypeID(CalleeTypeID);
6837 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6838 if (!FTy)
6839 return error("Callee is not of pointer to function type");
6840 }
6841 if (Record.size() < FTy->getNumParams() + OpNum)
6842 return error("Insufficient operands to call");
6843
6844 SmallVector<Value*, 16> Args;
6845 SmallVector<unsigned, 16> ArgTyIDs;
6846 // Read the fixed params.
6847 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6848 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6849 if (FTy->getParamType(i)->isLabelTy())
6850 Args.push_back(getBasicBlock(Record[OpNum]));
6851 else
6852 Args.push_back(getValue(Record, OpNum, NextValueNo,
6853 FTy->getParamType(i), ArgTyID, CurBB));
6854 ArgTyIDs.push_back(ArgTyID);
6855 if (!Args.back())
6856 return error("Invalid call record");
6857 }
6858
6859 // Read type/value pairs for varargs params.
6860 if (!FTy->isVarArg()) {
6861 if (OpNum != Record.size())
6862 return error("Invalid call record");
6863 } else {
6864 while (OpNum != Record.size()) {
6865 Value *Op;
6866 unsigned OpTypeID;
6867 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6868 return error("Invalid call record");
6869 Args.push_back(Op);
6870 ArgTyIDs.push_back(OpTypeID);
6871 }
6872 }
6873
6874 // Upgrade the bundles if needed.
6875 if (!OperandBundles.empty())
6876 UpgradeOperandBundles(OperandBundles);
6877
6878 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
6879 ResTypeID = getContainedTypeID(FTyID);
6880 OperandBundles.clear();
6881 InstructionList.push_back(I);
6882 cast<CallInst>(I)->setCallingConv(
6883 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6885 if (CCInfo & (1 << bitc::CALL_TAIL))
6886 TCK = CallInst::TCK_Tail;
6887 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
6889 if (CCInfo & (1 << bitc::CALL_NOTAIL))
6891 cast<CallInst>(I)->setTailCallKind(TCK);
6892 cast<CallInst>(I)->setAttributes(PAL);
6894 SeenDebugIntrinsic = true;
6895 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
6896 I->deleteValue();
6897 return Err;
6898 }
6899 if (FMF.any()) {
6900 if (!isa<FPMathOperator>(I))
6901 return error("Fast-math-flags specified for call without "
6902 "floating-point scalar or vector return type");
6903 I->setFastMathFlags(FMF);
6904 }
6905 break;
6906 }
6907 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
6908 if (Record.size() < 3)
6909 return error("Invalid va_arg record");
6910 unsigned OpTyID = Record[0];
6911 Type *OpTy = getTypeByID(OpTyID);
6912 Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6913 ResTypeID = Record[2];
6914 Type *ResTy = getTypeByID(ResTypeID);
6915 if (!OpTy || !Op || !ResTy)
6916 return error("Invalid va_arg record");
6917 I = new VAArgInst(Op, ResTy);
6918 InstructionList.push_back(I);
6919 break;
6920 }
6921
6923 // A call or an invoke can be optionally prefixed with some variable
6924 // number of operand bundle blocks. These blocks are read into
6925 // OperandBundles and consumed at the next call or invoke instruction.
6926
6927 if (Record.empty() || Record[0] >= BundleTags.size())
6928 return error("Invalid operand bundle record");
6929
6930 std::vector<Value *> Inputs;
6931
6932 unsigned OpNum = 1;
6933 while (OpNum != Record.size()) {
6934 Value *Op;
6935 if (getValueOrMetadata(Record, OpNum, NextValueNo, Op, CurBB))
6936 return error("Invalid operand bundle record");
6937 Inputs.push_back(Op);
6938 }
6939
6940 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6941 continue;
6942 }
6943
6944 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6945 unsigned OpNum = 0;
6946 Value *Op = nullptr;
6947 unsigned OpTypeID;
6948 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6949 return error("Invalid freeze record");
6950 if (OpNum != Record.size())
6951 return error("Invalid freeze record");
6952
6953 I = new FreezeInst(Op);
6954 ResTypeID = OpTypeID;
6955 InstructionList.push_back(I);
6956 break;
6957 }
6958 }
6959
6960 // Add instruction to end of current BB. If there is no current BB, reject
6961 // this file.
6962 if (!CurBB) {
6963 I->deleteValue();
6964 return error("Invalid instruction with no BB");
6965 }
6966 if (!OperandBundles.empty()) {
6967 I->deleteValue();
6968 return error("Operand bundles found with no consumer");
6969 }
6970 I->insertInto(CurBB, CurBB->end());
6971
6972 // If this was a terminator instruction, move to the next block.
6973 if (I->isTerminator()) {
6974 ++CurBBNo;
6975 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
6976 }
6977
6978 // Non-void values get registered in the value table for future use.
6979 if (!I->getType()->isVoidTy()) {
6980 assert(I->getType() == getTypeByID(ResTypeID) &&
6981 "Incorrect result type ID");
6982 if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
6983 return Err;
6984 }
6985 }
6986
6987OutOfRecordLoop:
6988
6989 if (!OperandBundles.empty())
6990 return error("Operand bundles found with no consumer");
6991
6992 // Check the function list for unresolved values.
6993 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
6994 if (!A->getParent()) {
6995 // We found at least one unresolved value. Nuke them all to avoid leaks.
6996 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
6997 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6998 A->replaceAllUsesWith(PoisonValue::get(A->getType()));
6999 delete A;
7000 }
7001 }
7002 return error("Never resolved value found in function");
7003 }
7004 }
7005
7006 // Unexpected unresolved metadata about to be dropped.
7007 if (MDLoader->hasFwdRefs())
7008 return error("Invalid function metadata: outgoing forward refs");
7009
7010 if (PhiConstExprBB)
7011 PhiConstExprBB->eraseFromParent();
7012
7013 for (const auto &Pair : ConstExprEdgeBBs) {
7014 BasicBlock *From = Pair.first.first;
7015 BasicBlock *To = Pair.first.second;
7016 BasicBlock *EdgeBB = Pair.second;
7017 UncondBrInst::Create(To, EdgeBB);
7018 From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
7019 To->replacePhiUsesWith(From, EdgeBB);
7020 EdgeBB->moveBefore(To);
7021 }
7022
7023 // Trim the value list down to the size it was before we parsed this function.
7024 ValueList.shrinkTo(ModuleValueListSize);
7025 MDLoader->shrinkTo(ModuleMDLoaderSize);
7026 std::vector<BasicBlock*>().swap(FunctionBBs);
7027 return Error::success();
7028}
7029
7030/// Find the function body in the bitcode stream
7031Error BitcodeReader::findFunctionInStream(
7032 Function *F,
7033 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7034 while (DeferredFunctionInfoIterator->second == 0) {
7035 // This is the fallback handling for the old format bitcode that
7036 // didn't contain the function index in the VST, or when we have
7037 // an anonymous function which would not have a VST entry.
7038 // Assert that we have one of those two cases.
7039 assert(VSTOffset == 0 || !F->hasName());
7040 // Parse the next body in the stream and set its position in the
7041 // DeferredFunctionInfo map.
7042 if (Error Err = rememberAndSkipFunctionBodies())
7043 return Err;
7044 }
7045 return Error::success();
7046}
7047
7048SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
7049 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
7050 return SyncScope::ID(Val);
7051 if (Val >= SSIDs.size())
7052 return SyncScope::System; // Map unknown synchronization scopes to system.
7053 return SSIDs[Val];
7054}
7055
7056//===----------------------------------------------------------------------===//
7057// GVMaterializer implementation
7058//===----------------------------------------------------------------------===//
7059
7060Error BitcodeReader::materialize(GlobalValue *GV) {
7062 // If it's not a function or is already material, ignore the request.
7063 if (!F || !F->isMaterializable())
7064 return Error::success();
7065
7066 auto DFII = DeferredFunctionInfo.find(F);
7067 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
7068 // If its position is recorded as 0, its body is somewhere in the stream
7069 // but we haven't seen it yet.
7070 if (DFII->second == 0)
7071 if (Error Err = findFunctionInStream(F, DFII))
7072 return Err;
7073
7074 // Materialize metadata before parsing any function bodies.
7075 if (Error Err = materializeMetadata())
7076 return Err;
7077
7078 // Move the bit stream to the saved position of the deferred function body.
7079 if (Error JumpFailed = Stream.JumpToBit(DFII->second))
7080 return JumpFailed;
7081
7082 if (Error Err = parseFunctionBody(F))
7083 return Err;
7084 F->setIsMaterializable(false);
7085
7086 // All parsed Functions should load into the debug info format dictated by the
7087 // Module.
7088 if (SeenDebugIntrinsic && SeenDebugRecord)
7089 return error("Mixed debug intrinsics and debug records in bitcode module!");
7090
7091 if (StripDebugInfo)
7092 stripDebugInfo(*F);
7093
7094 // Finish fn->subprogram upgrade for materialized functions.
7095 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
7096 F->setSubprogram(SP);
7097
7098 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
7099 if (!MDLoader->isStrippingTBAA()) {
7100 for (auto &I : instructions(F)) {
7101 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
7102 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(&I, TBAA))
7103 continue;
7104 MDLoader->setStripTBAA(true);
7105 stripTBAA(F->getParent());
7106 }
7107 }
7108
7109 for (auto &I : make_early_inc_range(instructions(F))) {
7110 // "Upgrade" older incorrect branch weights by dropping them.
7111 if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
7112 if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
7113 MDString *MDS = cast<MDString>(MD->getOperand(0));
7114 StringRef ProfName = MDS->getString();
7115 // Check consistency of !prof branch_weights metadata.
7116 if (ProfName != MDProfLabels::BranchWeights)
7117 continue;
7118 unsigned ExpectedNumOperands = 0;
7119 if (isa<CondBrInst>(&I))
7120 ExpectedNumOperands = 2;
7121 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
7122 ExpectedNumOperands = SI->getNumSuccessors();
7123 else if (isa<CallInst>(&I))
7124 ExpectedNumOperands = 1;
7125 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
7126 ExpectedNumOperands = IBI->getNumDestinations();
7127 else if (isa<SelectInst>(&I))
7128 ExpectedNumOperands = 2;
7129 else
7130 continue; // ignore and continue.
7131
7132 unsigned Offset = getBranchWeightOffset(MD);
7133
7134 // If branch weight doesn't match, just strip branch weight.
7135 if (MD->getNumOperands() != Offset + ExpectedNumOperands)
7136 I.setMetadata(LLVMContext::MD_prof, nullptr);
7137 }
7138 }
7139
7140 if (auto *CI = dyn_cast<CallBase>(&I)) {
7141 // Remove incompatible attributes on function calls.
7142 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7143 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7144
7145 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7146 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7147 CI->getArgOperand(ArgNo)->getType(),
7148 CI->getParamAttributes(ArgNo)));
7149
7150 // Upgrade intrinsics.
7151 if (Function *OldFn = CI->getCalledFunction()) {
7152 auto It = UpgradedIntrinsics.find(OldFn);
7153 if (It != UpgradedIntrinsics.end())
7154 UpgradeIntrinsicCall(CI, It->second);
7155 }
7156 } else if (auto *BC = dyn_cast<BitCastInst>(&I);
7157 BC && BC->getSrcTy() == BC->getDestTy() &&
7158 isa_and_nonnull<ReturnInst>(BC->getNextNode())) {
7159 // Old bitcode allowed an optional bitcast between a musttail call and its
7160 // return. Under opaque pointers that cast is always a no-op, and the
7161 // verifier no longer accepts it, so drop it.
7162 if (auto *CI = dyn_cast<CallInst>(BC->getOperand(0));
7163 CI && CI->isMustTailCall() && CI->getNextNode() == BC) {
7164 BC->replaceAllUsesWith(CI);
7165 BC->eraseFromParent();
7166 }
7167 }
7168 }
7169
7170 // Look for functions that rely on old function attribute behavior.
7172
7173 // Bring in any functions that this function forward-referenced via
7174 // blockaddresses.
7175 return materializeForwardReferencedFunctions();
7176}
7177
7178Error BitcodeReader::materializeModule() {
7179 if (Error Err = materializeMetadata())
7180 return Err;
7181
7182 // Promise to materialize all forward references.
7183 WillMaterializeAllForwardRefs = true;
7184
7185 // Iterate over the module, deserializing any functions that are still on
7186 // disk.
7187 for (Function &F : *TheModule) {
7188 if (Error Err = materialize(&F))
7189 return Err;
7190 }
7191 // At this point, if there are any function bodies, parse the rest of
7192 // the bits in the module past the last function block we have recorded
7193 // through either lazy scanning or the VST.
7194 if (LastFunctionBlockBit || NextUnreadBit)
7195 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
7196 ? LastFunctionBlockBit
7197 : NextUnreadBit))
7198 return Err;
7199
7200 // Check that all block address forward references got resolved (as we
7201 // promised above).
7202 if (!BasicBlockFwdRefs.empty())
7203 return error("Never resolved function from blockaddress");
7204
7205 // Upgrade any intrinsic calls that slipped through (should not happen!) and
7206 // delete the old functions to clean up. We can't do this unless the entire
7207 // module is materialized because there could always be another function body
7208 // with calls to the old function.
7209 for (auto &I : UpgradedIntrinsics) {
7210 for (auto *U : I.first->users()) {
7211 if (CallInst *CI = dyn_cast<CallInst>(U))
7212 UpgradeIntrinsicCall(CI, I.second);
7213 }
7214 if (I.first != I.second) {
7215 if (!I.first->use_empty())
7216 I.first->replaceAllUsesWith(I.second);
7217 I.first->eraseFromParent();
7218 }
7219 }
7220 UpgradedIntrinsics.clear();
7221
7222 UpgradeDebugInfo(*TheModule);
7223
7224 UpgradeModuleFlags(*TheModule);
7225
7226 UpgradeNVVMAnnotations(*TheModule);
7227
7228 UpgradeARCRuntime(*TheModule);
7229
7230 copyModuleAttrToFunctions(*TheModule);
7231
7232 return Error::success();
7233}
7234
7235std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
7236 return IdentifiedStructTypes;
7237}
7238
7239ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7240 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7241 StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
7242 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
7243 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7244
7245void ModuleSummaryIndexBitcodeReader::addThisModule() {
7246 TheIndex.addModule(ModulePath);
7247}
7248
7250ModuleSummaryIndexBitcodeReader::getThisModule() {
7251 return TheIndex.getModule(ModulePath);
7252}
7253
7254template <bool AllowNullValueInfo>
7255std::pair<ValueInfo, GlobalValue::GUID>
7256ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
7257 auto VGI = ValueIdToValueInfoMap[ValueId];
7258 // We can have a null value info in distributed ThinLTO index files:
7259 // - For memprof callsite info records when the callee function summary is not
7260 // included in the index.
7261 // - For alias summary when its aliasee summary is not included in the index.
7262 // The bitcode writer records 0 in these cases,
7263 // and the caller of this helper will set AllowNullValueInfo to true.
7264 assert(AllowNullValueInfo || std::get<0>(VGI));
7265 return VGI;
7266}
7267
7268void ModuleSummaryIndexBitcodeReader::setValueGUID(
7269 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
7270 StringRef SourceFileName) {
7271 std::string GlobalId =
7273 auto ValueGUID = GlobalValue::getGUIDAssumingExternalLinkage(GlobalId);
7274 auto OriginalNameID = ValueGUID;
7278 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
7279 << ValueName << "\n";
7280
7281 // UseStrtab is false for legacy summary formats and value names are
7282 // created on stack. In that case we save the name in a string saver in
7283 // the index so that the value name can be recorded.
7284 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7285 TheIndex.getOrInsertValueInfo(
7286 ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
7287 OriginalNameID);
7288}
7289
7290// Specialized value symbol table parser used when reading module index
7291// blocks where we don't actually create global values. The parsed information
7292// is saved in the bitcode reader for use when later parsing summaries.
7293Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7294 uint64_t Offset,
7295 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7296 // With a strtab the VST is not required to parse the summary.
7297 if (UseStrtab)
7298 return Error::success();
7299
7300 assert(Offset > 0 && "Expected non-zero VST offset");
7301 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
7302 if (!MaybeCurrentBit)
7303 return MaybeCurrentBit.takeError();
7304 uint64_t CurrentBit = MaybeCurrentBit.get();
7305
7307 return Err;
7308
7309 SmallVector<uint64_t, 64> Record;
7310
7311 // Read all the records for this value table.
7312 SmallString<128> ValueName;
7313
7314 while (true) {
7315 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7316 if (!MaybeEntry)
7317 return MaybeEntry.takeError();
7318 BitstreamEntry Entry = MaybeEntry.get();
7319
7320 switch (Entry.Kind) {
7321 case BitstreamEntry::SubBlock: // Handled for us already.
7323 return error("Malformed block");
7325 // Done parsing VST, jump back to wherever we came from.
7326 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
7327 return JumpFailed;
7328 return Error::success();
7330 // The interesting case.
7331 break;
7332 }
7333
7334 // Read a record.
7335 Record.clear();
7336 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7337 if (!MaybeRecord)
7338 return MaybeRecord.takeError();
7339 switch (MaybeRecord.get()) {
7340 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
7341 break;
7342 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
7343 if (convertToString(Record, 1, ValueName))
7344 return error("Invalid vst_code_entry record");
7345 unsigned ValueID = Record[0];
7346 assert(!SourceFileName.empty());
7347 auto VLI = ValueIdToLinkageMap.find(ValueID);
7348 assert(VLI != ValueIdToLinkageMap.end() &&
7349 "No linkage found for VST entry?");
7350 auto Linkage = VLI->second;
7351 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7352 ValueName.clear();
7353 break;
7354 }
7356 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
7357 if (convertToString(Record, 2, ValueName))
7358 return error("Invalid vst_code_fnentry record");
7359 unsigned ValueID = Record[0];
7360 assert(!SourceFileName.empty());
7361 auto VLI = ValueIdToLinkageMap.find(ValueID);
7362 assert(VLI != ValueIdToLinkageMap.end() &&
7363 "No linkage found for VST entry?");
7364 auto Linkage = VLI->second;
7365 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7366 ValueName.clear();
7367 break;
7368 }
7370 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
7371 unsigned ValueID = Record[0];
7372 GlobalValue::GUID RefGUID = Record[1];
7373 // The "original name", which is the second value of the pair will be
7374 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
7375 ValueIdToValueInfoMap[ValueID] =
7376 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
7377 break;
7378 }
7379 }
7380 }
7381}
7382
7383// Parse just the blocks needed for building the index out of the module.
7384// At the end of this routine the module Index is populated with a map
7385// from global value id to GlobalValueSummary objects.
7386Error ModuleSummaryIndexBitcodeReader::parseModule() {
7387 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
7388 return Err;
7389
7390 SmallVector<uint64_t, 64> Record;
7391 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7392 unsigned ValueId = 0;
7393
7394 // Read the index for this module.
7395 while (true) {
7396 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7397 if (!MaybeEntry)
7398 return MaybeEntry.takeError();
7399 llvm::BitstreamEntry Entry = MaybeEntry.get();
7400
7401 switch (Entry.Kind) {
7403 return error("Malformed block");
7405 return Error::success();
7406
7408 switch (Entry.ID) {
7409 default: // Skip unknown content.
7410 if (Error Err = Stream.SkipBlock())
7411 return Err;
7412 break;
7414 // Need to parse these to get abbrev ids (e.g. for VST)
7415 if (Error Err = readBlockInfo())
7416 return Err;
7417 break;
7419 // Should have been parsed earlier via VSTOffset, unless there
7420 // is no summary section.
7421 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7422 !SeenGlobalValSummary) &&
7423 "Expected early VST parse via VSTOffset record");
7424 if (Error Err = Stream.SkipBlock())
7425 return Err;
7426 break;
7429 // Add the module if it is a per-module index (has a source file name).
7430 if (!SourceFileName.empty())
7431 addThisModule();
7432 assert(!SeenValueSymbolTable &&
7433 "Already read VST when parsing summary block?");
7434 // We might not have a VST if there were no values in the
7435 // summary. An empty summary block generated when we are
7436 // performing ThinLTO compiles so we don't later invoke
7437 // the regular LTO process on them.
7438 if (VSTOffset > 0) {
7439 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7440 return Err;
7441 SeenValueSymbolTable = true;
7442 }
7443 SeenGlobalValSummary = true;
7444 if (Error Err = parseEntireSummary(Entry.ID))
7445 return Err;
7446 break;
7448 if (Error Err = parseModuleStringTable())
7449 return Err;
7450 break;
7451 }
7452 continue;
7453
7455 Record.clear();
7456 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7457 if (!MaybeBitCode)
7458 return MaybeBitCode.takeError();
7459 switch (MaybeBitCode.get()) {
7460 default:
7461 break; // Default behavior, ignore unknown content.
7463 if (Error Err = parseVersionRecord(Record).takeError())
7464 return Err;
7465 break;
7466 }
7467 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
7469 SmallString<128> ValueName;
7470 if (convertToString(Record, 0, ValueName))
7471 return error("Invalid source filename record");
7472 SourceFileName = ValueName.c_str();
7473 break;
7474 }
7475 /// MODULE_CODE_HASH: [5*i32]
7477 if (Record.size() != 5)
7478 return error("Invalid hash length " + Twine(Record.size()).str());
7479 auto &Hash = getThisModule()->second;
7480 int Pos = 0;
7481 for (auto &Val : Record) {
7482 assert(!(Val >> 32) && "Unexpected high bits set");
7483 Hash[Pos++] = Val;
7484 }
7485 break;
7486 }
7487 /// MODULE_CODE_VSTOFFSET: [offset]
7489 if (Record.empty())
7490 return error("Invalid vstoffset record");
7491 // Note that we subtract 1 here because the offset is relative to one
7492 // word before the start of the identification or module block, which
7493 // was historically always the start of the regular bitcode header.
7494 VSTOffset = Record[0] - 1;
7495 break;
7496 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
7497 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
7498 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
7499 // v2: [strtab offset, strtab size, v1]
7503 StringRef Name;
7504 ArrayRef<uint64_t> GVRecord;
7505 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7506 if (GVRecord.size() <= 3)
7507 return error("Invalid global record");
7508 uint64_t RawLinkage = GVRecord[3];
7510 if (!UseStrtab) {
7511 ValueIdToLinkageMap[ValueId++] = Linkage;
7512 break;
7513 }
7514
7515 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
7516 break;
7517 }
7518 }
7519 }
7520 continue;
7521 }
7522 }
7523}
7524
7526ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7528 Ret.reserve(Record.size());
7529 for (uint64_t RefValueId : Record)
7530 Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7531 return Ret;
7532}
7533
7535ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7536 bool IsOldProfileFormat,
7537 bool HasProfile, bool HasRelBF) {
7539 // In the case of new profile formats, there are two Record entries per
7540 // Edge. Otherwise, conservatively reserve up to Record.size.
7541 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7542 Ret.reserve(Record.size() / 2);
7543 else
7544 Ret.reserve(Record.size());
7545
7546 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
7547 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7548 bool HasTailCall = false;
7549 uint64_t RelBF = 0;
7550 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7551 if (IsOldProfileFormat) {
7552 I += 1; // Skip old callsitecount field
7553 if (HasProfile)
7554 I += 1; // Skip old profilecount field
7555 } else if (HasProfile)
7556 std::tie(Hotness, HasTailCall) =
7558 // Deprecated, but still needed to read old bitcode files.
7559 else if (HasRelBF)
7560 getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
7561 Ret.push_back(
7562 FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, HasTailCall)});
7563 }
7564 return Ret;
7565}
7566
7567static void
7570 uint64_t ArgNum = Record[Slot++];
7572 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
7573 Slot += ArgNum;
7574
7575 B.TheKind =
7577 B.Info = Record[Slot++];
7578 B.Byte = Record[Slot++];
7579 B.Bit = Record[Slot++];
7580}
7581
7583 StringRef Strtab, size_t &Slot,
7584 TypeIdSummary &TypeId) {
7585 uint64_t Id = Record[Slot++];
7586 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
7587
7588 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
7589 Wpd.SingleImplName = {Strtab.data() + Record[Slot],
7590 static_cast<size_t>(Record[Slot + 1])};
7591 Slot += 2;
7592
7593 uint64_t ResByArgNum = Record[Slot++];
7594 for (uint64_t I = 0; I != ResByArgNum; ++I)
7596}
7597
7599 StringRef Strtab,
7600 ModuleSummaryIndex &TheIndex) {
7601 size_t Slot = 0;
7602 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
7603 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
7604 Slot += 2;
7605
7606 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
7607 TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
7608 TypeId.TTRes.AlignLog2 = Record[Slot++];
7609 TypeId.TTRes.SizeM1 = Record[Slot++];
7610 TypeId.TTRes.BitMask = Record[Slot++];
7611 TypeId.TTRes.InlineBits = Record[Slot++];
7612
7613 while (Slot < Record.size())
7614 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
7615}
7616
7617std::vector<FunctionSummary::ParamAccess>
7618ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7619 auto ReadRange = [&]() {
7621 BitcodeReader::decodeSignRotatedValue(Record.consume_front()));
7623 BitcodeReader::decodeSignRotatedValue(Record.consume_front()));
7624 ConstantRange Range{Lower, Upper};
7627 return Range;
7628 };
7629
7630 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7631 while (!Record.empty()) {
7632 PendingParamAccesses.emplace_back();
7633 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7634 ParamAccess.ParamNo = Record.consume_front();
7635 ParamAccess.Use = ReadRange();
7636 ParamAccess.Calls.resize(Record.consume_front());
7637 for (auto &Call : ParamAccess.Calls) {
7638 Call.ParamNo = Record.consume_front();
7639 Call.Callee =
7640 std::get<0>(getValueInfoFromValueId(Record.consume_front()));
7641 Call.Offsets = ReadRange();
7642 }
7643 }
7644 return PendingParamAccesses;
7645}
7646
7647void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7648 ArrayRef<uint64_t> Record, size_t &Slot,
7650 uint64_t Offset = Record[Slot++];
7651 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7652 TypeId.push_back({Offset, Callee});
7653}
7654
7655void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7656 ArrayRef<uint64_t> Record) {
7657 size_t Slot = 0;
7660 {Strtab.data() + Record[Slot],
7661 static_cast<size_t>(Record[Slot + 1])});
7662 Slot += 2;
7663
7664 while (Slot < Record.size())
7665 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7666}
7667
7668SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7669 ArrayRef<uint64_t> Record, unsigned &I) {
7670 SmallVector<unsigned> StackIdList;
7671 // For backwards compatibility with old format before radix tree was
7672 // used, simply see if we found a radix tree array record (and thus if
7673 // the RadixArray is non-empty).
7674 if (RadixArray.empty()) {
7675 unsigned NumStackEntries = Record[I++];
7676 assert(Record.size() - I >= NumStackEntries);
7677 StackIdList.reserve(NumStackEntries);
7678 for (unsigned J = 0; J < NumStackEntries; J++) {
7679 assert(Record[I] < StackIds.size());
7680 StackIdList.push_back(getStackIdIndex(Record[I++]));
7681 }
7682 } else {
7683 unsigned RadixIndex = Record[I++];
7684 // See the comments above CallStackRadixTreeBuilder in ProfileData/MemProf.h
7685 // for a detailed description of the radix tree array format. Briefly, the
7686 // first entry will be the number of frames, any negative values are the
7687 // negative of the offset of the next frame, and otherwise the frames are in
7688 // increasing linear order.
7689 assert(RadixIndex < RadixArray.size());
7690 unsigned NumStackIds = RadixArray[RadixIndex++];
7691 StackIdList.reserve(NumStackIds);
7692 while (NumStackIds--) {
7693 assert(RadixIndex < RadixArray.size());
7694 unsigned Elem = RadixArray[RadixIndex];
7695 if (static_cast<std::make_signed_t<unsigned>>(Elem) < 0) {
7696 RadixIndex = RadixIndex - Elem;
7697 assert(RadixIndex < RadixArray.size());
7698 Elem = RadixArray[RadixIndex];
7699 // We shouldn't encounter a second offset in a row.
7700 assert(static_cast<std::make_signed_t<unsigned>>(Elem) >= 0);
7701 }
7702 RadixIndex++;
7703 StackIdList.push_back(getStackIdIndex(Elem));
7704 }
7705 }
7706 return StackIdList;
7707}
7708
7709static void setSpecialRefs(SmallVectorImpl<ValueInfo> &Refs, unsigned ROCnt,
7710 unsigned WOCnt) {
7711 // Readonly and writeonly refs are in the end of the refs list.
7712 assert(ROCnt + WOCnt <= Refs.size());
7713 unsigned FirstWORef = Refs.size() - WOCnt;
7714 unsigned RefNo = FirstWORef - ROCnt;
7715 for (; RefNo < FirstWORef; ++RefNo)
7716 Refs[RefNo].setReadOnly();
7717 for (; RefNo < Refs.size(); ++RefNo)
7718 Refs[RefNo].setWriteOnly();
7719}
7720
7721// Eagerly parse the entire summary block. This populates the GlobalValueSummary
7722// objects in the index.
7723Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
7724 if (Error Err = Stream.EnterSubBlock(ID))
7725 return Err;
7726 SmallVector<uint64_t, 64> Record;
7727
7728 // Parse version
7729 {
7730 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7731 if (!MaybeEntry)
7732 return MaybeEntry.takeError();
7733 BitstreamEntry Entry = MaybeEntry.get();
7734
7735 if (Entry.Kind != BitstreamEntry::Record)
7736 return error("Invalid Summary Block: record for version expected");
7737 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7738 if (!MaybeRecord)
7739 return MaybeRecord.takeError();
7740 if (MaybeRecord.get() != bitc::FS_VERSION)
7741 return error("Invalid Summary Block: version expected");
7742 }
7743 const uint64_t Version = Record[0];
7744 const bool IsOldProfileFormat = Version == 1;
7745 // Starting with bitcode summary version 13, MemProf records follow the
7746 // corresponding function summary.
7747 const bool MemProfAfterFunctionSummary = Version >= 13;
7749 return error("Invalid summary version " + Twine(Version) +
7750 ". Version should be in the range [1-" +
7752 "].");
7753 Record.clear();
7754
7755 // Keep around the last seen summary to be used when we see an optional
7756 // "OriginalName" attachement.
7757 GlobalValueSummary *LastSeenSummary = nullptr;
7758 GlobalValue::GUID LastSeenGUID = 0;
7759
7760 // Track the most recent function summary if it was prevailing, and while we
7761 // are not done processing any subsequent memprof records. Starting with
7762 // summary version 13 (tracked by MemProfAfterFunctionSummary), MemProf
7763 // records follow the function summary and we skip processing them when the
7764 // summary is not prevailing. Note that when reading a combined index we don't
7765 // know what is prevailing so this should always be set in the new format when
7766 // we encounter MemProf records.
7767 FunctionSummary *CurrentPrevailingFS = nullptr;
7768
7769 // We can expect to see any number of type ID information records before
7770 // each function summary records; these variables store the information
7771 // collected so far so that it can be used to create the summary object.
7772 std::vector<GlobalValue::GUID> PendingTypeTests;
7773 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7774 PendingTypeCheckedLoadVCalls;
7775 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7776 PendingTypeCheckedLoadConstVCalls;
7777 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7778
7779 std::vector<CallsiteInfo> PendingCallsites;
7780 std::vector<AllocInfo> PendingAllocs;
7781 std::vector<uint64_t> PendingContextIds;
7782
7783 while (true) {
7784 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7785 if (!MaybeEntry)
7786 return MaybeEntry.takeError();
7787 BitstreamEntry Entry = MaybeEntry.get();
7788
7789 switch (Entry.Kind) {
7790 case BitstreamEntry::SubBlock: // Handled for us already.
7792 return error("Malformed block");
7794 return Error::success();
7796 // The interesting case.
7797 break;
7798 }
7799
7800 // Read a record. The record format depends on whether this
7801 // is a per-module index or a combined index file. In the per-module
7802 // case the records contain the associated value's ID for correlation
7803 // with VST entries. In the combined index the correlation is done
7804 // via the bitcode offset of the summary records (which were saved
7805 // in the combined index VST entries). The records also contain
7806 // information used for ThinLTO renaming and importing.
7807 Record.clear();
7808 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7809 if (!MaybeBitCode)
7810 return MaybeBitCode.takeError();
7811 unsigned BitCode = MaybeBitCode.get();
7812
7813 switch (BitCode) {
7814 default: // Default behavior: ignore.
7815 break;
7816 case bitc::FS_FLAGS: { // [flags]
7817 TheIndex.setFlags(Record[0]);
7818 break;
7819 }
7820 case bitc::FS_VALUE_GUID: { // [valueid, refguid_upper32, refguid_lower32]
7821 uint64_t ValueID = Record[0];
7822 GlobalValue::GUID RefGUID;
7823 if (Version >= 11) {
7824 RefGUID = Record[1] << 32 | Record[2];
7825 } else {
7826 RefGUID = Record[1];
7827 }
7828 ValueIdToValueInfoMap[ValueID] =
7829 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
7830 break;
7831 }
7832 // FS_PERMODULE is legacy and does not have support for the tail call flag.
7833 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7834 // numrefs x valueid, n x (valueid)]
7835 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7836 // numrefs x valueid,
7837 // n x (valueid, hotness+tailcall flags)]
7838 // Deprecated, but still needed to read old bitcode files.
7839 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7840 // numrefs x valueid,
7841 // n x (valueid, relblockfreq+tailcall)]
7842 case bitc::FS_PERMODULE:
7844 // Deprecated, but still needed to read old bitcode files.
7846 unsigned ValueID = Record[0];
7847 uint64_t RawFlags = Record[1];
7848 unsigned InstCount = Record[2];
7849 uint64_t RawFunFlags = 0;
7850 unsigned NumRefs = Record[3];
7851 unsigned NumRORefs = 0, NumWORefs = 0;
7852 int RefListStartIndex = 4;
7853 if (Version >= 4) {
7854 RawFunFlags = Record[3];
7855 NumRefs = Record[4];
7856 RefListStartIndex = 5;
7857 if (Version >= 5) {
7858 NumRORefs = Record[5];
7859 RefListStartIndex = 6;
7860 if (Version >= 7) {
7861 NumWORefs = Record[6];
7862 RefListStartIndex = 7;
7863 }
7864 }
7865 }
7866
7867 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7868 // The module path string ref set in the summary must be owned by the
7869 // index's module string table. Since we don't have a module path
7870 // string table section in the per-module index, we create a single
7871 // module path string table entry with an empty (0) ID to take
7872 // ownership.
7873 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7874 assert(Record.size() >= RefListStartIndex + NumRefs &&
7875 "Record size inconsistent with number of references");
7876 SmallVector<ValueInfo, 0> Refs = makeRefList(
7877 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7878 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
7879 // Deprecated, but still needed to read old bitcode files.
7880 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
7881 SmallVector<FunctionSummary::EdgeTy, 0> Calls = makeCallList(
7882 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7883 IsOldProfileFormat, HasProfile, HasRelBF);
7884 setSpecialRefs(Refs, NumRORefs, NumWORefs);
7885 auto [VI, GUID] = getValueInfoFromValueId(ValueID);
7886
7887 // The linker doesn't resolve local linkage values so don't check whether
7888 // those are prevailing (set IsPrevailingSym so they are always processed
7889 // and kept).
7890 auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7891 bool IsPrevailingSym = !IsPrevailing || GlobalValue::isLocalLinkage(LT) ||
7892 IsPrevailing(VI.getGUID());
7893
7894 // If this is not the prevailing copy, and the records are in the "old"
7895 // order (preceding), clear them now. They should already be empty in
7896 // the new order (following), as they are processed or skipped immediately
7897 // when they follow the summary.
7898 assert(!MemProfAfterFunctionSummary ||
7899 (PendingCallsites.empty() && PendingAllocs.empty()));
7900 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
7901 PendingCallsites.clear();
7902 PendingAllocs.clear();
7903 }
7904
7905 auto FS = std::make_unique<FunctionSummary>(
7906 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
7907 std::move(Calls), std::move(PendingTypeTests),
7908 std::move(PendingTypeTestAssumeVCalls),
7909 std::move(PendingTypeCheckedLoadVCalls),
7910 std::move(PendingTypeTestAssumeConstVCalls),
7911 std::move(PendingTypeCheckedLoadConstVCalls),
7912 std::move(PendingParamAccesses), std::move(PendingCallsites),
7913 std::move(PendingAllocs));
7914 FS->setModulePath(getThisModule()->first());
7915 FS->setOriginalName(GUID);
7916 // Set CurrentPrevailingFS only if prevailing, so subsequent MemProf
7917 // records are attached (new order) or skipped.
7918 if (MemProfAfterFunctionSummary) {
7919 if (IsPrevailingSym)
7920 CurrentPrevailingFS = FS.get();
7921 else
7922 CurrentPrevailingFS = nullptr;
7923 }
7924 TheIndex.addGlobalValueSummary(VI, std::move(FS));
7925 break;
7926 }
7927 // FS_ALIAS: [valueid, flags, valueid]
7928 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7929 // they expect all aliasee summaries to be available.
7930 case bitc::FS_ALIAS: {
7931 unsigned ValueID = Record[0];
7932 uint64_t RawFlags = Record[1];
7933 unsigned AliaseeID = Record[2];
7934 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7935 auto AS = std::make_unique<AliasSummary>(Flags);
7936 // The module path string ref set in the summary must be owned by the
7937 // index's module string table. Since we don't have a module path
7938 // string table section in the per-module index, we create a single
7939 // module path string table entry with an empty (0) ID to take
7940 // ownership.
7941 AS->setModulePath(getThisModule()->first());
7942
7943 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7944 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
7945 if (!AliaseeInModule)
7946 return error("Alias expects aliasee summary to be parsed");
7947 AS->setAliasee(AliaseeVI, AliaseeInModule);
7948
7949 auto GUID = getValueInfoFromValueId(ValueID);
7950 AS->setOriginalName(std::get<1>(GUID));
7951 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
7952 break;
7953 }
7954 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7956 unsigned ValueID = Record[0];
7957 uint64_t RawFlags = Record[1];
7958 unsigned RefArrayStart = 2;
7959 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7960 /* WriteOnly */ false,
7961 /* Constant */ false,
7963 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7964 if (Version >= 5) {
7965 GVF = getDecodedGVarFlags(Record[2]);
7966 RefArrayStart = 3;
7967 }
7969 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7970 auto FS =
7971 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7972 FS->setModulePath(getThisModule()->first());
7973 auto GUID = getValueInfoFromValueId(ValueID);
7974 FS->setOriginalName(std::get<1>(GUID));
7975 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
7976 break;
7977 }
7978 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7979 // numrefs, numrefs x valueid,
7980 // n x (valueid, offset)]
7982 unsigned ValueID = Record[0];
7983 uint64_t RawFlags = Record[1];
7984 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
7985 unsigned NumRefs = Record[3];
7986 unsigned RefListStartIndex = 4;
7987 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7988 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7989 SmallVector<ValueInfo, 0> Refs = makeRefList(
7990 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7991 VTableFuncList VTableFuncs;
7992 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7993 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7994 uint64_t Offset = Record[++I];
7995 VTableFuncs.push_back({Callee, Offset});
7996 }
7997 auto VS =
7998 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7999 VS->setModulePath(getThisModule()->first());
8000 VS->setVTableFuncs(VTableFuncs);
8001 auto GUID = getValueInfoFromValueId(ValueID);
8002 VS->setOriginalName(std::get<1>(GUID));
8003 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
8004 break;
8005 }
8006 // FS_COMBINED is legacy and does not have support for the tail call flag.
8007 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
8008 // numrefs x valueid, n x (valueid)]
8009 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
8010 // numrefs x valueid,
8011 // n x (valueid, hotness+tailcall flags)]
8012 case bitc::FS_COMBINED:
8014 unsigned ValueID = Record[0];
8015 uint64_t ModuleId = Record[1];
8016 uint64_t RawFlags = Record[2];
8017 unsigned InstCount = Record[3];
8018 uint64_t RawFunFlags = 0;
8019 unsigned NumRefs = Record[4];
8020 unsigned NumRORefs = 0, NumWORefs = 0;
8021 int RefListStartIndex = 5;
8022
8023 if (Version >= 4) {
8024 RawFunFlags = Record[4];
8025 RefListStartIndex = 6;
8026 size_t NumRefsIndex = 5;
8027 if (Version >= 5) {
8028 unsigned NumRORefsOffset = 1;
8029 RefListStartIndex = 7;
8030 if (Version >= 6) {
8031 NumRefsIndex = 6;
8032 RefListStartIndex = 8;
8033 if (Version >= 7) {
8034 RefListStartIndex = 9;
8035 NumWORefs = Record[8];
8036 NumRORefsOffset = 2;
8037 }
8038 }
8039 NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
8040 }
8041 NumRefs = Record[NumRefsIndex];
8042 }
8043
8044 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
8045 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8046 assert(Record.size() >= RefListStartIndex + NumRefs &&
8047 "Record size inconsistent with number of references");
8048 SmallVector<ValueInfo, 0> Refs = makeRefList(
8049 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8050 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
8051 SmallVector<FunctionSummary::EdgeTy, 0> Edges = makeCallList(
8052 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8053 IsOldProfileFormat, HasProfile, false);
8054 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8055 setSpecialRefs(Refs, NumRORefs, NumWORefs);
8056 auto FS = std::make_unique<FunctionSummary>(
8057 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
8058 std::move(Edges), std::move(PendingTypeTests),
8059 std::move(PendingTypeTestAssumeVCalls),
8060 std::move(PendingTypeCheckedLoadVCalls),
8061 std::move(PendingTypeTestAssumeConstVCalls),
8062 std::move(PendingTypeCheckedLoadConstVCalls),
8063 std::move(PendingParamAccesses), std::move(PendingCallsites),
8064 std::move(PendingAllocs));
8065 LastSeenSummary = FS.get();
8066 if (MemProfAfterFunctionSummary)
8067 CurrentPrevailingFS = FS.get();
8068 LastSeenGUID = VI.getGUID();
8069 FS->setModulePath(ModuleIdMap[ModuleId]);
8070 TheIndex.addGlobalValueSummary(VI, std::move(FS));
8071 break;
8072 }
8073 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
8074 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
8075 // they expect all aliasee summaries to be available.
8077 unsigned ValueID = Record[0];
8078 uint64_t ModuleId = Record[1];
8079 uint64_t RawFlags = Record[2];
8080 unsigned AliaseeValueId = Record[3];
8081 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
8082 auto AS = std::make_unique<AliasSummary>(Flags);
8083 LastSeenSummary = AS.get();
8084 AS->setModulePath(ModuleIdMap[ModuleId]);
8085
8086 auto AliaseeVI = std::get<0>(
8087 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8088 if (AliaseeVI) {
8089 auto AliaseeInModule =
8090 TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
8091 AS->setAliasee(AliaseeVI, AliaseeInModule);
8092 }
8093 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8094 LastSeenGUID = VI.getGUID();
8095 TheIndex.addGlobalValueSummary(VI, std::move(AS));
8096 break;
8097 }
8098 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
8100 unsigned ValueID = Record[0];
8101 uint64_t ModuleId = Record[1];
8102 uint64_t RawFlags = Record[2];
8103 unsigned RefArrayStart = 3;
8104 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
8105 /* WriteOnly */ false,
8106 /* Constant */ false,
8108 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
8109 if (Version >= 5) {
8110 GVF = getDecodedGVarFlags(Record[3]);
8111 RefArrayStart = 4;
8112 }
8114 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8115 auto FS =
8116 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8117 LastSeenSummary = FS.get();
8118 FS->setModulePath(ModuleIdMap[ModuleId]);
8119 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8120 LastSeenGUID = VI.getGUID();
8121 TheIndex.addGlobalValueSummary(VI, std::move(FS));
8122 break;
8123 }
8124 // FS_COMBINED_ORIGINAL_NAME: [original_name]
8126 uint64_t OriginalName = Record[0];
8127 if (!LastSeenSummary)
8128 return error("Name attachment that does not follow a combined record");
8129 LastSeenSummary->setOriginalName(OriginalName);
8130 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
8131 // Reset the LastSeenSummary
8132 LastSeenSummary = nullptr;
8133 LastSeenGUID = 0;
8134 break;
8135 }
8137 assert(PendingTypeTests.empty());
8138 llvm::append_range(PendingTypeTests, Record);
8139 break;
8140
8142 assert(PendingTypeTestAssumeVCalls.empty());
8143 for (unsigned I = 0; I != Record.size(); I += 2)
8144 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8145 break;
8146
8148 assert(PendingTypeCheckedLoadVCalls.empty());
8149 for (unsigned I = 0; I != Record.size(); I += 2)
8150 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8151 break;
8152
8154 PendingTypeTestAssumeConstVCalls.push_back(
8155 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
8156 break;
8157
8159 PendingTypeCheckedLoadConstVCalls.push_back(
8160 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
8161 break;
8162
8164 auto &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
8165 if (Version < 14) {
8166 for (unsigned I = 0; I != Record.size(); I += 2) {
8167 StringRef Name(Strtab.data() + Record[I],
8168 static_cast<size_t>(Record[I + 1]));
8171 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, GUID);
8172 }
8173 } else {
8174 for (unsigned I = 0; I != Record.size(); I += 3) {
8175 GlobalValue::GUID ThinLTOGUID = Record[I];
8176 StringRef Name(Strtab.data() + Record[I + 1],
8177 static_cast<size_t>(Record[I + 2]));
8178 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8179 }
8180 }
8181 break;
8182 }
8183
8185 auto &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
8186 if (Version < 14) {
8187 for (unsigned I = 0; I != Record.size(); I += 2) {
8188 StringRef Name(Strtab.data() + Record[I],
8189 static_cast<size_t>(Record[I + 1]));
8192 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, GUID);
8193 }
8194 } else {
8195 for (unsigned I = 0; I != Record.size(); I += 3) {
8196 GlobalValue::GUID ThinLTOGUID = Record[I];
8197 StringRef Name(Strtab.data() + Record[I + 1],
8198 static_cast<size_t>(Record[I + 2]));
8199 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8200 }
8201 }
8202 break;
8203 }
8204
8205 case bitc::FS_TYPE_ID:
8206 parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
8207 break;
8208
8210 parseTypeIdCompatibleVtableSummaryRecord(Record);
8211 break;
8212
8214 TheIndex.addBlockCount(Record[0]);
8215 break;
8216
8217 case bitc::FS_PARAM_ACCESS: {
8218 PendingParamAccesses = parseParamAccesses(Record);
8219 break;
8220 }
8221
8222 case bitc::FS_STACK_IDS: { // [n x stackid]
8223 // Save stack ids in the reader to consult when adding stack ids from the
8224 // lists in the stack node and alloc node entries.
8225 assert(StackIds.empty());
8226 if (Version <= 11) {
8227 StackIds = ArrayRef<uint64_t>(Record);
8228 } else {
8229 // This is an array of 32-bit fixed-width values, holding each 64-bit
8230 // context id as a pair of adjacent (most significant first) 32-bit
8231 // words.
8232 assert(Record.size() % 2 == 0);
8233 StackIds.reserve(Record.size() / 2);
8234 for (auto R = Record.begin(); R != Record.end(); R += 2)
8235 StackIds.push_back(*R << 32 | *(R + 1));
8236 }
8237 assert(StackIdToIndex.empty());
8238 // Initialize with a marker to support lazy population.
8239 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8240 break;
8241 }
8242
8243 case bitc::FS_CONTEXT_RADIX_TREE_ARRAY: { // [n x entry]
8244 RadixArray = ArrayRef<uint64_t>(Record);
8245 break;
8246 }
8247
8249 // If they are in the new order (following), they are skipped when they
8250 // follow a non-prevailing summary (CurrentPrevailingFS will be null).
8251 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8252 break;
8253 unsigned ValueID = Record[0];
8254 SmallVector<unsigned> StackIdList;
8255 for (uint64_t R : drop_begin(Record)) {
8256 assert(R < StackIds.size());
8257 StackIdList.push_back(getStackIdIndex(R));
8258 }
8259 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8260 if (MemProfAfterFunctionSummary)
8261 CurrentPrevailingFS->addCallsite(
8262 CallsiteInfo({VI, std::move(StackIdList)}));
8263 else
8264 PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
8265 break;
8266 }
8267
8269 // In the combined index case we don't have a prevailing check,
8270 // so we should always have a CurrentPrevailingFS.
8271 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8272 auto RecordIter = Record.begin();
8273 unsigned ValueID = *RecordIter++;
8274 unsigned NumStackIds = *RecordIter++;
8275 unsigned NumVersions = *RecordIter++;
8276 assert(Record.size() == 3 + NumStackIds + NumVersions);
8277 SmallVector<unsigned> StackIdList;
8278 for (unsigned J = 0; J < NumStackIds; J++) {
8279 assert(*RecordIter < StackIds.size());
8280 StackIdList.push_back(getStackIdIndex(*RecordIter++));
8281 }
8282 SmallVector<unsigned> Versions;
8283 for (unsigned J = 0; J < NumVersions; J++)
8284 Versions.push_back(*RecordIter++);
8285 ValueInfo VI = std::get<0>(
8286 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8287 if (MemProfAfterFunctionSummary)
8288 CurrentPrevailingFS->addCallsite(
8289 CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
8290 else
8291 PendingCallsites.push_back(
8292 CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
8293 break;
8294 }
8295
8297 // If they are in the new order (following), they are skipped when they
8298 // follow a non-prevailing summary (CurrentPrevailingFS will be null).
8299 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8300 break;
8301 // This is an array of 32-bit fixed-width values, holding each 64-bit
8302 // context id as a pair of adjacent (most significant first) 32-bit words.
8303 assert(Record.size() % 2 == 0);
8304 PendingContextIds.reserve(Record.size() / 2);
8305 for (auto R = Record.begin(); R != Record.end(); R += 2)
8306 PendingContextIds.push_back(*R << 32 | *(R + 1));
8307 break;
8308 }
8309
8311 // If they are in the new order (following), they are skipped when they
8312 // follow a non-prevailing summary (CurrentPrevailingFS will be null).
8313 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8314 PendingContextIds.clear();
8315 break;
8316 }
8317 unsigned I = 0;
8318 std::vector<MIBInfo> MIBs;
8319 unsigned NumMIBs = 0;
8320 if (Version >= 10)
8321 NumMIBs = Record[I++];
8322 unsigned MIBsRead = 0;
8323 while ((Version >= 10 && MIBsRead++ < NumMIBs) ||
8324 (Version < 10 && I < Record.size())) {
8325 assert(Record.size() - I >= 2);
8327 auto StackIdList = parseAllocInfoContext(Record, I);
8328 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8329 }
8330 // We either have nothing left or at least NumMIBs context size info
8331 // indices left (for the total sizes included when reporting of hinted
8332 // bytes is enabled).
8333 assert(I == Record.size() || Record.size() - I >= NumMIBs);
8334 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8335 if (I < Record.size()) {
8336 assert(!PendingContextIds.empty() &&
8337 "Missing context ids for alloc sizes");
8338 unsigned ContextIdIndex = 0;
8339 MIBsRead = 0;
8340 // The sizes are a linearized array of sizes, where for each MIB there
8341 // is 1 or more sizes (due to context trimming, each MIB in the metadata
8342 // and summarized here can correspond to more than one original context
8343 // from the profile).
8344 while (MIBsRead++ < NumMIBs) {
8345 // First read the number of contexts recorded for this MIB.
8346 unsigned NumContextSizeInfoEntries = Record[I++];
8347 assert(Record.size() - I >= NumContextSizeInfoEntries);
8348 std::vector<ContextTotalSize> ContextSizes;
8349 ContextSizes.reserve(NumContextSizeInfoEntries);
8350 for (unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8351 assert(ContextIdIndex < PendingContextIds.size());
8352 // Skip any 0 entries for MIBs without the context size info.
8353 if (PendingContextIds[ContextIdIndex] == 0) {
8354 // The size should also be 0 if the context was 0.
8355 assert(!Record[I]);
8356 ContextIdIndex++;
8357 I++;
8358 continue;
8359 }
8360 // PendingContextIds read from the preceding FS_ALLOC_CONTEXT_IDS
8361 // should be in the same order as the total sizes.
8362 ContextSizes.push_back(
8363 {PendingContextIds[ContextIdIndex++], Record[I++]});
8364 }
8365 AllContextSizes.push_back(std::move(ContextSizes));
8366 }
8367 PendingContextIds.clear();
8368 }
8369 AllocInfo AI(std::move(MIBs));
8370 if (!AllContextSizes.empty()) {
8371 assert(AI.MIBs.size() == AllContextSizes.size());
8372 AI.ContextSizeInfos = std::move(AllContextSizes);
8373 }
8374
8375 if (MemProfAfterFunctionSummary)
8376 CurrentPrevailingFS->addAlloc(std::move(AI));
8377 else
8378 PendingAllocs.push_back(std::move(AI));
8379 break;
8380 }
8381
8384 // In the combined index case we don't have a prevailing check,
8385 // so we should always have a CurrentPrevailingFS.
8386 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8387 unsigned I = 0;
8388 std::vector<MIBInfo> MIBs;
8389 unsigned NumMIBs = Record[I++];
8390 unsigned NumVersions = Record[I++];
8391 unsigned MIBsRead = 0;
8392 while (MIBsRead++ < NumMIBs) {
8393 assert(Record.size() - I >= 2);
8395 SmallVector<unsigned> StackIdList;
8396 if (BitCode == bitc::FS_COMBINED_ALLOC_INFO)
8397 StackIdList = parseAllocInfoContext(Record, I);
8398 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8399 }
8400 assert(Record.size() - I >= NumVersions);
8401 SmallVector<uint8_t> Versions;
8402 for (unsigned J = 0; J < NumVersions; J++)
8403 Versions.push_back(Record[I++]);
8404 assert(I == Record.size());
8405 AllocInfo AI(std::move(Versions), std::move(MIBs));
8406 if (MemProfAfterFunctionSummary)
8407 CurrentPrevailingFS->addAlloc(std::move(AI));
8408 else
8409 PendingAllocs.push_back(std::move(AI));
8410 break;
8411 }
8412 }
8413 }
8414 llvm_unreachable("Exit infinite loop");
8415}
8416
8417// Parse the module string table block into the Index.
8418// This populates the ModulePathStringTable map in the index.
8419Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8421 return Err;
8422
8423 SmallVector<uint64_t, 64> Record;
8424
8425 SmallString<128> ModulePath;
8426 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
8427
8428 while (true) {
8429 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
8430 if (!MaybeEntry)
8431 return MaybeEntry.takeError();
8432 BitstreamEntry Entry = MaybeEntry.get();
8433
8434 switch (Entry.Kind) {
8435 case BitstreamEntry::SubBlock: // Handled for us already.
8437 return error("Malformed block");
8439 return Error::success();
8441 // The interesting case.
8442 break;
8443 }
8444
8445 Record.clear();
8446 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
8447 if (!MaybeRecord)
8448 return MaybeRecord.takeError();
8449 switch (MaybeRecord.get()) {
8450 default: // Default behavior: ignore.
8451 break;
8452 case bitc::MST_CODE_ENTRY: {
8453 // MST_ENTRY: [modid, namechar x N]
8454 uint64_t ModuleId = Record[0];
8455
8456 if (convertToString(Record, 1, ModulePath))
8457 return error("Invalid code_entry record");
8458
8459 LastSeenModule = TheIndex.addModule(ModulePath);
8460 ModuleIdMap[ModuleId] = LastSeenModule->first();
8461
8462 ModulePath.clear();
8463 break;
8464 }
8465 /// MST_CODE_HASH: [5*i32]
8466 case bitc::MST_CODE_HASH: {
8467 if (Record.size() != 5)
8468 return error("Invalid hash length " + Twine(Record.size()).str());
8469 if (!LastSeenModule)
8470 return error("Invalid hash that does not follow a module path");
8471 int Pos = 0;
8472 for (auto &Val : Record) {
8473 assert(!(Val >> 32) && "Unexpected high bits set");
8474 LastSeenModule->second[Pos++] = Val;
8475 }
8476 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
8477 LastSeenModule = nullptr;
8478 break;
8479 }
8480 }
8481 }
8482 llvm_unreachable("Exit infinite loop");
8483}
8484
8485namespace {
8486
8487// FIXME: This class is only here to support the transition to llvm::Error. It
8488// will be removed once this transition is complete. Clients should prefer to
8489// deal with the Error value directly, rather than converting to error_code.
8490class BitcodeErrorCategoryType : public std::error_category {
8491 const char *name() const noexcept override {
8492 return "llvm.bitcode";
8493 }
8494
8495 std::string message(int IE) const override {
8496 BitcodeError E = static_cast<BitcodeError>(IE);
8497 switch (E) {
8498 case BitcodeError::CorruptedBitcode:
8499 return "Corrupted bitcode";
8500 }
8501 llvm_unreachable("Unknown error type!");
8502 }
8503};
8504
8505} // end anonymous namespace
8506
8507const std::error_category &llvm::BitcodeErrorCategory() {
8508 static BitcodeErrorCategoryType ErrorCategory;
8509 return ErrorCategory;
8510}
8511
8513 unsigned Block, unsigned RecordID) {
8514 if (Error Err = Stream.EnterSubBlock(Block))
8515 return std::move(Err);
8516
8517 StringRef Strtab;
8518 while (true) {
8519 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8520 if (!MaybeEntry)
8521 return MaybeEntry.takeError();
8522 llvm::BitstreamEntry Entry = MaybeEntry.get();
8523
8524 switch (Entry.Kind) {
8526 return Strtab;
8527
8529 return error("Malformed block");
8530
8532 if (Error Err = Stream.SkipBlock())
8533 return std::move(Err);
8534 break;
8535
8537 StringRef Blob;
8539 Expected<unsigned> MaybeRecord =
8540 Stream.readRecord(Entry.ID, Record, &Blob);
8541 if (!MaybeRecord)
8542 return MaybeRecord.takeError();
8543 if (MaybeRecord.get() == RecordID)
8544 Strtab = Blob;
8545 break;
8546 }
8547 }
8548}
8549
8550//===----------------------------------------------------------------------===//
8551// External interface
8552//===----------------------------------------------------------------------===//
8553
8554Expected<std::vector<BitcodeModule>>
8556 auto FOrErr = getBitcodeFileContents(Buffer);
8557 if (!FOrErr)
8558 return FOrErr.takeError();
8559 return std::move(FOrErr->Mods);
8560}
8561
8564 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8565 if (!StreamOrErr)
8566 return StreamOrErr.takeError();
8567 BitstreamCursor &Stream = *StreamOrErr;
8568
8570 while (true) {
8571 uint64_t BCBegin = Stream.getCurrentByteNo();
8572
8573 // We may be consuming bitcode from a client that leaves garbage at the end
8574 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
8575 // the end that there cannot possibly be another module, stop looking.
8576 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
8577 return F;
8578
8579 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8580 if (!MaybeEntry)
8581 return MaybeEntry.takeError();
8582 llvm::BitstreamEntry Entry = MaybeEntry.get();
8583
8584 switch (Entry.Kind) {
8587 return error("Malformed block");
8588
8590 uint64_t IdentificationBit = -1ull;
8591 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
8592 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8593 if (Error Err = Stream.SkipBlock())
8594 return std::move(Err);
8595
8596 {
8597 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8598 if (!MaybeEntry)
8599 return MaybeEntry.takeError();
8600 Entry = MaybeEntry.get();
8601 }
8602
8603 if (Entry.Kind != BitstreamEntry::SubBlock ||
8604 Entry.ID != bitc::MODULE_BLOCK_ID)
8605 return error("Malformed block");
8606 }
8607
8608 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
8609 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8610 if (Error Err = Stream.SkipBlock())
8611 return std::move(Err);
8612
8613 F.Mods.push_back({Stream.getBitcodeBytes().slice(
8614 BCBegin, Stream.getCurrentByteNo() - BCBegin),
8615 Buffer.getBufferIdentifier(), IdentificationBit,
8616 ModuleBit});
8617 continue;
8618 }
8619
8620 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
8621 Expected<StringRef> Strtab =
8623 if (!Strtab)
8624 return Strtab.takeError();
8625 // This string table is used by every preceding bitcode module that does
8626 // not have its own string table. A bitcode file may have multiple
8627 // string tables if it was created by binary concatenation, for example
8628 // with "llvm-cat -b".
8629 for (BitcodeModule &I : llvm::reverse(F.Mods)) {
8630 if (!I.Strtab.empty())
8631 break;
8632 I.Strtab = *Strtab;
8633 }
8634 // Similarly, the string table is used by every preceding symbol table;
8635 // normally there will be just one unless the bitcode file was created
8636 // by binary concatenation.
8637 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
8638 F.StrtabForSymtab = *Strtab;
8639 continue;
8640 }
8641
8642 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
8643 Expected<StringRef> SymtabOrErr =
8645 if (!SymtabOrErr)
8646 return SymtabOrErr.takeError();
8647
8648 // We can expect the bitcode file to have multiple symbol tables if it
8649 // was created by binary concatenation. In that case we silently
8650 // ignore any subsequent symbol tables, which is fine because this is a
8651 // low level function. The client is expected to notice that the number
8652 // of modules in the symbol table does not match the number of modules
8653 // in the input file and regenerate the symbol table.
8654 if (F.Symtab.empty())
8655 F.Symtab = *SymtabOrErr;
8656 continue;
8657 }
8658
8659 if (Error Err = Stream.SkipBlock())
8660 return std::move(Err);
8661 continue;
8662 }
8664 if (Error E = Stream.skipRecord(Entry.ID).takeError())
8665 return std::move(E);
8666 continue;
8667 }
8668 }
8669}
8670
8671/// Get a lazy one-at-time loading module from bitcode.
8672///
8673/// This isn't always used in a lazy context. In particular, it's also used by
8674/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
8675/// in forward-referenced functions from block address references.
8676///
8677/// \param[in] MaterializeAll Set to \c true if we should materialize
8678/// everything.
8680BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
8681 bool ShouldLazyLoadMetadata, bool IsImporting,
8682 ParserCallbacks Callbacks) {
8683 BitstreamCursor Stream(Buffer);
8684
8685 std::string ProducerIdentification;
8686 if (IdentificationBit != -1ull) {
8687 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8688 return std::move(JumpFailed);
8689 if (Error E =
8690 readIdentificationBlock(Stream).moveInto(ProducerIdentification))
8691 return std::move(E);
8692 }
8693
8694 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8695 return std::move(JumpFailed);
8696 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8697 Context);
8698
8699 std::unique_ptr<Module> M =
8700 std::make_unique<Module>(ModuleIdentifier, Context);
8701 M->setMaterializer(R);
8702
8703 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8704 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8705 IsImporting, Callbacks))
8706 return std::move(Err);
8707
8708 if (MaterializeAll) {
8709 // Read in the entire module, and destroy the BitcodeReader.
8710 if (Error Err = M->materializeAll())
8711 return std::move(Err);
8712 } else {
8713 // Resolve forward references from blockaddresses.
8714 if (Error Err = R->materializeForwardReferencedFunctions())
8715 return std::move(Err);
8716 }
8717
8718 return std::move(M);
8719}
8720
8721Expected<std::unique_ptr<Module>>
8722BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8723 bool IsImporting, ParserCallbacks Callbacks) {
8724 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8725 Callbacks);
8726}
8727
8728// Parse the specified bitcode buffer and merge the index into CombinedIndex.
8729// We don't use ModuleIdentifier here because the client may need to control the
8730// module path used in the combined summary (e.g. when reading summaries for
8731// regular LTO modules).
8733 ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8734 std::function<bool(GlobalValue::GUID)> IsPrevailing) {
8735 BitstreamCursor Stream(Buffer);
8736 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8737 return JumpFailed;
8738
8739 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8740 ModulePath, IsPrevailing);
8741 return R.parseModule();
8742}
8743
8744// Parse the specified bitcode buffer, returning the function info index.
8746 BitstreamCursor Stream(Buffer);
8747 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8748 return std::move(JumpFailed);
8749
8750 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
8751 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8752 ModuleIdentifier, 0);
8753
8754 if (Error Err = R.parseModule())
8755 return std::move(Err);
8756
8757 return std::move(Index);
8758}
8759
8762 if (Error Err = Stream.EnterSubBlock(ID))
8763 return std::move(Err);
8764
8766 while (true) {
8767 BitstreamEntry Entry;
8768 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8769 return std::move(E);
8770
8771 switch (Entry.Kind) {
8772 case BitstreamEntry::SubBlock: // Handled for us already.
8774 return error("Malformed block");
8776 // If no flags record found, return both flags as false.
8777 return std::make_pair(false, false);
8778 }
8780 // The interesting case.
8781 break;
8782 }
8783
8784 // Look for the FS_FLAGS record.
8785 Record.clear();
8786 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
8787 if (!MaybeBitCode)
8788 return MaybeBitCode.takeError();
8789 switch (MaybeBitCode.get()) {
8790 default: // Default behavior: ignore.
8791 break;
8792 case bitc::FS_FLAGS: { // [flags]
8793 uint64_t Flags = Record[0];
8794 // Scan flags.
8795 assert(Flags <= 0x7ff && "Unexpected bits in flag");
8796
8797 bool EnableSplitLTOUnit = Flags & 0x8;
8798 bool UnifiedLTO = Flags & 0x200;
8799 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8800 }
8801 }
8802 }
8803 llvm_unreachable("Exit infinite loop");
8804}
8805
8806// Check if the given bitcode buffer contains a global value summary block.
8808 BitstreamCursor Stream(Buffer);
8809 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8810 return std::move(JumpFailed);
8811
8812 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
8813 return std::move(Err);
8814
8815 while (true) {
8817 if (Error E = Stream.advance().moveInto(Entry))
8818 return std::move(E);
8819
8820 switch (Entry.Kind) {
8822 return error("Malformed block");
8824 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
8825 /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8826
8828 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID ||
8831 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID);
8832 if (!Flags)
8833 return Flags.takeError();
8834 BitcodeLTOInfo LTOInfo;
8835 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8836 LTOInfo.IsThinLTO = (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID);
8837 LTOInfo.HasSummary = true;
8838 return LTOInfo;
8839 }
8840
8841 // Ignore other sub-blocks.
8842 if (Error Err = Stream.SkipBlock())
8843 return std::move(Err);
8844 continue;
8845
8847 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
8848 continue;
8849 else
8850 return StreamFailed.takeError();
8851 }
8852 }
8853}
8854
8857 if (!MsOrErr)
8858 return MsOrErr.takeError();
8859
8860 if (MsOrErr->size() != 1)
8861 return error("Expected a single module");
8862
8863 return (*MsOrErr)[0];
8864}
8865
8866Expected<std::unique_ptr<Module>>
8868 bool ShouldLazyLoadMetadata, bool IsImporting,
8869 ParserCallbacks Callbacks) {
8871 if (!BM)
8872 return BM.takeError();
8873
8874 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8875 Callbacks);
8876}
8877
8879 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8880 bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
8881 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8882 IsImporting, Callbacks);
8883 if (MOrErr)
8884 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8885 return MOrErr;
8886}
8887
8890 return getModuleImpl(Context, true, false, false, Callbacks);
8891 // TODO: Restore the use-lists to the in-memory state when the bitcode was
8892 // written. We must defer until the Module has been fully materialized.
8893}
8894
8897 ParserCallbacks Callbacks) {
8899 if (!BM)
8900 return BM.takeError();
8901
8902 return BM->parseModule(Context, Callbacks);
8903}
8904
8906 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8907 if (!StreamOrErr)
8908 return StreamOrErr.takeError();
8909
8910 return readTriple(*StreamOrErr);
8911}
8912
8914 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8915 if (!StreamOrErr)
8916 return StreamOrErr.takeError();
8917
8918 return hasObjCCategory(*StreamOrErr);
8919}
8920
8922 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8923 if (!StreamOrErr)
8924 return StreamOrErr.takeError();
8925
8926 return readIdentificationCode(*StreamOrErr);
8927}
8928
8930 ModuleSummaryIndex &CombinedIndex) {
8932 if (!BM)
8933 return BM.takeError();
8934
8935 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8936}
8937
8941 if (!BM)
8942 return BM.takeError();
8943
8944 return BM->getSummary();
8945}
8946
8949 if (!BM)
8950 return BM.takeError();
8951
8952 return BM->getLTOInfo();
8953}
8954
8957 bool IgnoreEmptyThinLTOIndexFile) {
8960 if (!FileOrErr)
8961 return errorCodeToError(FileOrErr.getError());
8962 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
8963 return nullptr;
8964 return getModuleSummaryIndex(**FileOrErr);
8965}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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)
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 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...
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val, bool &IsElementwise)
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
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 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 Expected< std::pair< bool, bool > > getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID)
static bool isConstExprSupported(const BitcodeConstant *BC)
static int getDecodedCastOpcode(unsigned Val)
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase)
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
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.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
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
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
static const char * name
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallString class.
This file defines the SmallVector class.
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
PointerType * getType() const
Overload to return most specific pointer type.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
static bool isValidFailureOrdering(AtomicOrdering Ordering)
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:143
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
Definition Attributes.h:131
@ None
No attributes have been set.
Definition Attributes.h:126
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
Definition Attributes.h:130
@ EndAttrKinds
Sentinel value useful for loops.
Definition Attributes.h:129
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
bool empty() const
Definition BasicBlock.h:483
const Instruction & back() const
Definition BasicBlock.h:486
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI 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.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition BasicBlock.h:388
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI 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.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
LLVM_ABI 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.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI 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:50
void push_back(Value *V, unsigned TypeID)
Definition ValueList.h:52
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Definition ValueList.h:81
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
Definition ValueList.cpp:21
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 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.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI 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.
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
uint64_t getCurrentByteNo() const
LLVM_ABI Expected< std::optional< BitstreamBlockInfo > > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
bool canSkipToPos(size_t pos) const
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
@ MIN_BYTE_BITS
Minimum number of bits that can be specified.
@ MAX_BYTE_BITS
Maximum number of bits that can be specified Note that bit width is stored in the Type classes Subcla...
static LLVM_ABI ByteType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing a ByteType.
Definition Type.cpp:380
bool isInlineAsm() const
Check if this call is an inline asm statement.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
LLVM_ABI 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
AttributeList getAttributes() const
Return the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo createFromIntValue(uint32_t Data)
Definition ModRef.h:485
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
static LLVM_ABI 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 LLVM_ABI 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:740
static LLVM_ABI 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:845
bool isIntPredicate() const
Definition InstrTypes.h:846
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
static Constant * getRaw(StringRef Data, uint64_t NumElements, Type *ElementTy)
getRaw() constructor - Return a constant with vector type with an element count and element type matc...
Definition Constants.h:975
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1592
static LLVM_ABI 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.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
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:1464
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
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:168
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
LLVM_ABI bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static DeadOnReturnInfo createFromIntValue(uint64_t Data)
Definition Attributes.h:79
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:252
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:225
bool erase(const KeyT &Val)
Definition DenseMap.h:379
unsigned size() const
Definition DenseMap.h:174
bool empty() const
Definition DenseMap.h:173
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:221
iterator end()
Definition DenseMap.h:143
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:286
Base class for error info classes.
Definition Error.h:44
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
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:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
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)
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
void setFast(bool B=true)
Definition FMF.h:96
bool any() const
Definition FMF.h:56
void setAllowContract(bool B=true)
Definition FMF.h:90
void setAllowReciprocal(bool B=true)
Definition FMF.h:87
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
void setAllowReassoc(bool B=true)
Flag setters.
Definition FMF.h:75
void setApproxFunc(bool B=true)
Definition FMF.h:93
void setNoInfs(bool B=true)
Definition FMF.h:81
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:869
void addCallsite(CallsiteInfo &&Callsite)
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
void addAlloc(AllocInfo &&Alloc)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
BasicBlockListType::iterator iterator
Definition Function.h:70
bool empty() const
Definition Function.h:859
iterator begin()
Definition Function.h:853
iterator end()
Definition Function.h:855
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI 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:621
static LLVM_ABI 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:678
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:223
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:284
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
bool hasDefaultVisibility() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
bool hasExternalWeakLinkage() const
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:170
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:260
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:237
void setAttributes(AttributeSet A)
Set attribute list for this global.
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:589
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI 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 LLVM_ABI 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:123
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
bool isBinaryOp() const
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
const char * getOpcodeName() const
bool isUnaryOp() const
LLVM_ABI 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 LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:350
@ MIN_INT_BITS
Minimum number of bits that can be specified.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
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:68
static LLVM_ABI 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...
LLVM_ABI 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.
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:632
ValueT lookup(const KeyT &Key) const
Definition MapVector.h:110
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
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()
Definition ModRef.h:133
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:154
static MemoryEffectsBase createFromIntValue(uint32_t Data)
Definition ModRef.h:208
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:159
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:110
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.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
StringRef saveString(StringRef String)
LLVM_ABI void setFlags(uint64_t Flags)
CfiFunctionIndex & cfiFunctionDecls()
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.
CfiFunctionIndex & cfiFunctionDefs()
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:67
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:283
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition Module.cpp:301
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:308
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition Module.cpp:621
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:358
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
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 LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef first() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
static LLVM_ABI 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:479
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:685
LLVM_ABI 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:634
LLVM_ABI 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:604
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI 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:980
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI 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:46
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:279
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:230
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
Type * getArrayElementType() const
Definition Type.h:425
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:276
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
Definition Type.h:248
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:273
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition Type.h:397
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:233
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:509
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:107
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:212
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:185
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
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 Align[]
Key for Kernel::Arg::Metadata::mAlign.
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.
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.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
Definition GOFF.h:28
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:55
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
@ TYPE_CODE_TARGET_TYPE
@ TYPE_CODE_STRUCT_ANON
@ TYPE_CODE_STRUCT_NAME
@ TYPE_CODE_OPAQUE_POINTER
@ TYPE_CODE_FUNCTION_OLD
@ TYPE_CODE_STRUCT_NAMED
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_CFI_FUNCTION_DECLS
@ FS_COMBINED_CALLSITE_INFO
@ FS_COMBINED_ALLOC_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ BITCODE_CURRENT_EPOCH
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_CE_INBOUNDS_GEP
@ CST_CODE_INLINEASM_OLD3
@ CST_CODE_BLOCKADDRESS
@ CST_CODE_NO_CFI_VALUE
@ CST_CODE_CE_SHUFVEC_EX
@ CST_CODE_CE_EXTRACTELT
@ CST_CODE_INLINEASM_OLD
@ CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
@ CST_CODE_CE_SHUFFLEVEC
@ CST_CODE_WIDE_INTEGER
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_CE_INSERTELT
@ CST_CODE_INLINEASM_OLD2
@ CST_CODE_CE_GEP_WITH_INRANGE
@ VST_CODE_COMBINED_ENTRY
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_SWIFT_ERROR
@ ATTR_KIND_INACCESSIBLEMEM_ONLY
@ ATTR_KIND_NO_CALLBACK
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_INLINE_HINT
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_MUSTPROGRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_INITIALIZES
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_SKIP_PROFILE
@ ATTR_KIND_ELEMENTTYPE
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NO_DUPLICATE
@ ATTR_KIND_ALLOC_ALIGN
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_NO_RED_ZONE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_VSCALE_RANGE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_SPECULATABLE
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ ATTR_KIND_PREALLOCATED
@ ATTR_KIND_SWIFT_ASYNC
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ METADATA_KIND_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ METADATA_ATTACHMENT_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ MODULE_STRTAB_BLOCK_ID
@ VALUE_SYMTAB_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ MODULE_CODE_VERSION
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_DATALAYOUT
@ MODULE_CODE_GLOBALVAR
@ MODULE_CODE_ALIAS_OLD
@ MODULE_CODE_VSTOFFSET
@ FUNC_CODE_INST_ATOMICRMW_OLD
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_RESUME
@ FUNC_CODE_INST_CALLBR
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
@ FUNC_CODE_INST_VSELECT
@ FUNC_CODE_INST_GEP_OLD
@ FUNC_CODE_INST_STOREATOMIC_OLD
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_INST_LANDINGPAD_OLD
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_INST_INVOKE
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_SWITCH
@ FUNC_CODE_INST_ALLOCA
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_INST_SELECT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_STORE_OLD
@ FUNC_CODE_INST_FREEZE
@ FUNC_CODE_INST_CMPXCHG
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_CMPXCHG_OLD
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
constexpr double e
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
constexpr bool IsBigEndianHost
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:558
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:830
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ABI 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...
StringMapEntry< Value * > ValueName
Definition Value.h:56
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI 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:1668
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI 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:2553
std::error_code make_error_code(BitcodeError E)
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
AllocFnKind
Definition Attributes.h:53
LLVM_ABI 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:1013
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
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:633
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2110
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
LLVM_ABI void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:2025
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:334
LLVM_ABI 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:407
LLVM_ABI 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:154
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
Definition Error.h:221
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI 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:1752
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
LLVM_ABI 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:209
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
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:1916
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:559
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
LLVM_ABI void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
LLVM_ABI 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,...
LLVM_ABI 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.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:860
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
Basic information extracted from a bitcode module to be used for LTO.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
Definition Bitfields.h:207
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
static constexpr DenormalFPEnv createFromIntValue(uint32_t Data)
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
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.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const char * BranchWeights
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...
std::optional< DataLayoutCallbackFuncTy > DataLayout
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
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:54
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,...