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