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