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