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