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