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