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