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