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