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